diff --git a/.config/nextest.toml b/.config/nextest.toml index 1f9f3d156f4..4185644c452 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -43,3 +43,24 @@ threads-required = "num-test-threads" filter = "(test(/postgres_tests::/) or binary(/^postgres_/)) and not test(/(^|::)external_infra[^:]*::/)" setup = "postgres-template" run-wrapper = "postgres-isolation" + +[profile.flake] +# The advisory pull-request flake lane (scripts/flake-check.mjs rust) repeats +# a selection and must see every failed repetition, so no retries; the JUnit +# report gives it per-test statuses. +retries = 0 +fail-fast = false + +[profile.flake.junit] +path = "junit.xml" + +[test-groups.desktop-same-user-check] +# Most of buzz-cli's `desktop_provider::` tests reach the real same-user +# check, which runs `lsof` with a 5-second limit. Run all at once on a busy +# Mac, they starve each other past that limit, so the whole module takes +# turns; the few that never reach the check run serially too. +max-threads = 1 + +[[profile.default.overrides]] +filter = "package(buzz-cli) and test(/^desktop_provider::/)" +test-group = "desktop-same-user-check" diff --git a/.env.example b/.env.example index 73d4d9f6eab..eabaefc922f 100644 --- a/.env.example +++ b/.env.example @@ -27,23 +27,10 @@ PGUSER=buzz PGPASSWORD=buzz_dev PGDATABASE=buzz -# Fleet usage telemetry is replica-only and independent of serving-read -# routing. This freshness budget defaults to 30000ms; 0 disables the database -# telemetry families. When the reader is absent, stale, or unavailable, the -# relay skips the collection and reports its availability as 0 instead of -# falling back to the writer. -# BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS=30000 -# Per-community metric series are disabled by default to bound relay memory and -# monitoring cardinality. `all` is the temporary rollback mode. -# BUZZ_USAGE_METRICS_PER_COMMUNITY=off - # ----------------------------------------------------------------------------- # Redis 7 # ----------------------------------------------------------------------------- REDIS_URL=redis://localhost:6379 -# Max connections in the relay's shared Redis pool (default 16). -# BUZZ_REDIS_POOL_SIZE=16 - # Max connections in each of the relay's Postgres pools — writer and, when # READ_DATABASE_URL is set, reader (default 50). # BUZZ_DB_POOL_SIZE=50 @@ -52,6 +39,9 @@ REDIS_URL=redis://localhost:6379 # Emergency kill switch for all automatic partition DDL, including catch-all # advancement; audits remain enabled. # BUZZ_PARTITION_MANAGER_CREATE_ENABLED=true +# Which workflow runs may direct agents: any (default) or owner (owner-only +# agent mentions). See docs/operator-workflow-agent-mentions.md. +# BUZZ_WORKFLOW_AGENT_MENTIONS=owner # Replace an empty partition catch-all with six months of dedicated monthlies, # at startup and on every audit interval (default true). Has no effect while the # kill switch above is off. @@ -130,6 +120,15 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # origin in its NIP-11 document (`admin_api` field) so clients can auto-discover # the console without manual URL entry. # RELAY_OPERATOR_PUBKEYS=<64-char hex pubkey>[,<64-char hex pubkey>...] + +# Serve multiple communities (default true; strict boolean). With false, only +# the normalized RELAY_URL host (including a nondefault port) serves ordinary +# HTTP/WebSocket traffic. New operator creation is disabled; canonical startup +# bootstrap and authenticated admin/operator cleanup of existing extras remain +# available. Existing rows and background cleanup workers are retained. +# Restart every serving revision when changing this setting. Requires a supporting +# image: old images ignore unknown vars; rollback can reopen serving/creation. +# BUZZ_MULTI_COMMUNITY_RELAY=true # # Option B — BUZZ_ADMIN_AUTH=disabled (read-only, no authentication): # Anyone who can reach the relay can read, in every community: reports (with @@ -162,6 +161,13 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # BUZZ_OPERATOR_LISTENER_TIMEOUT_MS=5000 # BUZZ_OPERATOR_LISTENERS=<64-char hex pubkey>:https://listener.example/mentions +# Optional endpoint that receives each new per-community storage snapshot +# written by `buzz-admin storage-snapshot`, in NIP-98 relay-signed POST batches +# shaped like kgoose's storage-usage record request. One relay pod checks for a +# new snapshot every 5 minutes. Receivers must treat a repeated community and +# measured_at as already recorded. +# BUZZ_STORAGE_USAGE_URL=https://kgoose.example/cash-app/goose/v1/buzz/storage-usage/record + # Optional relay-owned KLIPY key. When set, NIP-11 advertises GIF search and # authenticated desktop clients use this relay as the metadata/search proxy. # Keep the real value in your deployment's secret manager; never commit it. @@ -191,6 +197,10 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # BUZZ_GIT_PACK_CACHE_MAX_BYTES=5368709120 # BUZZ_GIT_PACK_CACHE_MAX_CONCURRENT_POPULATIONS=2 +# Channel media revocation: off (default), shadow, enforce. Restart to change. +# Apply migration 0086 first; see docs/operator-private-media.md. +BUZZ_MEDIA_READ_MODE=off + # ----------------------------------------------------------------------------- # S3-Compatible Object Storage (media + Git/CAS) # ----------------------------------------------------------------------------- @@ -233,7 +243,80 @@ BUZZ_S3_ADDRESSING_STYLE=path RUST_LOG=buzz_relay=debug,buzz_datastore=info,buzz_db=debug,buzz_auth=debug,buzz_pubsub=debug,tower_http=debug # Optional OpenTelemetry-only target filter. This is deliberately independent # from RUST_LOG so log verbosity changes cannot break trace parentage. -# BUZZ_OTEL_FILTER=buzz_relay=info,buzz_datastore=info +# BUZZ_OTEL_FILTER=buzz_relay=info,buzz_relay::access=off,buzz_datastore=info +# +# Access log: the relay writes JSON lines for security-relevant actions under +# the `buzz_relay::access` target, with an `event` field of `http`, `auth`, +# `req`, `count`, `sync`, or `close`. `http` is one line per HTTP request, written +# by one layer when the response is ready (not proof the body was delivered): +# `route` is the matched route template (never the raw path), with the response +# `status` and `time_to_response_ms` on every line. It carries the login +# (`method`, `pubkey`, `pubkey_verified`) and `outcome` (`success`, `denied`, +# `failed`, `challenged`, or `undecided` when the route recorded no decision; a +# refusal is final). `/query` and `/count` add the filter summary and +# `result_count`; `/events` adds `accepted`, `kind`, `event_id` and a fixed +# `reject_reason` code; invite and admin attachment routes add their own fields +# (`invite_id`, `expires_at`, `max_uses`, `joined`, `feedback_id`, +# `attachment_sha256`). Invite codes, tokens and Blossom read hashes are never +# logged. An attachment read with admin auth disabled logs +# `method=network_trusted` and no key. A request dropped before its response +# logs `request=aborted` with no `status`. +# Every matched route is logged except `/` (non-upgrade), `/info`, +# `/.well-known/nostr.json`, `/health`, `/_liveness` and `/_readiness`. +# Requests matching no route log only at status 400 and above, as +# `route=""`, except that the SPA and static files the relay +# serves when enabled (web assets, invite landing pages, git web pages, the +# admin bundle) log nothing at any status, including 404. Successful WebSocket +# upgrades log no `http` line. +# `auth` is one line per WebSocket login, written when it succeeds or is +# refused; every root WebSocket `auth` line carries the TCP `peer_addr`. +# `req` / `count` / `sync` is one line per WebSocket read (a NIP-AR sync +# subscription is a `sync` read), with the same filter summary +# (search text is never logged, only `search: true`). A `sync` line is written +# when its initial set completes, not when live delivery ends: its summary is +# the registered live filter (kinds and channels, never artifact predicates) +# and `events_queued` counts the initial set. `buzz_ws_reads_total` counts +# parsed reads by `type` (`req`, `count`, `sync`). The summary lists up to +# 10 kinds, channel ids, authors and `p` values each; `kind_count`, +# `channel_count`, `author_count` and `p_count` appear only when the list is +# `*` or shows fewer values than the filters held. `close` is the +# connection's one line: duration, totals, the login's `pubkey`, `method` and +# `pubkey_verified`, and `reads_suppressed` / `auth_suppressed` for repeated +# refusals past the first 16. It is written however the connection ends, with +# `refused` (`not_admitted`, `connection_limit`) when the relay refused it +# before serving it. Refusals that arrive after `close` has been written log +# their own lines. +# Successful lines and git's credential-less first request +# (`outcome=challenged`) are INFO; refusals, error statuses and aborted +# requests are WARN. A successful `/query` or `/count` that returned nothing +# (`result_count=0`) is DEBUG, since polling clients make most of them. A +# WebSocket read is WARN only when it ends in `error`; +# refused and `aborted` reads stay INFO, since `aborted` means the read ended +# before completing: the client closed the connection or sent CLOSE, a same-ID +# REQ replaced it, or the session was cancelled, all of which are routine. Turn it down with +# `buzz_relay::access=warn` (keeps refusals, errors and aborted HTTP requests, +# and of WebSocket reads only `error` outcomes) or `buzz_relay::access=off` in +# RUST_LOG. +# It is off in the OTel export by default so lines are not shipped twice. +# Removed or renamed: `NIP-42 auth successful/failed`, `WebSocket connection +# established/closed` and the `event=connect` line (folded into `close`), `HTTP +# bridge request` (folded into the bridge's `http` line), `Event ingested via +# pipeline` (the WebSocket `Event ingested` line and the `/events` line carry +# its fields), `relay invite minted`, `relay member added via invite` and `admin +# feedback attachment read` (folded into the route's `http` line), the `addr` +# field, now `peer_addr`, and the JSON `span` field (`spans` already ends with +# the current span; a line logged under an explicit parent span loses that +# parent's fields). Git subprocess stderr moved from WARN to DEBUG because hook +# output can contain message text. + +# Request header holding the real client IP, logged as `client_ip` on `http`, +# `auth`, `close` and connection-limit lines next to `peer_addr` (optional, +# case-insensitive; unset or empty turns it off). A list value logs its +# rightmost entry; a value that isn't an IP address is not logged. Set it only +# when every request reaches the relay through a proxy that overwrites this +# header (for example `cf-connecting-ip` behind Cloudflare or `x-real-ip` +# behind nginx); otherwise clients can forge it. +# BUZZ_CLIENT_IP_HEADER=x-real-ip # OTLP tracing endpoint (optional — leave unset to disable) # OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 @@ -392,3 +475,22 @@ RUST_LOG=buzz_relay=debug,buzz_datastore=info,buzz_db=debug,buzz_auth=debug,buzz # BUZZ_NIP_FI_RESOLVER_NEGATIVE_CACHE_MAX=100000 # Concurrent live lookups; clamped below the database pool size. # BUZZ_NIP_FI_RESOLVER_MAX_INFLIGHT=8 + +# Optional absolute legacy-v1 invite cutoff, UTC RFC3339 whole seconds. +# Unset preserves natural token expiry; never changes v2 invitations. +# BUZZ_INVITE_V1_INVALID_AFTER=2026-12-01T00:00:00Z + +# Optional NIP-FI historical verified profiles (disabled by default): issuer JSON +# entries may set public_profile=true, public_issuer_label="Example Corp", and +# verified_at_refresh_seconds=3600 (integer 0..86400). Requires a stable relay +# key and NIP-FI enforcement. Profiles are historical records and are never +# retracted. + +# Permit community FI policy enables and disables only after the whole fleet +# supports policy management. A closed gate preserves receipt recovery/status. +BUZZ_NIP_FI_CHANGES=false + +# NIP-CL compact membership discovery. Deploy fleet-wide dark before enabling. +BUZZ_MEMBERSHIP_SNAPSHOT_ENABLED=false +# Independent listed-open public membership lookup; also deploy disabled. +BUZZ_MEMBERSHIP_PUBLIC_ENABLED=false diff --git a/.github/workflows/_ci-clients.yml b/.github/workflows/_ci-clients.yml index 23cf8091fba..bb34636882b 100644 --- a/.github/workflows/_ci-clients.yml +++ b/.github/workflows/_ci-clients.yml @@ -25,7 +25,7 @@ env: jobs: web: name: Web - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 15 if: inputs.lane == 'required' && (github.event_name == 'push' || inputs.web) permissions: @@ -61,7 +61,7 @@ jobs: # matrix result. Test shards split files, so each compiles only its own. mobile: name: Mobile (${{ matrix.name }}) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 30 # Dreamforge will publish its own phone app (plan Q8), but the fork does not build it # yet. Drop this block/buzz guard (here and on ci.yml's mobile jobs) with slice A2. @@ -135,28 +135,53 @@ jobs: run: cd mobile && flutter analyze - name: Test if: matrix.lane == 'test' - run: /bin/bash scripts/mobile-test-shard.sh ${{ matrix.shard }} 3 --dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example - - name: Test configured authentication domains + run: /bin/bash scripts/mobile-test-shard.sh ${{ matrix.shard }} 3 + - name: Test native secp256k1 package + if: matrix.lane == 'checks' + run: cd mobile/packages/buzz_secp256k1 && dart pub get && dart test + - name: Test internal build if: matrix.lane == 'checks' run: >- cd mobile && flutter test - --dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example - --dart-define=BUZZ_AUTH_DOMAINS=buzz.xyz,builderlab.xyz,builderlabstaging.xyz + --dart-define=BUZZ_DISTRIBUTION=internal + --dart-define=BUZZ_BUILDERLAB_URL=https://id.example.org + --dart-define=BUZZ_BUILDERLAB_RELAYS=buzz.example.org + test/features/onboarding/internal_build_entry_test.dart + - name: Test public build + if: matrix.lane == 'checks' + run: >- + cd mobile && flutter test + --dart-define=BUZZ_DISTRIBUTION=public + --dart-define=BUZZ_BUILDERLAB_URL=https://app.builderlab.xyz + --dart-define=BUZZ_BUILDERLAB_RELAYS=communities.buzz.xyz test/shared/auth/community_entry_requirements_test.dart + test/features/agents/agent_creation_link_journey_test.dart test/features/invites/invite_join_provider_test.dart test/features/onboarding/onboarding_entry_routes_test.dart - test/shared/hosted/hosted_environment_test.dart test/shared/hosted/self_hosted_entry_test.dart + test/features/agents/agents_signed_out_prompt_test.dart + test/features/agents/agents_restore_prompt_test.dart + test/shared/hosted/relay_auth_isolation_test.dart test/features/onboarding/hosted_app_gate_environment_test.dart + test/features/settings/builderlab_account_row_test.dart test/features/onboarding/hosted_journeys_test.dart + test/features/onboarding/hosted_backup_consent_test.dart + test/features/onboarding/onboarding_sign_out_test.dart test/features/onboarding/hosted_communities_test.dart test/features/pairing/pairing_hosted_handoff_test.dart - - name: Test mobile without push configuration - if: matrix.lane == 'checks' - run: cd mobile && flutter test test/shared/push/push_unconfigured_build_test.dart + test/shared/agents/remote_agents_test.dart + test/features/agents - name: Test mobile recipe argument forwarding if: matrix.lane == 'checks' run: /bin/bash scripts/test-mobile-gateway-recipes.sh + # ubuntu-26.04 defaults to JDK 25, which Gradle 8.14 does not + # support. Pin the JDK 17 the 24.04 image used. + - name: Set up JDK 17 + if: matrix.lane == 'android' + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: temurin + java-version: "17" - name: Restore Gradle cache if: matrix.lane == 'android' uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 @@ -166,6 +191,13 @@ jobs: ~/.gradle/wrapper key: gradle-${{ runner.os }}-${{ hashFiles('mobile/android/**/*.gradle*', 'mobile/android/gradle/wrapper/gradle-wrapper.properties', 'mobile/pubspec.lock') }} restore-keys: gradle-${{ runner.os }}- + # The Hermit package cache above holds only Flutter, so the build's first + # just and cmake calls download them. + - name: Fetch Hermit tools + if: matrix.lane == 'android' + run: | + scripts/ci-hermit-retry.sh ./bin/just --version + scripts/ci-hermit-retry.sh ./bin/cmake --version # SDK component and plugin downloads intermittently fail on hosted # runners; retry once only for those, so real build failures still fail. - name: Build Android debug APK @@ -239,7 +271,6 @@ jobs: /bin/bash scripts/test-mobile-pagination-accessibility.sh "$device" /bin/bash scripts/test-mobile-carousel.sh "$device" /bin/bash scripts/test-mobile-member-picker.sh "$device" - /bin/bash scripts/test-mobile-me-agent-accessibility.sh "$device" if ! wait "$build"; then cat "$build_log" exit 1 @@ -257,7 +288,7 @@ jobs: name: Results if: ${{ always() }} needs: [web, mobile, mobile-swift] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} outputs: diff --git a/.github/workflows/_ci-desktop-macos.yml b/.github/workflows/_ci-desktop-macos.yml index c9474870d3f..5f9c6d4aa51 100644 --- a/.github/workflows/_ci-desktop-macos.yml +++ b/.github/workflows/_ci-desktop-macos.yml @@ -31,6 +31,8 @@ jobs: steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + - name: Fetch Hermit tools + run: scripts/ci-hermit-retry.sh ./bin/just --version - name: Verify macOS icon representations run: scripts/macos-icon.sh --check - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 @@ -103,7 +105,7 @@ jobs: name: Results if: ${{ always() }} needs: [desktop-build-macos] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} outputs: diff --git a/.github/workflows/_ci-desktop.yml b/.github/workflows/_ci-desktop.yml index 106d3c9a172..4438c82bb07 100644 --- a/.github/workflows/_ci-desktop.yml +++ b/.github/workflows/_ci-desktop.yml @@ -26,7 +26,7 @@ jobs: # relayReconnectReplay.test.mjs), so Rust changes select this job too. desktop-js: name: Desktop JS - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 20 # Keep in sync with JS_SELECTED in the Desktop gate (pinned by ci-required-gates.test.mjs). if: github.event_name == 'push' || inputs.desktop || inputs.rust @@ -52,6 +52,8 @@ jobs: run: just desktop-check - name: Desktop unit tests run: just desktop-test + - name: Flake check selection tests + run: node --test scripts/flake-check.test.mjs - name: Desktop build run: just desktop-build - name: Save pnpm store cache @@ -66,7 +68,7 @@ jobs: # cache read-only; the mesh-llm feature pulls its own dependency graph. desktop-tauri: name: Desktop Tauri (${{ matrix.lane }}) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 # A lane needs up to ~15m. ci-apt-retry.sh bounds the apt step at ~45m worst # case (update ~14m + install ~31m); 65m fits both, so a degraded mirror # fails with the wrapper's error instead of the job timeout. @@ -91,6 +93,22 @@ jobs: run: just desktop-tauri-test-compiled-flags permissions: contents: read + env: + # Resolved and installed by the steps below; the .deb cache key hashes + # what apt resolves for this list. + TAURI_APT_PACKAGES: >- + build-essential + curl + file + libasound2-dev + libayatana-appindicator3-dev + libgtk-3-dev + librsvg2-dev + libssl-dev + libwebkit2gtk-4.1-dev + libxdo-dev + patchelf + wget steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: @@ -99,28 +117,74 @@ jobs: - uses: rui314/setup-mold@7e4f20ad28a2e8ca6fd0892ccf72e2abb706b9c3 # v1 - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 with: - prefix-key: v0-rust-ubuntu2404 + prefix-key: v0-rust-ubuntu2604 workspaces: desktop/src-tauri shared-key: ${{ matrix.cache }} save-if: ${{ matrix.save-cache && github.event_name != 'pull_request' }} + # A degraded Ubuntu mirror serves .debs at ~50 KB/s, and the ~62 MB + # Tauri download (one 25.5 MB libwebkit2gtk .deb) then outlasts every + # ci-apt-retry.sh attempt. Cache the .debs in the Actions cache so the + # mirror only serves `apt-get update` and packages Ubuntu has updated + # since main last saved. + - name: Resolve Tauri apt archives + id: tauri-debs + run: | + set -euo pipefail + CI_APT_ATTEMPT_SECONDS=90 scripts/ci-apt-retry.sh sudo apt-get update + read -ra packages <<< "$TAURI_APT_PACKAGES" + # Name, size and SHA256 (from the signed index) of each .deb the + # install will fetch. The mirror URI is left out so the key doesn't + # depend on which mirror answered. Runs before the restore: + # --print-uris omits files that are already in + # /var/cache/apt/archives. + sudo apt-get install --print-uris -qq -y --no-install-recommends \ + -o Acquire::ForceHash=SHA256 "${packages[@]}" | + awk '{print $2, $3, $4}' | sort > "$RUNNER_TEMP/tauri-debs.txt" + . /etc/os-release + prefix="tauri-debs-${ID}${VERSION_ID}-" + echo "prefix=$prefix" >> "$GITHUB_OUTPUT" + echo "key=$prefix$(sha256sum "$RUNNER_TEMP/tauri-debs.txt" | cut -c1-16)" >> "$GITHUB_OUTPUT" + - name: Restore Tauri apt archives + id: tauri-debs-cache + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ~/.cache/tauri-debs + key: ${{ steps.tauri-debs.outputs.key }} + restore-keys: ${{ steps.tauri-debs.outputs.prefix }} - name: Install Tauri dependencies (Linux) + id: tauri-debs-install env: DEBIAN_FRONTEND: noninteractive run: | - CI_APT_ATTEMPT_SECONDS=90 scripts/ci-apt-retry.sh sudo apt-get update - scripts/ci-apt-retry.sh sudo apt-get install -y --no-install-recommends \ - build-essential \ - curl \ - file \ - libasound2-dev \ - libayatana-appindicator3-dev \ - libgtk-3-dev \ - librsvg2-dev \ - libssl-dev \ - libwebkit2gtk-4.1-dev \ - libxdo-dev \ - patchelf \ - wget + set -euo pipefail + debs=~/.cache/tauri-debs + mkdir -p "$debs" + # apt reuses an archived .deb of the expected size without checking + # its hash, so seed only restored files whose SHA256 matches the + # signed index. apt downloads and verifies the rest. sha256sum exits + # non-zero when a file fails or none is restored; neither is fatal. + awk '{sub(/^SHA256:/, "", $3); print $3 " " $1}' "$RUNNER_TEMP/tauri-debs.txt" > "$RUNNER_TEMP/tauri-debs.sha256" + (cd "$debs" && { sha256sum --check --ignore-missing "$RUNNER_TEMP/tauri-debs.sha256" || true; }) | + sed -n 's/: OK$//p' | (cd "$debs" && xargs -r sudo cp -t /var/cache/apt/archives/) + read -ra packages <<< "$TAURI_APT_PACKAGES" + scripts/ci-apt-retry.sh sudo apt-get install -y --no-install-recommends "${packages[@]}" + # Keep exactly the resolved files, so a restore-keys fallback can't + # pile up superseded versions. The packages are installed by now, so + # a failure here only warns and skips the save. + if rm -rf "$debs" && mkdir -p "$debs" && + awk '{print "/var/cache/apt/archives/" $1}' "$RUNNER_TEMP/tauri-debs.txt" | xargs -r cp -t "$debs"; then + echo "rebuilt=true" >> "$GITHUB_OUTPUT" + else + echo "::warning::Could not rebuild the Tauri apt archive cache; not saving it." + fi + # Like the other caches here, only pushes save; PR runs restore. All + # three lanes resolve the same key, so one lane saves it. + - name: Save Tauri apt archives + if: matrix.lane == 'core' && github.event_name == 'push' && steps.tauri-debs-cache.outputs.cache-hit != 'true' && steps.tauri-debs-install.outputs.rebuilt == 'true' + uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ~/.cache/tauri-debs + key: ${{ steps.tauri-debs.outputs.key }} - name: Desktop Tauri ${{ matrix.lane }} run: ${{ matrix.run }} env: @@ -128,7 +192,7 @@ jobs: desktop-smoke-e2e: name: Desktop Smoke E2E (${{ matrix.shard }}) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 # A smoke shard needs ~12m, and Chromium dependency setup is bounded by # ci-apt-retry.sh (~31m worst case). Leave time for the full suite # and its reports to finish. @@ -166,10 +230,9 @@ jobs: with: path: ${{ env.PLAYWRIGHT_BROWSERS_PATH }} key: playwright-${{ runner.os }}-${{ steps.pw-version.outputs.version }} - # GitHub moved ubuntu-latest to 26.04, where Playwright 1.60 can't install - # Chromium. Every Linux CI job stays on 24.04, so relay binaries and the + # Every Linux CI job runs on one Ubuntu image, so relay binaries and the # jobs that run them share one glibc. Rust caches carry the image in their - # prefix-key. Move them together, after a Playwright bump that supports 26.04. + # prefix-key (v0-rust-ubuntu2604). Change the runners and the prefix together. - name: Install Playwright Chromium if: steps.playwright-cache.outputs.cache-hit != 'true' run: cd desktop && pnpm exec playwright install chromium @@ -203,7 +266,7 @@ jobs: desktop: name: Desktop - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 needs: [desktop-js, desktop-tauri, desktop-smoke-e2e, desktop-windows-build] if: always() && (github.event_name == 'push' || inputs.desktop || inputs.desktop_rust || inputs.rust) @@ -271,7 +334,7 @@ jobs: name: Results if: ${{ always() }} needs: [desktop] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} outputs: diff --git a/.github/workflows/_ci-flake.yml b/.github/workflows/_ci-flake.yml new file mode 100644 index 00000000000..fab0cbb38ef --- /dev/null +++ b/.github/workflows/_ci-flake.yml @@ -0,0 +1,335 @@ +name: CI / Flake Check +on: + workflow_call: + +env: + CARGO_TERM_COLOR: always + BUZZ_TEST_POSTGRES_PASSWORD: buzz_dev + PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/.cache/ms-playwright + +# Advisory flake check: repeat the tests a pull request changes, ten times +# each with retries off, so a race inside a test surfaces before it lands on +# main. The lanes skip when no test changed, so they stay out of the required +# checks in ci.yml (whose gates reject skipped lanes); their own statuses and +# step summaries carry the result. Selections reach the lanes through env +# vars, never interpolated into run scripts; flake-check.mjs admits only plain +# path and identifier characters. +jobs: + flake-select: + name: Flake check selection + # Block's advisory lane; on the fork every lane below skips with this job + # (keeps PR CI volume down). Guarded here so ci.yml keeps Block's line. + if: github.repository == 'block/buzz' + runs-on: ubuntu-26.04 + timeout-minutes: 10 + permissions: + contents: read + outputs: + rust: ${{ steps.select.outputs.rust }} + tauri: ${{ steps.select.outputs.tauri }} + node: ${{ steps.select.outputs.node }} + playwright: ${{ steps.select.outputs.playwright }} + playwright_shards: ${{ steps.select.outputs.playwright_shards }} + playwright_shard_total: ${{ steps.select.outputs.playwright_shard_total }} + dart: ${{ steps.select.outputs.dart }} + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + # The merge commit's first parent is the base branch tip, so this + # diff is exactly the pull request's change without a full clone. + fetch-depth: 2 + - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + # Only a changed spec needs desktop dependencies: Playwright lists its + # smoke journeys and the desktop app's TypeScript parses it. Pull + # requests without one skip the install. + - name: Check for changed Playwright specs + id: specs + run: | + if git diff --quiet --diff-filter=AM HEAD^1 HEAD -- 'desktop/tests/e2e/*.spec.ts'; then + echo "changed=false" >> "$GITHUB_OUTPUT" + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + - name: Get pnpm store directory + if: steps.specs.outputs.changed == 'true' + id: pnpm-cache + run: echo "STORE_PATH=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" + - name: Restore pnpm store cache + if: steps.specs.outputs.changed == 'true' + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} + key: pnpm-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: pnpm-${{ runner.os }}- + - name: Install desktop dependencies + if: steps.specs.outputs.changed == 'true' + run: just desktop-install-ci + - name: Map changed hunks to tests + id: select + run: node scripts/flake-check.mjs select HEAD^1 HEAD + + flake-rust: + name: Flake check (Rust) + needs: [flake-select] + if: needs.flake-select.outputs.rust != '' + runs-on: ubuntu-26.04 + timeout-minutes: 30 + permissions: + contents: read + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 + # Restores the Unit Tests lane's cache (_ci-rust.yml) read-only; this + # lane never saves one of its own. The restore only hits while the cache + # key matches: the same shared-key, and rust-cache's environment hash — + # the CARGO*/RUST*/CC* environment variables, the lockfiles and the rustc + # version — must stay identical to the Unit Tests job's, so any env this + # job sets must be set there too (scripts/test-rust-cache-contract.sh + # checks the key). + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 + with: + shared-key: unit-tests-sherpa-cache-v1 + save-if: false + - name: Install cargo-nextest + uses: taiki-e/install-action@0fd46367812ee04360509b4169d9f659d6892bb2 # v2.79.15 + with: + tool: cargo-nextest@0.9.136 + # nextest has no repeat flag; the script runs the selection once per + # iteration under the `flake` profile (.config/nextest.toml). + - name: Repeat changed Rust tests + env: + SELECTED: ${{ needs.flake-select.outputs.rust }} + run: node scripts/flake-check.mjs rust --iterations=10 $SELECTED + - name: Rust iteration reports + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: flake-rust + path: test-results/flake + if-no-files-found: ignore + retention-days: 7 + + flake-tauri: + name: Flake check (Desktop Tauri) + needs: [flake-select] + if: needs.flake-select.outputs.tauri != '' + runs-on: ubuntu-26.04 + # A Desktop Tauri lane's bound (_ci-desktop.yml: ci-apt-retry.sh bounds + # the apt step at ~34m worst case and a cold build needs ~15m), plus a + # second cold build: a lib selection also builds the mesh-llm graph. + timeout-minutes: 70 + permissions: + contents: read + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 + # Restores the Desktop Tauri core lane's cache (_ci-desktop.yml) + # read-only, under the same constraints as flake-rust's restore above: + # the workspace, shared-key and environment hash must stay identical to + # that job's. + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 + with: + workspaces: desktop/src-tauri + shared-key: desktop-core + save-if: false + - name: Install Tauri dependencies (Linux) + env: + DEBIAN_FRONTEND: noninteractive + run: | + CI_APT_ATTEMPT_SECONDS=90 scripts/ci-apt-retry.sh sudo apt-get update + scripts/ci-apt-retry.sh sudo apt-get install -y --no-install-recommends \ + build-essential \ + curl \ + file \ + libasound2-dev \ + libayatana-appindicator3-dev \ + libgtk-3-dev \ + librsvg2-dev \ + libssl-dev \ + libwebkit2gtk-4.1-dev \ + libxdo-dev \ + patchelf \ + wget + - name: Install cargo-nextest + uses: taiki-e/install-action@0fd46367812ee04360509b4169d9f659d6892bb2 # v2.79.15 + with: + tool: cargo-nextest@0.9.136 + # tauri-build validates the sidecar binaries at compile time; the Desktop + # Tauri recipes create the same empty stubs. + - name: Create sidecar stubs + run: just _ensure-sidecar-stubs + # Same script as flake-rust, against the Tauri workspace's manifest and + # its own .config/nextest.toml `flake` profile. A selected lib test also + # repeats under mesh-llm, as desktop-tauri-test-mesh runs it; the + # restored desktop-core cache does not hold that dependency graph, so a + # lib selection builds it cold, and an integration-test one never does. + - name: Repeat changed desktop Tauri tests + env: + CMAKE_POLICY_VERSION_MINIMUM: "3.5" + SELECTED: ${{ needs.flake-select.outputs.tauri }} + run: node scripts/flake-check.mjs tauri --iterations=10 $SELECTED + - name: Desktop Tauri iteration reports + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: flake-tauri + path: test-results/flake + if-no-files-found: ignore + retention-days: 7 + + flake-node: + name: Flake check (node:test) + needs: [flake-select] + if: needs.flake-select.outputs.node != '' + runs-on: ubuntu-26.04 + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + - name: Get pnpm store directory + id: pnpm-cache + run: echo "STORE_PATH=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" + - name: Restore pnpm store cache + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} + key: pnpm-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: pnpm-${{ runner.os }}- + - name: Install desktop dependencies + run: just desktop-install-ci + - name: Repeat changed node:test files + env: + SELECTED: ${{ needs.flake-select.outputs.node }} + run: node scripts/flake-check.mjs node --iterations=10 $SELECTED + - name: node:test iteration logs + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: flake-node + path: test-results/flake + if-no-files-found: ignore + retention-days: 7 + + flake-playwright: + name: Flake check (Playwright smoke, ${{ matrix.shard }}/${{ needs.flake-select.outputs.playwright_shard_total }}) + needs: [flake-select] + if: needs.flake-select.outputs.playwright != '' + runs-on: ubuntu-26.04 + # Same bound as a smoke shard: Chromium dependency setup is bounded by + # ci-apt-retry.sh (~25m worst case), and flake-check.mjs sizes the shards + # so the repetitions fit the rest. + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + shard: ${{ fromJSON(needs.flake-select.outputs.playwright_shards) }} + permissions: + contents: read + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + - name: Get pnpm store directory + id: pnpm-cache + run: echo "STORE_PATH=$(pnpm store path --silent)" >> "$GITHUB_OUTPUT" + - name: Restore pnpm store cache + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} + key: pnpm-${{ runner.os }}-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: pnpm-${{ runner.os }}- + - name: Install desktop dependencies + run: just desktop-install-ci + - name: Get Playwright version + id: pw-version + run: echo "version=$(cd desktop && node -e "console.log(require('@playwright/test/package.json').version)")" >> "$GITHUB_OUTPUT" + - name: Restore Playwright browser cache + id: playwright-cache + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ${{ env.PLAYWRIGHT_BROWSERS_PATH }} + key: playwright-${{ runner.os }}-${{ steps.pw-version.outputs.version }} + - name: Install Playwright Chromium + if: steps.playwright-cache.outputs.cache-hit != 'true' + run: cd desktop && pnpm exec playwright install chromium + - name: Install Playwright system dependencies + run: cd desktop && ../scripts/ci-apt-retry.sh pnpm exec playwright install-deps chromium + - name: Desktop E2E build + run: pnpm -C desktop build:e2e + # --retries=0 overrides the config's CI retries, so every failed + # repetition reports as unexpected and fails the step. + - name: Repeat changed smoke journeys + env: + PLAYWRIGHT_JSON_OUTPUT_FILE: playwright-report.json + SELECTED: ${{ needs.flake-select.outputs.playwright }} + SHARD: ${{ matrix.shard }} + SHARD_TOTAL: ${{ needs.flake-select.outputs.playwright_shard_total }} + run: cd desktop && pnpm exec playwright test --project=smoke --repeat-each=10 --retries=0 --shard="$SHARD/$SHARD_TOTAL" --reporter=list,json $SELECTED + - name: Summarize repetitions + if: ${{ !cancelled() }} + env: + SHARD: ${{ matrix.shard }} + SHARD_TOTAL: ${{ needs.flake-select.outputs.playwright_shard_total }} + run: node scripts/flake-check.mjs playwright-summary desktop/playwright-report.json "Flake check (Playwright smoke, $SHARD/$SHARD_TOTAL)" + - name: Playwright repetition artifacts + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: flake-playwright-${{ matrix.shard }} + path: | + desktop/playwright-report.json + desktop/test-results + if-no-files-found: ignore + retention-days: 7 + + flake-dart: + name: Flake check (Flutter) + needs: [flake-select] + if: needs.flake-select.outputs.dart != '' + runs-on: ubuntu-26.04 + # Large mobile changes take about three minutes per repetition, plus SDK + # setup. Allow all ten repetitions to finish with runner variance. + timeout-minutes: 45 + permissions: + contents: read + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + # Restores the Mobile lane's Hermit and pub caches read-only; that lane + # saves them. + - name: Compute Hermit cache key + id: hermit-bin-hash + run: | + hash="$(find ./bin ! -type d | sort | xargs openssl sha256 | openssl sha256 -r | cut -d' ' -f1)" + echo "hash=$hash" >> "$GITHUB_OUTPUT" + - name: Restore Hermit package cache + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ~/.cache/hermit/pkg + key: ${{ runner.os }}-hermit-cache-${{ steps.hermit-bin-hash.outputs.hash }} + restore-keys: ${{ runner.os }}-hermit-cache- + - name: Prime Flutter SDK + run: flutter --version + - name: Restore pub cache + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ~/.pub-cache + key: pub-${{ runner.os }}-${{ hashFiles('mobile/pubspec.lock') }} + restore-keys: pub-${{ runner.os }}- + - name: Install dependencies + run: cd mobile && flutter pub get + - name: Repeat changed Flutter tests + env: + SELECTED: ${{ needs.flake-select.outputs.dart }} + run: node scripts/flake-check.mjs dart --iterations=10 $SELECTED + - name: Flutter iteration reports + if: ${{ !cancelled() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: flake-dart + path: test-results/flake + if-no-files-found: ignore + retention-days: 7 diff --git a/.github/workflows/_ci-relay.yml b/.github/workflows/_ci-relay.yml index be988bad9dd..d59c226edcb 100644 --- a/.github/workflows/_ci-relay.yml +++ b/.github/workflows/_ci-relay.yml @@ -37,7 +37,7 @@ jobs: # artifact into target/ci as before. desktop-e2e-relay: name: Desktop E2E Relay (${{ matrix.artifact }}) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 45 if: inputs.lane == 'artifacts' && (github.event_name == 'push' || inputs.desktop || inputs.desktop_rust || inputs.rust) strategy: @@ -77,7 +77,7 @@ jobs: - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' with: - prefix-key: v0-rust-ubuntu2404 + prefix-key: v0-rust-ubuntu2604 workspaces: | . desktop/src-tauri @@ -89,6 +89,21 @@ jobs: uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 # zizmor: ignore[cache-poisoning] Bounded trial: only PR 5224 writes to its isolated merge-ref scope; trusted pushes retain production writes. with: version: v0.16.0 + # The sccache server checks its GHA cache storage at startup and refuses to + # start when that fails (egress over the account limit, a failed read), + # which used to fail cargo's first `sccache rustc -vV` and the build. + # SCCACHE_IGNORE_SERVER_IO_ERROR doesn't cover startup in v0.16.0, so start + # it here and build with plain rustc if it won't start. + - name: Start sccache + id: sccache + if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' + run: | + if sccache --start-server; then + echo "wrapper=sccache" >> "$GITHUB_OUTPUT" + else + echo "::warning::sccache did not start; building without it" + echo "wrapper=" >> "$GITHUB_OUTPUT" + fi - name: Install cargo-nextest if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' && matrix.artifact != 'relay-binaries' uses: taiki-e/install-action@0fd46367812ee04360509b4169d9f659d6892bb2 # v2.79.15 @@ -97,17 +112,19 @@ jobs: - name: Build relay binaries if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' && matrix.artifact == 'relay-binaries' env: - RUSTC_WRAPPER: sccache + RUSTC_WRAPPER: ${{ steps.sccache.outputs.wrapper }} run: cargo build --profile ci -p buzz-relay -p git-credential-nostr - name: Build backend integration test archive if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' && matrix.artifact == 'backend-integration-tests' env: - RUSTC_WRAPPER: sccache + RUSTC_WRAPPER: ${{ steps.sccache.outputs.wrapper }} run: | cargo nextest archive \ --cargo-profile ci \ -p buzz-db \ + -p buzz-pubsub \ -p buzz-relay \ + -p buzz-relay-mesh \ -p buzz-test-client \ --lib \ --test e2e_event_reminder \ @@ -117,7 +134,7 @@ jobs: - name: Build PostgreSQL test archive if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' && matrix.artifact == 'postgres-tests' env: - RUSTC_WRAPPER: sccache + RUSTC_WRAPPER: ${{ steps.sccache.outputs.wrapper }} run: | postgres_package_args=() while IFS= read -r package; do @@ -151,7 +168,7 @@ jobs: postgres-tests: name: PostgreSQL Tests - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 10 if: inputs.lane == 'postgres' && (github.event_name == 'push' || inputs.rust) permissions: @@ -192,6 +209,9 @@ jobs: steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + # pgschema has no --version; --help exits 0 once Hermit has fetched it. + - name: Fetch Hermit tools + run: scripts/ci-hermit-retry.sh ./bin/pgschema --help - name: Tune disposable PostgreSQL env: PGPASSWORD: ${{ env.BUZZ_TEST_POSTGRES_PASSWORD }} @@ -229,7 +249,7 @@ jobs: desktop-e2e-integration-shard: name: Desktop E2E Integration (${{ matrix.shard }}/${{ strategy.job-total }}) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 # A shard needs ~10m; Playwright install-deps is bounded by # ci-apt-retry.sh (~31m worst case), so a degraded mirror fails with its # own error instead of the job timeout. @@ -244,6 +264,9 @@ jobs: steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + # pgschema has no --version; --help exits 0 once Hermit has fetched it. + - name: Fetch Hermit tools + run: scripts/ci-hermit-retry.sh ./bin/pgschema --help - name: Start integration services run: | for attempt in 1 2 3; do @@ -409,7 +432,7 @@ jobs: desktop-e2e-integration: name: Desktop E2E Integration - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 needs: [desktop-e2e-integration-shard] if: always() && inputs.lane == 'required' && (github.event_name == 'push' || inputs.desktop || inputs.desktop_rust || inputs.rust) @@ -426,7 +449,7 @@ jobs: backend-integration: name: Backend Integration (relay e2e) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 20 if: inputs.lane == 'required' && (github.event_name == 'push' || inputs.rust) permissions: @@ -434,6 +457,9 @@ jobs: steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + # pgschema has no --version; --help exits 0 once Hermit has fetched it. + - name: Fetch Hermit tools + run: scripts/ci-hermit-retry.sh ./bin/pgschema --help - name: Install cargo-nextest uses: taiki-e/install-action@0fd46367812ee04360509b4169d9f659d6892bb2 # v2.79.15 with: @@ -523,6 +549,31 @@ jobs: --archive-file target/ci/backend-integration-tests.tar.zst \ -E 'package(buzz-relay) and test(/api::git::settings::tests::external_infra::/)' \ --run-ignored ignored-only + - name: Admin attachment access-log regression + env: + # This test builds its state from Config::for_test(), which reads the + # relay's own DATABASE_URL and BUZZ_S3_* variables. + DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz + BUZZ_S3_ENDPOINT: http://localhost:9000 + BUZZ_S3_BUCKET: buzz-media + run: | + cargo nextest run \ + --archive-file target/ci/backend-integration-tests.tar.zst \ + -E 'package(buzz-relay) and test(/api::admin::postgres_tests::external_infra_minio_tests::/)' \ + --run-ignored ignored-only + - name: Media thumbnail regeneration regressions + # The tests share one fixture image's storage keys, and nextest gives + # each its own process, so their in-process lock can't order them. + env: + BUZZ_TEST_DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz + BUZZ_S3_ENDPOINT: http://localhost:9000 + BUZZ_S3_BUCKET: buzz-media + run: | + cargo nextest run \ + --archive-file target/ci/backend-integration-tests.tar.zst \ + -E 'package(buzz-relay) and test(/^api::media::tests::postgres_tests::external_infra_minio_tests::/)' \ + --run-ignored ignored-only \ + --test-threads 1 - name: Relay quota accounting and rejection regressions env: BUZZ_TEST_REDIS_URL: redis://localhost:6379 @@ -539,6 +590,21 @@ jobs: --archive-file target/ci/backend-integration-tests.tar.zst \ -E 'package(buzz-relay) and test(/^api::nip_fi::route_integration_tests::external_infra_redis::/)' \ --run-ignored ignored-only + - name: Mesh ready-registry index regressions + env: + BUZZ_TEST_REDIS_URL: redis://localhost:6379 + run: | + cargo nextest run \ + --archive-file target/ci/backend-integration-tests.tar.zst \ + -E 'package(buzz-relay-mesh) and test(/^registry::tests::external_infra_redis::/)' \ + --run-ignored ignored-only + - name: Pubsub subscriber reconciliation regression + # Runs the live Redis subscriber; the test dials redis://127.0.0.1:6379. + run: | + cargo nextest run \ + --archive-file target/ci/backend-integration-tests.tar.zst \ + -E 'package(buzz-pubsub) and test(=tests::live_subscriber_recovers_a_dropped_subscribe_hint)' \ + --run-ignored ignored-only - name: Workflow message provenance unit tests # The relay's workflow_sink suite is not selected by the infra-free # unit job. Its ignored database cases run in the isolated PostgreSQL @@ -599,7 +665,7 @@ jobs: relay-e2e: name: Relay E2E - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 20 if: inputs.lane == 'required' && (github.event_name == 'push' || inputs.rust) permissions: @@ -609,7 +675,7 @@ jobs: - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 with: - prefix-key: v0-rust-ubuntu2404 + prefix-key: v0-rust-ubuntu2604 save-if: ${{ github.event_name != 'pull_request' }} # Reuse the relay + git-credential-nostr built by Desktop E2E Relay # instead of compiling them a second time. @@ -620,6 +686,8 @@ jobs: merge-multiple: true path: target/ci - name: Start relay + env: + BUZZ_MEDIA_READ_MODE: enforce run: | chmod +x ./target/ci/buzz-relay ./target/ci/git-credential-nostr ./scripts/start-relay-for-tests.sh --no-build @@ -665,7 +733,7 @@ jobs: name: Results if: ${{ always() }} needs: [desktop-e2e-relay, postgres-tests, desktop-e2e-integration, backend-integration, relay-e2e] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} outputs: diff --git a/.github/workflows/_ci-rust.yml b/.github/workflows/_ci-rust.yml index 874495370e4..65e48e25d8c 100644 --- a/.github/workflows/_ci-rust.yml +++ b/.github/workflows/_ci-rust.yml @@ -27,7 +27,7 @@ env: jobs: rust-lint: name: Rust Lint - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 30 if: inputs.lane == 'required' && (github.event_name == 'push' || inputs.rust || inputs.desktop_rust) permissions: @@ -37,7 +37,7 @@ jobs: - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 with: - prefix-key: v0-rust-ubuntu2404 + prefix-key: v0-rust-ubuntu2604 save-if: ${{ github.event_name != 'pull_request' }} - name: Format check run: just fmt-check @@ -48,7 +48,7 @@ jobs: unit-tests: name: Unit Tests - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 30 if: inputs.lane == 'required' && (github.event_name == 'push' || inputs.rust) permissions: @@ -59,8 +59,11 @@ jobs: - uses: rui314/setup-mold@7e4f20ad28a2e8ca6fd0892ccf72e2abb706b9c3 # v1 - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 with: - prefix-key: v0-rust-ubuntu2404 - key: sherpa-cache-v1 + prefix-key: v0-rust-ubuntu2604 + # Named so the advisory flake lane (_ci-flake.yml) can restore it; + # with shared-key set, rust-cache ignores `key`, so the cache-bust + # suffix lives here. Bump it to discard every saved cache. + shared-key: unit-tests-sherpa-cache-v1 save-if: ${{ github.event_name != 'pull_request' }} - name: Install cargo-nextest uses: taiki-e/install-action@0fd46367812ee04360509b4169d9f659d6892bb2 # v2.79.15 @@ -77,7 +80,7 @@ jobs: server-cross-compile: name: Server Cross-Compile - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 30 if: inputs.lane == 'cross-compile' && (github.event_name == 'push' || inputs.rust) permissions: @@ -93,7 +96,7 @@ jobs: - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 with: - prefix-key: v0-rust-ubuntu2404 + prefix-key: v0-rust-ubuntu2604 key: cross-${{ matrix.target }} save-if: ${{ github.event_name != 'pull_request' }} - name: Install cross @@ -117,10 +120,11 @@ jobs: windows-rust: name: Windows Rust (x86_64-pc-windows-msvc) runs-on: windows-latest - # Windows runners are slow and this compiles the workspace + Tauri crate - # cold across four steps; budget generously. A toolchain bump empties the - # cache and a cold run takes 41-46 min, and the cache only saves after a - # finished run, so 45 left main stuck red. + # With no rust-cache (after a toolchain bump or eviction), the steps take + # 39-41m on main (2026-10-22..26): clippy 17-18m, Tauri check ~6m, Tauri + # tests 10-11m, the rest ~5m. The cache save that follows takes ~4.5m and + # runs inside this cap. If the cap kills it, nothing is saved and the next + # push is cold again. 60m leaves ~15m over that; warm runs take 15-23m. timeout-minutes: 60 if: inputs.lane == 'required' && (github.event_name == 'push' || inputs.rust || inputs.desktop_rust) permissions: @@ -152,10 +156,10 @@ jobs: for bin in buzz-acp buzz-agent buzz-dev-mcp git-credential-nostr buzz; do touch "desktop/src-tauri/binaries/${bin}-${TARGET}.exe" done + # Clippy type-checks everything `cargo check` would, so no separate + # workspace check step. - name: Clippy (workspace) run: cargo clippy --workspace --all-targets --target $env:TARGET -- -D warnings - - name: Check (workspace) - run: cargo check --workspace --all-targets --target $env:TARGET - name: Test (buzz-dev-mcp) # The Windows-only bash resolver lives in buzz-dev-mcp; its unit tests # only gate if this crate is tested ON Windows. @@ -225,7 +229,7 @@ jobs: name: Results if: ${{ always() }} needs: [rust-lint, unit-tests, server-cross-compile, windows-rust] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} outputs: diff --git a/.github/workflows/_ci-security.yml b/.github/workflows/_ci-security.yml index 032b6250078..cc2d407922f 100644 --- a/.github/workflows/_ci-security.yml +++ b/.github/workflows/_ci-security.yml @@ -17,7 +17,7 @@ env: jobs: security: name: Security - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 20 if: github.event_name == 'push' || inputs.rust permissions: @@ -39,7 +39,7 @@ jobs: name: Results if: ${{ always() }} needs: [security] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} outputs: diff --git a/.github/workflows/auto-tag-on-release-pr-merge.yml b/.github/workflows/auto-tag-on-release-pr-merge.yml index 3db5c6baaaf..d42ab4c90e2 100644 --- a/.github/workflows/auto-tag-on-release-pr-merge.yml +++ b/.github/workflows/auto-tag-on-release-pr-merge.yml @@ -11,9 +11,10 @@ name: Auto-tag on Release PR Merge # any internal PR that bumps deploy/charts/buzz/Chart.yaml `version` # → tag chart-v → helm-chart.yml (helm chart) # -# Mobile candidate tags do not come from merged PRs. Operators create immutable -# mobile-v-rc.N tags directly from remote main with scripts/mobile-release.sh, -# then hand the exact tag to buzz-releases. +# Mobile candidate tags do not come from merged PRs or from this App. Release +# managers push immutable mobile-v-rc.N tags themselves with +# scripts/mobile-release.sh, gated by a dedicated mobile tag ruleset whose only +# bypass is the mobile release team, then hand the exact tag to buzz-releases. # # Release tags are created with a short-lived token from the dedicated # buzz-release-bot GitHub App. GitHub attributes the ref creation to that diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d5495f7bf81..c4036eba9b5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ env: jobs: changes: name: Detect Changed Paths - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 # The steps take about 75 seconds, but GitHub can finish the job minutes # after the last step. A 2-minute limit cancelled finished runs. timeout-minutes: 10 @@ -34,6 +34,12 @@ jobs: with: fetch-depth: 2 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + # The first call of each Hermit tool downloads it. A stalled Node download + # hung the selection step until this job's cap cancelled every gate. One + # invocation fetches both tools, so its worst case (under 6 minutes) + # still leaves the rest of the job inside the 10-minute cap. + - name: Fetch Hermit tools + run: scripts/ci-hermit-retry.sh sh -c './bin/node --version && ./bin/just --version' - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 id: filter with: @@ -69,6 +75,7 @@ jobs: - 'scripts/model-capabilities.json' - 'scripts/normative-corpus.json' - 'scripts/ci-apt-retry.sh' + - 'scripts/ci-hermit-retry.sh' - 'Justfile' desktop: - '.github/workflows/ci.yml' @@ -83,6 +90,9 @@ jobs: - 'scripts/normative-corpus.json' - 'desktop/**' - 'pnpm-lock.yaml' + - 'scripts/flake-check.mjs' + - 'scripts/flake-check.test.mjs' + - '.github/workflows/_ci-flake.yml' desktop-rust: - 'desktop/src-tauri/**' web: @@ -96,12 +106,10 @@ jobs: - 'scripts/mobile-release-source.sh' - 'scripts/mobile-worktree-overrides.sh' - 'scripts/mobile-worktree-clean.sh' - - 'scripts/publish-mobile-release-candidate.sh' - 'scripts/release-rulesets.sh' - 'scripts/test-mobile-release-contract.sh' - - 'scripts/test-mobile-release-candidate-publisher.sh' - 'scripts/test-mobile-worktree-overrides.sh' - - '.github/workflows/mobile-release-candidate.yml' + - 'scripts/ci-hermit-retry.sh' - '.github/workflows/ci.yml' - '.github/workflows/_ci-*.yml' - name: Select runtime suites conservatively at the PR file-list limit @@ -125,9 +133,7 @@ jobs: scripts/test-oss-desktop-promotion.sh scripts/test-oss-desktop-promotion-behavior.sh - name: Mobile release contract - run: | - scripts/test-mobile-release-contract.sh - scripts/test-mobile-release-candidate-publisher.sh + run: scripts/test-mobile-release-contract.sh - name: Desktop instance environment contract run: scripts/test-desktop-instance-detection.sh - name: Mobile worktree identity contract @@ -138,16 +144,20 @@ jobs: run: | scripts/test-rust-cache-contract.sh scripts/test-rust-cache-contract-regressions.sh + - name: SQLx dependency pin + run: | + python3 scripts/check-sqlx-pin.py + python3 scripts/test-sqlx-pin.py - name: CI required-context isolation contract run: scripts/test-ci-required-context-isolation.sh - name: CI path selection regression tests - run: node --test scripts/ci-selection.test.mjs scripts/ci-required-gates.test.mjs scripts/ci-apt-retry.test.mjs + run: node --test scripts/ci-selection.test.mjs scripts/ci-required-gates.test.mjs scripts/ci-apt-retry.test.mjs scripts/ci-hermit-retry.test.mjs - name: File size policy run: just file-size-check dead-token-guard: name: Dead Token Reference Guard - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: contents: read @@ -260,6 +270,14 @@ jobs: mobile: ${{ needs.changes.outputs.mobile == 'true' }} lane: mobile-swift + # Advisory flake check: repeats the tests a pull request changes. Its lanes + # skip when no test changed and none of the required gates below reads them; + # their own statuses and step summaries carry the result. + flake-check: + name: Flake Check + if: github.event_name == 'pull_request' + uses: ./.github/workflows/_ci-flake.yml + security-domain: name: Security Domain needs: [changes] @@ -272,7 +290,7 @@ jobs: name: Rust Lint if: always() && (needs.changes.result != 'success' || ((github.event_name == 'push' || needs.changes.outputs.rust == 'true' || needs.changes.outputs.desktop-rust == 'true'))) needs: [changes, rust] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -286,7 +304,7 @@ jobs: name: Unit Tests if: always() && (needs.changes.result != 'success' || ((github.event_name == 'push' || needs.changes.outputs.rust == 'true'))) needs: [changes, rust] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -300,7 +318,7 @@ jobs: name: Windows Rust (x86_64-pc-windows-msvc) if: always() && (needs.changes.result != 'success' || ((github.event_name == 'push' || needs.changes.outputs.rust == 'true' || needs.changes.outputs.desktop-rust == 'true'))) needs: [changes, rust] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -314,7 +332,7 @@ jobs: name: Desktop if: always() && (needs.changes.result != 'success' || ((github.event_name == 'push' || needs.changes.outputs.desktop == 'true' || needs.changes.outputs.desktop-rust == 'true' || needs.changes.outputs.rust == 'true'))) needs: [changes, desktop-domain] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -328,7 +346,7 @@ jobs: name: Desktop Build (macOS) if: always() && (needs.changes.result != 'success' || ((github.event_name == 'push' || needs.changes.outputs.desktop == 'true' || needs.changes.outputs.desktop-rust == 'true' || needs.changes.outputs.rust == 'true'))) needs: [changes, desktop-macos-domain] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -342,7 +360,7 @@ jobs: name: Desktop E2E Relay if: always() && (needs.changes.result != 'success' || ((github.event_name == 'push' || needs.changes.outputs.desktop == 'true' || needs.changes.outputs.desktop-rust == 'true' || needs.changes.outputs.rust == 'true'))) needs: [changes, relay-artifacts-domain] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -356,7 +374,7 @@ jobs: name: Desktop E2E Integration if: always() && (needs.changes.result != 'success' || (needs.relay-artifacts-domain.result == 'success' && (github.event_name == 'push' || needs.changes.outputs.desktop == 'true' || needs.changes.outputs.desktop-rust == 'true' || needs.changes.outputs.rust == 'true'))) needs: [changes, relay-artifacts-domain, relay-domain] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -370,7 +388,7 @@ jobs: name: Backend Integration (relay e2e) if: always() && (needs.changes.result != 'success' || (needs.relay-artifacts-domain.result == 'success' && (github.event_name == 'push' || needs.changes.outputs.rust == 'true'))) needs: [changes, relay-artifacts-domain, relay-domain] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -384,7 +402,7 @@ jobs: name: PostgreSQL Tests if: always() && (needs.changes.result != 'success' || (needs.relay-artifacts-domain.result == 'success' && (github.event_name == 'push' || needs.changes.outputs.rust == 'true'))) needs: [changes, relay-artifacts-domain, postgres-domain] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -398,7 +416,7 @@ jobs: name: Relay E2E if: always() && (needs.changes.result != 'success' || (needs.relay-artifacts-domain.result == 'success' && (github.event_name == 'push' || needs.changes.outputs.rust == 'true'))) needs: [changes, relay-artifacts-domain, relay-domain] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -412,7 +430,7 @@ jobs: name: Web if: always() && (needs.changes.result != 'success' || ((github.event_name == 'push' || needs.changes.outputs.web == 'true'))) needs: [changes, clients] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -427,7 +445,7 @@ jobs: # The Dreamforge fork does not build or ship the phone app (owners use Block's store build). if: always() && github.repository == 'block/buzz' && (needs.changes.result != 'success' || ((github.event_name == 'push' || needs.changes.outputs.mobile == 'true'))) needs: [changes, clients] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: @@ -441,7 +459,7 @@ jobs: name: Security if: always() && (needs.changes.result != 'success' || github.event_name == 'push' || needs.changes.outputs.rust == 'true' || needs.changes.outputs.desktop-rust == 'true') needs: [changes, security-domain] - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 timeout-minutes: 5 permissions: {} steps: diff --git a/.github/workflows/desktop-release-candidate.yml b/.github/workflows/desktop-release-candidate.yml index 61ccc800af3..9533e0c2a6a 100644 --- a/.github/workflows/desktop-release-candidate.yml +++ b/.github/workflows/desktop-release-candidate.yml @@ -3,6 +3,12 @@ name: Desktop Release Candidate on: pull_request: branches: [main] + workflow_dispatch: + inputs: + version: + description: Existing candidate version to validate (version-bump/) + required: true + type: string permissions: contents: read @@ -12,17 +18,38 @@ jobs: validate: name: Desktop Release Candidate runs-on: ubuntu-latest + timeout-minutes: 10 steps: + - name: Authorize manual candidate validation + if: github.event_name == 'workflow_dispatch' + env: + GH_TOKEN: ${{ github.token }} + DISPATCH_REF: ${{ github.ref }} + TRIGGERING_ACTOR: ${{ github.triggering_actor }} + run: | + set -euo pipefail + if [[ "$DISPATCH_REF" != refs/heads/main ]]; then + echo "::error::Dispatch candidate validation from main." + exit 1 + fi + # Re-runs retain the original actor; authorize the re-runner too. + for actor in "$GITHUB_ACTOR" "$TRIGGERING_ACTOR"; do + permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$actor/permission" --jq '.permission') + if [[ "$permission" != admin ]]; then + echo "::error::Manual candidate validation requires repository admin permission." + exit 1 + fi + done - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/heads/version-bump/{0}', inputs.version) || github.event.pull_request.head.sha }} fetch-depth: 0 persist-credentials: false - name: Validate immutable desktop candidate - if: startsWith(github.event.pull_request.head.ref, 'version-bump/') + if: github.event_name == 'workflow_dispatch' || startsWith(github.event.pull_request.head.ref, 'version-bump/') env: GH_TOKEN: ${{ github.token }} - VERSION: ${{ github.event.pull_request.head.ref }} + VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs.version || github.event.pull_request.head.ref }} run: | VERSION="${VERSION#version-bump/}" scripts/desktop_release.py validate --candidate HEAD --version "$VERSION" --repo "$GITHUB_REPOSITORY" diff --git a/.github/workflows/docker-manual.yml b/.github/workflows/docker-manual.yml new file mode 100644 index 00000000000..5d7a40d4155 --- /dev/null +++ b/.github/workflows/docker-manual.yml @@ -0,0 +1,248 @@ +name: Manual relay image +run-name: Manual relay image · ${{ inputs.source_ref }} + +# Operator-only publishing. This deliberately does not qualify the source via CI. +# Publish manual-* tags only; normal release publishing remains in docker.yml. +on: + workflow_dispatch: + inputs: + source_ref: + description: block/buzz branch, tag, or full SHA reachable from a repository branch + required: true + type: string + +permissions: {} + +env: + IMAGE_NAME: ${{ vars.GHCR_IMAGE != '' && vars.GHCR_IMAGE || 'ghcr.io/block/buzz' }} + +jobs: + resolve: + name: Resolve the selected source + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + outputs: + sha: ${{ steps.source.outputs.sha }} + tag: ${{ steps.source.outputs.tag }} + steps: + - name: Require block/buzz repository + env: + REPOSITORY: ${{ github.repository }} + shell: bash + run: | + set -euo pipefail + [[ "$REPOSITORY" == block/buzz ]] || { + echo '::error::Run this workflow in block/buzz; use source_ref to select repository code.' + exit 1 + } + - name: Resolve a source reachable from a repository branch + id: source + env: + SOURCE_REF: ${{ inputs.source_ref }} + shell: bash + run: | + set -euo pipefail + if [[ -z "$SOURCE_REF" || ${#SOURCE_REF} -gt 255 || ! "$SOURCE_REF" =~ ^[A-Za-z0-9._/@-]+$ ]]; then + echo '::error::Supply a repository branch, tag, or full commit SHA.' + exit 1 + fi + case "$SOURCE_REF" in + -*|*..*|*.lock|refs/pull/*|pull/*|*/pull/*) + echo '::error::PR refs and malformed refs are not allowed.' + exit 1 + ;; + esac + workdir=$(mktemp -d) + trap 'rm -rf "$workdir"' EXIT + git -C "$workdir" init --quiet + git -C "$workdir" remote add origin https://github.com/block/buzz.git + # Fetch only canonical branch histories, never refs/pull or arbitrary SHAs. + # Full history is needed to prove ancestry; blobs are fetched only by build jobs. + git -C "$workdir" fetch --filter=blob:none --no-tags origin \ + '+refs/heads/*:refs/remotes/origin/*' + if [[ "$SOURCE_REF" =~ ^[0-9a-fA-F]{40}$ ]]; then + sha=$(git -C "$workdir" rev-parse --verify "${SOURCE_REF}^{commit}") + elif [[ "$SOURCE_REF" == refs/heads/* ]]; then + sha=$(git -C "$workdir" rev-parse --verify "refs/remotes/origin/${SOURCE_REF#refs/heads/}^{commit}") + else + tag_ref="$SOURCE_REF" + if [[ "$SOURCE_REF" != refs/* ]] && \ + sha=$(git -C "$workdir" rev-parse --verify "refs/remotes/origin/${SOURCE_REF}^{commit}" 2>/dev/null); then + : + else + if [[ "$SOURCE_REF" != refs/* ]]; then + tag_ref="refs/tags/$SOURCE_REF" + fi + [[ "$tag_ref" == refs/tags/* ]] || { + echo '::error::Only repository branches and tags are allowed.' + exit 1 + } + git -C "$workdir" fetch --no-tags origin "$tag_ref:refs/tags/manual-source" + sha=$(git -C "$workdir" rev-parse --verify 'refs/tags/manual-source^{commit}') + fi + fi + [[ "$sha" =~ ^[0-9a-f]{40}$ ]] + branches=$(git -C "$workdir" for-each-ref --format='%(refname)' --contains="$sha" refs/remotes/origin/) + [[ -n "$branches" ]] || { + echo '::error::Selected commit must be reachable from a block/buzz branch; PR-only commits are not allowed.' + exit 1 + } + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "tag=manual-${sha:0:12}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" >> "$GITHUB_OUTPUT" + echo "Selected source: $sha. CI qualification is skipped." + + build: + name: Build (${{ matrix.platform }}) + needs: resolve + runs-on: ${{ matrix.runner }} + timeout-minutes: 90 + permissions: + contents: read + packages: write + strategy: + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-24.04 + arch: amd64 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + arch: arm64 + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + ref: ${{ needs.resolve.outputs.sha }} + persist-credentials: false + - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + with: + buildkitd-config-inline: | + [worker.oci] + max-parallelism = 2 + - uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Build and push the runtime by digest + id: build + uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0 + with: + context: . + file: ./Dockerfile + target: runtime + platforms: ${{ matrix.platform }} + build-args: | + BUZZ_SOURCE_SHA=${{ needs.resolve.outputs.sha }} + BUZZ_BUILD_ID=manual-actions:${{ github.run_id }}:${{ github.run_attempt }} + BUZZ_BUILD_URL=https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }} + labels: | + org.opencontainers.image.source=https://github.com/${{ github.repository }} + org.opencontainers.image.revision=${{ needs.resolve.outputs.sha }} + xyz.buzz.manual-build=true + outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true + cache-from: | + type=registry,ref=${{ env.IMAGE_NAME }}-buildcache:${{ matrix.arch }} + type=registry,ref=${{ env.IMAGE_NAME }}-buildcache:manual-${{ matrix.arch }} + cache-to: type=registry,ref=${{ env.IMAGE_NAME }}-buildcache:manual-${{ matrix.arch }},mode=max,compression=zstd + - name: Record this architecture's published digest + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + shell: bash + run: | + set -euo pipefail + [[ "$IMAGE_DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]] + mkdir -p "$RUNNER_TEMP/manual-digest" + printf '%s\n' "$IMAGE_DIGEST" > "$RUNNER_TEMP/manual-digest/digest" + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: manual-digest-${{ matrix.arch }} + path: ${{ runner.temp }}/manual-digest/digest + if-no-files-found: error + overwrite: true + retention-days: 7 + + publish: + name: Publish and verify the combined image + needs: [resolve, build] + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + packages: write + steps: + - uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + - uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: manual-digest-* + path: ${{ runner.temp }}/manual-digests + - name: Assemble and verify the published image + env: + SOURCE_SHA: ${{ needs.resolve.outputs.sha }} + MANUAL_TAG: ${{ needs.resolve.outputs.tag }} + shell: bash + run: | + set -euo pipefail + digests=() + for arch in amd64 arm64; do + digest=$(cat "$RUNNER_TEMP/manual-digests/manual-digest-$arch/digest") + [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] + digests+=("$IMAGE_NAME@$digest") + done + image="$IMAGE_NAME:$MANUAL_TAG" + docker buildx imagetools create --tag "$image" \ + --annotation "index:org.opencontainers.image.revision=$SOURCE_SHA" \ + --annotation "index:org.opencontainers.image.source=https://github.com/$GITHUB_REPOSITORY" \ + --annotation "index:xyz.buzz.manual-build=true" "${digests[@]}" + # Verify the published bytes using this workflow, not scripts from the selected source. + merged_digest=$(docker buildx imagetools inspect "$image" --format '{{json .Manifest}}' | + jq -er '.digest | select(test("^sha256:[0-9a-f]{64}$"))') + pinned="$IMAGE_NAME@$merged_digest" + source_url="https://github.com/$GITHUB_REPOSITORY" + docker buildx imagetools inspect "$pinned" --raw > "$RUNNER_TEMP/index.json" + jq -e '.manifests | + map(select((.platform.os == "unknown" and .platform.architecture == "unknown") | not)) | + map(.platform.os + "/" + .platform.architecture) | sort == ["linux/amd64", "linux/arm64"]' \ + "$RUNNER_TEMP/index.json" >/dev/null + runtime_digests='{}' + for arch in amd64 arm64; do + child=$(jq -er --arg arch "$arch" '.manifests[] | + select(.platform.os == "linux" and .platform.architecture == $arch) | + .digest | select(test("^sha256:[0-9a-f]{64}$"))' "$RUNNER_TEMP/index.json") + docker buildx imagetools inspect "$IMAGE_NAME@$child" --format '{{json .Image}}' | + jq -e --arg arch "$arch" --arg sha "$SOURCE_SHA" --arg source "$source_url" ' + .os == "linux" and .architecture == $arch and + .config.Labels["org.opencontainers.image.revision"] == $sha and + .config.Labels["org.opencontainers.image.source"] == $source' >/dev/null + runtime_digests=$(jq -cn --argjson current "$runtime_digests" \ + --arg platform "linux/$arch" --arg digest "$child" '$current + {($platform): $digest}') + done + jq -n --arg image "$pinned" --arg tag "$image" --arg digest "$merged_digest" \ + --arg sha "$SOURCE_SHA" --arg source "$source_url" --argjson platforms "$runtime_digests" \ + '{image:$image, tag:$tag, digest:$digest, source_sha:$sha, source_url:$source, + platforms:$platforms, + ci_qualification:"skipped", status:"registry-verified"}' \ + > "$RUNNER_TEMP/manual-image.json" + { + echo '## Manual relay image published to GHCR' + echo + echo "Source commit: $SOURCE_SHA" + echo "Registry tag: $image" + echo "Digest: $(jq -r .digest "$RUNNER_TEMP/manual-image.json")" + echo 'Platforms: linux/amd64, linux/arm64' + echo 'CI qualification was skipped. No deployment was started.' + echo 'Any downstream registry import must be verified separately.' + } >> "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: manual-image-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/manual-image.json + if-no-files-found: error + retention-days: 30 diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index dd9c184b276..4036786f209 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -17,7 +17,8 @@ name: Docker image # # Triggers: # - push to main → :main + :sha-<7> + :main--<7> -# + the matching :debug-* tags +# + the matching :debug-* tags, only when the +# push touches the image build context (below) # - push tags relay-v*.*.* → :{version} + :{major}.{minor} + :{major} # + matching :debug-* tags # (+ :latest/:debug-latest for stable releases) @@ -49,10 +50,26 @@ name: Docker image # semver, so relay-v0.3.0-rc.1 publishes :0.3.0-rc.1 without moving :latest, # and main pushes (no semver tag) never produce :latest. +# Main pushes skip paths that .dockerignore keeps out of the build context: +# they cannot change either image, and every published :main--<7> +# tag rolls staging through Kargo. .github/ is ignored by Docker too, but this +# workflow defines the build, so it is re-included. GitHub does not evaluate +# path filters for tag pushes, so relay-v* tags always publish. +# scripts/test-relay-image-eligibility-workflow.sh checks every exclusion +# against .dockerignore. on: push: branches: [main] tags: ["relay-v[0-9]*"] + paths: + - "**" + - "!desktop/**" + - "!mobile/**" + - "!docs/**" + - "!bin/**" + - "!sidecars/**" + - "!.github/**" + - ".github/workflows/docker.yml" pull_request: paths: - "Dockerfile" diff --git a/.github/workflows/loadgen-image.yml b/.github/workflows/loadgen-image.yml new file mode 100644 index 00000000000..3e634ae657f --- /dev/null +++ b/.github/workflows/loadgen-image.yml @@ -0,0 +1,225 @@ +name: Loadgen image + +# Builds and publishes the relay load generator image as +# ghcr.io/block/buzz-loadgen (see Dockerfile.loadgen and perf/LOADGEN.md). +# +# Strategy mirrors sprig-image.yml: each architecture builds on its native +# runner, pushes to GHCR by digest, then a merge job stitches the per-arch +# digests into one multi-arch manifest and attests provenance. +# +# Triggers: +# - push to main (paths-filtered) → :main + :sha-<7> +# - pull_request (paths-filtered) → build only, no image push (same-repo +# PRs still write the registry build cache, as in sprig-image.yml) +# - workflow_dispatch → manual publish at the current ref +# +# NOTE: the first push creates the GHCR package PRIVATE by default. An org +# admin must flip ghcr.io/block/buzz-loadgen to public once (Package settings → +# Change visibility). Subsequent pushes keep the visibility. + +on: + push: + branches: [main] + paths: + - "Dockerfile.loadgen" + - ".github/workflows/loadgen-image.yml" + - ".cargo/config.toml" + - "Cargo.toml" + - "Cargo.lock" + - "rust-toolchain.toml" + - "crates/buzz-test-client/**" + - "crates/buzz-ws-client/**" + - "crates/buzz-core/**" + pull_request: + paths: + - "Dockerfile.loadgen" + - ".github/workflows/loadgen-image.yml" + workflow_dispatch: {} + +concurrency: + group: loadgen-image-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: {} + +env: + IMAGE_NAME: ghcr.io/block/buzz-loadgen + +jobs: + build: + name: Build (${{ matrix.platform }}) + # Publishes to ghcr.io/block/buzz-loadgen, which only block/buzz can write; + # on a fork every main push would fail (as docker.yml, fork #20). + if: github.repository == 'block/buzz' + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + permissions: + contents: read + packages: write + id-token: write + attestations: write + strategy: + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-24.04 + arch: amd64 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + arch: arm64 + + steps: + - name: Checkout + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + with: + # Same OOM cap as docker.yml and sprig-image.yml. + buildkitd-config-inline: | + [worker.oci] + max-parallelism = 2 + + - name: Log in to GHCR + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 + with: + images: ${{ env.IMAGE_NAME }} + flavor: | + latest=false + tags: | + type=ref,event=branch + type=sha,prefix=sha-,format=short + labels: | + org.opencontainers.image.title=Buzz Loadgen + org.opencontainers.image.description=Scenario-driven Buzz relay load generator + org.opencontainers.image.licenses=Apache-2.0 + + - name: Build and push by digest + id: build + uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0 + with: + context: . + file: ./Dockerfile.loadgen + platforms: ${{ matrix.platform }} + labels: ${{ steps.meta.outputs.labels }} + outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=${{ github.event_name != 'pull_request' }} + cache-from: | + type=registry,ref=${{ env.IMAGE_NAME }}-buildcache:${{ matrix.arch }} + cache-to: | + ${{ (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && format('type=registry,ref={0}-buildcache:{1},mode=max,compression=zstd', env.IMAGE_NAME, matrix.arch) || '' }} + + - name: Export digest + if: github.event_name != 'pull_request' + env: + DIGEST: ${{ steps.build.outputs.digest }} + run: | + mkdir -p /tmp/digests + touch "/tmp/digests/${DIGEST#sha256:}" + + - name: Upload digest + if: github.event_name != 'pull_request' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: loadgen-digest-${{ matrix.arch }} + path: /tmp/digests/* + if-no-files-found: error + retention-days: 1 + + merge: + name: Merge multi-arch manifest + if: github.repository == 'block/buzz' && github.event_name != 'pull_request' + runs-on: ubuntu-24.04 + needs: build + timeout-minutes: 15 + permissions: + contents: read + packages: write + id-token: write + attestations: write + + steps: + - name: Download per-arch digests + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + path: /tmp/digests + pattern: loadgen-digest-* + merge-multiple: true + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0 + + - name: Log in to GHCR + uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v6.1.0 + with: + images: ${{ env.IMAGE_NAME }} + # Must mirror the build job's tag matrix exactly. + flavor: | + latest=false + tags: | + type=ref,event=branch + type=sha,prefix=sha-,format=short + + - name: Create and push manifest list + id: manifest + working-directory: /tmp/digests + env: + IMAGE_NAME: ${{ env.IMAGE_NAME }} + META_TAGS: ${{ steps.meta.outputs.tags }} + run: | + set -euo pipefail + tags=() + while IFS= read -r tag; do + [ -n "$tag" ] && tags+=("-t" "$tag") + done <<< "$META_TAGS" + + digests=() + for digest in *; do + digests+=("${IMAGE_NAME}@sha256:${digest}") + done + + docker buildx imagetools create "${tags[@]}" "${digests[@]}" + + first_tag=$(echo "$META_TAGS" | head -n1) + merged_digest=$(docker buildx imagetools inspect "$first_tag" \ + --format '{{json .Manifest}}' | jq -r '.digest') + echo "digest=${merged_digest}" >> "$GITHUB_OUTPUT" + + - name: Attest provenance for the merged image + # Verify with: gh attestation verify oci://ghcr.io/block/buzz-loadgen: --owner block + uses: actions/attest-build-provenance@0f67c3f4856b2e3261c31976d6725780e5e4c373 # v4.1.1 + with: + subject-name: ${{ env.IMAGE_NAME }} + subject-digest: ${{ steps.manifest.outputs.digest }} + push-to-registry: true + + - name: Summary + env: + IMAGE_NAME: ${{ env.IMAGE_NAME }} + DIGEST: ${{ steps.manifest.outputs.digest }} + run: | + { + echo "### Loadgen image published" + echo '```' + echo "${IMAGE_NAME}@${DIGEST}" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/mobile-release-candidate.yml b/.github/workflows/mobile-release-candidate.yml deleted file mode 100644 index 131e8aab0b5..00000000000 --- a/.github/workflows/mobile-release-candidate.yml +++ /dev/null @@ -1,75 +0,0 @@ -name: Publish Mobile Release Candidate -run-name: Publish mobile-v${{ inputs.version }}-rc.${{ inputs.candidate_number }} - -on: - workflow_dispatch: - inputs: - version: - description: Mobile marketing version (X.Y.Z) - required: true - type: string - candidate_number: - description: Expected next release-candidate number - required: true - type: string - source_branch: - description: Source branch (main or mobile-vMAJOR.MINOR matching version) - required: true - default: main - type: string - target_sha: - description: Pinned commit in the selected source branch history - required: true - type: string - -concurrency: - group: mobile-release-candidate-${{ inputs.version }} - cancel-in-progress: false - -permissions: - contents: read - -jobs: - publish: - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - name: Require the reviewed workflow from main - env: - DISPATCH_REF: ${{ github.ref }} - run: | - if [ "$DISPATCH_REF" != "refs/heads/main" ]; then - echo "::error::Mobile candidates must be dispatched from main, not $DISPATCH_REF" - exit 1 - fi - - - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - with: - ref: ${{ github.sha }} - persist-credentials: false - - - name: Require canonical repository - env: - REPOSITORY: ${{ github.repository }} - run: | - if [ "$REPOSITORY" != "block/buzz" ]; then - echo "::error::Mobile candidate publication is restricted to block/buzz" - exit 1 - fi - - - name: Create release tagger token - id: release-tagger - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 - with: - client-id: ${{ vars.BUZZ_RELEASE_TAGGER_CLIENT_ID }} - private-key: ${{ secrets.BUZZ_RELEASE_TAGGER_PRIVATE_KEY }} - permission-contents: write - - - name: Publish annotated candidate tag - env: - GH_TOKEN: ${{ steps.release-tagger.outputs.token }} - MOBILE_VERSION: ${{ inputs.version }} - CANDIDATE_NUMBER: ${{ inputs.candidate_number }} - SOURCE_BRANCH: ${{ inputs.source_branch }} - TARGET_SHA: ${{ inputs.target_sha }} - run: scripts/publish-mobile-release-candidate.sh "$MOBILE_VERSION" "$CANDIDATE_NUMBER" "$TARGET_SHA" "$SOURCE_BRANCH" diff --git a/.github/workflows/spec.yml b/.github/workflows/spec.yml new file mode 100644 index 00000000000..a86e8a78741 --- /dev/null +++ b/.github/workflows/spec.yml @@ -0,0 +1,77 @@ +name: formal specs + +# Re-checks the Git-on-object-storage models whenever they, or the script that +# runs them, change. docs/spec/check.sh model-checks the protocol with TLC and +# requires every seeded design error to be detected; docs/spec/lean holds a +# machine-checked proof of the pointer discipline for unbounded parameters. + +on: + push: + branches: [main] + paths: + - "docs/spec/**" + - ".github/workflows/spec.yml" + pull_request: + paths: + - "docs/spec/**" + - ".github/workflows/spec.yml" + +permissions: {} + +concurrency: + group: spec-${{ github.ref }} + cancel-in-progress: true + +jobs: + tlc: + name: TLC model check + # Block's storage-protocol models; the fork doesn't run them (CI volume). + if: github.repository == 'block/buzz' + runs-on: ubuntu-latest + # About three minutes on 16 cores; the hosted runner has fewer. + timeout-minutes: 45 + permissions: + contents: read + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + # The runner image provides Java; check.sh fetches TLC at a pinned + # version and verifies its SHA-256 before running it. + - name: Model-check the protocol and the seeded design errors + run: docs/spec/check.sh + + lean: + name: Lean proof + # Block's storage-protocol models; the fork doesn't run them (CI volume). + if: github.repository == 'block/buzz' + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + env: + ELAN_VERSION: v4.2.4 + ELAN_SHA256: 42b94d4244e8353142c456ec0e4ca6528fd898a6c604d4059f494e706e431f63 + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + persist-credentials: false + - name: Install elan (pinned, hash-checked) + run: | + set -euo pipefail + archive=elan-x86_64-unknown-linux-gnu.tar.gz + curl -fsSL -o "$RUNNER_TEMP/$archive" \ + "https://github.com/leanprover/elan/releases/download/$ELAN_VERSION/$archive" + echo "$ELAN_SHA256 $RUNNER_TEMP/$archive" | sha256sum -c - + tar -xzf "$RUNNER_TEMP/$archive" -C "$RUNNER_TEMP" + "$RUNNER_TEMP/elan-init" -y --default-toolchain none + echo "$HOME/.elan/bin" >> "$GITHUB_PATH" + # The toolchain is the one named in docs/spec/lean/lean-toolchain. + - name: Check the proof + working-directory: docs/spec/lean + run: | + set -euo pipefail + lake build 2>&1 | tee "$RUNNER_TEMP/lean.log" + # A proof that used `sorry` would build with a warning and would + # list `sorryAx` among the axioms it depends on. + ! grep -E "sorryAx|declaration uses 'sorry'" "$RUNNER_TEMP/lean.log" diff --git a/.release/desktop-candidate.json b/.release/desktop-candidate.json index 4df6aa008bf..c0384530b12 100644 --- a/.release/desktop-candidate.json +++ b/.release/desktop-candidate.json @@ -1,10 +1,10 @@ { "schema": 2, - "version": "0.5.28", - "base_sha": "5142cf6b2a0f44686eeda1ed07905ee3560fd78e", - "previous_tag": "desktop-v0.5.27", - "previous_base_sha": "af5bb0af488784c3707e99c87e0675a729711a6e", - "previous_merge_sha": "001290a34d4b854f0b5d354ae848163b43e6ff85", - "tag": "desktop-v0.5.28", - "commit_count": 41 + "version": "0.5.30", + "base_sha": "bf422ac8e1a34893e15c91bfc86a74d990547feb", + "previous_tag": "desktop-v0.5.29", + "previous_base_sha": "41587e0284f277d13e5d3a40b169c1dcd54d2894", + "previous_merge_sha": "8436d226c8d174c3d83385d32abe3cf7613c8dc9", + "tag": "desktop-v0.5.30", + "commit_count": 23 } diff --git a/AGENTS.md b/AGENTS.md index 665ac303120..6535e485211 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,8 +17,9 @@ Before planning or reviewing a non-trivial change: 4. For any change to `migrations/`, `schema/`, or schema-dependent `buzz-db` queries, read [docs/database.md](docs/database.md): no new triggers, functions, or foreign keys; no data backfills in migrations; update every - schema location; and keep every migration compatible with the relay that - is currently deployed. + schema location; keep every migration compatible with the relay that + is currently deployed; and never make a migration refuse a populated + table. 5. Check that the proposed design advances, or at least does not contradict, that product intent. Call out any intentional tension explicitly. @@ -59,7 +60,7 @@ confirmation, not app runs. - Before reviewing, read [VISION.md](VISION.md), the `VISION_*.md` docs for the affected surface, and the PR's stated goal and linked issue. Review the change against what it is trying to do. -- Check the change against the [Review-Proven Rules](#review-proven-rules): the defects reviewers here find most often. +- Check the change against the [Review-Proven Rules](#review-proven-rules): the defects reviewers and load tests here find most often. - Judge minimalism, elegance, and correctness, aiming for 9/10 on each. A score below 9 names the concrete defect and the fix. - Recommend blocking only for concrete correctness, security, or agreed-contract @@ -72,25 +73,28 @@ confirmation, not app runs. - Agents post reviews as comments, never Request Changes. Humans decide which findings must be fixed. +## Open-source boundary + +This repository is public and contains the relay, NIP specifications, legacy desktop app, and mobile clients. Never commit values that only make sense inside Block: the employee-only bb-block community and its hosts (`block.builderlab.xyz`, `buzz.block.builderlab.xyz`, `*.communities.block.xyz`), private GitHub organizations or repositories, organization-specific SSH users, internal hosts, cloud accounts, IAM roles or buckets, internal ticket keys, `go/` links, internal Slack channels, or real employees' names and personal setups. Public Builderlab (`app.builderlab.xyz`, `*.communities.builderlab.xyz`) is supported and fine. + +Distributor-specific values belong in the relevant release configuration: build-time settings for clients and deployment configuration for the relay. If a setting is missing, add a generic one; never hardcode a Block-only value or special-case a host or organization. + +The rule covers functionality, not only identifiers. Every feature here must be generic: useful to any operator or distributor, with no knowledge of one company's internal services, workflows or identity setup. Functionality that only serves Block lives in Block's private repositories (release builds, deployment configuration, private plugins) and reaches this code only through generic settings or documented extension points that never name, detect or special-case a specific organization, plugin or service. Review judges a change's purpose and approach, not just its strings. + +Tests, fixtures, docs, and examples use example values (`example.org`, `example-org`, fictional names). + +Reviewers treat a violation as a blocking finding. + ## Ecosystem -Buzz spans five repos. This one (`block/buzz`) is the OSS source for the relay, desktop, mobile, and CLI. The others handle internal builds and deployment: +This repository (`block/buzz`) is the OSS source for the relay, mobile, CLI, and the deprecated Buzz 0.X desktop app. [block/buzz-app](https://github.com/block/buzz-app) is the OSS source for the Buzz 1.0 desktop and web app. Block's internal builds and deployments live in private repositories. | Repo | Purpose | |------|---------| -| [block/buzz](https://github.com/block/buzz) | OSS source — relay, desktop app, mobile app, CLI, agent harness | -| [squareup/buzz-releases](https://github.com/squareup/buzz-releases) | Buildkite pipelines producing Block-signed macOS + iOS builds with `-block` desktop version suffix | -| [squareup/sprout-oss](https://github.com/squareup/sprout-oss) | CI pipeline building the relay Docker image and pushing to internal ECR | -| [squareup/block-coder-tf-stacks](https://github.com/squareup/block-coder-tf-stacks) | Terraform + ArgoCD deploying the relay to the staging Kubernetes cluster | -| [squareup/sprout-backend-blox](https://github.com/squareup/sprout-backend-blox) | Desktop backend provider script connecting Blox workstation agents to the relay | +| [block/buzz](https://github.com/block/buzz) | OSS source — relay, mobile app, CLI, agent harness, deprecated Buzz 0.X desktop app | +| [block/buzz-app](https://github.com/block/buzz-app) | OSS source — Buzz 1.0 desktop and web app; all new desktop feature work | -``` -block/buzz (source) - ├─► buzz-releases (desktop + mobile builds → Artifactory, GitHub, Mobile Releases) - ├─► sprout-oss (relay Docker image → ECR) - │ └─► block-coder-tf-stacks (Helm chart → ArgoCD → staging cluster) - └─── sprout-backend-blox (Blox compute provider for Desktop agent launch) -``` +> In QuicksilverSlick/buzz, `desktop/` is Dreamforge, not deprecated: see the Fork note under Desktop App. See [RELEASING.md](RELEASING.md) for the desktop release flow and [CONTRIBUTING.md § Ecosystem](CONTRIBUTING.md#ecosystem) for contributor @@ -130,7 +134,8 @@ crates/ buzz-test-client # Integration test client and E2E test suite sprig # All-in-one harness bundling ACP, agent, and dev MCP -desktop/ # Tauri 2 + React 19 desktop app +desktop/ # Buzz 0.X Tauri desktop app (deprecated: new desktop work goes to block/buzz-app) + # QuicksilverSlick/buzz: desktop/ is Dreamforge (Fork note under Desktop App) web/ # Browser web client (repo browser, served by the relay) mobile/ # Flutter mobile app migrations/ # SQL migrations (run at relay startup when BUZZ_AUTO_MIGRATE is on: binary default off, Helm default on; deployments at scale apply them out of band — see docs/database.md) @@ -214,7 +219,8 @@ once flagged: test-seam binding and unbounded-resource findings were fixed **100%** of the time, swallowed-error findings **90%**, stale-state races **70%** — these are not style opinions, they are defects authors agree with on sight. Authors apply them **before writing code**, and reviewers check -against them; each cites the PRs where reviewers litigated it. +against them; each cites the PRs where reviewers litigated it. Rules +mined from other sources, such as load tests, say so in their text. 1. **Every caught failure must leave a durable retry record or propagate.** Never catch-log-and-return-success (opt-out revocation permanently @@ -286,6 +292,32 @@ against them; each cites the PRs where reviewers litigated it. non-primary ones — that's where the defects were. (PRs #5958, #5972, #6793, #6860, #6862, #6908, #7006) +9. **Design every client-driven path for the whole fleet running it at + once.** This rule comes from relay load tests rather than review + mining. A rollout drain, node eviction, relay restart, or network blip + makes every connected client run its reconnect, renewal, and catch-up + paths in the same few seconds, so cost per client times clients is the + load that matters. Before adding or changing a connect, reconnect, + renewal, poll, or catch-up path: + - **Count its relay reads per client** and keep reconnect to a delta + from the client's cursor, not a rebuild. One replay filter per + channel meant ~306 filters per reconnect for a 300-channel client + (block/buzz-app#2308). + - **Jitter its start and back off on failure with a cap** (backoff: + see rule 4). Spread the server side of a mass close, too (drain close + jitter, PR #4542). + - **Prefer an event-driven refresh with a long backstop over a short + poll.** For example, a full channel-list re-read every 60 s became + every 15 min (block/buzz-app#2215). + - **On the relay, assume a 0% hit rate for every cache on a connect + or auth path.** Concurrent misses for one key share one read, with a + bounded wait and a fallback read if the leader fails or hangs. Date + each entry from when its read checked out a connection: stamped before + the pool wait, 1 s entries expired on insert and storms ran uncached; + stamped at insert, they would outlive their staleness bound (PRs + #8846, #9012). + (PRs #4542, #8846, #9012; block/buzz-app#2215, #2308) + --- ## Key Patterns @@ -619,6 +651,26 @@ description. See [PR #803](https://github.com/block/buzz/pull/803). ## Desktop App +> **`desktop/` is deprecated.** It is the Buzz 0.X desktop app. The Buzz 1.0 +> desktop app lives in [block/buzz-app](https://github.com/block/buzz-app). +> Do not open block/buzz PRs that add features to `desktop/`; build desktop +> features in block/buzz-app (or as a Buzz plugin) instead. Change `desktop/` +> here only to fix a 0.X bug, or to keep it compiling when a shared crate it +> depends on changes. This includes agent guidance bundled with the 0.X app, +> such as `desktop/src-tauri/src/managed_agents/nest_skill.md`: CLI PRs do not +> need to update it. Never use it as an implementation or design reference for +> the mobile app, which is current. + +> **Fork note (QuicksilverSlick/buzz, Dreamforge).** In this repository +> `desktop/` is Dreamforge, the product we ship, and it is not deprecated here. +> The rule above ("no new desktop features") is Block's rule for PRs to +> block/buzz; in QuicksilverSlick/buzz, desktop feature work is normal. Keep +> Dreamforge branding on every surface, and keep Block's new-app banner and +> installer download unmounted (`desktop/src/app/AppShell.tsx`, +> `desktop/src/main.tsx`), and keep `RelayEntryGate` pointing at the admin, +> not Block's download. Added 15 Nov 2026 by Claude-Account +> russelledeming@gmail.com for the upstream catch-up. + The desktop app is Tauri 2 + React 19 + Vite + Tailwind CSS. Features are organized under `desktop/src/features/`. Biome handles linting and formatting. @@ -699,13 +751,20 @@ Key files: The mobile app lives in `mobile/` — a Flutter app using Riverpod + Hooks. +The mobile app is current. Do not use the legacy `desktop/` app as an +implementation or design reference for it: `desktop/` will soon be superseded +by [block/buzz-app](https://github.com/block/buzz-app). This does not relax +cross-client wire compatibility: mobile must keep reading and writing the same +event payloads as other clients (for example the `channel-sort` NIP-78 payload, +which buzz-app also uses), even where a payload is documented only in code. + ### Architecture - **State management:** Riverpod + `flutter_hooks` (`HookConsumerWidget`) -- **Theme:** Catppuccin Latte (light) / Macchiato (dark) — matches desktop +- **Theme:** Catppuccin Latte (light) / Macchiato (dark) - **Features:** Isolated under `lib/features/`, shared code in `lib/shared/` - **Nostr models:** `lib/shared/relay/nostr_models.dart` — event kinds must - stay in sync with `desktop/src/shared/constants/kinds.ts` + stay in sync with `crates/buzz-core/src/kind.rs` ### Rules @@ -750,7 +809,7 @@ The mobile app lives in `mobile/` — a Flutter app using Riverpod + Hooks. cd mobile dart format --output=none --set-exit-if-changed . flutter analyze -flutter test --dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example +flutter test ``` Or from repo root: `just mobile-fmt` (auto-fix), `just mobile-check` (lint + fmt check), `just mobile-test` (tests). diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7ff26b4ef74..a4b90dec11a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -378,7 +378,7 @@ This prevents a race where a non-member receives live fan-out events from a priv ### Historical Query (EOSE) -After registering, the REQ handler queries Postgres for stored events matching the filters (up to 500 per filter, hard cap). These are sent as `["EVENT", sub_id, event]` frames before `["EOSE", sub_id]`. New events arriving after EOSE are delivered via the fan-out path. +After registering, the REQ handler queries Postgres for stored events matching the filters (up to 500 per filter, hard cap). These are sent as `["EVENT", sub_id, event]` frames before `["EOSE", sub_id]`. New events arriving after EOSE are delivered via the fan-out path. For an ordinary (non-search) REQ, EOSE marks a successful bounded history query, so a failed history read never ends in EOSE: it retires the subscription with `["CLOSED", sub_id, "error: query timed out"]` for a statement timeout or `"error: database error"` for anything else. **Client consumption invariant.** A client rebuilding channel state must open its live subscription before (or overlapping) the finite history @@ -504,6 +504,8 @@ shape is an explicit transition, not a flag day: never spans communities. Serving leases use the same application admission. Startup and deletion catalog validation tolerate the universal fence objects being absent; inventories still record live fences for older executors. + Desired-state bootstraps install only explicitly declared legacy fences. + New tenant-owned tables rely on application admission, without a fence trigger. - **Replica floor (transition foundation):** runtime now provides a shared replica-floor lock helper for compliant channel-event writers, and the writer probe handshake takes the exclusive counterpart before sampling `S`, scanning @@ -548,7 +550,7 @@ Subscriber → dedicated PubSub → PSUBSCRIBE buzz:channel:* The subscriber uses a **dedicated** `redis::aio::PubSub` connection — not from the pool. This is intentional: pool connections cannot hold `PSUBSCRIBE` state. -**Current state:** The subscriber loop is spawned in `buzz-relay/src/main.rs` and populates the broadcast channel. A consumer task subscribes via `pubsub.subscribe_local()`, calls `sub_registry.fan_out()` on each received event, and delivers matches to local WebSocket connections via `conn_manager.send_to()`. Multi-node fan-out is now wired end-to-end. Local-echo deduplication is implemented via `AppState.local_event_ids` — events published by the local relay instance are tracked and skipped when received via the Redis round-trip. +**Current state:** The subscriber loop is spawned in `buzz-relay/src/main.rs` and populates the broadcast channel. A dispatcher task subscribes via `pubsub.subscribe_local()` and routes each event to one of 16 delivery workers by `(community, topic)`, so one channel's events keep their order while channels deliver concurrently (`handlers/multinode_fanout.rs`). Each worker calls `sub_registry.fan_out()`, applies the access gate (one bulk membership read for the recipients the membership cache lacks), and delivers matches to local WebSocket connections via `conn_manager.send_to()`. A slow delivery holds only its own worker and arrives late; falling behind never closes a connection, because a database stall slows every node at once and closing recipients then would send the whole fleet back to that database together. An event is dropped on this node only when its worker's bounded queue is full, one delivery attempt runs past 30 s from when the worker starts it (so a database connection that stops answering cannot hold the worker forever), or the dispatcher lags the broadcast; both are counted (`buzz_multinode_fanout_dropped_total`, `buzz_multinode_fanout_lag_total`), and the affected syncs get `CLOSED "resync: ..."` (NIP-AR Sync rule 5). A recipient the access gate cannot check misses that event. Multi-node fan-out is now wired end-to-end. Local-echo deduplication is implemented via `AppState.local_event_ids` — events published by the local relay instance are tracked and skipped when received via the Redis round-trip. **Reconnection:** exponential backoff 1s → 30s (`backoff_secs * 2`). Backoff resets to 1s only after a clean stream end, not on each reconnect attempt. @@ -577,15 +579,25 @@ multi-community mode every query filter includes `community_id`, so the shared `events` table is infrastructure, not a cross-community result space; the relay re-authorizes every candidate hit before returning it. +A database built from `migrations/0008_fresh_install_search_allowlist.sql` indexes +only an allowlist of kinds, and so does one converted by +`scripts/maintenance/nip_rs_search_allowlist.sql`. Such a database does not index +kind 30180 (custom emoji entries) until an operator runs the updated maintenance +script, which must happen before the emoji migration rollout. + **Key behaviors:** - `SearchService::new(pool)` wraps a `PgPool`; `search(&SearchQuery)` runs a parameterized FTS query against the `events.search_tsv` GIN index and returns - `SearchResult` (candidate `SearchHit`s). + `SearchResult` (candidate `SearchHit`s). Prefix-mode relevance (outside + profile search) ranks only the newest 1000 matches, which Postgres may read + from the primary key backward instead of the GIN index. - `ChannelScope` makes the channel constraint explicit (`Any` / `ChannelLessOnly` / `Channels` / `ChannelsOrChannelLess`), closing the ambiguity the old `Option> + bool` matrix could not express. -- Every query carries `community_id`; the FTS predicate is BitmapAnd-ed with - the community-leading btree filters so a query never crosses tenants. +- Every query carries `community_id`, and every access path leads with it (the + FTS predicate BitmapAnd-ed with community-leading btree filters, or the + `(community_id, created_at, id)` primary key read backward), so a query never + crosses tenants. - Permission filtering is **caller's responsibility** — `buzz-search` returns candidate hits; the relay re-authorizes each one (channel membership, `#p`, owner gates) before delivering it. @@ -732,6 +744,8 @@ pub struct ConnectionState { pub enum AuthState { Pending { challenge: String }, Authenticated(AuthContext), Failed } ``` +**Community FI admission:** Protected HTTP and root/audio WebSocket requests read the normalized Host's active authentication policy from the primary database. Stored `requires_nip_fi` OR global enforce requires FI; repair mode denies first. HTTP middleware shares one request-local policy read with handlers. Root NIP-11 and `/info` publish a no-store host-specific requirement and compatible capability fields. Policy lookup failure is unavailable, never optional. See [community auth upgrades](docs/community-auth-upgrades.md); completed activation additionally requires existing-session drain evidence. + **HTTP endpoints:** | Method | Path | Handler | @@ -957,7 +971,10 @@ kinds via `CASE WHEN kind IN (1059, 30300, 30622) THEN NULL`, so those rows are storage-level unsearchable (a `NULL` tsvector never matches `@@`). A GIN index (`idx_events_search_tsv`) backs the `@@` probe; in multi-community mode the community-leading btree filters BitmapAnd with the GIN probe so every query is -fenced to its `community_id`. +fenced to its `community_id`. Prefix-mode relevance ranks only the newest 1000 +matches; for a common prefix Postgres reads the `(community_id, created_at, id)` +primary key backward and stops there, still fenced by its leading +`community_id`. --- diff --git a/CHANGELOG.md b/CHANGELOG.md index c8c8de39b99..fb4779ccc9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,637 @@ # Changelog +## v0.5.30 + +### Desktop and shared changes + +- feat(db): label advisory-lock metrics with the locked event kind ([#9472](https://github.com/block/buzz/pull/9472)) ([`359839f70b6ec2401207c9fb29116efc87b75701`](https://github.com/block/buzz/commit/359839f70b6ec2401207c9fb29116efc87b75701)) + +### Other repository changes + +- perf(mobile): parse each event's thread reference once ([#9460](https://github.com/block/buzz/pull/9460)) ([`bf422ac8e1a34893e15c91bfc86a74d990547feb`](https://github.com/block/buzz/commit/bf422ac8e1a34893e15c91bfc86a74d990547feb)) +- perf(mobile): load only the directory when search opens ([#9466](https://github.com/block/buzz/pull/9466)) ([`c97c85d8faee7aee989f5a110e38cd38eff551b2`](https://github.com/block/buzz/commit/c97c85d8faee7aee989f5a110e38cd38eff551b2)) +- perf(mobile): stop rebuilding Home's channel list when a route covers it ([#9459](https://github.com/block/buzz/pull/9459)) ([`5f1cd679853b6623582f97154dd0352ccdd1caa3`](https://github.com/block/buzz/commit/5f1cd679853b6623582f97154dd0352ccdd1caa3)) +- perf(mobile): ask typing subscriptions only for the typing window ([#9454](https://github.com/block/buzz/pull/9454)) ([`3764a2e4d500bf36c434670b2597b02b289354ee`](https://github.com/block/buzz/commit/3764a2e4d500bf36c434670b2597b02b289354ee)) +- perf(mobile): skip avatar URL parsing for non-HTTP URLs ([#9448](https://github.com/block/buzz/pull/9448)) ([`11ea8c928efb17528ed6033dbeb8e6035d135203`](https://github.com/block/buzz/commit/11ea8c928efb17528ed6033dbeb8e6035d135203)) +- perf(mobile): download the identity archive list only when it changed ([#9445](https://github.com/block/buzz/pull/9445)) ([`5e52fa98313a7e646e994e47c5a36a88f4cd707f`](https://github.com/block/buzz/commit/5e52fa98313a7e646e994e47c5a36a88f4cd707f)) +- perf(mobile): don't treat a Control Center pull as a resume ([#9443](https://github.com/block/buzz/pull/9443)) ([`9e40bf5d795848927547d5d6dd21ba0c9e37a40d`](https://github.com/block/buzz/commit/9e40bf5d795848927547d5d6dd21ba0c9e37a40d)) +- fix(mobile): keep a superseded roster read out of the offline snapshot ([#9452](https://github.com/block/buzz/pull/9452)) ([`15c65c76d93ac677c17001b4337b0e608cf810ed`](https://github.com/block/buzz/commit/15c65c76d93ac677c17001b4337b0e608cf810ed)) +- perf(mobile): read channel bot roles from the member list ([#9451](https://github.com/block/buzz/pull/9451)) ([`99e65b6c22dcd78658715b6dae06aa9febf14ed3`](https://github.com/block/buzz/commit/99e65b6c22dcd78658715b6dae06aa9febf14ed3)) +- perf(mobile): read Activity once per reconnect ([#9455](https://github.com/block/buzz/pull/9455)) ([`3dcdf1c0562fb77cc724d9cb425f9156db24204b`](https://github.com/block/buzz/commit/3dcdf1c0562fb77cc724d9cb425f9156db24204b)) +- fix(mobile): offer role controls for agents ([#9475](https://github.com/block/buzz/pull/9475)) ([`04af7081c87ac14cabc61bd8b4f95aa2ef0ce809`](https://github.com/block/buzz/commit/04af7081c87ac14cabc61bd8b4f95aa2ef0ce809)) +- perf(mobile): stop rebuilding the native nav bar on every scrolled frame ([#9458](https://github.com/block/buzz/pull/9458)) ([`b6db61faa0fcb467ce523e1bacae917f1f588fb9`](https://github.com/block/buzz/commit/b6db61faa0fcb467ce523e1bacae917f1f588fb9)) +- perf(mobile): keep verified-name batches open as people are added ([#9450](https://github.com/block/buzz/pull/9450)) ([`93bbd452a71827d1905a44ceafc687c1f93dcf9f`](https://github.com/block/buzz/commit/93bbd452a71827d1905a44ceafc687c1f93dcf9f)) +- perf(mobile): read only changed custom emoji sets on reconnect ([#9446](https://github.com/block/buzz/pull/9446)) ([`9fc2b333202cd94f9a29538950f29e1420411095`](https://github.com/block/buzz/commit/9fc2b333202cd94f9a29538950f29e1420411095)) +- perf(mobile): keep latest-message times on a directory load ([#9457](https://github.com/block/buzz/pull/9457)) ([`237a39fe765d9ffd7848ed4a6036cd78a955d5cf`](https://github.com/block/buzz/commit/237a39fe765d9ffd7848ed4a6036cd78a955d5cf)) +- perf(mobile): don't refetch profiles that are already on the wire ([#9447](https://github.com/block/buzz/pull/9447)) ([`a540e7bd3067a036329fefa52b48b7f12761b660`](https://github.com/block/buzz/commit/a540e7bd3067a036329fefa52b48b7f12761b660)) +- perf(mobile): use HTTP/2 on Android through app-wide Cronet engines ([#9435](https://github.com/block/buzz/pull/9435)) ([`d1a8c3607dfbaf69ce34f2c765dc69279a92c62b`](https://github.com/block/buzz/commit/d1a8c3607dfbaf69ce34f2c765dc69279a92c62b)) +- perf(mobile): subscribe to presence only for people on screen ([#9444](https://github.com/block/buzz/pull/9444)) ([`36fa0fe318e34eeb916a77e5833a7fbd736ad24c`](https://github.com/block/buzz/commit/36fa0fe318e34eeb916a77e5833a7fbd736ad24c)) +- fix(mobile): require Builderlab consent for existing identities ([#8823](https://github.com/block/buzz/pull/8823)) ([`59ae028a360242d43ffbfdafca8a76eda00484d9`](https://github.com/block/buzz/commit/59ae028a360242d43ffbfdafca8a76eda00484d9)) +- feat(mobile): use HTTP/2 on iOS through app-wide URLSessions ([#8897](https://github.com/block/buzz/pull/8897)) ([`a2d4ba02677f157a95ae0d84ef3be37953a7ed24`](https://github.com/block/buzz/commit/a2d4ba02677f157a95ae0d84ef3be37953a7ed24)) +- fix(relay): publish a git push only when refs changed; check the protocol by refinement ([#9425](https://github.com/block/buzz/pull/9425)) ([`1fb33e4545660196d4c863daf70e1d3bc245f164`](https://github.com/block/buzz/commit/1fb33e4545660196d4c863daf70e1d3bc245f164)) +- fix(mobile): show shared chats under Solo ([#9348](https://github.com/block/buzz/pull/9348)) ([`642ce4165cc84d67b99f25b05444dbfff456bce7`](https://github.com/block/buzz/commit/642ce4165cc84d67b99f25b05444dbfff456bce7)) + +[Compare desktop-v0.5.29...desktop-v0.5.30](https://github.com/block/buzz/compare/desktop-v0.5.29...desktop-v0.5.30) + +## v0.5.29 + +### Desktop and shared changes + +- feat(desktop): add dismissible banner pointing to the new buzz app ([#9379](https://github.com/block/buzz/pull/9379)) ([`1fc6a71ef9803192c3deed0f335ba557cc2efecc`](https://github.com/block/buzz/commit/1fc6a71ef9803192c3deed0f335ba557cc2efecc)) +- ci: fix main — stale RunCause call sites and Playwright on ubuntu-26.04 ([#9418](https://github.com/block/buzz/pull/9418)) ([`ce42853982d4e1673fadfd5fbde7e691cfde9694`](https://github.com/block/buzz/commit/ce42853982d4e1673fadfd5fbde7e691cfde9694)) +- fix(media): run thumbnail regeneration tests in CI and cap rebuild pixels ([#9198](https://github.com/block/buzz/pull/9198)) ([`432df8aa529c8e30dc768b6f6a3c273190a34862`](https://github.com/block/buzz/commit/432df8aa529c8e30dc768b6f6a3c273190a34862)) +- chore(deps): bump hickory-proto to 0.26.2 for RUSTSEC-2026-0487..0491 ([#9351](https://github.com/block/buzz/pull/9351)) ([`e5dee91c90fdc5f81f04fd609b7c99e31fa7570f`](https://github.com/block/buzz/commit/e5dee91c90fdc5f81f04fd609b7c99e31fa7570f)) +- fix(relay): saturate filter limits instead of casting ([#9230](https://github.com/block/buzz/pull/9230)) ([`47674dc3224383b110c36ee1b752c7fd60ee3d7d`](https://github.com/block/buzz/commit/47674dc3224383b110c36ee1b752c7fd60ee3d7d)) +- test: fix timing-dependent unit tests in buzz-cli, buzz-agent and buzz-admin ([#9273](https://github.com/block/buzz/pull/9273)) ([`85996fdff49191f0f999d50bad201d4ef60e8d69`](https://github.com/block/buzz/commit/85996fdff49191f0f999d50bad201d4ef60e8d69)) +- test(desktop): wait on real readiness signals in audience and community-rail specs ([#9277](https://github.com/block/buzz/pull/9277)) ([`15c2ca1b018dfb959eb9221f168952df812b4850`](https://github.com/block/buzz/commit/15c2ca1b018dfb959eb9221f168952df812b4850)) +- fix(cli): preserve attachments across successive edits ([#9226](https://github.com/block/buzz/pull/9226)) ([`8130cd9fc7d8fce315eb34fb14207d915841e8c5`](https://github.com/block/buzz/commit/8130cd9fc7d8fce315eb34fb14207d915841e8c5)) +- fix(media): revoke private channel attachment reads ([#9077](https://github.com/block/buzz/pull/9077)) ([`96af488d968a1ae9d961c2132bea27822735f8da`](https://github.com/block/buzz/commit/96af488d968a1ae9d961c2132bea27822735f8da)) +- fix(relay): regenerate missing image thumbnails on request ([#9174](https://github.com/block/buzz/pull/9174)) ([`1bb2ad443d4ee4512dd0927888ad21a4a1c041bc`](https://github.com/block/buzz/commit/1bb2ad443d4ee4512dd0927888ad21a4a1c041bc)) +- feat(relay): log WebSocket EVENT writes on the access target ([#9154](https://github.com/block/buzz/pull/9154)) ([`fba8a7a94febd4fbfb97df90f7c6be8fb258cf4c`](https://github.com/block/buzz/commit/fba8a7a94febd4fbfb97df90f7c6be8fb258cf4c)) +- feat(cli): send NIP-FI evidence via credential chain and Buzz desktop ([#8999](https://github.com/block/buzz/pull/8999)) ([`e3a0f3d59dfd08696cff80badb2d80d9a5096a61`](https://github.com/block/buzz/commit/e3a0f3d59dfd08696cff80badb2d80d9a5096a61)) +- feat(protocol): define compact membership discovery (BUZZ-615) ([#9117](https://github.com/block/buzz/pull/9117)) ([`66c3d6917ddd88c98a0bc2a31663d60f209e0088`](https://github.com/block/buzz/commit/66c3d6917ddd88c98a0bc2a31663d60f209e0088)) +- feat(cli): user status expiry and status read ([#8777](https://github.com/block/buzz/pull/8777)) ([`b0f68a06ad25889fb304a88889a679a7ef15b862`](https://github.com/block/buzz/commit/b0f68a06ad25889fb304a88889a679a7ef15b862)) +- feat(relay): add kind 30180 custom emoji entry ([#8783](https://github.com/block/buzz/pull/8783)) ([`5c91e0d6fe4e834b2aba49a3e8e9653bffafd4b4`](https://github.com/block/buzz/commit/5c91e0d6fe4e834b2aba49a3e8e9653bffafd4b4)) +- feat(cli): report a message to relay moderators ([#8829](https://github.com/block/buzz/pull/8829)) ([`82bc5a47c5e58d4c4579420cd4dab16b8a3f3da3`](https://github.com/block/buzz/commit/82bc5a47c5e58d4c4579420cd4dab16b8a3f3da3)) +- fix(desktop): keep an own send out of the frozen timeline tail ([#9095](https://github.com/block/buzz/pull/9095)) ([`e94b547f600db5a2c3130005c75aadec2e623398`](https://github.com/block/buzz/commit/e94b547f600db5a2c3130005c75aadec2e623398)) +- fix(desktop): compensate head trims from the unclamped scroll offset ([#9094](https://github.com/block/buzz/pull/9094)) ([`bdd76baea552c3e90386734ec531e8dd62b3646f`](https://github.com/block/buzz/commit/bdd76baea552c3e90386734ec531e8dd62b3646f)) +- Expose strict code-entry pairing and live authorization bindings ([#9061](https://github.com/block/buzz/pull/9061)) ([`120d75d9762e0ea9876dc8df7f7bb834c3dfb042`](https://github.com/block/buzz/commit/120d75d9762e0ea9876dc8df7f7bb834c3dfb042)) +- fix(desktop): show upgrade guidance (BUZZ-517) ([#9033](https://github.com/block/buzz/pull/9033)) ([`8a113ed99e0485d5ed3fb4deaf80d9a93a6bc6c0`](https://github.com/block/buzz/commit/8a113ed99e0485d5ed3fb4deaf80d9a93a6bc6c0)) +- docs: mark desktop/ as the deprecated Buzz 0.X app ([#8840](https://github.com/block/buzz/pull/8840)) ([`ab399231c29ab31d982769b6f235ea06bee312c1`](https://github.com/block/buzz/commit/ab399231c29ab31d982769b6f235ea06bee312c1)) +- feat(relay): persist NIP-FI upgrades (BUZZ-510) ([#8985](https://github.com/block/buzz/pull/8985)) ([`a1f79e3aba6fd6d352d53f249cf0ef0fdf83316f`](https://github.com/block/buzz/commit/a1f79e3aba6fd6d352d53f249cf0ef0fdf83316f)) +- fix(media): keep transparency in image thumbnails with WebP ([#9003](https://github.com/block/buzz/pull/9003)) ([`f9ef721e688847ed0c1512081160b6e42cdf92fd`](https://github.com/block/buzz/commit/f9ef721e688847ed0c1512081160b6e42cdf92fd)) +- perf(relay): keep 1 s read caches warm when the pool is saturated ([#9012](https://github.com/block/buzz/pull/9012)) ([`d21f0c0fdbec9534b9396552b2550ab306d218df`](https://github.com/block/buzz/commit/d21f0c0fdbec9534b9396552b2550ab306d218df)) +- fix(desktop): hold a deep-linked message against bottom settles ([#8742](https://github.com/block/buzz/pull/8742)) ([`069cb9a0fe7a67e21a57e4a8780c5208f3a0eb01`](https://github.com/block/buzz/commit/069cb9a0fe7a67e21a57e4a8780c5208f3a0eb01)) +- fix(desktop): skip a starter channel the relay will never create ([#8911](https://github.com/block/buzz/pull/8911)) ([`f99807a79ae060eae4e087781e3c8dc9a237b1df`](https://github.com/block/buzz/commit/f99807a79ae060eae4e087781e3c8dc9a237b1df)) +- test(desktop): stop four E2E specs racing scroll settles and focus ([#8743](https://github.com/block/buzz/pull/8743)) ([`a83926da5d0d66f0d5e7d5025628b75e9b86c539`](https://github.com/block/buzz/commit/a83926da5d0d66f0d5e7d5025628b75e9b86c539)) +- feat(relay): auto-join new community members to default channels ([#8594](https://github.com/block/buzz/pull/8594)) ([`cde6c1bf5b1fa1fde6045de8ea29f6ac1c7e6867`](https://github.com/block/buzz/commit/cde6c1bf5b1fa1fde6045de8ea29f6ac1c7e6867)) +- feat(relay): publish NIP-FI verified profiles (BUZZ-433) ([#8774](https://github.com/block/buzz/pull/8774)) ([`7d00c708059df3b73bc7eb78d28066a707b7dbad`](https://github.com/block/buzz/commit/7d00c708059df3b73bc7eb78d28066a707b7dbad)) +- test(desktop): settle five E2E flake classes and clear a draft by Backspace ([#8744](https://github.com/block/buzz/pull/8744)) ([`fc0bb778b06da0f68aea5774148991bbc59cd1e1`](https://github.com/block/buzz/commit/fc0bb778b06da0f68aea5774148991bbc59cd1e1)) +- test: stop desktop, buzz-agent and mobile tests leaking temp files ([#8748](https://github.com/block/buzz/pull/8748)) ([`d14e95f90ec856d5997a4f4d301cf1d38af534de`](https://github.com/block/buzz/commit/d14e95f90ec856d5997a4f4d301cf1d38af534de)) +- test(desktop): keep unit tests away from the real ~/.buzz nest ([#8749](https://github.com/block/buzz/pull/8749)) ([`704f2b8c27a0663445bdbbe7acaea5d992313e35`](https://github.com/block/buzz/commit/704f2b8c27a0663445bdbbe7acaea5d992313e35)) +- feat(relay): NIP-AR sync subscriptions ([#8522](https://github.com/block/buzz/pull/8522)) ([`a56966b777278f703040b4686820a201bc278c57`](https://github.com/block/buzz/commit/a56966b777278f703040b4686820a201bc278c57)) +- fix(desktop): fix the product races behind four E2E flakes ([#8680](https://github.com/block/buzz/pull/8680)) ([`1eb67bb525d66448b56d79f98c4ba0e2188b44c5`](https://github.com/block/buzz/commit/1eb67bb525d66448b56d79f98c4ba0e2188b44c5)) +- test(desktop): gate flaky E2E specs on the state they assume ([#8681](https://github.com/block/buzz/pull/8681)) ([`0052b2354eb5618f42f7607633b994253e03e2d2`](https://github.com/block/buzz/commit/0052b2354eb5618f42f7607633b994253e03e2d2)) +- test(desktop): settle composer edits and press hover-only row actions by keyboard ([#8682](https://github.com/block/buzz/pull/8682)) ([`428f0dcd22ac6639bcd4ef38e3dd511e578c21ee`](https://github.com/block/buzz/commit/428f0dcd22ac6639bcd4ef38e3dd511e578c21ee)) +- test(desktop): measure inline video controls against their player ([#8683](https://github.com/block/buzz/pull/8683)) ([`425284aa2c25463263a8dd12c9ebd9cfa2d6fe9c`](https://github.com/block/buzz/commit/425284aa2c25463263a8dd12c9ebd9cfa2d6fe9c)) +- fix: don't notify workflow owners through their attribution tag ([#8694](https://github.com/block/buzz/pull/8694)) ([`4b21a10c4b100bfccfa03ab4a0e85329c9880c9f`](https://github.com/block/buzz/commit/4b21a10c4b100bfccfa03ab4a0e85329c9880c9f)) +- fix(desktop): resume reconnect replay from the last live point ([#8652](https://github.com/block/buzz/pull/8652)) ([`ae689ab54d716d6f6df6bf18c67f12a3a810ecfe`](https://github.com/block/buzz/commit/ae689ab54d716d6f6df6bf18c67f12a3a810ecfe)) +- fix(desktop): always flash a linked message in the channel timeline ([#8660](https://github.com/block/buzz/pull/8660)) ([`5ea5ae1727fc6701a6b06595f0f920ec4f079b52`](https://github.com/block/buzz/commit/5ea5ae1727fc6701a6b06595f0f920ec4f079b52)) +- ci: repeat changed tests ten times on pull requests ([#8613](https://github.com/block/buzz/pull/8613)) ([`eda26b9423328a06960bb0d5fd4c1af54600c419`](https://github.com/block/buzz/commit/eda26b9423328a06960bb0d5fd4c1af54600c419)) +- fix(relay): revoke invitations and restrict claims ([#8237](https://github.com/block/buzz/pull/8237)) ([`d6196a16c1eec7268e1fc5124ca89ee3d03d6d3e`](https://github.com/block/buzz/commit/d6196a16c1eec7268e1fc5124ca89ee3d03d6d3e)) +- fix(desktop): keep FileCard inside narrow message rows ([#8612](https://github.com/block/buzz/pull/8612)) ([`6861e18a86972a300d5b7c6207a3ff6d4865b41c`](https://github.com/block/buzz/commit/6861e18a86972a300d5b7c6207a3ff6d4865b41c)) +- chore(toolchain): bump Rust to 1.98.1 for macOS 27 proc-macro loading ([#8598](https://github.com/block/buzz/pull/8598)) ([`8216db1c712cefdc0e2af7191d501adae03ba392`](https://github.com/block/buzz/commit/8216db1c712cefdc0e2af7191d501adae03ba392)) +- fix(desktop): recognize agents without NIP-OA in Huddles ([#8544](https://github.com/block/buzz/pull/8544)) ([`a38fedb2340bd3d66a4f8d6a9d479439db7b427c`](https://github.com/block/buzz/commit/a38fedb2340bd3d66a4f8d6a9d479439db7b427c)) +- feat(relay): add an unlisted channel setting ([#8579](https://github.com/block/buzz/pull/8579)) ([`a3a47e6294c29b5ce3fb7747cb0e42e45a8d5440`](https://github.com/block/buzz/commit/a3a47e6294c29b5ce3fb7747cb0e42e45a8d5440)) +- feat(relay): add several people with one kind:9000 ([#8575](https://github.com/block/buzz/pull/8575)) ([`d0dee1cb50736c5dff4b4b2ad3dad0acf2be7794`](https://github.com/block/buzz/commit/d0dee1cb50736c5dff4b4b2ad3dad0acf2be7794)) +- fix(deps): bump ctutils to 0.4.5 for RUSTSEC-2026-0385 ([#8560](https://github.com/block/buzz/pull/8560)) ([`9e8c9fc04daf20259cd259dcaec89109587cc7f5`](https://github.com/block/buzz/commit/9e8c9fc04daf20259cd259dcaec89109587cc7f5)) +- feat(relay): add announce channels with a join_role setting ([#8143](https://github.com/block/buzz/pull/8143)) ([`d97f6b4c6ed616be0c3f1eb0e13d1eaa9e338a66`](https://github.com/block/buzz/commit/d97f6b4c6ed616be0c3f1eb0e13d1eaa9e338a66)) +- BUZZ-357: feat(cli): token-lean agent output format for event reads ([#8234](https://github.com/block/buzz/pull/8234)) ([`76d792f2884f312983cdad58c97ca342de866e22`](https://github.com/block/buzz/commit/76d792f2884f312983cdad58c97ca342de866e22)) +- fix(desktop): surface a missing DATABRICKS_HOST instead of loading models forever ([#8504](https://github.com/block/buzz/pull/8504)) ([`427488e2fcb6ef9c5eb3d73e8801f8ba1ab2ad85`](https://github.com/block/buzz/commit/427488e2fcb6ef9c5eb3d73e8801f8ba1ab2ad85)) +- fix(deps): bump webpki crates for RUSTSEC-2026-0381/0382/0383 ([#8499](https://github.com/block/buzz/pull/8499)) ([`8bbfe44f771a092223947440040b7aa4ce256d34`](https://github.com/block/buzz/commit/8bbfe44f771a092223947440040b7aa4ce256d34)) +- fix(sdk): reject malformed mention pubkeys before signing p tags ([#6372](https://github.com/block/buzz/pull/6372)) ([`a5767c67deb951d64b8465b5da32c1dfc7a9ba40`](https://github.com/block/buzz/commit/a5767c67deb951d64b8465b5da32c1dfc7a9ba40)) +- fix(mobile): restore channel icons and align chat colors with desktop ([#8478](https://github.com/block/buzz/pull/8478)) ([`5fefec604f5a98d78ed13a110d586b2f8424b5fb`](https://github.com/block/buzz/commit/5fefec604f5a98d78ed13a110d586b2f8424b5fb)) +- test(desktop): read only the open effort menu in effort-picker e2e ([#8476](https://github.com/block/buzz/pull/8476)) ([`0b53fc699dd649ec483c07d628f9c41197607a3c`](https://github.com/block/buzz/commit/0b53fc699dd649ec483c07d628f9c41197607a3c)) +- fix(mobile): restore Solo chats from channel labels ([#8466](https://github.com/block/buzz/pull/8466)) ([`c9e35f8ac71f4f2eb7a8e256d0bc83f3518031af`](https://github.com/block/buzz/commit/c9e35f8ac71f4f2eb7a8e256d0bc83f3518031af)) +- fix(relay): show only legacy channel types to reads that name no channel ([#8469](https://github.com/block/buzz/pull/8469)) ([`25bcb791b4105594940bb77cadaf556a34427a8c`](https://github.com/block/buzz/commit/25bcb791b4105594940bb77cadaf556a34427a8c)) +- fix(desktop): set window title to "Buzz" for Windows taskbar ([#6317](https://github.com/block/buzz/pull/6317)) ([`139f8903d5fd075a172b7555d88ae0e616cdcb39`](https://github.com/block/buzz/commit/139f8903d5fd075a172b7555d88ae0e616cdcb39)) +- feat(relay): tag every membership notice with its channel type ([#8406](https://github.com/block/buzz/pull/8406)) ([`cc6336d9851983ca341d40cf2332052e9394a4f2`](https://github.com/block/buzz/commit/cc6336d9851983ca341d40cf2332052e9394a4f2)) +- fix(desktop): release the live tail after a single scroll back to bottom ([#8465](https://github.com/block/buzz/pull/8465)) ([`e73ba22e15807c2a39b0990a9a316d231156a879`](https://github.com/block/buzz/commit/e73ba22e15807c2a39b0990a9a316d231156a879)) +- fix(desktop): bump zip to 9 for RUSTSEC-2026-0367/0368/0369 ([#8412](https://github.com/block/buzz/pull/8412)) ([`6f67dcdac4fdc948660d6b78baa673252c94284f`](https://github.com/block/buzz/commit/6f67dcdac4fdc948660d6b78baa673252c94284f)) +- test: fix recurring CI flakes in desktop and Postgres lanes ([#8343](https://github.com/block/buzz/pull/8343)) ([`7b11c6147df099cd28729f340ea032630bab38cc`](https://github.com/block/buzz/commit/7b11c6147df099cd28729f340ea032630bab38cc)) +- feat(relay): deliver full signed events to operator listeners ([#8309](https://github.com/block/buzz/pull/8309)) ([`8b60dcf8e3f520c651598aa13b4cccc0009bc255`](https://github.com/block/buzz/commit/8b60dcf8e3f520c651598aa13b4cccc0009bc255)) +- feat(relay): add the system channel type ([#8180](https://github.com/block/buzz/pull/8180)) ([`71d7aa04369a6e86e158dc6d46246c8a3ce6d166`](https://github.com/block/buzz/commit/71d7aa04369a6e86e158dc6d46246c8a3ce6d166)) +- feat(relay): channel labels ([#8175](https://github.com/block/buzz/pull/8175)) ([`2f79374f4867035c33dace91c683440e7e011826`](https://github.com/block/buzz/commit/2f79374f4867035c33dace91c683440e7e011826)) +- fix(deps): bump rustls to 0.23.46 for RUSTSEC-2026-0346 and -0347 ([#8319](https://github.com/block/buzz/pull/8319)) ([`67c4fe5e17c5e7b25bf6f5ddbe0b4aeeb0531c2f`](https://github.com/block/buzz/commit/67c4fe5e17c5e7b25bf6f5ddbe0b4aeeb0531c2f)) +- feat(relay): publish channel type and creator on every channel-state event ([#8174](https://github.com/block/buzz/pull/8174)) ([`8bb49a1b6a5ffb5b89eb2e860673ee7bff2fd29b`](https://github.com/block/buzz/commit/8bb49a1b6a5ffb5b89eb2e860673ee7bff2fd29b)) +- Extract shared Huddle audio client for desktop consumers ([#8129](https://github.com/block/buzz/pull/8129)) ([`5dc693aeafc780565d1fa6da3882090aadb8b06c`](https://github.com/block/buzz/commit/5dc693aeafc780565d1fa6da3882090aadb8b06c)) +- fix(relay): hide deletions of author-only events from other readers ([#8197](https://github.com/block/buzz/pull/8197)) ([`40c1c474e74686cbd3218866ee926211cb3365db`](https://github.com/block/buzz/commit/40c1c474e74686cbd3218866ee926211cb3365db)) +- feat(relay): accept an owner's presence for its agents (kind 20003) ([#8261](https://github.com/block/buzz/pull/8261)) ([`1d9f2c81a5583f12be1239a088e2f0b379292dc3`](https://github.com/block/buzz/commit/1d9f2c81a5583f12be1239a088e2f0b379292dc3)) +- docs(nest): replace commit attribution policy with the runtime facts ([#8236](https://github.com/block/buzz/pull/8236)) ([`30873ba46b5e08602ae61a2a0592ecedd37f7289`](https://github.com/block/buzz/commit/30873ba46b5e08602ae61a2a0592ecedd37f7289)) +- feat(relay): accept typing indicators over HTTP POST /events ([#8207](https://github.com/block/buzz/pull/8207)) ([`6c388bde62114feabf5408729533ee52a19845a5`](https://github.com/block/buzz/commit/6c388bde62114feabf5408729533ee52a19845a5)) + +### Other repository changes + +- feat(mobile): render messages with gpt_markdown 1.3.4 plusparse ([#8945](https://github.com/block/buzz/pull/8945)) ([`41587e0284f277d13e5d3a40b169c1dcd54d2894`](https://github.com/block/buzz/commit/41587e0284f277d13e5d3a40b169c1dcd54d2894)) +- fix(acp): bound observer retention by bytes (#7987) ([#9436](https://github.com/block/buzz/pull/9436)) ([`bd031a05af163c4b144ba5518358b5b7b00230a7`](https://github.com/block/buzz/commit/bd031a05af163c4b144ba5518358b5b7b00230a7)) +- Tune release codegen for faster/smaller binaries ([#9434](https://github.com/block/buzz/pull/9434)) ([`471ca6b1ae7979acc0deb95eafc09e1fc4f83bd8`](https://github.com/block/buzz/commit/471ca6b1ae7979acc0deb95eafc09e1fc4f83bd8)) +- fix(mobile): keep publishing presence while the app is open ([#9441](https://github.com/block/buzz/pull/9441)) ([`3d3f9cf1537c1901a7b7e7d0d2746218e4f89564`](https://github.com/block/buzz/commit/3d3f9cf1537c1901a7b7e7d0d2746218e4f89564)) +- feat(mobile): share into Buzz from the iOS share sheet ([#9433](https://github.com/block/buzz/pull/9433)) ([`2b428f56b872d69126d63576ff2fd4a253532140`](https://github.com/block/buzz/commit/2b428f56b872d69126d63576ff2fd4a253532140)) +- fix(mobile): qualify every namesake mention and keep authored mention casing ([#9325](https://github.com/block/buzz/pull/9325)) ([`3c0adc188206bab8551a7af53dcf6bd54c9d0d09`](https://github.com/block/buzz/commit/3c0adc188206bab8551a7af53dcf6bd54c9d0d09)) +- fix(mobile): match browser GIF timing in the iOS reaction sheet ([#9437](https://github.com/block/buzz/pull/9437)) ([`bf3bdd0eaefe39289bf9620594f254c7f68897f5`](https://github.com/block/buzz/commit/bf3bdd0eaefe39289bf9620594f254c7f68897f5)) +- fix(mobile): play short-delay animation frames at browser speed ([#9432](https://github.com/block/buzz/pull/9432)) ([`0bbcf3e7c24c6bb46a4bd3f5fd7fb94aa391a3f3`](https://github.com/block/buzz/commit/0bbcf3e7c24c6bb46a4bd3f5fd7fb94aa391a3f3)) +- buzz-search: read profile names without the profile_name_fields function ([#9397](https://github.com/block/buzz/pull/9397)) ([`279a31daac4604836b6795410dad68462dd18620`](https://github.com/block/buzz/commit/279a31daac4604836b6795410dad68462dd18620)) +- buzz-db: build the community deletion lock key in Rust ([#9396](https://github.com/block/buzz/pull/9396)) ([`745f7dac7cd01f171abcc3058e89069c66df1dd6`](https://github.com/block/buzz/commit/745f7dac7cd01f171abcc3058e89069c66df1dd6)) +- fix(cli): pair for the active community, skip stopped desktops, accept a bare relay host ([#9417](https://github.com/block/buzz/pull/9417)) ([`630922a9e1f891380a61f5b7d726d05ca948cc64`](https://github.com/block/buzz/commit/630922a9e1f891380a61f5b7d726d05ca948cc64)) +- test(mobile): run push tests without a gateway dart-define ([#9423](https://github.com/block/buzz/pull/9423)) ([`8f3f4e266a25d8112d687cfbc1d41feeeebcaf59`](https://github.com/block/buzz/commit/8f3f4e266a25d8112d687cfbc1d41feeeebcaf59)) +- fix(mobile): never pop Home when archiving from channel settings ([#9387](https://github.com/block/buzz/pull/9387)) ([`5bfbda4c3355771601b921f90d8941a7c80c9899`](https://github.com/block/buzz/commit/5bfbda4c3355771601b921f90d8941a7c80c9899)) +- perf(acp): reduce observer CPU and lock overhead ([#9381](https://github.com/block/buzz/pull/9381)) ([`a314975ce7bf9aa00baebfef874b6e69474a95cf`](https://github.com/block/buzz/commit/a314975ce7bf9aa00baebfef874b6e69474a95cf)) +- fix(mobile): keep shortcut taps and the member picker from wedging ([#9388](https://github.com/block/buzz/pull/9388)) ([`60b7fb8178b079e810c3258613f9d5552468539c`](https://github.com/block/buzz/commit/60b7fb8178b079e810c3258613f9d5552468539c)) +- fix(mobile/ios): close notification code blocks only at line-ending fences ([#9349](https://github.com/block/buzz/pull/9349)) ([`defc2d5ea3ae9cfabf31bc0af9433351ad6c4d82`](https://github.com/block/buzz/commit/defc2d5ea3ae9cfabf31bc0af9433351ad6c4d82)) +- fix(mobile): never show emoji shortcodes in reaction pills ([#9411](https://github.com/block/buzz/pull/9411)) ([`4a101752fbed03420252888bfecc40eff0a78b84`](https://github.com/block/buzz/commit/4a101752fbed03420252888bfecc40eff0a78b84)) +- fix(mobile): isolate channel header scroll rebuilds ([#9400](https://github.com/block/buzz/pull/9400)) ([`2f792c2f6b15d81dc67856168247b5ca2c5656c8`](https://github.com/block/buzz/commit/2f792c2f6b15d81dc67856168247b5ca2c5656c8)) +- fix(mobile): build channel section rows lazily ([#9401](https://github.com/block/buzz/pull/9401)) ([`2636e986a06ca5b34027d27cd1c08b36f649ce41`](https://github.com/block/buzz/commit/2636e986a06ca5b34027d27cd1c08b36f649ce41)) +- fix(cli): treat a retried sidebar write the relay already stored as success ([#9202](https://github.com/block/buzz/pull/9202)) ([`745d2a86e01c0c9781793d98c881858e9136f091`](https://github.com/block/buzz/commit/745d2a86e01c0c9781793d98c881858e9136f091)) +- feat(workflow): add owner-only agent mentions for workflow messages ([#9227](https://github.com/block/buzz/pull/9227)) ([`fc8c802253155fa8721bafb26e442cd3986ff303`](https://github.com/block/buzz/commit/fc8c802253155fa8721bafb26e442cd3986ff303)) +- Adapt iPhone Duo layouts, rail navigation, and native sheets ([#8568](https://github.com/block/buzz/pull/8568)) ([`cb69ad9e4f21b25954d76f4ce1b406f882dafecc`](https://github.com/block/buzz/commit/cb69ad9e4f21b25954d76f4ce1b406f882dafecc)) +- End last-human agent Huddles and preserve mobile transcript access ([#9375](https://github.com/block/buzz/pull/9375)) ([`5f81803cb16acc7976dabedd03d87bd927a9ef70`](https://github.com/block/buzz/commit/5f81803cb16acc7976dabedd03d87bd927a9ef70)) +- buzz-db: pin explicit FK-child cleanup and same-workflow fire links ([#8317](https://github.com/block/buzz/pull/8317)) ([`aa9b44ef369759b9d564214c7f6101fb0b200de2`](https://github.com/block/buzz/commit/aa9b44ef369759b9d564214c7f6101fb0b200de2)) +- chore(deps): bump hickory to 0.26.3 for RUSTSEC-2026-0506..0520 ([#9394](https://github.com/block/buzz/pull/9394)) ([`0c58b33e64e3c2297dd0c0551d9bff4dacf84082`](https://github.com/block/buzz/commit/0c58b33e64e3c2297dd0c0551d9bff4dacf84082)) +- fix(db): seek replaceable heads by channel ([#9147](https://github.com/block/buzz/pull/9147)) ([`193fda22f5f7350427e564f40d28881c2997f364`](https://github.com/block/buzz/commit/193fda22f5f7350427e564f40d28881c2997f364)) +- buzz-db: check events created_at floor in app writers (phase 1) ([#8325](https://github.com/block/buzz/pull/8325)) ([`68785206041813cd10a25f2898f26ff9c85fc927`](https://github.com/block/buzz/commit/68785206041813cd10a25f2898f26ff9c85fc927)) +- fix(mobile): keep a thread tail behind the keyboard unread ([#9295](https://github.com/block/buzz/pull/9295)) ([`473d592602162194c11c4ce48bb3d2d9cb0a20a4`](https://github.com/block/buzz/commit/473d592602162194c11c4ce48bb3d2d9cb0a20a4)) +- fix(mobile): restore header cues and per-channel identity check for #9369 ([#9370](https://github.com/block/buzz/pull/9370)) ([`c0e30110ddb9321c7c8591f15d40a716efe17025`](https://github.com/block/buzz/commit/c0e30110ddb9321c7c8591f15d40a716efe17025)) +- fix(relay): treat empty filter sets as match-nothing in SQL ([#9342](https://github.com/block/buzz/pull/9342)) ([`e715fbb3629c40eac0fe371b15405ad114ffa19c`](https://github.com/block/buzz/commit/e715fbb3629c40eac0fe371b15405ad114ffa19c)) +- buzz-cli: add --before and --before-id to messages search ([#9382](https://github.com/block/buzz/pull/9382)) ([`0e6037c74d67930de36143ed4661f469039d8dc7`](https://github.com/block/buzz/commit/0e6037c74d67930de36143ed4661f469039d8dc7)) +- feat(relay): agents cannot write in DMs except with their owner ([#9371](https://github.com/block/buzz/pull/9371)) ([`a09b84d23d8c90f24ce5bec8a4e5259fd3a5b1f7`](https://github.com/block/buzz/commit/a09b84d23d8c90f24ce5bec8a4e5259fd3a5b1f7)) +- fix(relay): bound each cross-node delivery attempt ([#9305](https://github.com/block/buzz/pull/9305)) ([`1b190d21fc0bba06bade342c9f6201ff0d10c2ba`](https://github.com/block/buzz/commit/1b190d21fc0bba06bade342c9f6201ff0d10c2ba)) +- feat(mobile): add iOS Home Screen shortcuts for New chat, New DM and the Bestie ([#9360](https://github.com/block/buzz/pull/9360)) ([`27f0fe75276f93d56cdf878643a4d676f99dc618`](https://github.com/block/buzz/commit/27f0fe75276f93d56cdf878643a4d676f99dc618)) +- perf(mobile): stop downloading whole videos for posterless stills ([#9367](https://github.com/block/buzz/pull/9367)) ([`85c7156085d902f5d5fd59e193263b109c6d5ba0`](https://github.com/block/buzz/commit/85c7156085d902f5d5fd59e193263b109c6d5ba0)) +- Enforce single-community relay mode ([#9149](https://github.com/block/buzz/pull/9149)) ([`4c60be6a1e8dc2c7839f7c0294391fb93941ed9f`](https://github.com/block/buzz/commit/4c60be6a1e8dc2c7839f7c0294391fb93941ed9f)) +- fix(relay): match #a tag filters in SQL before LIMIT ([#9339](https://github.com/block/buzz/pull/9339)) ([`695c1c3aaec05e4f01929fe68cc902314fe64331`](https://github.com/block/buzz/commit/695c1c3aaec05e4f01929fe68cc902314fe64331)) +- Add participant avatars to mobile conversation headers ([#9369](https://github.com/block/buzz/pull/9369)) ([`96e56c5b33ad8547b12f3514d0ee6b63491d0320`](https://github.com/block/buzz/commit/96e56c5b33ad8547b12f3514d0ee6b63491d0320)) +- fix(mobile): stop asking for an API token when the channel list is refused ([#9327](https://github.com/block/buzz/pull/9327)) ([`8f80b172ea0d7dc559807723f8ad4a2334d7a6fd`](https://github.com/block/buzz/commit/8f80b172ea0d7dc559807723f8ad4a2334d7a6fd)) +- chore(release): release Buzz Relay version 0.3.0 ([#9362](https://github.com/block/buzz/pull/9362)) ([`75d38b6c2d5f357348288ded8c15aba15f765ea5`](https://github.com/block/buzz/commit/75d38b6c2d5f357348288ded8c15aba15f765ea5)) +- Fix gallery video selection, thumbnails, and swipe dismissal ([#9356](https://github.com/block/buzz/pull/9356)) ([`ef57fec4d26cee1939a329acd7c8c2b079b56576`](https://github.com/block/buzz/commit/ef57fec4d26cee1939a329acd7c8c2b079b56576)) +- feat(mobile/ios): show the message's own text in notifications ([#9346](https://github.com/block/buzz/pull/9346)) ([`95dd9d67dd943cd30fd02dee8e5c11d13639d2ad`](https://github.com/block/buzz/commit/95dd9d67dd943cd30fd02dee8e5c11d13639d2ad)) +- feat(mobile): prefill the agents you last tagged in a conversation ([#9248](https://github.com/block/buzz/pull/9248)) ([`1adde0e6bfe732b1b66a1db140596108c5f294a4`](https://github.com/block/buzz/commit/1adde0e6bfe732b1b66a1db140596108c5f294a4)) +- feat(mobile): start a Solo chat from a message or inbox row ([#9251](https://github.com/block/buzz/pull/9251)) ([`0ac71eaf955e7f556d35122b9e9bc19828becadf`](https://github.com/block/buzz/commit/0ac71eaf955e7f556d35122b9e9bc19828becadf)) +- feat(mobile): link to Builderlab web from Settings ([#9300](https://github.com/block/buzz/pull/9300)) ([`045b637b0d05096e30d6cca7d99143ab18f36730`](https://github.com/block/buzz/commit/045b637b0d05096e30d6cca7d99143ab18f36730)) +- fix(relay): bound invite preview host lookup ([#9308](https://github.com/block/buzz/pull/9308)) ([`2c5c8343ef8c39cad0cb27cbc07bffc7141e345a`](https://github.com/block/buzz/commit/2c5c8343ef8c39cad0cb27cbc07bffc7141e345a)) +- fix(mobile): tell same-name agents apart in Solo ([#9321](https://github.com/block/buzz/pull/9321)) ([`b483bbe765d0ceb5f0d571910059d3abb84217b6`](https://github.com/block/buzz/commit/b483bbe765d0ceb5f0d571910059d3abb84217b6)) +- fix(mobile): join an open channel from the chat footer ([#9253](https://github.com/block/buzz/pull/9253)) ([`0aca7588e3a49719c177c2179a5e5201f1959a49`](https://github.com/block/buzz/commit/0aca7588e3a49719c177c2179a5e5201f1959a49)) +- fix(relay): fence pending subscriptions on close or replacement ([#2382](https://github.com/block/buzz/pull/2382)) ([`30e1fa47fb9a67cbc408cfcee83dcf280ab49595`](https://github.com/block/buzz/commit/30e1fa47fb9a67cbc408cfcee83dcf280ab49595)) +- fix(mobile): hide archived people and agents from choices; give them their own members section ([#9320](https://github.com/block/buzz/pull/9320)) ([`dd2d3cf4eaa93fe8250bb4b5054024c6e4993ee5`](https://github.com/block/buzz/commit/dd2d3cf4eaa93fe8250bb4b5054024c6e4993ee5)) +- Add video stacks and native iOS zoom playback ([#9316](https://github.com/block/buzz/pull/9316)) ([`b40f22114bac744d91c8afb25d644826646fb776`](https://github.com/block/buzz/commit/b40f22114bac744d91c8afb25d644826646fb776)) +- Support PNG and HEIC photos in the native iOS zoom gallery ([#9314](https://github.com/block/buzz/pull/9314)) ([`e2dc54e22fc113f298889d76c3acf674cb46db4b`](https://github.com/block/buzz/commit/e2dc54e22fc113f298889d76c3acf674cb46db4b)) +- fix(mobile): list known people in recipient pickers before a name is typed ([#9311](https://github.com/block/buzz/pull/9311)) ([`13a6aa19f42b3c11c3db4e3b19e9bb5905787042`](https://github.com/block/buzz/commit/13a6aa19f42b3c11c3db4e3b19e9bb5905787042)) +- feat(mobile): mark edited messages after the body ([#8863](https://github.com/block/buzz/pull/8863)) ([`6384c6cdfa764fe393ac5860e00f414cc9d85804`](https://github.com/block/buzz/commit/6384c6cdfa764fe393ac5860e00f414cc9d85804)) +- Add swipeable photo stacks and native iOS gallery preview ([#9259](https://github.com/block/buzz/pull/9259)) ([`44b3c4823f0cf1f7715f85dbf5566cb64e848162`](https://github.com/block/buzz/commit/44b3c4823f0cf1f7715f85dbf5566cb64e848162)) +- ci(docker): skip relay image publishes for main pushes outside the build context ([#9310](https://github.com/block/buzz/pull/9310)) ([`e8a4bc15917e61dc0b8066e24c026dc6f3e7ce36`](https://github.com/block/buzz/commit/e8a4bc15917e61dc0b8066e24c026dc6f3e7ce36)) +- Add manual-only relay image publishing ([#9303](https://github.com/block/buzz/pull/9303)) ([`3e9d2e90ce87243a7c5de473ac6326a92aedaa32`](https://github.com/block/buzz/commit/3e9d2e90ce87243a7c5de473ac6326a92aedaa32)) +- fix(mobile): bump Flutter to 3.47.9 for Android TLS fix ([#9309](https://github.com/block/buzz/pull/9309)) ([`402bd1897f8b7a822819e13fe8afa20037dd1865`](https://github.com/block/buzz/commit/402bd1897f8b7a822819e13fe8afa20037dd1865)) +- Serve video and poster previews for invite links ([#9306](https://github.com/block/buzz/pull/9306)) ([`773849665e0592b9f99dbfbaa2f706de01a8f5a7`](https://github.com/block/buzz/commit/773849665e0592b9f99dbfbaa2f706de01a8f5a7)) +- docs: point the README to Buzz 1.0 in block/buzz-app ([#9296](https://github.com/block/buzz/pull/9296)) ([`18f3e35413c6fd9b5ebc9254aca4981c6ca7fd5c`](https://github.com/block/buzz/commit/18f3e35413c6fd9b5ebc9254aca4981c6ca7fd5c)) +- fix(db): give the replica-fence probe its own pool and instrument it ([#9297](https://github.com/block/buzz/pull/9297)) ([`5b1698ec244d6687ff60be0c29b95348d18c610f`](https://github.com/block/buzz/commit/5b1698ec244d6687ff60be0c29b95348d18c610f)) +- fix(relay): never close connections when cross-node fan-out falls behind ([#9302](https://github.com/block/buzz/pull/9302)) ([`dd9da3ac6d854ec199e8b3dc661fdb84eb995a8c`](https://github.com/block/buzz/commit/dd9da3ac6d854ec199e8b3dc661fdb84eb995a8c)) +- fix(ci): classify hermit retry timeouts by watchdog kill, not whole seconds ([#9274](https://github.com/block/buzz/pull/9274)) ([`d2c3234cb9829962627a70366d406489059f1816`](https://github.com/block/buzz/commit/d2c3234cb9829962627a70366d406489059f1816)) +- test(ios): wait for a key, foreground-active window before presenting in RunnerTests ([#9275](https://github.com/block/buzz/pull/9275)) ([`ea548da80895b5f71537af0d2ad7a193ba8bdbd1`](https://github.com/block/buzz/commit/ea548da80895b5f71537af0d2ad7a193ba8bdbd1)) +- feat(relay): let an operator mint invites for a community owner or admin ([#9265](https://github.com/block/buzz/pull/9265)) ([`2b16d0ea1a5550146c3dbe303ad918debcf0094e`](https://github.com/block/buzz/commit/2b16d0ea1a5550146c3dbe303ad918debcf0094e)) +- fix: inline ARM64 atomics in Sprig image build ([#9291](https://github.com/block/buzz/pull/9291)) ([`66095e55985777dd84be140b328f0ee97af19ae9`](https://github.com/block/buzz/commit/66095e55985777dd84be140b328f0ee97af19ae9)) +- fix(mobile): show observed thread replies in Activity ([#9286](https://github.com/block/buzz/pull/9286)) ([`49511f02b6020ccd195848b3bfd431f0ec82d3c0`](https://github.com/block/buzz/commit/49511f02b6020ccd195848b3bfd431f0ec82d3c0)) +- Enable mobile huddles with Codex agents ([#9269](https://github.com/block/buzz/pull/9269)) ([`2bbaa061d023ec6934707b9b6d27d12ee09b6a67`](https://github.com/block/buzz/commit/2bbaa061d023ec6934707b9b6d27d12ee09b6a67)) +- fix(mobile): read mentions taller than the screen ([#9243](https://github.com/block/buzz/pull/9243)) ([`c1ce2ca8001cbc90ff83b92c7fcfb249cedf7959`](https://github.com/block/buzz/commit/c1ce2ca8001cbc90ff83b92c7fcfb249cedf7959)) +- test(relay): give every media e2e upload its own blob hash ([#9272](https://github.com/block/buzz/pull/9272)) ([`b082b1464ce51be18cc5e260ec0f29bca63ef8d0`](https://github.com/block/buzz/commit/b082b1464ce51be18cc5e260ec0f29bca63ef8d0)) +- Add invite preview video and fallback poster ([#9282](https://github.com/block/buzz/pull/9282)) ([`838976d6e454996037460eeca1cced2bc7c686e1`](https://github.com/block/buzz/commit/838976d6e454996037460eeca1cced2bc7c686e1)) +- NEXUS-4336: Wait for desktop-provider socket ownership proof ([#9270](https://github.com/block/buzz/pull/9270)) ([`3071279cd8636a4be9a0f7e16182e2391f4d4347`](https://github.com/block/buzz/commit/3071279cd8636a4be9a0f7e16182e2391f4d4347)) +- fix: unblock image audit with patched MCP SDK ([#9287](https://github.com/block/buzz/pull/9287)) ([`658253009c5117e03563ef779742931b312c1b58`](https://github.com/block/buzz/commit/658253009c5117e03563ef779742931b312c1b58)) +- feat(ci): allow admin dispatch of desktop candidate validation ([#9288](https://github.com/block/buzz/pull/9288)) ([`34bab2f64b6a6417323b4dc948b2e3e898d26617`](https://github.com/block/buzz/commit/34bab2f64b6a6417323b4dc948b2e3e898d26617)) +- feat(mobile): tag the reacted-to message author on reactions ([#9141](https://github.com/block/buzz/pull/9141)) ([`c502e53e634bbd4945fc0dcd49e104dc57acf470`](https://github.com/block/buzz/commit/c502e53e634bbd4945fc0dcd49e104dc57acf470)) +- fix(mobile): steady New DM picker rows and animate picks ([#9249](https://github.com/block/buzz/pull/9249)) ([`5f59940544815bb7584f5122047e5ec9ef0bbdd9`](https://github.com/block/buzz/commit/5f59940544815bb7584f5122047e5ec9ef0bbdd9)) +- perf(mobile): keep remote images on disk and show small ones as thumbnails ([#9158](https://github.com/block/buzz/pull/9158)) ([`52cb6818face2bcc1a2aeaceb44d183b6ff9f2e9`](https://github.com/block/buzz/commit/52cb6818face2bcc1a2aeaceb44d183b6ff9f2e9)) +- fix(relay): deliver slow cross-node events late instead of closing their recipients ([#9235](https://github.com/block/buzz/pull/9235)) ([`15174bc2b2631531bc45d8ec72d8499f1b194660`](https://github.com/block/buzz/commit/15174bc2b2631531bc45d8ec72d8499f1b194660)) +- fix(mobile): read only shown events from filtered Activity rows ([#9215](https://github.com/block/buzz/pull/9215)) ([`f38285562c6d0b9771a90cead0447c1f24a581d2`](https://github.com/block/buzz/commit/f38285562c6d0b9771a90cead0447c1f24a581d2)) +- fix(mobile): show the channel name as the notification subtitle ([#9173](https://github.com/block/buzz/pull/9173)) ([`58696ff577c96ff40e2cb155cf8595d03262c307`](https://github.com/block/buzz/commit/58696ff577c96ff40e2cb155cf8595d03262c307)) +- fix(mobile): keep Home's header clean under sheets ([#9152](https://github.com/block/buzz/pull/9152)) ([`e1e1cd50abdc254c7e64e97d565458088971ed8f`](https://github.com/block/buzz/commit/e1e1cd50abdc254c7e64e97d565458088971ed8f)) +- fix(mobile): show already-loaded custom emoji in the iOS reactions sheet ([#9150](https://github.com/block/buzz/pull/9150)) ([`ac2c5831f32fd8b2e38f77a3a68de7a8701b11bd`](https://github.com/block/buzz/commit/ac2c5831f32fd8b2e38f77a3a68de7a8701b11bd)) +- mobile: add follow and remind actions to inbox row menu ([#9142](https://github.com/block/buzz/pull/9142)) ([`40cfa72cd411851f84f022b17e730dc8afe39723`](https://github.com/block/buzz/commit/40cfa72cd411851f84f022b17e730dc8afe39723)) +- fix(mobile): start no threads in Solo chats ([#9123](https://github.com/block/buzz/pull/9123)) ([`ad5699d05aa2c49f918b960feddb7692e6f6706d`](https://github.com/block/buzz/commit/ad5699d05aa2c49f918b960feddb7692e6f6706d)) +- mobile: persist user profiles so names and avatars render on launch ([#9116](https://github.com/block/buzz/pull/9116)) ([`733d164e8068eed5f0416afb36dfe7912aaa2688`](https://github.com/block/buzz/commit/733d164e8068eed5f0416afb36dfe7912aaa2688)) +- fix(mobile): keep a sent thread reply above the composer ([#9026](https://github.com/block/buzz/pull/9026)) ([`439d7bcc12c5a174c2d3b8416500ebd1ee9da348`](https://github.com/block/buzz/commit/439d7bcc12c5a174c2d3b8416500ebd1ee9da348)) +- [buzz] Recover database pool capacity after stalled connections ([#9267](https://github.com/block/buzz/pull/9267)) ([`22d96d94ef043292803b6d5c929652abd69612dd`](https://github.com/block/buzz/commit/22d96d94ef043292803b6d5c929652abd69612dd)) +- feat: send a User-Agent on relay WebSocket upgrades ([#9246](https://github.com/block/buzz/pull/9246)) ([`65e864301d2e51a93003816b45e77cae96be901f`](https://github.com/block/buzz/commit/65e864301d2e51a93003816b45e77cae96be901f)) +- Record why relay connections close and quiet close warnings ([#9245](https://github.com/block/buzz/pull/9245)) ([`31fa53174d5bf7995c6cab18954514cc036125e2`](https://github.com/block/buzz/commit/31fa53174d5bf7995c6cab18954514cc036125e2)) +- fix(relay): say "channel owner or admin" in the call_webhook save refusal ([#9169](https://github.com/block/buzz/pull/9169)) ([`4bfe60197e8c390a8701053228cd50c5391f37d3`](https://github.com/block/buzz/commit/4bfe60197e8c390a8701053228cd50c5391f37d3)) +- feat(mobile): consolidate Solo chat settings in one sheet ([#9255](https://github.com/block/buzz/pull/9255)) ([`8cce12f591988f29cc2beab5ff0c89d51862f31b`](https://github.com/block/buzz/commit/8cce12f591988f29cc2beab5ff0c89d51862f31b)) +- fix(mobile): swipe left to reply so swipe-back keeps rightward drags ([#9127](https://github.com/block/buzz/pull/9127)) ([`d839d3731a11ab363a69e7f5b851c3031b7680dd`](https://github.com/block/buzz/commit/d839d3731a11ab363a69e7f5b851c3031b7680dd)) +- mobile: long-press a message link for open, copy and share ([#9135](https://github.com/block/buzz/pull/9135)) ([`a7a534d476927dce4f468706589227ea5d1794ff`](https://github.com/block/buzz/commit/a7a534d476927dce4f468706589227ea5d1794ff)) +- feat(mobile): long-press a Solo chat to open its details sheet ([#9163](https://github.com/block/buzz/pull/9163)) ([`e86d0e23a335d6c061fa7d8ea081165089526d7d`](https://github.com/block/buzz/commit/e86d0e23a335d6c061fa7d8ea081165089526d7d)) +- fix(mobile): shimmer loading photos in the iOS carousel ([#9167](https://github.com/block/buzz/pull/9167)) ([`1a0dae77bfc39b67c6d4bc4a00565c03ca4b4fc6`](https://github.com/block/buzz/commit/1a0dae77bfc39b67c6d4bc4a00565c03ca4b4fc6)) +- fix(mobile): keep Home bell tappable while scrolled ([#9241](https://github.com/block/buzz/pull/9241)) ([`f3b127e3af5c14d2314faa2b63556c3f51ec6743`](https://github.com/block/buzz/commit/f3b127e3af5c14d2314faa2b63556c3f51ec6743)) +- feat(mobile): one Builderlab per build, internal and public distributions ([#9224](https://github.com/block/buzz/pull/9224)) ([`12f3d510011b1c57c1f51f9aaa25a307fa0bb883`](https://github.com/block/buzz/commit/12f3d510011b1c57c1f51f9aaa25a307fa0bb883)) +- fix(ios): mint hosted NIP-FI assertions in the notification extension ([#9228](https://github.com/block/buzz/pull/9228)) ([`794ee6418341c835c2c80a9f14187e2b46834e3a`](https://github.com/block/buzz/commit/794ee6418341c835c2c80a9f14187e2b46834e3a)) +- fix(mobile): request hosted relay assertions only when NIP-FI is required ([#9225](https://github.com/block/buzz/pull/9225)) ([`b58ee0840454d1708ef6ff5c4439f39fca25c716`](https://github.com/block/buzz/commit/b58ee0840454d1708ef6ff5c4439f39fca25c716)) +- Manage community NIP-FI policy with enable, disable and status ([#9176](https://github.com/block/buzz/pull/9176)) ([`2cd40badb85de059a6916206e133da7a0a88fb2e`](https://github.com/block/buzz/commit/2cd40badb85de059a6916206e133da7a0a88fb2e)) +- [buzz] Recover interrupted default-channel auto-joins ([#9045](https://github.com/block/buzz/pull/9045)) ([`39d5159caf748d9696646fc0c761ff639d919f0d`](https://github.com/block/buzz/commit/39d5159caf748d9696646fc0c761ff639d919f0d)) +- fix(db): keep retained fence proofs when a probe fails ([#9200](https://github.com/block/buzz/pull/9200)) ([`38795ada8749509607caddbafd4049162f8a31f9`](https://github.com/block/buzz/commit/38795ada8749509607caddbafd4049162f8a31f9)) +- feat(mobile): rename Activity and add header filters ([#9213](https://github.com/block/buzz/pull/9213)) ([`597a8d1970301ffbd089194d3f849da9d9b21489`](https://github.com/block/buzz/commit/597a8d1970301ffbd089194d3f849da9d9b21489)) +- fix(relay): set received_at in the system-channel fan-out test helper ([#9214](https://github.com/block/buzz/pull/9214)) ([`6c3ffd160bc0caf8946ce57f3aa50e4f5c615e8e`](https://github.com/block/buzz/commit/6c3ffd160bc0caf8946ce57f3aa50e4f5c615e8e)) +- feat(mobile): move Activity to a Home bell and align Home spacing ([#9212](https://github.com/block/buzz/pull/9212)) ([`beec0553003ed71c34fcb11b9b7a64a4766f6b3c`](https://github.com/block/buzz/commit/beec0553003ed71c34fcb11b9b7a64a4766f6b3c)) +- Allow operators to set initial NIP-FI policy on create ([#9211](https://github.com/block/buzz/pull/9211)) ([`446e9e0762a4bfe4c74e138eacf44d7d9d657ca9`](https://github.com/block/buzz/commit/446e9e0762a4bfe4c74e138eacf44d7d9d657ca9)) +- perf(loadgen): spread seed writes across channel creators ([#9206](https://github.com/block/buzz/pull/9206)) ([`e670b672b8b25dae5bc387d683cf2b4e28ea3092`](https://github.com/block/buzz/commit/e670b672b8b25dae5bc387d683cf2b4e28ea3092)) +- feat(relay): runtime-tunable history-read and AUTH concurrency caps via feature flags ([#9170](https://github.com/block/buzz/pull/9170)) ([`a17243d846c887fbab862f494ec474821e6ca1cc`](https://github.com/block/buzz/commit/a17243d846c887fbab862f494ec474821e6ca1cc)) +- fix(relay): route live REQ events by each filter's own channel scope ([#8519](https://github.com/block/buzz/pull/8519)) ([`01d9778606bd5a1bbe80a743a1c2cc659721cf12`](https://github.com/block/buzz/commit/01d9778606bd5a1bbe80a743a1c2cc659721cf12)) +- fix(relay): deliver multi-node fan-out concurrently and never drop silently ([#9195](https://github.com/block/buzz/pull/9195)) ([`27ab6a085a6689da5c0c81ca74ee5ccc90ed2003`](https://github.com/block/buzz/commit/27ab6a085a6689da5c0c81ca74ee5ccc90ed2003)) +- perf(db): bound since-limited events reads with the month-floor literal ([#9197](https://github.com/block/buzz/pull/9197)) ([`0d5edb8bb36bbcbe78180ad3d63eaca38a6fdd20`](https://github.com/block/buzz/commit/0d5edb8bb36bbcbe78180ad3d63eaca38a6fdd20)) +- fix(mobile): match Agents sign-in to Home’s reconnect capsule ([#9204](https://github.com/block/buzz/pull/9204)) ([`a25f3cd1d7942f9ec666910471232b8193774496`](https://github.com/block/buzz/commit/a25f3cd1d7942f9ec666910471232b8193774496)) +- fix(cli): clearer desktop pairing errors, paired default relay, and auth desktop list ([#9196](https://github.com/block/buzz/pull/9196)) ([`c8d736642e1cddaca5797c54c0c625d16a1724ed`](https://github.com/block/buzz/commit/c8d736642e1cddaca5797c54c0c625d16a1724ed)) +- perf(relay): serve restriction rows for 10 s with cross-pod invalidation ([#9199](https://github.com/block/buzz/pull/9199)) ([`744f3946f6fe1ff7a649c132638d5af608900dbd`](https://github.com/block/buzz/commit/744f3946f6fe1ff7a649c132638d5af608900dbd)) +- Pin sqlx to the upstream fix for a cancelled BEGIN ([#9192](https://github.com/block/buzz/pull/9192)) ([`abb2586f8ca67414b5c6e796d2c468755fe26ee3`](https://github.com/block/buzz/commit/abb2586f8ca67414b5c6e796d2c468755fe26ee3)) +- feat(cli): manage sidebar sections with `buzz sidebar sections` ([#9191](https://github.com/block/buzz/pull/9191)) ([`e43d57c6ba2d1d07e0aa8842aa1a7006c92371e7`](https://github.com/block/buzz/commit/e43d57c6ba2d1d07e0aa8842aa1a7006c92371e7)) +- Show mobile floating dates while scrolling ([#9185](https://github.com/block/buzz/pull/9185)) ([`0a4d209046ee04d9b3a28642367b40a1dd810e4a`](https://github.com/block/buzz/commit/0a4d209046ee04d9b3a28642367b40a1dd810e4a)) +- feat(loadgen): model agent turns and sustained holds ([#9182](https://github.com/block/buzz/pull/9182)) ([`3fdd8c6ff1ca42fe0be9f8ae78a8f8f7b8075711`](https://github.com/block/buzz/commit/3fdd8c6ff1ca42fe0be9f8ae78a8f8f7b8075711)) +- fix(cli): list DMs, attach any file, validate kinds, default the relay ([#9168](https://github.com/block/buzz/pull/9168)) ([`b329e05c5b755de455d07acdf463f9a35518a5ce`](https://github.com/block/buzz/commit/b329e05c5b755de455d07acdf463f9a35518a5ce)) +- Add avatar color backdrop to mobile agent creation ([#9184](https://github.com/block/buzz/pull/9184)) ([`962b3fdd882b2cd78699ea2896beb9f1cbebf305`](https://github.com/block/buzz/commit/962b3fdd882b2cd78699ea2896beb9f1cbebf305)) +- Cache channel memberships once per user ([#9060](https://github.com/block/buzz/pull/9060)) ([`32997e2e1b57d0d1140075f644938ca1538a6309`](https://github.com/block/buzz/commit/32997e2e1b57d0d1140075f644938ca1538a6309)) +- mobile: make the first-agent card stand out in dark mode ([#9171](https://github.com/block/buzz/pull/9171)) ([`9a6cb3ffdfe8bf077e184674d8850fdf48bfbdcd`](https://github.com/block/buzz/commit/9a6cb3ffdfe8bf077e184674d8850fdf48bfbdcd)) +- fix(relay): close legacy sockets after community FI upgrades ([#8991](https://github.com/block/buzz/pull/8991)) ([`4e28176f13957f4bb77f58c5b4aa0ad137017423`](https://github.com/block/buzz/commit/4e28176f13957f4bb77f58c5b4aa0ad137017423)) +- fix(mobile): show transparent avatars without a black background ([#9105](https://github.com/block/buzz/pull/9105)) ([`b894fb02ffb1352f075484a08c409fdb131aed3e`](https://github.com/block/buzz/commit/b894fb02ffb1352f075484a08c409fdb131aed3e)) +- fix(mobile): delete composer chips as one unit ([#9133](https://github.com/block/buzz/pull/9133)) ([`a1efbf63bddbde35d9a3e12eba568c3596534d14`](https://github.com/block/buzz/commit/a1efbf63bddbde35d9a3e12eba568c3596534d14)) +- test(mobile): drop the video preview step removed with native frame loading ([#9164](https://github.com/block/buzz/pull/9164)) ([`fbfbf3d64f028da95368f8cd5c80ca0f77e482d0`](https://github.com/block/buzz/commit/fbfbf3d64f028da95368f8cd5c80ca0f77e482d0)) +- fix(relay): close a WS search whose hit hydration fails instead of sending EOSE ([#9148](https://github.com/block/buzz/pull/9148)) ([`1bb44ae9effd78a87c684a47edf5cc335b8091a8`](https://github.com/block/buzz/commit/1bb44ae9effd78a87c684a47edf5cc335b8091a8)) +- perf(db): stop the events recent pass at a ceiling for regular-kind reads ([#9157](https://github.com/block/buzz/pull/9157)) ([`8ae35c5c92694af7488bbf6a2140c27aed9d0798`](https://github.com/block/buzz/commit/8ae35c5c92694af7488bbf6a2140c27aed9d0798)) +- feat(relay): project compact viewer memberships (BUZZ-615) ([#9118](https://github.com/block/buzz/pull/9118)) ([`bb3c5f7175041907db50df9640d6377a69cf9be9`](https://github.com/block/buzz/commit/bb3c5f7175041907db50df9640d6377a69cf9be9)) +- perf(mobile): rank search channels once per query ([#9136](https://github.com/block/buzz/pull/9136)) ([`fd0ec105050db430751b43b82e190b7bf4220e35`](https://github.com/block/buzz/commit/fd0ec105050db430751b43b82e190b7bf4220e35)) +- mobile: start new agents on the server-recommended model ([#9151](https://github.com/block/buzz/pull/9151)) ([`1a30e51689b982e8d5aa093fc849a98bcf35e63b`](https://github.com/block/buzz/commit/1a30e51689b982e8d5aa093fc849a98bcf35e63b)) +- release(mobile): push candidate tags as the operator, not the App ([#9084](https://github.com/block/buzz/pull/9084)) ([`5d094cd76992b840365d33c34006393d6eccd8b0`](https://github.com/block/buzz/commit/5d094cd76992b840365d33c34006393d6eccd8b0)) +- test(mobile): check posterless video previews renew the relay assertion ([#9144](https://github.com/block/buzz/pull/9144)) ([`fc85b0d1547d29a389a9eb9fdf8abcf933a239e8`](https://github.com/block/buzz/commit/fc85b0d1547d29a389a9eb9fdf8abcf933a239e8)) +- perf(db): plan multi-value #d reads with their values ([#9131](https://github.com/block/buzz/pull/9131)) ([`bd1b17dee8348b21b33abe35ee4eafa8730f8a83`](https://github.com/block/buzz/commit/bd1b17dee8348b21b33abe35ee4eafa8730f8a83)) +- fix(mobile): confirm before starting a Huddle from the header ([#9155](https://github.com/block/buzz/pull/9155)) ([`133c883b8ca1221d82d17c94249809844d2b80b3`](https://github.com/block/buzz/commit/133c883b8ca1221d82d17c94249809844d2b80b3)) +- fix(mobile): find verified people who have no profile ([#9086](https://github.com/block/buzz/pull/9086)) ([`c39ee507b27354b34baec635c8835c7ebe6f1de0`](https://github.com/block/buzz/commit/c39ee507b27354b34baec635c8835c7ebe6f1de0)) +- perf(db): hydrate search hits with exact event timestamps ([#9126](https://github.com/block/buzz/pull/9126)) ([`cec47c20a3f1220961a80306209b0668fff57b6a`](https://github.com/block/buzz/commit/cec47c20a3f1220961a80306209b0668fff57b6a)) +- perf(db): prune post-commit push enqueue by signed event timestamp ([#9128](https://github.com/block/buzz/pull/9128)) ([`997ce3a2c9cd9e51f8168c64756782aca1c51b89`](https://github.com/block/buzz/commit/997ce3a2c9cd9e51f8168c64756782aca1c51b89)) +- perf(db): use exact event timestamps for transactional deletion ([#9130](https://github.com/block/buzz/pull/9130)) ([`0cfa50ac70b26208367c56dc5ddf3fcef61808e4`](https://github.com/block/buzz/commit/0cfa50ac70b26208367c56dc5ddf3fcef61808e4)) +- perf(redis): index mesh ready records and share one Redis connection ([#9113](https://github.com/block/buzz/pull/9113)) ([`b6d4403149af700c0c11ce07b85c3bc105a1b605`](https://github.com/block/buzz/commit/b6d4403149af700c0c11ce07b85c3bc105a1b605)) +- fix(mobile): delay iOS message actions until a deliberate hold ([#9049](https://github.com/block/buzz/pull/9049)) ([`4aae6c22aa734df508eee5f46a8e72a11ff89dd3`](https://github.com/block/buzz/commit/4aae6c22aa734df508eee5f46a8e72a11ff89dd3)) +- feat(cli): send a thread message to the channel ([#8778](https://github.com/block/buzz/pull/8778)) ([`303157f53d289bb8e67e372897274d835fa9a8b3`](https://github.com/block/buzz/commit/303157f53d289bb8e67e372897274d835fa9a8b3)) +- feat(cli): read-only unread state (NIP-RS) ([#8789](https://github.com/block/buzz/pull/8789)) ([`171100f308713d23d5f477dab93f6423eca8de8d`](https://github.com/block/buzz/commit/171100f308713d23d5f477dab93f6423eca8de8d)) +- buzz-db: read explicit #h sets one channel at a time ([#9110](https://github.com/block/buzz/pull/9110)) ([`0ada1d37077f701507855fe58a4e78ac4e345f30`](https://github.com/block/buzz/commit/0ada1d37077f701507855fe58a4e78ac4e345f30)) +- feat(cli): list huddles and their participants ([#8830](https://github.com/block/buzz/pull/8830)) ([`198c4c3e9bff1a94ea601f3290c8adce436992e2`](https://github.com/block/buzz/commit/198c4c3e9bff1a94ea601f3290c8adce436992e2)) +- docs(agents): add open-source boundary and drop private repo list ([#9114](https://github.com/block/buzz/pull/9114)) ([`f82944e3180e28502f5ea599ac9973aa6398ddb3`](https://github.com/block/buzz/commit/f82944e3180e28502f5ea599ac9973aa6398ddb3)) +- fix(mobile): answer push snapshot bridge calls at user-initiated QoS; report hop latency on callback timeout ([#8916](https://github.com/block/buzz/pull/8916)) ([`2bd491782534ea1885138a9927db91b308f93fa7`](https://github.com/block/buzz/commit/2bd491782534ea1885138a9927db91b308f93fa7)) +- test(mobile): lock in invite-page and bare-host community link entry ([#9047](https://github.com/block/buzz/pull/9047)) ([`46cdc52d234c92191a6b79de9cc20db4f14d74b3`](https://github.com/block/buzz/commit/46cdc52d234c92191a6b79de9cc20db4f14d74b3)) +- fix(db): end each table's maintenance transaction before the next ([#9096](https://github.com/block/buzz/pull/9096)) ([`4c7c15a9c2b91504c7d2c2562c8c75a667199f33`](https://github.com/block/buzz/commit/4c7c15a9c2b91504c7d2c2562c8c75a667199f33)) +- perf(mobile): show a static placeholder for posterless videos ([#9138](https://github.com/block/buzz/pull/9138)) ([`cec918ae7a13549ba113f4d6d50d71dcbe0daba2`](https://github.com/block/buzz/commit/cec918ae7a13549ba113f4d6d50d71dcbe0daba2)) +- fix(relay): read kind:39000/39001 inputs behind the replacement lock ([#9035](https://github.com/block/buzz/pull/9035)) ([`1a42b5c39cdebfc703004fec951790e363de9d9c`](https://github.com/block/buzz/commit/1a42b5c39cdebfc703004fec951790e363de9d9c)) +- fix(db): unlock the storage-accounting lease before its session closes ([#9097](https://github.com/block/buzz/pull/9097)) ([`580caca66714b3e09fd3e0eb2e522d6f4aa5cc12`](https://github.com/block/buzz/commit/580caca66714b3e09fd3e0eb2e522d6f4aa5cc12)) +- test(relay,db): remove three timing races from Postgres and E2E tests ([#9098](https://github.com/block/buzz/pull/9098)) ([`a22ff133b49a06a447ca341c12f00f335990c3b4`](https://github.com/block/buzz/commit/a22ff133b49a06a447ca341c12f00f335990c3b4)) +- fix(db): keep busy-reader history reads off the writer and cap them per pod ([#9132](https://github.com/block/buzz/pull/9132)) ([`47be2e2d3f2a438b3a5fd7df0c710b81d8c0d87e`](https://github.com/block/buzz/commit/47be2e2d3f2a438b3a5fd7df0c710b81d8c0d87e)) +- perf(mobile): memoize npub labels ([#9137](https://github.com/block/buzz/pull/9137)) ([`7ac16b2917bfb64b8142f06036274e83f3aa5d9f`](https://github.com/block/buzz/commit/7ac16b2917bfb64b8142f06036274e83f3aa5d9f)) +- mobile: stop re-parsing messages on every resume ([#9140](https://github.com/block/buzz/pull/9140)) ([`1ce831645c5f210f8fc7883bb9fc63dae6e52a12`](https://github.com/block/buzz/commit/1ce831645c5f210f8fc7883bb9fc63dae6e52a12)) +- fix(mobile): renew expired assertions for native media and drop retired-session avatars ([#9134](https://github.com/block/buzz/pull/9134)) ([`1b9b3071765fc5d9064b98738e5ad424d71ac427`](https://github.com/block/buzz/commit/1b9b3071765fc5d9064b98738e5ad424d71ac427)) +- perf(db): split newest-first events reads at a month floor so Postgres prunes partitions ([#9091](https://github.com/block/buzz/pull/9091)) ([`74abe2f0fe1a5341c8c7637b79569dd59176be27`](https://github.com/block/buzz/commit/74abe2f0fe1a5341c8c7637b79569dd59176be27)) +- fix(relay): bound mesh dials and keep failing pods out of the mesh ([#8752](https://github.com/block/buzz/pull/8752)) ([`9b4b73eb088dc18c58b4da8388436bea9c89fdb1`](https://github.com/block/buzz/commit/9b4b73eb088dc18c58b4da8388436bea9c89fdb1)) +- fix(mobile): send hosted relay assertion from native media and tombstone paths ([#9069](https://github.com/block/buzz/pull/9069)) ([`97ede701c0a10379fda53dbd36415f50a4611bbf`](https://github.com/block/buzz/commit/97ede701c0a10379fda53dbd36415f50a4611bbf)) +- fix(mobile): focus the search field when search opens ([#9120](https://github.com/block/buzz/pull/9120)) ([`6793cbd25b7f1fa0c3e4750423bbbf4039e2a279`](https://github.com/block/buzz/commit/6793cbd25b7f1fa0c3e4750423bbbf4039e2a279)) +- perf(mobile): validate each verified profile once, not on every publish ([#9101](https://github.com/block/buzz/pull/9101)) ([`9aa70124bae4f6763babd9daaacbc5157ce1fc56`](https://github.com/block/buzz/commit/9aa70124bae4f6763babd9daaacbc5157ce1fc56)) +- fix(mobile): offer a new identity beside saved keys on unclaimed accounts ([#9107](https://github.com/block/buzz/pull/9107)) ([`c848b6dcadee682ddc3415d81bc069a686028503`](https://github.com/block/buzz/commit/c848b6dcadee682ddc3415d81bc069a686028503)) +- fix(mobile): skip the read-state snapshot when nothing needs publishing ([#9093](https://github.com/block/buzz/pull/9093)) ([`dce37f74d787982ae8946cadff3f7144e7eca5f5`](https://github.com/block/buzz/commit/dce37f74d787982ae8946cadff3f7144e7eca5f5)) +- fix(mobile): keep verified names on screen in channels with over 1,024 members ([#9111](https://github.com/block/buzz/pull/9111)) ([`cf8fbbba55705a4330547e5045ff1253dd670289`](https://github.com/block/buzz/commit/cf8fbbba55705a4330547e5045ff1253dd670289)) +- mobile: reuse channel message rows that did not change ([#9115](https://github.com/block/buzz/pull/9115)) ([`244038b495290eec3050f37cae00c81e1e9c7cc0`](https://github.com/block/buzz/commit/244038b495290eec3050f37cae00c81e1e9c7cc0)) +- fix(mobile): back off push bootstrap retries ([#9092](https://github.com/block/buzz/pull/9092)) ([`3ff4154ca61c88dfc1ddcfef568d6d7eea2dbf9d`](https://github.com/block/buzz/commit/3ff4154ca61c88dfc1ddcfef568d6d7eea2dbf9d)) +- fix(mobile): keep reply counts on screen while a reconnect catches up ([#9100](https://github.com/block/buzz/pull/9100)) ([`e34acb0ac5dbd1a1247692bd81d6f80c6b5c0761`](https://github.com/block/buzz/commit/e34acb0ac5dbd1a1247692bd81d6f80c6b5c0761)) +- fix(mobile): inflate gzip read-state snapshot responses ([#9089](https://github.com/block/buzz/pull/9089)) ([`5e36d65c9e6462860c7296a425208643918e25e3`](https://github.com/block/buzz/commit/5e36d65c9e6462860c7296a425208643918e25e3)) +- perf(relay): cache the community-active check on socket admission ([#9109](https://github.com/block/buzz/pull/9109)) ([`50c10dc7b26e63dc8b02b6533b50727ce121b09c`](https://github.com/block/buzz/commit/50c10dc7b26e63dc8b02b6533b50727ce121b09c)) +- fix(db): auto-migrate prebuild-guarded indexes on small databases ([#8802](https://github.com/block/buzz/pull/8802)) ([`ff15c347c2f6cc688c163495125e849f85bbd55c`](https://github.com/block/buzz/commit/ff15c347c2f6cc688c163495125e849f85bbd55c)) +- docs(agents): add Review-Proven Rule 9, design client paths for the whole fleet ([#9106](https://github.com/block/buzz/pull/9106)) ([`bc99726f5c8994119822fabf92f8fae6da339324`](https://github.com/block/buzz/commit/bc99726f5c8994119822fabf92f8fae6da339324)) +- perf(db): serve single-root thread reply reads from thread_metadata ([#9075](https://github.com/block/buzz/pull/9075)) ([`aa749a862ef60887de5507b425a70f3024a6b61c`](https://github.com/block/buzz/commit/aa749a862ef60887de5507b425a70f3024a6b61c)) +- fix(mobile): send hosted relay auth with iOS custom emoji downloads ([#9056](https://github.com/block/buzz/pull/9056)) ([`6b8a72e8355125d24e4f4fab1e083dced4119f5c`](https://github.com/block/buzz/commit/6b8a72e8355125d24e4f4fab1e083dced4119f5c)) +- perf(mobile): keep covered pages still while the keyboard moves ([#8941](https://github.com/block/buzz/pull/8941)) ([`920b1e64bdd05c6605a2562b5b05618bc8bb264a`](https://github.com/block/buzz/commit/920b1e64bdd05c6605a2562b5b05618bc8bb264a)) +- feat(db): enforce unique listed channel names with an index ([#8787](https://github.com/block/buzz/pull/8787)) ([`700e69019321a927ce853f2572524bb6635b8834`](https://github.com/block/buzz/commit/700e69019321a927ce853f2572524bb6635b8834)) +- BUZZ-511: Honor relay mode for community NIP-FI enforcement ([#8988](https://github.com/block/buzz/pull/8988)) ([`64d12e29751981ad92ab3cc8edadaf3e3b5797f3`](https://github.com/block/buzz/commit/64d12e29751981ad92ab3cc8edadaf3e3b5797f3)) +- refactor(relay): remove database usage-metric queries ([#9040](https://github.com/block/buzz/pull/9040)) ([`506a588f889b6d010705a564e91fdfa1660c06e7`](https://github.com/block/buzz/commit/506a588f889b6d010705a564e91fdfa1660c06e7)) +- fix(mobile): restore keysForNsec after the native key derivation change ([#9085](https://github.com/block/buzz/pull/9085)) ([`34174214fcaf5dbb660380c89afaeeaca8280af1`](https://github.com/block/buzz/commit/34174214fcaf5dbb660380c89afaeeaca8280af1)) +- Mobile: one New chat screen ([#9079](https://github.com/block/buzz/pull/9079)) ([`e558f15faa49a5d9944ee7785b6fa31839ab5af9`](https://github.com/block/buzz/commit/e558f15faa49a5d9944ee7785b6fa31839ab5af9)) +- perf(mobile): skip re-decrypting read-state blobs ([#8966](https://github.com/block/buzz/pull/8966)) ([`237d794acbce5645b0bc7b2ff4856fb1969a70fe`](https://github.com/block/buzz/commit/237d794acbce5645b0bc7b2ff4856fb1969a70fe)) +- perf(mobile): derive keys natively and hash NIP-98 bodies faster ([#8965](https://github.com/block/buzz/pull/8965)) ([`9c5032b63bcf7de5b6623b8f1831b861b1d13923`](https://github.com/block/buzz/commit/9c5032b63bcf7de5b6623b8f1831b861b1d13923)) +- mobile: invite new users to create their first agent with a bold card ([#9036](https://github.com/block/buzz/pull/9036)) ([`5d44038ea544e6ca6921f8f497780a28a552521e`](https://github.com/block/buzz/commit/5d44038ea544e6ca6921f8f497780a28a552521e)) +- fix(mobile): streamline identity setup and community selection ([#9070](https://github.com/block/buzz/pull/9070)) ([`af54258f19ac32667c027f889652bdeb479c8e13`](https://github.com/block/buzz/commit/af54258f19ac32667c027f889652bdeb479c8e13)) +- Make mobile New DM and Add members pick recipients like mention autocomplete ([#9065](https://github.com/block/buzz/pull/9065)) ([`ec21753e1b4ca3cd0f208b5fb42cb22a1e29a433`](https://github.com/block/buzz/commit/ec21753e1b4ca3cd0f208b5fb42cb22a1e29a433)) +- fix(mobile): keep the composer focused through iOS inactive spells ([#9055](https://github.com/block/buzz/pull/9055)) ([`f09956179d5b1c7d604a4d746fffad048716686a`](https://github.com/block/buzz/commit/f09956179d5b1c7d604a4d746fffad048716686a)) +- fix(mobile): keep the iOS 27 header blur in long chats ([#8971](https://github.com/block/buzz/pull/8971)) ([`7157a55f5f3dc05a9fd9eee3b713ceefe3323794`](https://github.com/block/buzz/commit/7157a55f5f3dc05a9fd9eee3b713ceefe3323794)) +- fix(ios): saturate the push dedupe cutoff so extreme timestamps can't crash ([#9010](https://github.com/block/buzz/pull/9010)) ([`041956ea446c851dc0b0d2aacf35ced89f238616`](https://github.com/block/buzz/commit/041956ea446c851dc0b0d2aacf35ced89f238616)) +- fix(mobile): bound notices to loaded message history ([#9062](https://github.com/block/buzz/pull/9062)) ([`7b3c2f95f21720d52f524440fddad67ca4505a22`](https://github.com/block/buzz/commit/7b3c2f95f21720d52f524440fddad67ca4505a22)) +- Keep sign-in toasts usable at large text sizes ([#9057](https://github.com/block/buzz/pull/9057)) ([`99873459e940c210025d468b7ac40afb4b7316e0`](https://github.com/block/buzz/commit/99873459e940c210025d468b7ac40afb4b7316e0)) +- fix(mobile): use join template for community creation ([#9072](https://github.com/block/buzz/pull/9072)) ([`ce94656b0d81259e7f0ba88bae21d092ea8e900b`](https://github.com/block/buzz/commit/ce94656b0d81259e7f0ba88bae21d092ea8e900b)) +- feat(mobile): back up nsec to org builderlab account ([#9029](https://github.com/block/buzz/pull/9029)) ([`90de03aa63f3ba675573d7840564f22547681daa`](https://github.com/block/buzz/commit/90de03aa63f3ba675573d7840564f22547681daa)) +- relay: time every WebSocket read and every stored EVENT outcome ([#9052](https://github.com/block/buzz/pull/9052)) ([`4813b8cd15411355f05599e263ab15dd04e7afcc`](https://github.com/block/buzz/commit/4813b8cd15411355f05599e263ab15dd04e7afcc)) +- fix(loadgen): bound desktop reads at stop, keep timely EOSEs, model presence and probes ([#9016](https://github.com/block/buzz/pull/9016)) ([`25abfc41177b5b99e8aa21b33c400c3c33d5f3d7`](https://github.com/block/buzz/commit/25abfc41177b5b99e8aa21b33c400c3c33d5f3d7)) +- Restyle mobile organization sign-in prompts as toasts ([#9050](https://github.com/block/buzz/pull/9050)) ([`5b738eb647fb793057bcfe11638a5a1781b2dd76`](https://github.com/block/buzz/commit/5b738eb647fb793057bcfe11638a5a1781b2dd76)) +- mobile: simplify verified profiles and prioritize full names ([#9051](https://github.com/block/buzz/pull/9051)) ([`0bdad8ea965d17926a86dcfbcf3f9a2778062a34`](https://github.com/block/buzz/commit/0bdad8ea965d17926a86dcfbcf3f9a2778062a34)) +- mobile: refine message avatars, metadata and reply gestures ([#9046](https://github.com/block/buzz/pull/9046)) ([`49fcab3324549cba9043b661c4fd0acf0f980a03`](https://github.com/block/buzz/commit/49fcab3324549cba9043b661c4fd0acf0f980a03)) +- mobile: start new agents on Sonnet at medium effort ([#9034](https://github.com/block/buzz/pull/9034)) ([`0dd778f800afbecc1887788ce614b57f13d664f5`](https://github.com/block/buzz/commit/0dd778f800afbecc1887788ce614b57f13d664f5)) +- fix(mobile): close the community switcher when the org relay refuses the key ([#9042](https://github.com/block/buzz/pull/9042)) ([`f04fa0904c99df3e7c0a1ba29faf945cbce3c6e1`](https://github.com/block/buzz/commit/f04fa0904c99df3e7c0a1ba29faf945cbce3c6e1)) +- fix(mobile): show organization sign-in after pairing ([#9028](https://github.com/block/buzz/pull/9028)) ([`ba7d7825ea8e109af532e9c9c9855b3485f13a82`](https://github.com/block/buzz/commit/ba7d7825ea8e109af532e9c9c9855b3485f13a82)) +- fix(mobile): show progress after pairing QR scans ([#9009](https://github.com/block/buzz/pull/9009)) ([`14037e32780ec8be103ec4caa42fb57adc731d60`](https://github.com/block/buzz/commit/14037e32780ec8be103ec4caa42fb57adc731d60)) +- fix(mobile): show a taken channel name plainly and keep invites working ([#8807](https://github.com/block/buzz/pull/8807)) ([`1055f79d048ef22c878d02a7afb04f49c753564f`](https://github.com/block/buzz/commit/1055f79d048ef22c878d02a7afb04f49c753564f)) +- mobile: tap the settings version footer to copy it ([#9021](https://github.com/block/buzz/pull/9021)) ([`38a5d9a1ffe27c8f403dd0b4d1c8aa408a474d40`](https://github.com/block/buzz/commit/38a5d9a1ffe27c8f403dd0b4d1c8aa408a474d40)) +- feat(relay): match verified names in profile search ([#9019](https://github.com/block/buzz/pull/9019)) ([`3d26ed7dfdd237f99bb65b623070d546384c2538`](https://github.com/block/buzz/commit/3d26ed7dfdd237f99bb65b623070d546384c2538)) +- fix(mobile): stop QR pairing to organization relays from hanging ([#9001](https://github.com/block/buzz/pull/9001)) ([`83d0bd32034e4684836b10d0854e107c410c1e39`](https://github.com/block/buzz/commit/83d0bd32034e4684836b10d0854e107c410c1e39)) +- fix(mobile): show newly created remote agents in the new-chat picker ([#9030](https://github.com/block/buzz/pull/9030)) ([`1bef1da77d4ca31be54ee5b176a83986733c2099`](https://github.com/block/buzz/commit/1bef1da77d4ca31be54ee5b176a83986733c2099)) +- docs(nip-fa): define agent grant, assertion and revocation routes ([#9015](https://github.com/block/buzz/pull/9015)) ([`b14899ffb1d26aca96a0d0369cb3f39c7ba2b2f4`](https://github.com/block/buzz/commit/b14899ffb1d26aca96a0d0369cb3f39c7ba2b2f4)) +- fix(db): use ScratchDb in the storage usage delivery test ([#9032](https://github.com/block/buzz/pull/9032)) ([`865b150371d4e15562d63f0e9837bca0c32540d7`](https://github.com/block/buzz/commit/865b150371d4e15562d63f0e9837bca0c32540d7)) +- mobile: hide self-joins and leaves, collapse membership runs like desktop ([#8962](https://github.com/block/buzz/pull/8962)) ([`9f88eb9c459d671fad7811d442a1dd436389f195`](https://github.com/block/buzz/commit/9f88eb9c459d671fad7811d442a1dd436389f195)) +- feat(mobile): persist frontier-only NIP-RS read state across devices and restarts ([#8998](https://github.com/block/buzz/pull/8998)) ([`dafe31bfe5507b49cb204c1bf18134c71bac8bb1`](https://github.com/block/buzz/commit/dafe31bfe5507b49cb204c1bf18134c71bac8bb1)) +- feat(relay): log reads, logins and connections on access target ([#8376](https://github.com/block/buzz/pull/8376)) ([`0a06c0b3cb1741447c122a4f2275ca4ee541014b`](https://github.com/block/buzz/commit/0a06c0b3cb1741447c122a4f2275ca4ee541014b)) +- feat(relay): push per-community storage usage to kgoose ([#8714](https://github.com/block/buzz/pull/8714)) ([`fa7a3bfbda8300d4d9686c1d45ecd1ee649dd443`](https://github.com/block/buzz/commit/fa7a3bfbda8300d4d9686c1d45ecd1ee649dd443)) +- fix(mobile): size reply labels correctly with Bold Text ([#9013](https://github.com/block/buzz/pull/9013)) ([`8312419652d9e5ad5dbaae9c2a8e83b4e95f0961`](https://github.com/block/buzz/commit/8312419652d9e5ad5dbaae9c2a8e83b4e95f0961)) +- fix(relay): stop logging unmapped-host NIP-FI denials as server failures ([#8997](https://github.com/block/buzz/pull/8997)) ([`6847882b149f88f044064887791f47a488833fa0`](https://github.com/block/buzz/commit/6847882b149f88f044064887791f47a488833fa0)) +- Open the new Bestie's chat after creating it ([#8972](https://github.com/block/buzz/pull/8972)) ([`c24b0f472e47514faff5dba64027535569d30ad6`](https://github.com/block/buzz/commit/c24b0f472e47514faff5dba64027535569d30ad6)) +- feat(loadgen): model desktop clients and large-community shape ([#9005](https://github.com/block/buzz/pull/9005)) ([`152441ae0a56b204b42b6faa56a36ad2b98218b1`](https://github.com/block/buzz/commit/152441ae0a56b204b42b6faa56a36ad2b98218b1)) +- fix(relay): apply kind 5 / 9005 deletions atomically ([#8944](https://github.com/block/buzz/pull/8944)) ([`88697f1c597cda5790d4c702520d0651c48496c0`](https://github.com/block/buzz/commit/88697f1c597cda5790d4c702520d0651c48496c0)) +- fix(db): drop a superseded head's mention rows with it ([#8948](https://github.com/block/buzz/pull/8948)) ([`b8b425e8b1bf3d6895afeba702929d7dc0bc64d5`](https://github.com/block/buzz/commit/b8b425e8b1bf3d6895afeba702929d7dc0bc64d5)) +- perf(db): bind the channel scope as one array ([#8946](https://github.com/block/buzz/pull/8946)) ([`298a555e341ff7cf8faaefd833d6c6022bab6a4c`](https://github.com/block/buzz/commit/298a555e341ff7cf8faaefd833d6c6022bab6a4c)) +- feat(relay): record NIP-FI enforce denials at parity with shadow ([#8974](https://github.com/block/buzz/pull/8974)) ([`f6198f699750a8e99b59c93df29cc7d0c325892a`](https://github.com/block/buzz/commit/f6198f699750a8e99b59c93df29cc7d0c325892a)) +- fix(ios): mint NIP-FI assertions in the notification extension ([#8982](https://github.com/block/buzz/pull/8982)) ([`bf13f7c83bdd871828e9cb4b9be5e03197de84c6`](https://github.com/block/buzz/commit/bf13f7c83bdd871828e9cb4b9be5e03197de84c6)) +- Enable incremental artifact reads on every relay ([#8975](https://github.com/block/buzz/pull/8975)) ([`a9aa1f73b01b37cccaaa60b615625c2fe64315ff`](https://github.com/block/buzz/commit/a9aa1f73b01b37cccaaa60b615625c2fe64315ff)) +- fix(relay): send membership notices on channel delete, moderation kick and moderation DM ([#8977](https://github.com/block/buzz/pull/8977)) ([`ce47aefdc3fc9b9c845eaf047a8335a421f14580`](https://github.com/block/buzz/commit/ce47aefdc3fc9b9c845eaf047a8335a421f14580)) +- fix(ios): stop repeating an old message in push notifications ([#8973](https://github.com/block/buzz/pull/8973)) ([`7d40a661264ff4453128413fd55f30b1e02fc5be`](https://github.com/block/buzz/commit/7d40a661264ff4453128413fd55f30b1e02fc5be)) +- perf(mobile): evict verified-profile interest in one pass ([#9007](https://github.com/block/buzz/pull/9007)) ([`40fe4b5d9a98f81230369eec3f1bfcba737d2dd1`](https://github.com/block/buzz/commit/40fe4b5d9a98f81230369eec3f1bfcba737d2dd1)) +- fix(mobile): let users sign out after leaving all communities ([#8993](https://github.com/block/buzz/pull/8993)) ([`33eaa73c8313ff1520b8e25fd33c4f0e1c04f58f`](https://github.com/block/buzz/commit/33eaa73c8313ff1520b8e25fd33c4f0e1c04f58f)) +- perf(search): rank only the newest prefix matches and plan with the real tsquery ([#8976](https://github.com/block/buzz/pull/8976)) ([`d3a4909ccad7c75a8c13ca91ccdaffd2c83024df`](https://github.com/block/buzz/commit/d3a4909ccad7c75a8c13ca91ccdaffd2c83024df)) +- fix(mobile): restore ordinary DM behavior for Bestie ([#8987](https://github.com/block/buzz/pull/8987)) ([`3f03aa0450854625da69aacdeea6a77b4f32bd86`](https://github.com/block/buzz/commit/3f03aa0450854625da69aacdeea6a77b4f32bd86)) +- Modernize mobile channel and DM creation sheets ([#8942](https://github.com/block/buzz/pull/8942)) ([`a66cb5f7ab77427e59ca100d447cb1e4a32041b0`](https://github.com/block/buzz/commit/a66cb5f7ab77427e59ca100d447cb1e4a32041b0)) +- Add mobile Bestie onboarding and fix remote agent presence ([#8957](https://github.com/block/buzz/pull/8957)) ([`344f007f364c9c4198ff7277d9f1e3e3d4ee93db`](https://github.com/block/buzz/commit/344f007f364c9c4198ff7277d9f1e3e3d4ee93db)) +- perf(mobile): evict verified-profile interest in constant time ([#8931](https://github.com/block/buzz/pull/8931)) ([`0e5a69962e5cbe5e81ea46b557770ce27a120a14`](https://github.com/block/buzz/commit/0e5a69962e5cbe5e81ea46b557770ce27a120a14)) +- perf(relay): cut writer-pool round trips past the 48k relay ceiling ([#8846](https://github.com/block/buzz/pull/8846)) ([`d44031f4187b285dad9b367c114f017c7858df9b`](https://github.com/block/buzz/commit/d44031f4187b285dad9b367c114f017c7858df9b)) +- fix(search): skip message prefix search below three characters ([#8947](https://github.com/block/buzz/pull/8947)) ([`d005c7bb9cff17bc7fd44587f5586e08f67e21cf`](https://github.com/block/buzz/commit/d005c7bb9cff17bc7fd44587f5586e08f67e21cf)) +- perf(mobile): cheaper identity-name rebuilds for large rosters ([#8936](https://github.com/block/buzz/pull/8936)) ([`58eb36dd5791c1bc93c7f373db3d58cc2468b39a`](https://github.com/block/buzz/commit/58eb36dd5791c1bc93c7f373db3d58cc2468b39a)) +- perf(mobile): stop re-parsing message markdown on every rebuild ([#8928](https://github.com/block/buzz/pull/8928)) ([`369e1ef3229d5f8b49cae9ba111f72ff5dc55baf`](https://github.com/block/buzz/commit/369e1ef3229d5f8b49cae9ba111f72ff5dc55baf)) +- perf(mobile): verify owned-agent registrations natively ([#8938](https://github.com/block/buzz/pull/8938)) ([`eee75a1c7ba1520571cdb432baa51fc4ea7367bd`](https://github.com/block/buzz/commit/eee75a1c7ba1520571cdb432baa51fc4ea7367bd)) +- perf(mobile): build composer channel names once per channel list ([#8943](https://github.com/block/buzz/pull/8943)) ([`cad7f1d53d2c81a86835fcc26ac06cfb5e29e697`](https://github.com/block/buzz/commit/cad7f1d53d2c81a86835fcc26ac06cfb5e29e697)) +- perf(mobile): format a channel timeline only when its events change ([#8929](https://github.com/block/buzz/pull/8929)) ([`fc9e652c0ee83537b844922747074394bd210d7a`](https://github.com/block/buzz/commit/fc9e652c0ee83537b844922747074394bd210d7a)) +- docs(mobile): recommend Xcode 27.1 ([#8949](https://github.com/block/buzz/pull/8949)) ([`478cf0a97e4eb0ffb6300e96dbb88b16689962b8`](https://github.com/block/buzz/commit/478cf0a97e4eb0ffb6300e96dbb88b16689962b8)) +- mobile: hold a queued list read for the 10s gap ([#8958](https://github.com/block/buzz/pull/8958)) ([`76bc66acfcaebda487813b2495adf8fec82c0b8a`](https://github.com/block/buzz/commit/76bc66acfcaebda487813b2495adf8fec82c0b8a)) +- fix(mobile): drop the # from Solo chat names in push notifications ([#8955](https://github.com/block/buzz/pull/8955)) ([`ff6ab96e42b1fc64bfc1236104478a84e11b5abd`](https://github.com/block/buzz/commit/ff6ab96e42b1fc64bfc1236104478a84e11b5abd)) +- fix(mobile): allow community removal without a cached push grant ([#8978](https://github.com/block/buzz/pull/8978)) ([`972e89ac8972552f68efca53349f86104f6c7e0e`](https://github.com/block/buzz/commit/972e89ac8972552f68efca53349f86104f6c7e0e)) +- fix(mobile): label community switching consistently ([#8979](https://github.com/block/buzz/pull/8979)) ([`09b21cbe632ca35b096fa7dff43ebbab06518ba1`](https://github.com/block/buzz/commit/09b21cbe632ca35b096fa7dff43ebbab06518ba1)) +- fix(mobile): make the Join button readable in dark mode ([#8969](https://github.com/block/buzz/pull/8969)) ([`6684f7e2f0dc2add9c6fcb05736af76f03fb71aa`](https://github.com/block/buzz/commit/6684f7e2f0dc2add9c6fcb05736af76f03fb71aa)) +- fix(loadgen): sign public URLs when dialling connect_addr in plaintext ([#8926](https://github.com/block/buzz/pull/8926)) ([`83bd8b1caed7b86d4edf61ec413d82f7110b8cf6`](https://github.com/block/buzz/commit/83bd8b1caed7b86d4edf61ec413d82f7110b8cf6)) +- fix(mobile): show the Join prompt when an invite launches Buzz ([#8970](https://github.com/block/buzz/pull/8970)) ([`1c143a40b77a05917e8cfd47b60d4d5dc66f0d5b`](https://github.com/block/buzz/commit/1c143a40b77a05917e8cfd47b60d4d5dc66f0d5b)) +- fix(mobile): retry failed channel searches after reconnecting ([#8968](https://github.com/block/buzz/pull/8968)) ([`205ff47744bd7a2dc542346b900a06363fb57f67`](https://github.com/block/buzz/commit/205ff47744bd7a2dc542346b900a06363fb57f67)) +- fix(mobile): let starter setup retry after a connection failure ([#8967](https://github.com/block/buzz/pull/8967)) ([`cdd2af1a35257ec8789acde2f99df89ac6e855d4`](https://github.com/block/buzz/commit/cdd2af1a35257ec8789acde2f99df89ac6e855d4)) +- fix(mobile): open consent for scanned and pasted invites ([#8952](https://github.com/block/buzz/pull/8952)) ([`0ec74838a5bd29f29346ee9319a6f49c755a1e34`](https://github.com/block/buzz/commit/0ec74838a5bd29f29346ee9319a6f49c755a1e34)) +- db: recycle pool connections after 5 minutes instead of 30 ([#8951](https://github.com/block/buzz/pull/8951)) ([`46da35810d6575f63a92ce5917c5abc901b29f52`](https://github.com/block/buzz/commit/46da35810d6575f63a92ce5917c5abc901b29f52)) +- fix(relay): cap bridge searches in flight per user ([#8956](https://github.com/block/buzz/pull/8956)) ([`02925ceb6e7318f2214de274050825bb1da6477c`](https://github.com/block/buzz/commit/02925ceb6e7318f2214de274050825bb1da6477c)) +- fix(search): cancel abandoned searches and bound the search pool ([#8954](https://github.com/block/buzz/pull/8954)) ([`949f61dfab060fa12e83f63c210b0cecd8c3ce2c`](https://github.com/block/buzz/commit/949f61dfab060fa12e83f63c210b0cecd8c3ce2c)) +- perf(mobile): read the channel list after live changes, not every minute ([#8910](https://github.com/block/buzz/pull/8910)) ([`009dc103f61582dbed5dcd84697365518a5fcf71`](https://github.com/block/buzz/commit/009dc103f61582dbed5dcd84697365518a5fcf71)) +- feat(mobile): open a prefilled Create agent form from Builderlab agent cards ([#8912](https://github.com/block/buzz/pull/8912)) ([`fa395e9e80e3201f0d9cdde87d18b211a095478d`](https://github.com/block/buzz/commit/fa395e9e80e3201f0d9cdde87d18b211a095478d)) +- fix(mobile): open unjoined channels from links and search results ([#8923](https://github.com/block/buzz/pull/8923)) ([`61b8455a3c2680a129c887421b4280d30541bf7c`](https://github.com/block/buzz/commit/61b8455a3c2680a129c887421b4280d30541bf7c)) +- docs(mobile): describe the role split in the media image keys ([#8932](https://github.com/block/buzz/pull/8932)) ([`97ff4e19d15ba9b653991c0ccee385650cbe8aed`](https://github.com/block/buzz/commit/97ff4e19d15ba9b653991c0ccee385650cbe8aed)) +- fix(db): preserve partition reader grants ([#8485](https://github.com/block/buzz/pull/8485)) ([`8f83c6320994be69f486ba42bf69cea6d8bb9df8`](https://github.com/block/buzz/commit/8f83c6320994be69f486ba42bf69cea6d8bb9df8)) +- fix(mobile): split escaped voice-note links into their own segment ([#8940](https://github.com/block/buzz/pull/8940)) ([`35df866b334c905559e10caf0ea2ea56ee1886ee`](https://github.com/block/buzz/commit/35df866b334c905559e10caf0ea2ea56ee1886ee)) +- fix(mobile): let the issuer choose relay assertion lifetime ([#8935](https://github.com/block/buzz/pull/8935)) ([`b5b69d3de8e964c57a2d3598a627224064628cac`](https://github.com/block/buzz/commit/b5b69d3de8e964c57a2d3598a627224064628cac)) +- fix(mobile): load earlier edits to thread replies when a thread opens ([#8870](https://github.com/block/buzz/pull/8870)) ([`2fd5c122e8bb6d826549d070cb918747a95432ac`](https://github.com/block/buzz/commit/2fd5c122e8bb6d826549d070cb918747a95432ac)) +- fix(mobile): render Markdown backslash escapes ([#8925](https://github.com/block/buzz/pull/8925)) ([`54ca2a3cc6b8f163cda6571c91b93d983594b4bd`](https://github.com/block/buzz/commit/54ca2a3cc6b8f163cda6571c91b93d983594b4bd)) +- fix(relay): refuse a second listed open channel with the same name ([#8782](https://github.com/block/buzz/pull/8782)) ([`5f8d0aab98298f05b8676c1176d693e8db2c89d6`](https://github.com/block/buzz/commit/5f8d0aab98298f05b8676c1176d693e8db2c89d6)) +- docs(nip-fa): make assertion lifetime issuer operator policy ([#8934](https://github.com/block/buzz/pull/8934)) ([`f1ce1c5d47443ce250ccec6d0277e94b3a6b62ed`](https://github.com/block/buzz/commit/f1ce1c5d47443ce250ccec6d0277e94b3a6b62ed)) +- fix(mobile): open the public Builderlab login the iOS bridge allows ([#8914](https://github.com/block/buzz/pull/8914)) ([`da93ce3f6290df374a8b1e78ebedf5a2d28c85ae`](https://github.com/block/buzz/commit/da93ce3f6290df374a8b1e78ebedf5a2d28c85ae)) +- fix(mobile): hide the Flutter debug banner ([#8915](https://github.com/block/buzz/pull/8915)) ([`3ae2b6a3771bf667d4f7015a95971140beba5fa7`](https://github.com/block/buzz/commit/3ae2b6a3771bf667d4f7015a95971140beba5fa7)) +- mobile: keep a thumbnail fallback apart from a direct load of the same URL ([#8913](https://github.com/block/buzz/pull/8913)) ([`9f8913dd1b8647589c1c8452137fb3502176b1bf`](https://github.com/block/buzz/commit/9f8913dd1b8647589c1c8452137fb3502176b1bf)) +- fix(mobile): prompt Builderlab sign-in instead of labeling agents desktop-only ([#8907](https://github.com/block/buzz/pull/8907)) ([`daeb463f37fc7dfe27ba3c6ff33588e9b56ac81c`](https://github.com/block/buzz/commit/daeb463f37fc7dfe27ba3c6ff33588e9b56ac81c)) +- feat(mobile): add Buzzies and refresh agent avatar picker ([#8921](https://github.com/block/buzz/pull/8921)) ([`b4509dee8b5aba6649dde0572e89049f11d16c29`](https://github.com/block/buzz/commit/b4509dee8b5aba6649dde0572e89049f11d16c29)) +- fix(deps): clear RUSTSEC-2026-0433 and RUSTSEC-2026-0429 from the dependency policy ([#8922](https://github.com/block/buzz/pull/8922)) ([`c9b8f1176ecef588d3607ed2402d0e97ef365206`](https://github.com/block/buzz/commit/c9b8f1176ecef588d3607ed2402d0e97ef365206)) +- test(relay): hold the replica's second aux page and move media's DB tests ([#8740](https://github.com/block/buzz/pull/8740)) ([`322fdbf086cd5fc6a7a528236446c68f372145b5`](https://github.com/block/buzz/commit/322fdbf086cd5fc6a7a528236446c68f372145b5)) +- fix(mobile): catch up unread from the newest message already seen ([#8901](https://github.com/block/buzz/pull/8901)) ([`d342cf141cb3211c8e5a6c74f881cf1d39ad3b12`](https://github.com/block/buzz/commit/d342cf141cb3211c8e5a6c74f881cf1d39ad3b12)) +- fix(mobile): resync read state from the last fetch, not the whole week ([#8903](https://github.com/block/buzz/pull/8903)) ([`464448c7b2aecb207158b0cac504fa72ad512a84`](https://github.com/block/buzz/commit/464448c7b2aecb207158b0cac504fa72ad512a84)) +- fix(mobile): show remote agent instructions from the registry ([#8908](https://github.com/block/buzz/pull/8908)) ([`9d1b6844557252bf1d78037d595cf9dd3083cbec`](https://github.com/block/buzz/commit/9d1b6844557252bf1d78037d595cf9dd3083cbec)) +- feat(mobile): show NIP-FI verified names ([#8858](https://github.com/block/buzz/pull/8858)) ([`985de41f146298418484a81d3f1fcd961e1703a4`](https://github.com/block/buzz/commit/985de41f146298418484a81d3f1fcd961e1703a4)) +- fix(mobile): keep community icons on originals and record thumbnail 404s at fetch ([#8896](https://github.com/block/buzz/pull/8896)) ([`220cec677a324884ea0bd10ee52cdcf29867e17d`](https://github.com/block/buzz/commit/220cec677a324884ea0bd10ee52cdcf29867e17d)) +- chore(mobile): delete dead code with no remaining UI path ([#8880](https://github.com/block/buzz/pull/8880)) ([`f6f6d9a673b50ef02a9108a486f65e93599c541a`](https://github.com/block/buzz/commit/f6f6d9a673b50ef02a9108a486f65e93599c541a)) +- fix(mobile): let slow image downloads finish ([#8881](https://github.com/block/buzz/pull/8881)) ([`2e0abbcc0c3a74bfc9d88a1f9c324893f45723a7`](https://github.com/block/buzz/commit/2e0abbcc0c3a74bfc9d88a1f9c324893f45723a7)) +- fix(mobile): show Bestie as a continuous conversation ([#8890](https://github.com/block/buzz/pull/8890)) ([`76fd0c6151a5248e5cfaa94ab4c6ca8090398d76`](https://github.com/block/buzz/commit/76fd0c6151a5248e5cfaa94ab4c6ca8090398d76)) +- fix(mobile): keep mention rows still and cache directory searches ([#8875](https://github.com/block/buzz/pull/8875)) ([`53ca047cd3ea218813c833fefda5236288f4905c`](https://github.com/block/buzz/commit/53ca047cd3ea218813c833fefda5236288f4905c)) +- Standardize mobile navigation edges ([#8895](https://github.com/block/buzz/pull/8895)) ([`93b8b8febc85b91f1fb9e4dc1f8203778d438c10`](https://github.com/block/buzz/commit/93b8b8febc85b91f1fb9e4dc1f8203778d438c10)) +- Mobile: open Solo chats with Bestie and workspace controls ([#8884](https://github.com/block/buzz/pull/8884)) ([`634f48a8bda15b1a5509be56fccbc9b5254301c8`](https://github.com/block/buzz/commit/634f48a8bda15b1a5509be56fccbc9b5254301c8)) +- Fix mobile unread state retaining deleted messages ([#8883](https://github.com/block/buzz/pull/8883)) ([`21a9839826bad5861ef9be5df50910d3df04e1c9`](https://github.com/block/buzz/commit/21a9839826bad5861ef9be5df50910d3df04e1c9)) +- fix(mobile): fill uploaded avatars on the Agents page ([#8882](https://github.com/block/buzz/pull/8882)) ([`e18d422d7260d3faffb211c870510a5d6d51a7fd`](https://github.com/block/buzz/commit/e18d422d7260d3faffb211c870510a5d6d51a7fd)) +- fix(mobile): keep avatars and images loading on slow links ([#8879](https://github.com/block/buzz/pull/8879)) ([`90772a43e9994d00c8786ce0f0f89485a2023394`](https://github.com/block/buzz/commit/90772a43e9994d00c8786ce0f0f89485a2023394)) +- fix(mobile): list the same owned agents as desktop ([#8857](https://github.com/block/buzz/pull/8857)) ([`543ecf2b1f239beedeca0c72d7eaa6262523e763`](https://github.com/block/buzz/commit/543ecf2b1f239beedeca0c72d7eaa6262523e763)) +- fix(mobile): time out relay connects that never finish the handshake ([#8878](https://github.com/block/buzz/pull/8878)) ([`b41caeb5100bafcb8f4611909e4f42bf6dd40faa`](https://github.com/block/buzz/commit/b41caeb5100bafcb8f4611909e4f42bf6dd40faa)) +- mobile: quiet agent messages and caught-up channel highlights ([#8876](https://github.com/block/buzz/pull/8876)) ([`5f98a1fa0424228597e13085398be36a858d8005`](https://github.com/block/buzz/commit/5f98a1fa0424228597e13085398be36a858d8005)) +- fix(mobile): show hosted community names consistently ([#8872](https://github.com/block/buzz/pull/8872)) ([`83ec9c0e2b5105111ca3fac3902fb5e00b63b93e`](https://github.com/block/buzz/commit/83ec9c0e2b5105111ca3fac3902fb5e00b63b93e)) +- fix(mobile): keep loaded timeline visible while reconnecting ([#8864](https://github.com/block/buzz/pull/8864)) ([`e71fbe23df5c776be87d243a548c5ab7c9c1c346`](https://github.com/block/buzz/commit/e71fbe23df5c776be87d243a548c5ab7c9c1c346)) +- fix(mobile): find open channels in search and stop the stuck spinner ([#8764](https://github.com/block/buzz/pull/8764)) ([`2e4aacc9e05b88f2ab6327a29e123e1b8af4e382`](https://github.com/block/buzz/commit/2e4aacc9e05b88f2ab6327a29e123e1b8af4e382)) +- feat(mobile): organization sign-in for NIP-FI relays ([#8700](https://github.com/block/buzz/pull/8700)) ([`db4478e8d2d8d0fd6582db7ae152e41d3e67e447`](https://github.com/block/buzz/commit/db4478e8d2d8d0fd6582db7ae152e41d3e67e447)) +- fix(mobile): use the desktop agent squircle for every agent avatar ([#8873](https://github.com/block/buzz/pull/8873)) ([`acf56fff6fbfece9f143de3f096cb1d258fb9a9f`](https://github.com/block/buzz/commit/acf56fff6fbfece9f143de3f096cb1d258fb9a9f)) +- Fix mobile onboarding policy loading, browser cancellation and pairing feedback ([#8874](https://github.com/block/buzz/pull/8874)) ([`f59b3265682f82d4eafb7d5c5ef484acedf9b098`](https://github.com/block/buzz/commit/f59b3265682f82d4eafb7d5c5ef484acedf9b098)) +- feat(mobile): refine agent profiles and model selection ([#8773](https://github.com/block/buzz/pull/8773)) ([`a12ad1cdd29da8b2923eca5408e963a2659777ab`](https://github.com/block/buzz/commit/a12ad1cdd29da8b2923eca5408e963a2659777ab)) +- Align Android profile setup with iOS steps ([#8871](https://github.com/block/buzz/pull/8871)) ([`a2540fbe3d8a1c934073c28b95d53deeac911327`](https://github.com/block/buzz/commit/a2540fbe3d8a1c934073c28b95d53deeac911327)) +- fix(mobile): only render known channels as #channel chips ([#8862](https://github.com/block/buzz/pull/8862)) ([`20742a236db91a4480ff5e3a5574c41136ef7347`](https://github.com/block/buzz/commit/20742a236db91a4480ff5e3a5574c41136ef7347)) +- docs(agents): mark desktop/ as legacy, not a reference for mobile ([#8868](https://github.com/block/buzz/pull/8868)) ([`e3b1ef0d843e0639ed82cd4a500626f7c56b6531`](https://github.com/block/buzz/commit/e3b1ef0d843e0639ed82cd4a500626f7c56b6531)) +- fix(mobile): end #channel tokens at apostrophes, quotes and dashes ([#8860](https://github.com/block/buzz/pull/8860)) ([`b80217de32673dc55c5949dd492578e9bdcb0d32`](https://github.com/block/buzz/commit/b80217de32673dc55c5949dd492578e9bdcb0d32)) +- fix(mobile): keep toasts above native navigation and sheets ([#8866](https://github.com/block/buzz/pull/8866)) ([`d14f33a17088600a947ea23a19416e461152737b`](https://github.com/block/buzz/commit/d14f33a17088600a947ea23a19416e461152737b)) +- fix(mobile): restore inline typing groups and keep working thread links ([#8865](https://github.com/block/buzz/pull/8865)) ([`120cbae8e56fe831137ff5894be5a284b862f213`](https://github.com/block/buzz/commit/120cbae8e56fe831137ff5894be5a284b862f213)) +- Fade welcome bees with the QR scanner transition ([#8859](https://github.com/block/buzz/pull/8859)) ([`0a46f329c0ba757fa59cb9de297e19e7d8949dd5`](https://github.com/block/buzz/commit/0a46f329c0ba757fa59cb9de297e19e7d8949dd5)) +- Fix mobile Add Community loading and membership restoration ([#8796](https://github.com/block/buzz/pull/8796)) ([`2ca77747d11bea5fa8896d49c6dfefc8bd5400bc`](https://github.com/block/buzz/commit/2ca77747d11bea5fa8896d49c6dfefc8bd5400bc)) +- Update mobile toast animations ([#8855](https://github.com/block/buzz/pull/8855)) ([`cfcaef4e9fb562ff0acd4ed749464bdd733fdfc8`](https://github.com/block/buzz/commit/cfcaef4e9fb562ff0acd4ed749464bdd733fdfc8)) +- Bring buzz.xyz branding and animated bees to mobile welcome ([#8853](https://github.com/block/buzz/pull/8853)) ([`5f13984a1950e38e106c90fee61e9cc84a5c1085`](https://github.com/block/buzz/commit/5f13984a1950e38e106c90fee61e9cc84a5c1085)) +- Simplify mobile Solo and DM empty states ([#8851](https://github.com/block/buzz/pull/8851)) ([`4de1b6aeac3e77b8675e1ba5ba407eaa6c3da216`](https://github.com/block/buzz/commit/4de1b6aeac3e77b8675e1ba5ba407eaa6c3da216)) +- Simplify signed-in mobile community onboarding ([#8852](https://github.com/block/buzz/pull/8852)) ([`9c3ba83adbce8ec94d1ce435f2e84689956eec20`](https://github.com/block/buzz/commit/9c3ba83adbce8ec94d1ce435f2e84689956eec20)) +- ci: bound Hermit fetches and let relay builds run without sccache ([#8739](https://github.com/block/buzz/pull/8739)) ([`eafd77e9f6e96052476bdd88be732c046fdb7ab3`](https://github.com/block/buzz/commit/eafd77e9f6e96052476bdd88be732c046fdb7ab3)) +- fix(mobile): show channel posts before a burst of join notices ([#8798](https://github.com/block/buzz/pull/8798)) ([`547de61aa5fed28003c2d79e1720dfaaeae297c7`](https://github.com/block/buzz/commit/547de61aa5fed28003c2d79e1720dfaaeae297c7)) +- test(mobile): check the title fade's animation, wait 10 s for the alert ([#8741](https://github.com/block/buzz/pull/8741)) ([`6e6f4e8a0de2ee85c4a6366ecdb15e1fad7fe429`](https://github.com/block/buzz/commit/6e6f4e8a0de2ee85c4a6366ecdb15e1fad7fe429)) +- test(db): drop scratch databases and roles even when a test fails ([#8747](https://github.com/block/buzz/pull/8747)) ([`b7b545f090bfa17c23317f243becc15f807b636d`](https://github.com/block/buzz/commit/b7b545f090bfa17c23317f243becc15f807b636d)) +- feat(mobile): show conversation activity by the composer, as buzz-app does ([#8765](https://github.com/block/buzz/pull/8765)) ([`aa5f3e7bde9cf4412d6494e6a89a0d49e9a6a8f2`](https://github.com/block/buzz/commit/aa5f3e7bde9cf4412d6494e6a89a0d49e9a6a8f2)) +- feat(mobile): show your agents working in a thread on its root message ([#8754](https://github.com/block/buzz/pull/8754)) ([`851250524efef576f16b21c423c9ec272595da91`](https://github.com/block/buzz/commit/851250524efef576f16b21c423c9ec272595da91)) +- Clarify mobile community onboarding and saved identity selection ([#8729](https://github.com/block/buzz/pull/8729)) ([`f3a7bab098a530ba12b909cb7121b4fa9ce70731`](https://github.com/block/buzz/commit/f3a7bab098a530ba12b909cb7121b4fa9ce70731)) +- Add Buzz background and flying bees to invitations ([#8763](https://github.com/block/buzz/pull/8763)) ([`0c82435ae0ad37920b162742490ec48aae15fd8c`](https://github.com/block/buzz/commit/0c82435ae0ad37920b162742490ec48aae15fd8c)) +- Polish mobile navigation and restore community switch animation ([#8732](https://github.com/block/buzz/pull/8732)) ([`c0c606e2e3ee01f959d804698caf74b455ee08f1`](https://github.com/block/buzz/commit/c0c606e2e3ee01f959d804698caf74b455ee08f1)) +- feat(loadgen): add a hot-thread stressor and teardown ([#8746](https://github.com/block/buzz/pull/8746)) ([`4cf2a3bd6684982a69bd3c44bd466cf8ce31c5b6`](https://github.com/block/buzz/commit/4cf2a3bd6684982a69bd3c44bd466cf8ce31c5b6)) +- fix(mobile): retain invite keys and reject incomplete onboarding ([#8753](https://github.com/block/buzz/pull/8753)) ([`75854111b82694375dbf0f4dd67ddf8b100ba64c`](https://github.com/block/buzz/commit/75854111b82694375dbf0f4dd67ddf8b100ba64c)) +- Restyle community invitations ([#8728](https://github.com/block/buzz/pull/8728)) ([`5d70622ac0b1b7bf940803cc8f912f0e82a4c946`](https://github.com/block/buzz/commit/5d70622ac0b1b7bf940803cc8f912f0e82a4c946)) +- feat(relay): add incremental artifact reads ([#8523](https://github.com/block/buzz/pull/8523)) ([`a57349b237c67c3983dd7a09af378977ccd1e3f9`](https://github.com/block/buzz/commit/a57349b237c67c3983dd7a09af378977ccd1e3f9)) +- fix(mobile): show agent DM typing and balance reply bubble padding ([#8731](https://github.com/block/buzz/pull/8731)) ([`aae0081a9083650efbc3c2da421f5522df5a170a`](https://github.com/block/buzz/commit/aae0081a9083650efbc3c2da421f5522df5a170a)) +- perf(relay): route author- and #p-scoped global subscriptions by selector ([#8666](https://github.com/block/buzz/pull/8666)) ([`cc04cdca1a7a4094183dfaedbf09a52f5aa25d70`](https://github.com/block/buzz/commit/cc04cdca1a7a4094183dfaedbf09a52f5aa25d70)) +- test(scripts): stop file-size fixtures leaking git repos and fsmonitor daemons ([#8727](https://github.com/block/buzz/pull/8727)) ([`158b3bf562b09874d110e82a52e73f1fc92ad082`](https://github.com/block/buzz/commit/158b3bf562b09874d110e82a52e73f1fc92ad082)) +- test(mobile): keep late callbacks and fixed sleeps from failing tests ([#8678](https://github.com/block/buzz/pull/8678)) ([`fae3f0346c44bbdf9629a7b5967965391c2bd22f`](https://github.com/block/buzz/commit/fae3f0346c44bbdf9629a7b5967965391c2bd22f)) +- fix(mobile): resolve iOS pushes on a fresh connection and retry a stale one ([#8722](https://github.com/block/buzz/pull/8722)) ([`d263e2c7f7126b9a5caf1507140bb32e2c4e0ea3`](https://github.com/block/buzz/commit/d263e2c7f7126b9a5caf1507140bb32e2c4e0ea3)) +- ci(loadgen): publish buzz-loadgen as ghcr.io/block/buzz-loadgen ([#8717](https://github.com/block/buzz/pull/8717)) ([`ef0fce8c510320f60363974d91aef35ed5736ef5`](https://github.com/block/buzz/commit/ef0fce8c510320f60363974d91aef35ed5736ef5)) +- test(relay): fix main's build after the test-state helper rename ([#8718](https://github.com/block/buzz/pull/8718)) ([`0e8fb49bd09c070b619d3b560a5c55b4c3cc1eb6`](https://github.com/block/buzz/commit/0e8fb49bd09c070b619d3b560a5c55b4c3cc1eb6)) +- fix(db): keep lease releases durable and deflake PostgreSQL lane tests ([#8676](https://github.com/block/buzz/pull/8676)) ([`ef4130da4bfeea9fe37477d621166675e0ab3ef7`](https://github.com/block/buzz/commit/ef4130da4bfeea9fe37477d621166675e0ab3ef7)) +- test: dedupe collect_until_eose by event id and uncap two shell tests ([#8677](https://github.com/block/buzz/pull/8677)) ([`1893c3ab5a1361cda8457100dba948376b05703f`](https://github.com/block/buzz/commit/1893c3ab5a1361cda8457100dba948376b05703f)) +- ci: cache the Tauri apt .debs and fit a cold Windows Rust run in its cap ([#8679](https://github.com/block/buzz/pull/8679)) ([`b1f76ef4d20f177a996f2f13aad6d267023bb440`](https://github.com/block/buzz/commit/b1f76ef4d20f177a996f2f13aad6d267023bb440)) +- relay: open the search pool lazily so a dead reader can't block boot ([#8662](https://github.com/block/buzz/pull/8662)) ([`efcdf00101f56e11998e072a62502f1bcadc313c`](https://github.com/block/buzz/commit/efcdf00101f56e11998e072a62502f1bcadc313c)) +- fix(mobile): address #8650 second-pass review ([#8691](https://github.com/block/buzz/pull/8691)) ([`64312fa5bed4f2ba926f26c88f757012caac6d98`](https://github.com/block/buzz/commit/64312fa5bed4f2ba926f26c88f757012caac6d98)) +- Revert "fix(mobile): push every message in your own Solo chats (#8615)" ([#8690](https://github.com/block/buzz/pull/8690)) ([`a94ebece0eb1a6880482538136c0db75d02a39d9`](https://github.com/block/buzz/commit/a94ebece0eb1a6880482538136c0db75d02a39d9)) +- perf(relay): cut connect-burst CPU in log filtering and open-channel lookup ([#8670](https://github.com/block/buzz/pull/8670)) ([`1f16f621d87cdc0b03f41105f9d4201313054664`](https://github.com/block/buzz/commit/1f16f621d87cdc0b03f41105f9d4201313054664)) +- perf(mobile): skip unchanged message footer layout ([#8433](https://github.com/block/buzz/pull/8433)) ([`050d545264a88ed897884fa845d158dd59eeaf30`](https://github.com/block/buzz/commit/050d545264a88ed897884fa845d158dd59eeaf30)) +- ci: pin JDK 17 for the Android lane ([#8711](https://github.com/block/buzz/pull/8711)) ([`c609d33e8c3e7bb661521c055defc63f5f1cea53`](https://github.com/block/buzz/commit/c609d33e8c3e7bb661521c055defc63f5f1cea53)) +- BUZZ-272: Deny workflow runs for banned owners ([#8242](https://github.com/block/buzz/pull/8242)) ([`1fe120165f3026777c76526c4430e8ba14c76a75`](https://github.com/block/buzz/commit/1fe120165f3026777c76526c4430e8ba14c76a75)) +- docs(buzz-acp): fix stale prepare_reconnect doc comment ([#8697](https://github.com/block/buzz/pull/8697)) ([`f539ef4a87061fe70db07b44417b1c14355cb2f4`](https://github.com/block/buzz/commit/f539ef4a87061fe70db07b44417b1c14355cb2f4)) +- fix(relay): close a REQ whose history read failed instead of sending EOSE ([#8692](https://github.com/block/buzz/pull/8692)) ([`76cd4294f65bde33eff031315509e81deccf7c9d`](https://github.com/block/buzz/commit/76cd4294f65bde33eff031315509e81deccf7c9d)) +- perf(mobile): render inbox and search previews as plain text ([#8675](https://github.com/block/buzz/pull/8675)) ([`be1ac392e85ca414cd6736c807655c4269a34f39`](https://github.com/block/buzz/commit/be1ac392e85ca414cd6736c807655c4269a34f39)) +- fix(mobile): require lowercase hex in native verification ([#8702](https://github.com/block/buzz/pull/8702)) ([`762adad54f79fc07caecbefd102aa170a9b4cce3`](https://github.com/block/buzz/commit/762adad54f79fc07caecbefd102aa170a9b4cce3)) +- fix(mobile): recover Solo sync silently instead of showing a retry banner ([#8701](https://github.com/block/buzz/pull/8701)) ([`fffd8ca95784af5942927690f5390927f4754a63`](https://github.com/block/buzz/commit/fffd8ca95784af5942927690f5390927f4754a63)) +- perf(mobile): verify signatures with native libsecp256k1 ([#8657](https://github.com/block/buzz/pull/8657)) ([`ccfc1490e451b99e8bc472ab7df5d65b0f4d3837`](https://github.com/block/buzz/commit/ccfc1490e451b99e8bc472ab7df5d65b0f4d3837)) +- mobile: stop typing prune ticks from rebuilding channel pages ([#8695](https://github.com/block/buzz/pull/8695)) ([`ff284d00d38777930a0524f86152abf8ea201e24`](https://github.com/block/buzz/commit/ff284d00d38777930a0524f86152abf8ea201e24)) +- db: warm the relay read pool toward its ceiling at boot ([#8651](https://github.com/block/buzz/pull/8651)) ([`6d719c680a85c98153324809988be37425fba73e`](https://github.com/block/buzz/commit/6d719c680a85c98153324809988be37425fba73e)) +- Make mobile Agents a full-page owned-agent directory ([#8693](https://github.com/block/buzz/pull/8693)) ([`0cde1fe2f40478d58c34f7a7113ea62759e353ec`](https://github.com/block/buzz/commit/0cde1fe2f40478d58c34f7a7113ea62759e353ec)) +- db: answer match-nothing event reads without taking a connection ([#8663](https://github.com/block/buzz/pull/8663)) ([`f6d31d13e433da3c70158cc24f1107b2b2ca1143`](https://github.com/block/buzz/commit/f6d31d13e433da3c70158cc24f1107b2b2ca1143)) +- fix(buzz-acp): spread 1012 reconnects and keep replay gaps across a dropped socket ([#8653](https://github.com/block/buzz/pull/8653)) ([`cc28660c6117fb54d176b697b0db1059ed336e1f`](https://github.com/block/buzz/commit/cc28660c6117fb54d176b697b0db1059ed336e1f)) +- perf(mobile): compute NIP-44 ECDH with native libsecp256k1 ([#8656](https://github.com/block/buzz/pull/8656)) ([`3dbc95c3f668547e501c7d5f306d85ca5dcd055e`](https://github.com/block/buzz/commit/3dbc95c3f668547e501c7d5f306d85ca5dcd055e)) +- Add a scenario-driven relay load generator ([#8636](https://github.com/block/buzz/pull/8636)) ([`aed4be8592bf512f3d345e28d3c76fe6b55e3134`](https://github.com/block/buzz/commit/aed4be8592bf512f3d345e28d3c76fe6b55e3134)) +- Add standalone owned-community deletion handlers ([#8645](https://github.com/block/buzz/pull/8645)) ([`8caf8351c124a2a39f160e342587d427e8c32a51`](https://github.com/block/buzz/commit/8caf8351c124a2a39f160e342587d427e8c32a51)) +- Unify mobile onboarding and community entry screens ([#8687](https://github.com/block/buzz/pull/8687)) ([`e922dc08ffd08f21d20fa0900f5f109eb0a22c98`](https://github.com/block/buzz/commit/e922dc08ffd08f21d20fa0900f5f109eb0a22c98)) +- fix(mobile): keep read state across reconnects and resume ([#8672](https://github.com/block/buzz/pull/8672)) ([`8abcf2ea2a416c5cfceba797cb14487c3612b190`](https://github.com/block/buzz/commit/8abcf2ea2a416c5cfceba797cb14487c3612b190)) +- fix(mobile): wait for app activation before browser auth ([#8647](https://github.com/block/buzz/pull/8647)) ([`0d19ca69d3001520baa676172d6b7b250359bf18`](https://github.com/block/buzz/commit/0d19ca69d3001520baa676172d6b7b250359bf18)) +- perf(mobile): derive public keys with native libsecp256k1 ([#8655](https://github.com/block/buzz/pull/8655)) ([`8161a7cad02f32261a7bae00b33109b76743b0cb`](https://github.com/block/buzz/commit/8161a7cad02f32261a7bae00b33109b76743b0cb)) +- perf(mobile): decode relay query responses off the UI isolate ([#8669](https://github.com/block/buzz/pull/8669)) ([`770ab7ff82d704d96870d6043346d3fca181eb8d`](https://github.com/block/buzz/commit/770ab7ff82d704d96870d6043346d3fca181eb8d)) +- feat(mobile): choose remote agent models and gate agents on Builderlab sign-in ([#8650](https://github.com/block/buzz/pull/8650)) ([`a7e65c91da4937c6f825681c3f124b83380635a4`](https://github.com/block/buzz/commit/a7e65c91da4937c6f825681c3f124b83380635a4)) +- feat(mobile): unify Messages navigation with Solo and Team filters ([#8649](https://github.com/block/buzz/pull/8649)) ([`39b8b2b6a6d065b3da981e096b1a3881f1c63fd4`](https://github.com/block/buzz/commit/39b8b2b6a6d065b3da981e096b1a3881f1c63fd4)) +- Smooth profile avatar editor transitions ([#8640](https://github.com/block/buzz/pull/8640)) ([`7c165c371845792b6752c642c6351a16b025268c`](https://github.com/block/buzz/commit/7c165c371845792b6752c642c6351a16b025268c)) +- chore(desktop): point `just staging` at the new Block staging relay ([#8623](https://github.com/block/buzz/pull/8623)) ([`6e332f46c7f0b046c37355a1aca8f8189e6718c5`](https://github.com/block/buzz/commit/6e332f46c7f0b046c37355a1aca8f8189e6718c5)) +- fix(mobile): rebuild buzz_secp256k1 when vendored headers change ([#8664](https://github.com/block/buzz/pull/8664)) ([`82b27813766b6ae38602769a1166024cdc191260`](https://github.com/block/buzz/commit/82b27813766b6ae38602769a1166024cdc191260)) +- fix(push-gateway): log which App Attest certificate check failed ([#8671](https://github.com/block/buzz/pull/8671)) ([`713b864e2f6cc70889c41a1bcf5c7207547c104a`](https://github.com/block/buzz/commit/713b864e2f6cc70889c41a1bcf5c7207547c104a)) +- fix(mobile): resume reconnect replay from the last live point and spread reconnects ([#8659](https://github.com/block/buzz/pull/8659)) ([`974495fd4a5d77310efd9de45a6f4339e881446a`](https://github.com/block/buzz/commit/974495fd4a5d77310efd9de45a6f4339e881446a)) +- fix(mobile): push every message in your own Solo chats ([#8615](https://github.com/block/buzz/pull/8615)) ([`bad9d26142eaa9df8027b51a3b1bea0ca984309a`](https://github.com/block/buzz/commit/bad9d26142eaa9df8027b51a3b1bea0ca984309a)) +- perf(mobile): sign events with native libsecp256k1 on iOS and Android ([#8654](https://github.com/block/buzz/pull/8654)) ([`4ff02bf03b73b6e07ac45beca833652e0272478a`](https://github.com/block/buzz/commit/4ff02bf03b73b6e07ac45beca833652e0272478a)) +- perf(db,relay): bound thread participant scans and coalesce live summaries ([#8635](https://github.com/block/buzz/pull/8635)) ([`0a362eef150ab16453993d442a8037baad766797`](https://github.com/block/buzz/commit/0a362eef150ab16453993d442a8037baad766797)) +- mobile: find DMs opened ahead of the list everywhere ([#8646](https://github.com/block/buzz/pull/8646)) ([`b310fea05b2ed2c2d04cc0da4ad16f38108b6a3c`](https://github.com/block/buzz/commit/b310fea05b2ed2c2d04cc0da4ad16f38108b6a3c)) +- BUZZ-413: Add user deletion fence storage ([#8632](https://github.com/block/buzz/pull/8632)) ([`2c28e07133d306ced204ca17f97c4cb93c916f72`](https://github.com/block/buzz/commit/2c28e07133d306ced204ca17f97c4cb93c916f72)) +- fix(mobile): open new DMs without waiting for a full channel reload ([#8638](https://github.com/block/buzz/pull/8638)) ([`9e18d17a36d338b8a8e006d51ce5f971865d37c5`](https://github.com/block/buzz/commit/9e18d17a36d338b8a8e006d51ce5f971865d37c5)) +- Stop requiring the 0032 roster trigger at relay startup ([#8611](https://github.com/block/buzz/pull/8611)) ([`646ef8abf9bc5ac3e698826b38811033537a4806`](https://github.com/block/buzz/commit/646ef8abf9bc5ac3e698826b38811033537a4806)) +- fix(relay): store a kind:9000 and its membership writes in one transaction ([#8606](https://github.com/block/buzz/pull/8606)) ([`78b5dae1f608a33850137b5be5a1909390035cce`](https://github.com/block/buzz/commit/78b5dae1f608a33850137b5be5a1909390035cce)) +- fix(deps): bump pulldown-cmark to 0.13.5 for RUSTSEC-2026-0414 ([#8644](https://github.com/block/buzz/pull/8644)) ([`3ed07e5c758fe14c3712e6e8309dfe90942f1d81`](https://github.com/block/buzz/commit/3ed07e5c758fe14c3712e6e8309dfe90942f1d81)) +- feat(relay): log who and why for NIP-FI shadow would-deny ([#8634](https://github.com/block/buzz/pull/8634)) ([`24a370606044c0c7be787cc2fd98ec0bfe1d606b`](https://github.com/block/buzz/commit/24a370606044c0c7be787cc2fd98ec0bfe1d606b)) +- feat(mobile): add full-screen profile setup with inline avatar editing ([#8628](https://github.com/block/buzz/pull/8628)) ([`5c2ea2e507a6f79132edf7eb9e5be0e90aee5166`](https://github.com/block/buzz/commit/5c2ea2e507a6f79132edf7eb9e5be0e90aee5166)) +- fix(mobile): preserve invite onboarding and offer identity setup ([#8617](https://github.com/block/buzz/pull/8617)) ([`5a8102ee5b50da94588368b8d2ccb3def64033ca`](https://github.com/block/buzz/commit/5a8102ee5b50da94588368b8d2ccb3def64033ca)) +- refactor(schema): stop auto-fencing new tables in desired-state bootstrap ([#8620](https://github.com/block/buzz/pull/8620)) ([`f33ebaafa15626e0f8bc3e23341835e08ebf4a33`](https://github.com/block/buzz/commit/f33ebaafa15626e0f8bc3e23341835e08ebf4a33)) +- feat(mobile): manage Builderlab remote agents ([#8626](https://github.com/block/buzz/pull/8626)) ([`d4a07063c8b816124e27e00720e5b47f0a5ae1ce`](https://github.com/block/buzz/commit/d4a07063c8b816124e27e00720e5b47f0a5ae1ce)) +- fix(mobile): replace a push enrollment the gateway rejected ([#8629](https://github.com/block/buzz/pull/8629)) ([`b929b2cf84f76f804a750839a885d74090e629e5`](https://github.com/block/buzz/commit/b929b2cf84f76f804a750839a885d74090e629e5)) +- test(relay): give group-state Postgres tests a normal acquire timeout ([#8564](https://github.com/block/buzz/pull/8564)) ([`403855d7884971b4103ba094e3d24ba28bbf093a`](https://github.com/block/buzz/commit/403855d7884971b4103ba094e3d24ba28bbf093a)) +- fix(push-gateway): log which App Attest check rejected a device ([#8630](https://github.com/block/buzz/pull/8630)) ([`c477663211142cabd82329c97346b7f64f827a97`](https://github.com/block/buzz/commit/c477663211142cabd82329c97346b7f64f827a97)) +- docs(nip-ap): define agenttype on agent settings ([#8631](https://github.com/block/buzz/pull/8631)) ([`3ce3a2e2df815924f2519e08d5626a8f8bd8587b`](https://github.com/block/buzz/commit/3ce3a2e2df815924f2519e08d5626a8f8bd8587b)) +- fix(push): accept canonical channel UUIDs across versions ([#8609](https://github.com/block/buzz/pull/8609)) ([`f167c4c3e10469f4f75b5ecad83af50bb3d5de2c`](https://github.com/block/buzz/commit/f167c4c3e10469f4f75b5ecad83af50bb3d5de2c)) +- fix(mobile): align Solo agent policy and labels with the owner's inventory ([#8616](https://github.com/block/buzz/pull/8616)) ([`b77ad2ed10a00e869e4e64d06d70300d23616b7f`](https://github.com/block/buzz/commit/b77ad2ed10a00e869e4e64d06d70300d23616b7f)) +- fix(mobile): open message links to public channels the user has not joined ([#8518](https://github.com/block/buzz/pull/8518)) ([`a4e83dfb508b259a2f128b8268d7f7a9c8de00f5`](https://github.com/block/buzz/commit/a4e83dfb508b259a2f128b8268d7f7a9c8de00f5)) +- Make mobile onboarding QR-first and synchronize scanner motion ([#8599](https://github.com/block/buzz/pull/8599)) ([`ff9eb8f4dc56c312983287321ea8748b93c62145`](https://github.com/block/buzz/commit/ff9eb8f4dc56c312983287321ea8748b93c62145)) +- Speed up mobile Solo chat creation and agent discovery ([#8547](https://github.com/block/buzz/pull/8547)) ([`b14884980e9ff70c201ba97d459bed05286fdfd9`](https://github.com/block/buzz/commit/b14884980e9ff70c201ba97d459bed05286fdfd9)) +- fix(mobile): isolate push setup failures from app rendering ([#8610](https://github.com/block/buzz/pull/8610)) ([`5996e5dd8b7187bca49bac44b1d35da5fca56f77`](https://github.com/block/buzz/commit/5996e5dd8b7187bca49bac44b1d35da5fca56f77)) +- Generate user community inventory for the dummy deletion workflow ([#8605](https://github.com/block/buzz/pull/8605)) ([`834dca26bf0613581fc8199810f4693392aada3b`](https://github.com/block/buzz/commit/834dca26bf0613581fc8199810f4693392aada3b)) +- perf(mobile): batch initial channel read-state seeds ([#8607](https://github.com/block/buzz/pull/8607)) ([`8ceca8ac46ad1a76e037380236f90a9fce29e16b`](https://github.com/block/buzz/commit/8ceca8ac46ad1a76e037380236f90a9fce29e16b)) +- fix(mobile): ignore unrelated mutes when building push subscriptions ([#8608](https://github.com/block/buzz/pull/8608)) ([`209fcd21725b8728fed8b14dca1636018d175458`](https://github.com/block/buzz/commit/209fcd21725b8728fed8b14dca1636018d175458)) +- fix(db): keep the reader pool warm and drop its pre-acquire ping ([#8495](https://github.com/block/buzz/pull/8495)) ([`0e36dbc823f4754b98da64944cc015a9f7acbd6e`](https://github.com/block/buzz/commit/0e36dbc823f4754b98da64944cc015a9f7acbd6e)) +- perf(mobile): restore cached channels before community sync ([#8580](https://github.com/block/buzz/pull/8580)) ([`ab73cd9fb55e2f37803ac7dc8d1b62f1e47f2fb7`](https://github.com/block/buzz/commit/ab73cd9fb55e2f37803ac7dc8d1b62f1e47f2fb7)) +- perf(mobile): cut idle and resume sync churn ([#8490](https://github.com/block/buzz/pull/8490)) ([`d090ac24bb7c78eb8a9db68f422ffaf7f8c54bfc`](https://github.com/block/buzz/commit/d090ac24bb7c78eb8a9db68f422ffaf7f8c54bfc)) +- perf(push): avoid empty push delivery claims ([#8524](https://github.com/block/buzz/pull/8524)) ([`b8b1ab5b3cac3692f4231a32679de8d2e7113b70`](https://github.com/block/buzz/commit/b8b1ab5b3cac3692f4231a32679de8d2e7113b70)) +- docs(memory): add core-as-index and source metadata; frame memory as information ([#8548](https://github.com/block/buzz/pull/8548)) ([`d7270330ee26aecb411b080976a5e69a88818b2f`](https://github.com/block/buzz/commit/d7270330ee26aecb411b080976a5e69a88818b2f)) +- feat(relay): verify NIP-FI agent tokens and admit agents through owners ([#8401](https://github.com/block/buzz/pull/8401)) ([`369ffa0380ab2a987b5321d431b9b567aa2b8b38`](https://github.com/block/buzz/commit/369ffa0380ab2a987b5321d431b9b567aa2b8b38)) +- docs: remove NIP-FI migration gate from release procedure ([#8567](https://github.com/block/buzz/pull/8567)) ([`4c7ba3b97e44b2be2a305c510c1d4d4994964e24`](https://github.com/block/buzz/commit/4c7ba3b97e44b2be2a305c510c1d4d4994964e24)) +- Run user deletion through saved stage transitions ([#8520](https://github.com/block/buzz/pull/8520)) ([`4250014baee071f0f940c081afbbbf876c0d32d0`](https://github.com/block/buzz/commit/4250014baee071f0f940c081afbbbf876c0d32d0)) +- fix(mesh): expire dead peer records and instrument mesh boot ([#8503](https://github.com/block/buzz/pull/8503)) ([`7ce422417b139c2d622eccc6066b494c2e18bb9c`](https://github.com/block/buzz/commit/7ce422417b139c2d622eccc6066b494c2e18bb9c)) +- fix(deps): bump p256 to 0.14 for RUSTSEC-2026-0387 ([#8592](https://github.com/block/buzz/pull/8592)) ([`d676c7b8db30ccc15611b9ef51ed9c6f2e8a954a`](https://github.com/block/buzz/commit/d676c7b8db30ccc15611b9ef51ed9c6f2e8a954a)) +- docs(cli): drop private references from the agent format comment ([#8508](https://github.com/block/buzz/pull/8508)) ([`016310d3cc44688779a7d517a13d9cc8024ddfa8`](https://github.com/block/buzz/commit/016310d3cc44688779a7d517a13d9cc8024ddfa8)) +- Add project selection to new Solo chats on mobile ([#8546](https://github.com/block/buzz/pull/8546)) ([`dc25198d530acc6237a0320b697365f29daf0ea6`](https://github.com/block/buzz/commit/dc25198d530acc6237a0320b697365f29daf0ea6)) +- fix(db): rebuild events_pkey in declared order after pgschema apply ([#8525](https://github.com/block/buzz/pull/8525)) ([`20ba95ed8906b2b7ae1819bdddadf82c09778097`](https://github.com/block/buzz/commit/20ba95ed8906b2b7ae1819bdddadf82c09778097)) +- Polish mobile onboarding and profile setup ([#8438](https://github.com/block/buzz/pull/8438)) ([`f7708d0694dbbd92bb6f4cd2b6872f4bbdc3cebb`](https://github.com/block/buzz/commit/f7708d0694dbbd92bb6f4cd2b6872f4bbdc3cebb)) +- feat(mobile): group typing avatars into one animated indicator ([#8543](https://github.com/block/buzz/pull/8543)) ([`8260b6ef4c055bf85016499f48ed2ae580ffc2e7`](https://github.com/block/buzz/commit/8260b6ef4c055bf85016499f48ed2ae580ffc2e7)) +- BUZZ-301: Add user deletion request intake ([#8496](https://github.com/block/buzz/pull/8496)) ([`2d289f720de0012fa36b5f6faa0e3bdd845ccfcf`](https://github.com/block/buzz/commit/2d289f720de0012fa36b5f6faa0e3bdd845ccfcf)) +- fix(relay): apply channel setting changes atomically and lock every membership writer ([#8516](https://github.com/block/buzz/pull/8516)) ([`a2d28eb6c478b97c371e1e67a92d43bdfb8dd7b0`](https://github.com/block/buzz/commit/a2d28eb6c478b97c371e1e67a92d43bdfb8dd7b0)) +- fix(mobile): remove Browse channels from channel list ([#8539](https://github.com/block/buzz/pull/8539)) ([`e8781caa6f3bb00e0602c4ed9ffe885f7999d317`](https://github.com/block/buzz/commit/e8781caa6f3bb00e0602c4ed9ffe885f7999d317)) +- fix(db): keep pgschema re-apply from dropping runtime partitions ([#8487](https://github.com/block/buzz/pull/8487)) ([`347ce88d5dd8bc631c073f1947fea6b75d5a43c0`](https://github.com/block/buzz/commit/347ce88d5dd8bc631c073f1947fea6b75d5a43c0)) +- fix(db): bound every statement and the #p mention scan ([#8461](https://github.com/block/buzz/pull/8461)) ([`2f2f6e2774fb0899d2a927f5e5b1987603765f31`](https://github.com/block/buzz/commit/2f2f6e2774fb0899d2a927f5e5b1987603765f31)) +- fix(mobile): keep token labels visible in authored Markdown links ([#7545](https://github.com/block/buzz/pull/7545)) ([`1a54eec3dbfd049f98dfca678c3060c5c3a8f0a1`](https://github.com/block/buzz/commit/1a54eec3dbfd049f98dfca678c3060c5c3a8f0a1)) +- test(relay): cover system channels in the workflows API and push matcher ([#8509](https://github.com/block/buzz/pull/8509)) ([`c37d6b8eb62b6b1747985092a7c9dc677da89a61`](https://github.com/block/buzz/commit/c37d6b8eb62b6b1747985092a7c9dc677da89a61)) +- fix(relay): push system channel events to a lease that names them ([#8517](https://github.com/block/buzz/pull/8517)) ([`cd8a9681793fef83001eb44954734b47c1938550`](https://github.com/block/buzz/commit/cd8a9681793fef83001eb44954734b47c1938550)) +- fix(relay): scope push matches with the read path's channel rule ([#8507](https://github.com/block/buzz/pull/8507)) ([`4dea51f644cc5069aea24ff2f4df943f82d7b1c4`](https://github.com/block/buzz/commit/4dea51f644cc5069aea24ff2f4df943f82d7b1c4)) +- feat(ws-client): send custom headers on the WebSocket upgrade ([#8159](https://github.com/block/buzz/pull/8159)) ([`ce3fc78cbd2e978610e544c8fb305c2d0e552ab6`](https://github.com/block/buzz/commit/ce3fc78cbd2e978610e544c8fb305c2d0e552ab6)) +- feat(mobile): show inline human typing and outgoing avatars ([#8505](https://github.com/block/buzz/pull/8505)) ([`0768397092b055decd348a0ab202f22db83f1d45`](https://github.com/block/buzz/commit/0768397092b055decd348a0ab202f22db83f1d45)) +- feat(audio-client): accept a client request in connect ([#8497](https://github.com/block/buzz/pull/8497)) ([`7e6461242aa7d98f132919dd672f7cc5f4abbba6`](https://github.com/block/buzz/commit/7e6461242aa7d98f132919dd672f7cc5f4abbba6)) +- fix(mobile): lazily lay out new-DM recipients ([#8435](https://github.com/block/buzz/pull/8435)) ([`93114b4279a619613a6df8ef740472216e1d4cfb`](https://github.com/block/buzz/commit/93114b4279a619613a6df8ef740472216e1d4cfb)) +- fix(mobile): lazily lay out channel member groups ([#8437](https://github.com/block/buzz/pull/8437)) ([`bf4a1635103e4388d1656722aa136ea5b41b07ce`](https://github.com/block/buzz/commit/bf4a1635103e4388d1656722aa136ea5b41b07ce)) +- perf(mobile): retain preference crypto across reconnects ([#8442](https://github.com/block/buzz/pull/8442)) ([`a93f3282cc017e8decc8ea803d92967c4c3e36df`](https://github.com/block/buzz/commit/a93f3282cc017e8decc8ea803d92967c4c3e36df)) +- fix(mobile): simplify and refine the quick actions menu ([#8491](https://github.com/block/buzz/pull/8491)) ([`ca35114209bf275b35bf66a102f2f45ec643cb38`](https://github.com/block/buzz/commit/ca35114209bf275b35bf66a102f2f45ec643cb38)) +- fix(mobile): resolve DM display labels once per sort ([#8488](https://github.com/block/buzz/pull/8488)) ([`cdc2b129c006755bd923e75462c610df2815b383`](https://github.com/block/buzz/commit/cdc2b129c006755bd923e75462c610df2815b383)) +- docs(db): database target architecture and schema-change rules ([#8273](https://github.com/block/buzz/pull/8273)) ([`fcdabcf774203884c4f5b258aad000a740586eb6`](https://github.com/block/buzz/commit/fcdabcf774203884c4f5b258aad000a740586eb6)) +- fix(relay): advance the partition catch-all by default ([#8464](https://github.com/block/buzz/pull/8464)) ([`ca3be55018a37c4e7d342057260dd773190eae68`](https://github.com/block/buzz/commit/ca3be55018a37c4e7d342057260dd773190eae68)) +- feat(relay): write the NIP-43 member list in the membership transaction ([#8482](https://github.com/block/buzz/pull/8482)) ([`039e1c8d59232eb29d80e59b394d5cde825b389a`](https://github.com/block/buzz/commit/039e1c8d59232eb29d80e59b394d5cde825b389a)) +- fix(relay): delete the startup NIP-33 d_tag backfill ([#8468](https://github.com/block/buzz/pull/8468)) ([`c99872f749cb1214a3e69371c83a7f2f72aef704`](https://github.com/block/buzz/commit/c99872f749cb1214a3e69371c83a7f2f72aef704)) +- fix(relay): take NIP-43 snapshot reconcile off the startup path ([#8467](https://github.com/block/buzz/pull/8467)) ([`e6c56ee5ee80eace3c9eddf0bf22a020fa8f48f3`](https://github.com/block/buzz/commit/e6c56ee5ee80eace3c9eddf0bf22a020fa8f48f3)) +- test(buzz-db): fix two PostgreSQL-lane timing flakes ([#8472](https://github.com/block/buzz/pull/8472)) ([`6e6173acd58029bac800583c4cc7482dafed693a`](https://github.com/block/buzz/commit/6e6173acd58029bac800583c4cc7482dafed693a)) +- test(mobile): journey-first testing guidance and suite cleanup ([#8397](https://github.com/block/buzz/pull/8397)) ([`edbfbf08db4bbcae8b557d077460ff3498e12fe1`](https://github.com/block/buzz/commit/edbfbf08db4bbcae8b557d077460ff3498e12fe1)) +- fix(mobile): keep cached state with its community ([#8349](https://github.com/block/buzz/pull/8349)) ([`3ec632761880b3d8ab0be573869e0366edfe2db8`](https://github.com/block/buzz/commit/3ec632761880b3d8ab0be573869e0366edfe2db8)) +- fix(mobile): preserve saved identity lookup after enumeration fails ([#8470](https://github.com/block/buzz/pull/8470)) ([`dcced2c4f7232f09e04dc25c4d374a4dc8fb960c`](https://github.com/block/buzz/commit/dcced2c4f7232f09e04dc25c4d374a4dc8fb960c)) +- perf(mobile): reuse the derived pubkey when signing auth events ([#8460](https://github.com/block/buzz/pull/8460)) ([`91b1cc47610bc22cdd4ad0454dd8c47f48fa29c9`](https://github.com/block/buzz/commit/91b1cc47610bc22cdd4ad0454dd8c47f48fa29c9)) +- perf(mobile): stop an open chat rebuilding on other channels' events ([#8456](https://github.com/block/buzz/pull/8456)) ([`52aa37a929afb2b86a6ef2a74db5f613d96d1128`](https://github.com/block/buzz/commit/52aa37a929afb2b86a6ef2a74db5f613d96d1128)) +- perf(mobile): load the channel list's membership-scoped reads together ([#8462](https://github.com/block/buzz/pull/8462)) ([`db50afd8a78c6faf98d33789ef53d8205643d08b`](https://github.com/block/buzz/commit/db50afd8a78c6faf98d33789ef53d8205643d08b)) +- fix(mobile): stop Settings rows blinking while Settings opens ([#8463](https://github.com/block/buzz/pull/8463)) ([`bc9e7de9043970f4472d4bc73f6da42153f88bcb`](https://github.com/block/buzz/commit/bc9e7de9043970f4472d4bc73f6da42153f88bcb)) +- feat(mobile): account onboarding, key recovery and hosted reconnect ([#8375](https://github.com/block/buzz/pull/8375)) ([`b6aa5539e3a44fe32a4bfe2963dfb23f10316985`](https://github.com/block/buzz/commit/b6aa5539e3a44fe32a4bfe2963dfb23f10316985)) +- fix(relay): wait for the peer's Close before dropping any WebSocket ([#8426](https://github.com/block/buzz/pull/8426)) ([`91e7b469b82b235c62885f82a6323b7e666e9254`](https://github.com/block/buzz/commit/91e7b469b82b235c62885f82a6323b7e666e9254)) +- test(auth): read the clock once in NIP-FI until test ([#8457](https://github.com/block/buzz/pull/8457)) ([`af7979e1ca0c40af2ba4a8d05edad6bb5796c584`](https://github.com/block/buzz/commit/af7979e1ca0c40af2ba4a8d05edad6bb5796c584)) +- fix(mobile): reset community notification preferences ([#8455](https://github.com/block/buzz/pull/8455)) ([`dc4cdc4990877d400a435b481a416a73f17247bb`](https://github.com/block/buzz/commit/dc4cdc4990877d400a435b481a416a73f17247bb)) +- fix(release): keep mobile candidates pinned as branches advance ([#8454](https://github.com/block/buzz/pull/8454)) ([`5730c83f7dd2ae409de5efe2d023e46695c78b3e`](https://github.com/block/buzz/commit/5730c83f7dd2ae409de5efe2d023e46695c78b3e)) +- feat(relay): resolve NIP-FI issuer bindings from the database ([#8377](https://github.com/block/buzz/pull/8377)) ([`5b433d92926504370c6e12f651d5d010b5af33c2`](https://github.com/block/buzz/commit/5b433d92926504370c6e12f651d5d010b5af33c2)) +- test(mobile): remove flaky channel collection assertion ([#8440](https://github.com/block/buzz/pull/8440)) ([`4f1f1b5300f08c9f01a8bc09d263f332c5f69f30`](https://github.com/block/buzz/commit/4f1f1b5300f08c9f01a8bc09d263f332c5f69f30)) +- fix(ios): supply missing push notification sound at handoff ([#8443](https://github.com/block/buzz/pull/8443)) ([`3debf18f1448334aa7bc202d328d93bb9651e168`](https://github.com/block/buzz/commit/3debf18f1448334aa7bc202d328d93bb9651e168)) +- feat(release): support version-matched mobile stable branches ([#8430](https://github.com/block/buzz/pull/8430)) ([`30ca980b49a7479dd89cb1ced0871af05ff1e12e`](https://github.com/block/buzz/commit/30ca980b49a7479dd89cb1ced0871af05ff1e12e)) +- fix(mobile): default community push notifications to on ([#8425](https://github.com/block/buzz/pull/8425)) ([`8f2c7710e958952b53e8e280cde52eb0d51b7312`](https://github.com/block/buzz/commit/8f2c7710e958952b53e8e280cde52eb0d51b7312)) +- fix(push-gateway): request default notification sound ([#8431](https://github.com/block/buzz/pull/8431)) ([`305fb7b5cd913379c246a66ce04c38411bba612b`](https://github.com/block/buzz/commit/305fb7b5cd913379c246a66ce04c38411bba612b)) +- feat(mobile): add swipe-to-reply message gesture ([#8436](https://github.com/block/buzz/pull/8436)) ([`bbb5183f33df3c6a5f7c587cc41233bc555cd15c`](https://github.com/block/buzz/commit/bbb5183f33df3c6a5f7c587cc41233bc555cd15c)) +- chore(deny): check buzz-mesh-smoke in the root graph again ([#8424](https://github.com/block/buzz/pull/8424)) ([`7c1a8967e0d2e12fb8b2ec3ae9783869b4a8be9f`](https://github.com/block/buzz/commit/7c1a8967e0d2e12fb8b2ec3ae9783869b4a8be9f)) +- fix(mobile): bump Flutter 3.47, resolving memory leak ([#8419](https://github.com/block/buzz/pull/8419)) ([`819dd7924f1740b72b37a736393ae20509864e9e`](https://github.com/block/buzz/commit/819dd7924f1740b72b37a736393ae20509864e9e)) +- fix(mobile): bound search result rendering work ([#8418](https://github.com/block/buzz/pull/8418)) ([`e048f5ac788c65a447dcb83decef973da855779b`](https://github.com/block/buzz/commit/e048f5ac788c65a447dcb83decef973da855779b)) +- Polish mobile message layout and navigation controls ([#8427](https://github.com/block/buzz/pull/8427)) ([`27b9c827fc082ae16b36217f40a82c6453081eef`](https://github.com/block/buzz/commit/27b9c827fc082ae16b36217f40a82c6453081eef)) +- feat(relay): start a channel with its members in one create ([#8421](https://github.com/block/buzz/pull/8421)) ([`3ffbfa693c6727b04b01ef727ce4848e4695ac40`](https://github.com/block/buzz/commit/3ffbfa693c6727b04b01ef727ce4848e4695ac40)) +- fix(deps): bump negentropy to 0.5.2 for RUSTSEC-2026-0365 ([#8409](https://github.com/block/buzz/pull/8409)) ([`bc995041cdd0a6c68c1b8a988f4e73596b3a92f9`](https://github.com/block/buzz/commit/bc995041cdd0a6c68c1b8a988f4e73596b3a92f9)) +- chore(deny): exclude buzz-mesh-smoke from cargo-deny graph ([#8413](https://github.com/block/buzz/pull/8413)) ([`cf1bb8dd13cd9b722b96473870bae98c57609b87`](https://github.com/block/buzz/commit/cf1bb8dd13cd9b722b96473870bae98c57609b87)) +- fix(mobile): polish Inbox controls and system notices ([#8423](https://github.com/block/buzz/pull/8423)) ([`3a45e87b255adb2b43ac0de94dba7a485290d27e`](https://github.com/block/buzz/commit/3a45e87b255adb2b43ac0de94dba7a485290d27e)) +- fix(mobile perf): avoid eager emoji palette scans for prose ([#8416](https://github.com/block/buzz/pull/8416)) ([`a96ace4e55baa9c943cfbbfc323502ff2eff05f3`](https://github.com/block/buzz/commit/a96ace4e55baa9c943cfbbfc323502ff2eff05f3)) +- feat(relay): store per-community NIP-FI issuer bindings ([#8372](https://github.com/block/buzz/pull/8372)) ([`6286a5432111f529835da320e801af1901889b03`](https://github.com/block/buzz/commit/6286a5432111f529835da320e801af1901889b03)) +- Fix iOS channel crash from unbounded scroll depth ([#8407](https://github.com/block/buzz/pull/8407)) ([`bf8b356f3bf551a01cc24041605ca77d009681dd`](https://github.com/block/buzz/commit/bf8b356f3bf551a01cc24041605ca77d009681dd)) +- fix(db): validate channel roster snapshots in the app writer ([#8316](https://github.com/block/buzz/pull/8316)) ([`97e1f6a0828d97d0031e2a31402554b679bf1146`](https://github.com/block/buzz/commit/97e1f6a0828d97d0031e2a31402554b679bf1146)) +- fix(mobile): support DeviceHub in mobile-dev ([#8404](https://github.com/block/buzz/pull/8404)) ([`d79446316b9478ac092d7a18324f8e8802e9b8c4`](https://github.com/block/buzz/commit/d79446316b9478ac092d7a18324f8e8802e9b8c4)) +- fix(db): admit fleet sweeps per tenant instead of in-SQL fence predicate ([#8318](https://github.com/block/buzz/pull/8318)) ([`60de1db0b8813766d8e004297798f2ff759d3089`](https://github.com/block/buzz/commit/60de1db0b8813766d8e004297798f2ff759d3089)) +- buzz-db: tolerate absent universal write-fence objects (expand) ([#8322](https://github.com/block/buzz/pull/8322)) ([`2745a419a836fb6bc4753f0caf3c9cf9c9a4d274`](https://github.com/block/buzz/commit/2745a419a836fb6bc4753f0caf3c9cf9c9a4d274)) +- feat(auth): support explicit mesh JWKS transport ([#8382](https://github.com/block/buzz/pull/8382)) ([`2d0f78c6e1c43762aeb51efa633e9387fc301649`](https://github.com/block/buzz/commit/2d0f78c6e1c43762aeb51efa633e9387fc301649)) +- docs(ios): document Xcode 27 development setup ([#8400](https://github.com/block/buzz/pull/8400)) ([`2de484baf7bf379753c3073f40da3a178b2918a0`](https://github.com/block/buzz/commit/2de484baf7bf379753c3073f40da3a178b2918a0)) +- feat(mobile): polish Home navigation and Solo workspace ([#8393](https://github.com/block/buzz/pull/8393)) ([`c8ea4fb4ebdf124a273321287568407258f51a70`](https://github.com/block/buzz/commit/c8ea4fb4ebdf124a273321287568407258f51a70)) +- Use upstream C secp256k1 for native Nostr signatures ([#8398](https://github.com/block/buzz/pull/8398)) ([`73962435b6dd7c67b29e650e4f11ae8efcd9af5d`](https://github.com/block/buzz/commit/73962435b6dd7c67b29e650e4f11ae8efcd9af5d)) +- feat(buzz-db): retire the channel-TTL trigger ([#8210](https://github.com/block/buzz/pull/8210)) ([`c0ab789499bde118a468178d23b726fd109a8e1c`](https://github.com/block/buzz/commit/c0ab789499bde118a468178d23b726fd109a8e1c)) +- docs(nips): define agent-key assertions in NIP-FA and NIP-FI ([#8384](https://github.com/block/buzz/pull/8384)) ([`dff0d16b2a4da2ab362a8311070f2422e73bd2bd`](https://github.com/block/buzz/commit/dff0d16b2a4da2ab362a8311070f2422e73bd2bd)) +- feat(mobile): find people by name through the relay's name-only profile search ([#8333](https://github.com/block/buzz/pull/8333)) ([`93ffc37cbdb7ced6a07eca11744931cdffb82e20`](https://github.com/block/buzz/commit/93ffc37cbdb7ced6a07eca11744931cdffb82e20)) +- fix(ios): respect app minimum in generated CocoaPods targets ([#8379](https://github.com/block/buzz/pull/8379)) ([`46159fcf916691217ce6520735997b881be8d8d4`](https://github.com/block/buzz/commit/46159fcf916691217ce6520735997b881be8d8d4)) +- fix(relay): confirm requested channels in one membership query ([#8378](https://github.com/block/buzz/pull/8378)) ([`d039d9a2d541fe8b767462b2ddaca73889154c69`](https://github.com/block/buzz/commit/d039d9a2d541fe8b767462b2ddaca73889154c69)) +- fix(mobile): split channel history batches at the relay channel cap ([#8342](https://github.com/block/buzz/pull/8342)) ([`66d5354586c5f7c83f39b4d7873b538185729dd3`](https://github.com/block/buzz/commit/66d5354586c5f7c83f39b4d7873b538185729dd3)) +- fix(search): normalize profile name tiers in one place ([#8334](https://github.com/block/buzz/pull/8334)) ([`7852b1670c7588875fc43ef2613c8348893d5ab6`](https://github.com/block/buzz/commit/7852b1670c7588875fc43ef2613c8348893d5ab6)) +- feat(relay): add profile search over name and display_name only ([#8301](https://github.com/block/buzz/pull/8301)) ([`f148c0f22c35105524527dec8e4a7285c26804c6`](https://github.com/block/buzz/commit/f148c0f22c35105524527dec8e4a7285c26804c6)) +- Bring synced Solo chats and projects to mobile ([#8337](https://github.com/block/buzz/pull/8337)) ([`b1d60f98e2f7842afb07cd2a163b6eb5973bd1bf`](https://github.com/block/buzz/commit/b1d60f98e2f7842afb07cd2a163b6eb5973bd1bf)) +- feat(search): add newest-first sort to bridge search ([#8371](https://github.com/block/buzz/pull/8371)) ([`cdfc38ecbd4eb1a1cf5d45de9a5e982292574d5d`](https://github.com/block/buzz/commit/cdfc38ecbd4eb1a1cf5d45de9a5e982292574d5d)) +- fix(ios): fetch profiles and avatars in notification extension ([#8369](https://github.com/block/buzz/pull/8369)) ([`fea02d174d0762b18b73138abc833d7c140f9718`](https://github.com/block/buzz/commit/fea02d174d0762b18b73138abc833d7c140f9718)) +- Use native UIKit scrolling for iOS photo carousels ([#8361](https://github.com/block/buzz/pull/8361)) ([`d61fe2071d2b3d8e56dd931947f16bfe0d6173fe`](https://github.com/block/buzz/commit/d61fe2071d2b3d8e56dd931947f16bfe0d6173fe)) +- Match mobile reply links to desktop connectors ([#8362](https://github.com/block/buzz/pull/8362)) ([`9296660d1e0955a63a423344237eeec0396de7f1`](https://github.com/block/buzz/commit/9296660d1e0955a63a423344237eeec0396de7f1)) +- Polish mobile bubbles, mentions, galleries, and huddle cards ([#8359](https://github.com/block/buzz/pull/8359)) ([`42b395cdefcab1b33afa2be7bb44adf38c62aaef`](https://github.com/block/buzz/commit/42b395cdefcab1b33afa2be7bb44adf38c62aaef)) +- docs(nip-ap): narrow relay support and allow offline start ([#8368](https://github.com/block/buzz/pull/8368)) ([`90929506207ea11b2b010a2893a5e69f51cbfa87`](https://github.com/block/buzz/commit/90929506207ea11b2b010a2893a5e69f51cbfa87)) +- chore(push): retire push notification database trigger ([#8352](https://github.com/block/buzz/pull/8352)) ([`6766174673b99f031a1cee7a2d5ef007b5a8e66c`](https://github.com/block/buzz/commit/6766174673b99f031a1cee7a2d5ef007b5a8e66c)) +- fix(push): verify extended App Attest proofs with a focused owned module ([#8329](https://github.com/block/buzz/pull/8329)) ([`5397ea49e27fd56d4e0346e2120906d09ac91579`](https://github.com/block/buzz/commit/5397ea49e27fd56d4e0346e2120906d09ac91579)) +- Align mobile appearance and channels with desktop ([#8358](https://github.com/block/buzz/pull/8358)) ([`a5dfdd6d55773decff0ae3486f571fcce94b39f9`](https://github.com/block/buzz/commit/a5dfdd6d55773decff0ae3486f571fcce94b39f9)) +- feat(relay): let channel-state filters opt in to system channels ([#8182](https://github.com/block/buzz/pull/8182)) ([`d28f6b2f7095b50a2c987a42e9b4ca345f8e9dac`](https://github.com/block/buzz/commit/d28f6b2f7095b50a2c987a42e9b4ca345f8e9dac)) +- feat(relay): leave system channels out of reads that do not name them ([#8181](https://github.com/block/buzz/pull/8181)) ([`cdf03f618aee1fb2be91c0be9b8d5370d0e3109d`](https://github.com/block/buzz/commit/cdf03f618aee1fb2be91c0be9b8d5370d0e3109d)) +- perf(mobile): cut test wall time and run mobile CI lanes in parallel ([#8347](https://github.com/block/buzz/pull/8347)) ([`b77ba862627c7362a4b863a0a077677d811a7558`](https://github.com/block/buzz/commit/b77ba862627c7362a4b863a0a077677d811a7558)) +- fix(mobile): keep thread references consistent across push and Inbox ([#8332](https://github.com/block/buzz/pull/8332)) ([`8222e99915c7c4a3311e32c5dee989df88c49a48`](https://github.com/block/buzz/commit/8222e99915c7c4a3311e32c5dee989df88c49a48)) +- docs(nip-ap): store agent and team config as NIP-AR artifacts ([#8295](https://github.com/block/buzz/pull/8295)) ([`349f566e93bec9c0caa6df7161a4fdc592652430`](https://github.com/block/buzz/commit/349f566e93bec9c0caa6df7161a4fdc592652430)) +- fix(relay): match pushed-down tags by position, not containment ([#8335](https://github.com/block/buzz/pull/8335)) ([`e645918c6334f8a4d89638349106e73d318adff5`](https://github.com/block/buzz/commit/e645918c6334f8a4d89638349106e73d318adff5)) +- feat(mobile): write catch-up and visible-message read marks like the web app ([#8106](https://github.com/block/buzz/pull/8106)) ([`9ade5d1ad1448a05061d3c27dd181d814dde2cf3`](https://github.com/block/buzz/commit/9ade5d1ad1448a05061d3c27dd181d814dde2cf3)) +- feat(relay): match label and creator filters before the page limit ([#8176](https://github.com/block/buzz/pull/8176)) ([`a3909acc672619375669dff5274bb8e3cdfdc88b`](https://github.com/block/buzz/commit/a3909acc672619375669dff5274bb8e3cdfdc88b)) +- fix(relay): reject unreadable write targets as missing ([#8249](https://github.com/block/buzz/pull/8249)) ([`b3795236ccde4cefaebfd3da06ce4c838b76e78a`](https://github.com/block/buzz/commit/b3795236ccde4cefaebfd3da06ce4c838b76e78a)) +- fix(mobile): replay native navigation state when returning Home ([#8314](https://github.com/block/buzz/pull/8314)) ([`a83ea69b722a8dcfcacf7b560157651d208a1018`](https://github.com/block/buzz/commit/a83ea69b722a8dcfcacf7b560157651d208a1018)) +- Refresh mobile message bubbles, reactions, and activity cards ([#8281](https://github.com/block/buzz/pull/8281)) ([`231a469de5652ce425782e98fcd011881fb24fe8`](https://github.com/block/buzz/commit/231a469de5652ce425782e98fcd011881fb24fe8)) +- fix(ios): open push replies in their containing thread ([#8294](https://github.com/block/buzz/pull/8294)) ([`7b9551aba830019a875b6fc24b5a25d74eceeb65`](https://github.com/block/buzz/commit/7b9551aba830019a875b6fc24b5a25d74eceeb65)) +- fix(ci): remove Detect Changed Paths timeout and deletion test race ([#8300](https://github.com/block/buzz/pull/8300)) ([`ea24a3ee3d74679c8c489b83d351409e1b8d503e`](https://github.com/block/buzz/commit/ea24a3ee3d74679c8c489b83d351409e1b8d503e)) +- test(buzz-db): drop partition scratch schemas on panic ([#8293](https://github.com/block/buzz/pull/8293)) ([`2270b66e147c8955edbfc445aed4b9633f9dff6e`](https://github.com/block/buzz/commit/2270b66e147c8955edbfc445aed4b9633f9dff6e)) +- ci(docker): publish qualified, sortable push gateway main tags ([#8305](https://github.com/block/buzz/pull/8305)) ([`99c5fc8bba2c4037ac1d72a82f7afea18905d66d`](https://github.com/block/buzz/commit/99c5fc8bba2c4037ac1d72a82f7afea18905d66d)) +- docs: link the Buzz feedback community and @buzzdotxyz on X ([#8324](https://github.com/block/buzz/pull/8324)) ([`e68977f2708bf5666ae2e4946b6a860225bde49e`](https://github.com/block/buzz/commit/e68977f2708bf5666ae2e4946b6a860225bde49e)) +- buzz-db: admit every fenced-table writer in app code ([#8219](https://github.com/block/buzz/pull/8219)) ([`d25384a4f3c3a940b5b999f26105091c58ab76d6`](https://github.com/block/buzz/commit/d25384a4f3c3a940b5b999f26105091c58ab76d6)) +- fix(buzz-db): delete workflow and membership children explicitly ([#8212](https://github.com/block/buzz/pull/8212)) ([`52d13efc08ec2b80878f24672913ac465b37e148`](https://github.com/block/buzz/commit/52d13efc08ec2b80878f24672913ac465b37e148)) +- feat(relay): allow HTTP operator listener delivery URLs ([#8287](https://github.com/block/buzz/pull/8287)) ([`8599efb6a3cfbd3d4bc4534f6de766b4481c7fca`](https://github.com/block/buzz/commit/8599efb6a3cfbd3d4bc4534f6de766b4481c7fca)) +- docs(nips): allow NIP-FA session token on the adapter origin ([#8198](https://github.com/block/buzz/pull/8198)) ([`43b88c3a76dada96fcbdc23e521569b95c9fd206`](https://github.com/block/buzz/commit/43b88c3a76dada96fcbdc23e521569b95c9fd206)) +- fix(relay): partition audit observability follow-ups ([#7994](https://github.com/block/buzz/pull/7994)) ([`85b7331784804fbf9bb07df4199d4dc6a2b42ade`](https://github.com/block/buzz/commit/85b7331784804fbf9bb07df4199d4dc6a2b42ade)) +- ci(docker): publish a sortable main-- relay tag ([#8240](https://github.com/block/buzz/pull/8240)) ([`d6dc813290680231e90cf7954d99ec60055750dd`](https://github.com/block/buzz/commit/d6dc813290680231e90cf7954d99ec60055750dd)) +- Use grouped message action sheets and fix date layering ([#8280](https://github.com/block/buzz/pull/8280)) ([`b5223d2525defa2a53dcd29ddcc69f609b8711ab`](https://github.com/block/buzz/commit/b5223d2525defa2a53dcd29ddcc69f609b8711ab)) +- fix(ci): restore green main after merge skew and new advisory ([#8277](https://github.com/block/buzz/pull/8277)) ([`03ce924e32388b350b5235ed307629e41b518d88`](https://github.com/block/buzz/commit/03ce924e32388b350b5235ed307629e41b518d88)) +- Start the ACP idle interval when channel turns complete ([#8149](https://github.com/block/buzz/pull/8149)) ([`799cfd70504c78ebb1958279c08110ce925acd27`](https://github.com/block/buzz/commit/799cfd70504c78ebb1958279c08110ce925acd27)) +- fix(mobile): keep notification toggle usable and match row height ([#8223](https://github.com/block/buzz/pull/8223)) ([`c09730e87466de572fb6218375aef2c3d915dd7d`](https://github.com/block/buzz/commit/c09730e87466de572fb6218375aef2c3d915dd7d)) +- chore(hermit): share one CARGO_HOME across worktrees ([#8250](https://github.com/block/buzz/pull/8250)) ([`845fc16ebf5ec84f87a94ceaf69bb79c004b3a76`](https://github.com/block/buzz/commit/845fc16ebf5ec84f87a94ceaf69bb79c004b3a76)) +- perf(relay): drop per-pulse ban reads and owner-link writes on HTTP ([#8233](https://github.com/block/buzz/pull/8233)) ([`326e2301cb4b1edcb8a72d01ac4b19a83545365f`](https://github.com/block/buzz/commit/326e2301cb4b1edcb8a72d01ac4b19a83545365f)) +- release: publish push gateway chart 0.4.0 ([#8231](https://github.com/block/buzz/pull/8231)) ([`19aa619fdd70e916269b343232276d9ee68276df`](https://github.com/block/buzz/commit/19aa619fdd70e916269b343232276d9ee68276df)) +- refactor(push): one app profile per gateway ([#8206](https://github.com/block/buzz/pull/8206)) ([`868e2f8f3271af6625981219b0bce2093033e7be`](https://github.com/block/buzz/commit/868e2f8f3271af6625981219b0bce2093033e7be)) +- perf(relay): cache ephemeral-path serving and restriction reads ([#8208](https://github.com/block/buzz/pull/8208)) ([`bcc46fe8359a2bfd2bc26e6a7a1a1f8c29d44149`](https://github.com/block/buzz/commit/bcc46fe8359a2bfd2bc26e6a7a1a1f8c29d44149)) +- chore(ci): run Codex security review on gpt-6.1-sol ([#8228](https://github.com/block/buzz/pull/8228)) ([`2b3f5023fe8ff92f1e05f5753b1fc5869df4bd97`](https://github.com/block/buzz/commit/2b3f5023fe8ff92f1e05f5753b1fc5869df4bd97)) +- fix(push): isolate push enqueue and stop workers on rollback ([#8216](https://github.com/block/buzz/pull/8216)) ([`5b907b838a44d7985e98836177aec2903717381f`](https://github.com/block/buzz/commit/5b907b838a44d7985e98836177aec2903717381f)) +- feat(relay): reshape read-state API to the sidebar wire format ([#8220](https://github.com/block/buzz/pull/8220)) ([`1e80066c932250b87bd8a794f4143c0a88021c30`](https://github.com/block/buzz/commit/1e80066c932250b87bd8a794f4143c0a88021c30)) + +[Compare desktop-v0.5.28...desktop-v0.5.29](https://github.com/block/buzz/compare/desktop-v0.5.28...desktop-v0.5.29) + ## v0.5.28 ### Desktop and shared changes diff --git a/CONTEXT.md b/CONTEXT.md index c9f74be0dff..2dd6932bb45 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -1,6 +1,6 @@ # Buzz domain language -Shared terminology for Buzz product behavior. This glossary currently covers mobile [push suppression](#push-suppression); it is not a complete model of Buzz. +Shared terminology for Buzz product behavior. This glossary currently covers mobile [push suppression](#push-suppression), the [notification body](#notification-body), [mobile builds](#mobile-builds), [sharing](#sharing) and [quick send](#quick-send); it is not a complete model of Buzz. ## Notifications @@ -8,6 +8,10 @@ Shared terminology for Buzz product behavior. This glossary currently covers mob A notification directed to a user's mobile installation through the platform's push service. +### Notification body + +The text a [mobile push notification](#mobile-push-notification) shows for a message: the message's text with its Markdown syntax removed, cut only where the platform would cut it. See [ADR 0002](docs/adr/0002-notification-message-text.md). + ### Push suppression Withholding an otherwise eligible [mobile push notification](#mobile-push-notification) based on [desktop activity](#desktop-activity) and a working connection to the relevant community. It does not depend on whether desktop alerts can be shown. @@ -51,3 +55,45 @@ A [suppression activity signal](#suppression-activity-signal) that extends how l ### Inactivity cutoff The time of the last observed [desktop activity](#desktop-activity) plus the duration specified in the spec, when [desktop inactivity](#desktop-inactivity) begins. New desktop activity moves this cutoff forward. + +## Mobile builds + +### Internal build + +A mobile app an organization distributes only to its own members, for example through device management. It uses only that organization's Builderlab and reaches only that organization's community. + +_Avoid_: Dogfood build, enterprise build, org build + +### Public build + +The mobile app distributed through the App Store and TestFlight. It uses only the public Builderlab and cannot reach any organization's community. + +_Avoid_: App Store build, external build + +## Sharing + +### Share + +Bringing content such as a screenshot, screen recording, URL or text from another app into a Buzz conversation through the system share sheet. A share ends in that conversation's composer, where the person adds their own text and sends it. + +_Avoid_: Forward, post + +### Share target + +A conversation offered among the share sheet's suggested destinations: an existing channel or DM, or a new Solo chat. Share targets are learned from top-level messages a person sends in a conversation; thread replies and incoming messages never count. + +_Avoid_: Recipient, contact, suggestion + +## Agents and conversations + +### Bestie + +The one agent a person has chosen as their default in a community. A community has at most one Bestie per person. + +_Avoid_: Default agent, main agent, assistant + +### Quick send + +Sending a message to Buzz from outside the app (Siri, Shortcuts, the Action button) without opening Buzz. A quick send to the [Bestie](#bestie) posts the message in the person's DM with the Bestie. + +_Avoid_: Siri message, dictation, background send diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2beb40bd5a4..c7c79cf5ba9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -83,8 +83,8 @@ We review as capacity allows — focused PRs that follow this guide move fastest | Rust | 1.88+ | Install via [rustup](https://rustup.rs/) | | Node.js | 24+ | Required for desktop app commands and `just ci` | | pnpm | 10+ | Required for desktop app commands and `just ci` | -| Flutter | 3.47.7+ | Required for mobile app — install via [flutter.dev](https://docs.flutter.dev/get-started/install) | -| Xcode | 27.0 recommended; 26 supported | Required for iOS builds; see [iOS toolchain setup](mobile/README.md#ios-toolchain) | +| Flutter | 3.47.9+ | Required for mobile app — install via [flutter.dev](https://docs.flutter.dev/get-started/install) | +| Xcode | 27.1 recommended; 26 supported | Required for iOS builds; see [iOS toolchain setup](mobile/README.md#ios-toolchain) | | Docker | 24+ | For Postgres, Redis, MinIO | | `just` | latest | Task runner — `cargo install just` | | `lefthook` | 2.1.3 (Hermit-pinned) | Auto-installed by `just hooks` — no manual install needed | @@ -304,6 +304,34 @@ just ci This is the same check that runs in CI. PRs that fail `just ci` will not be merged. If `just ci` fails on formatting, `just fix-all` fixes it in one shot (`rustfmt` + Tauri fmt + desktop, web, and mobile formatters). +Pull requests also get an advisory **flake check**. `scripts/flake-check.mjs +select` maps the diff against the base branch to the Rust tests (in the root +and desktop Tauri workspaces), desktop `node --test` files, Playwright smoke +journeys and Flutter test files it changed: a hunk inside a test body selects +that test; a change anywhere else in a test file (imports, helpers, hooks, +the code under test beside Rust tests) or a new file selects the whole file. +An integration test binary's tests include those of the file modules its +root declares (`mod x;`, `#[path = "…"] mod x;`), and a change to a helper +module under a crate's `tests/` selects every integration test binary that +includes it. The `Flake check (…)` lanes then +run that selection ten times with retries off; a repetition that fails is +usually a race in the test or the code under it, worth fixing before it +lands, though a test that needs infrastructure or the regular lane's +cross-file concurrency can fail every repetition instead. Some changed tests +are deliberately not repeated: `#[ignore]`d and Postgres-backed Rust tests, +Playwright specs outside the `smoke` project, `*.perf.ts` measurements, and a +selection too large for its lane (over 64 KiB of entries, or more Playwright +journeys than ten repetitions can finish within the lane's timeout). +A Rust test repeats in every feature graph the regular lanes test its +package in that lists it (LaunchDarkly, the App Attest development feature, +the desktop crate's lib under `mesh-llm`), since a `#[cfg(feature = …)]` arm +compiles only in its own graph; the step summary marks a row from a feature +graph with that feature. A selected test that no such graph lists on the +Linux runner, such as a macOS-only one, fails its lane by name rather than +passing unrepeated. +The lanes skip when no test changed and are not required to merge; their +step summaries show the selection and the test × iteration table. + --- ## Code Style @@ -414,6 +442,11 @@ because we can't safely review them without prior discussion: - **Cosmetic renames or style-only churn** that doesn't fix a bug or improve clarity - **Entirely new features** with no prior discussion +- **Feature work in `desktop/`** — `desktop/` is the deprecated Buzz 0.X + desktop app. Build desktop features in + [block/buzz-app](https://github.com/block/buzz-app) instead; change + `desktop/` here only to fix a 0.X bug or to keep it compiling after a shared + crate change - **Drive-by changes bundled into an unrelated fix** — split them out If you're considering any of these, open an issue first and we'll tell you @@ -454,15 +487,18 @@ to existing clients. ## Ecosystem Buzz is developed across multiple repositories. This repo (`block/buzz`) -is the open-source home for all application code — the relay, desktop app, -mobile app, CLI, and agent harness. Internal repositories handle +is the open-source home for the relay, mobile app, CLI, and agent harness. +It also holds `desktop/`, the deprecated Buzz 0.X desktop app. The Buzz 1.0 +desktop and web app lives in [block/buzz-app](https://github.com/block/buzz-app), +and all new desktop feature work goes there. Internal repositories handle enterprise-signed builds and infrastructure deployment. See [AGENTS.md § Ecosystem](AGENTS.md#ecosystem) for the full repo table and dependency diagram. -**External contributors:** Fork `block/buzz`, open a PR, and CI runs -automatically. No special access is required. +**External contributors:** Fork `block/buzz` (or `block/buzz-app` for +desktop work), open a PR, and CI runs automatically. No special access is +required. **Block team members:** See the internal [sprout-releases CONTRIBUTING.md](https://github.com/squareup/sprout-releases/blob/main/CONTRIBUTING.md) diff --git a/Cargo.lock b/Cargo.lock index 47c88f626c4..c4cef47291d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -166,7 +166,7 @@ checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" dependencies = [ "keyring-core", "log", - "security-framework", + "security-framework 3.7.0", ] [[package]] @@ -971,6 +971,8 @@ name = "buzz-admin" version = "0.1.0" dependencies = [ "anyhow", + "axum", + "base64 0.22.1", "buzz-audit", "buzz-auth", "buzz-core", @@ -981,13 +983,15 @@ dependencies = [ "buzz-search", "buzz-workflow", "clap", - "deadpool-redis", "hex", "nostr 0.44.7", + "reqwest 0.13.4", "rustls", "serde", "serde_json", + "sha2 0.11.0", "sqlx", + "tempfile", "tokio", "tracing", "url", @@ -1076,6 +1080,8 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tracing", + "unicode-normalization", + "unicode-properties", "url", "uuid", ] @@ -1115,8 +1121,12 @@ dependencies = [ "clap", "diffy", "dirs", + "futures-util", "hex", + "httpdate", "infer", + "keyring 3.6.3", + "libc", "nostr 0.44.7", "rand 0.10.1", "reqwest 0.13.4", @@ -1127,6 +1137,7 @@ dependencies = [ "tempfile", "thiserror 2.0.18", "tokio", + "tokio-tungstenite 0.29.0", "url", "uuid", ] @@ -1212,9 +1223,9 @@ dependencies = [ "buzz-core", "buzz-db", "buzz-media", + "buzz-pubsub", "chrono", "clap", - "deadpool-redis", "hex", "nostr 0.44.7", "redis", @@ -1261,7 +1272,6 @@ dependencies = [ "http", "launchdarkly-server-sdk", "serde_json", - "tempfile", "thiserror 2.0.18", "tokio", ] @@ -1311,6 +1321,7 @@ dependencies = [ "tracing", "ulid", "uuid", + "webp", ] [[package]] @@ -1384,10 +1395,10 @@ dependencies = [ name = "buzz-pubsub" version = "0.1.0" dependencies = [ + "arc-swap", "buzz-auth", "buzz-core", "chrono", - "deadpool-redis", "futures-util", "nostr 0.44.7", "redis", @@ -1440,7 +1451,7 @@ dependencies = [ [[package]] name = "buzz-relay" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "arc-swap", @@ -1450,11 +1461,13 @@ dependencies = [ "base64 0.22.1", "buzz-audit", "buzz-auth", + "buzz-cli", "buzz-conformance", "buzz-core", "buzz-datastore-tracing", "buzz-db", "buzz-deletion", + "buzz-feature-flags", "buzz-media", "buzz-pubsub", "buzz-relay-mesh", @@ -1464,7 +1477,6 @@ dependencies = [ "bytes", "chrono", "dashmap", - "deadpool-redis", "flate2", "futures", "futures-util", @@ -1543,8 +1555,8 @@ dependencies = [ name = "buzz-relay-mesh" version = "0.1.0" dependencies = [ + "buzz-pubsub", "bytes", - "deadpool-redis", "futures-util", "hex", "hmac 0.13.0", @@ -1602,8 +1614,10 @@ dependencies = [ "buzz-sdk", "buzz-ws-client", "chrono", + "clap", "futures-util", "hex", + "image", "nostr 0.44.7", "rand 0.10.1", "reqwest 0.13.4", @@ -1616,6 +1630,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-tungstenite 0.29.0", + "toml", "tracing", "tracing-subscriber", "url", @@ -1653,15 +1668,18 @@ dependencies = [ "dashmap", "evalexpr", "hex", + "metrics", "moka", "nostr 0.44.7", "reqwest 0.13.4", "serde", "serde_json", "serde_yaml", + "sqlx", "thiserror 2.0.18", "tokio", "tracing", + "tracing-subscriber", "uuid", ] @@ -2645,33 +2663,33 @@ dependencies = [ ] [[package]] -name = "deadpool" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "883466cb8db62725aee5f4a6011e8a5d42912b42632df32aad57fc91127c6e04" -dependencies = [ - "deadpool-runtime", - "num_cpus", - "tokio", -] - -[[package]] -name = "deadpool-redis" -version = "0.23.0" +name = "dbus" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bafa30c49dafe086d10116074e422ad7fc1c3cf554697e744a3ab112599ebd09" +checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e" dependencies = [ - "deadpool", - "redis", + "libc", + "libdbus-sys", + "windows-sys 0.61.2", ] [[package]] -name = "deadpool-runtime" -version = "0.3.1" +name = "dbus-secret-service" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2657f61fb1dd8bf37a8d51093cc7cee4e77125b22f7753f49b289f831bec2bae" +checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" dependencies = [ - "tokio", + "aes 0.8.4", + "block-padding 0.3.3", + "cbc 0.1.2", + "dbus", + "fastrand", + "hkdf 0.12.4", + "num", + "once_cell", + "openssl", + "sha2 0.10.9", + "zeroize", ] [[package]] @@ -3524,8 +3542,8 @@ dependencies = [ "libc", "log", "rustversion", - "windows-link 0.2.1", - "windows-result 0.4.1", + "windows-link 0.1.3", + "windows-result 0.3.4", ] [[package]] @@ -3641,6 +3659,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "globset" version = "0.4.18" @@ -3954,6 +3978,15 @@ dependencies = [ "tracing", ] +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac 0.12.1", +] + [[package]] name = "hkdf" version = "0.13.0" @@ -4167,7 +4200,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core 0.62.2", + "windows-core 0.61.2", ] [[package]] @@ -4880,6 +4913,21 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "dbus-secret-service", + "log", + "openssl", + "secret-service 4.0.0", + "security-framework 2.11.1", + "security-framework 3.7.0", + "zeroize", +] + [[package]] name = "keyring" version = "4.2.0" @@ -5082,6 +5130,16 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libdbus-sys" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "libloading" version = "0.9.0" @@ -5118,6 +5176,16 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "libwebp-sys" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54cd30df7c7165ce74a456e4ca9732c603e8dc5e60784558c1c6dc047f876733" +dependencies = [ + "cc", + "glob", +] + [[package]] name = "line-clipping" version = "0.3.7" @@ -5564,7 +5632,7 @@ dependencies = [ "http-body-util", "httparse", "iroh", - "keyring", + "keyring 4.2.0", "libc", "mdns-sd", "mesh-llm-api-server", @@ -5651,7 +5719,7 @@ dependencies = [ "dirs", "ed25519-dalek", "hex", - "keyring", + "keyring 4.2.0", "rand 0.10.1", "serde", "serde_json", @@ -6729,16 +6797,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "num_cpus" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" -dependencies = [ - "hermit-abi", - "libc", -] - [[package]] name = "num_enum" version = "0.7.6" @@ -8124,7 +8182,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.60.2", + "windows-sys 0.59.0", ] [[package]] @@ -8445,14 +8503,11 @@ version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bae41a63fd0b8a5372f82b21e810e09a316f5dd7efd96bf08e678fb240fc1918" dependencies = [ - "arc-swap", "arcstr", "async-lock", - "backon", "bytes", "cfg-if 1.0.4", "combine", - "futures-channel", "futures-util", "itoa", "num-bigint", @@ -8895,7 +8950,7 @@ dependencies = [ "openssl-probe", "rustls-pki-types", "schannel", - "security-framework", + "security-framework 3.7.0", ] [[package]] @@ -8923,7 +8978,7 @@ dependencies = [ "rustls-native-certs", "rustls-platform-verifier-android", "rustls-webpki", - "security-framework", + "security-framework 3.7.0", "security-framework-sys", "webpki-root-certs", "windows-sys 0.61.2", @@ -9172,6 +9227,25 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secret-service" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" +dependencies = [ + "aes 0.8.4", + "cbc 0.1.2", + "futures-util", + "generic-array", + "hkdf 0.12.4", + "num", + "once_cell", + "rand 0.8.6", + "serde", + "sha2 0.10.9", + "zbus 4.4.0", +] + [[package]] name = "secret-service" version = "5.2.0" @@ -9182,13 +9256,26 @@ dependencies = [ "cbc 0.2.1", "futures-util", "getrandom 0.4.3", - "hkdf", + "hkdf 0.13.0", "hybrid-array", "num", "once_cell", "serde", "sha2 0.11.0", - "zbus", + "zbus 5.19.0", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.13.0", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", ] [[package]] @@ -9881,10 +9968,9 @@ dependencies = [ [[package]] name = "sqlx" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378620ccc25c62c89d8be1c819e76a88d59bdcc3304733330788948e619bfd71" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ - "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sqlx-core", "sqlx-macros", "sqlx-mysql", "sqlx-postgres", @@ -9894,8 +9980,7 @@ dependencies = [ [[package]] name = "sqlx-core" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "base64 0.22.1", "bytes", @@ -9918,7 +10003,7 @@ dependencies = [ "rustls", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "smallvec", "thiserror 2.0.18", "tokio", @@ -9929,48 +10014,14 @@ dependencies = [ "webpki-roots 1.0.10", ] -[[package]] -name = "sqlx-core" -version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=94aafe3a68884d923b0798a767c8d7f6cfda89d2#94aafe3a68884d923b0798a767c8d7f6cfda89d2" -dependencies = [ - "base64 0.22.1", - "bytes", - "cfg-if 1.0.4", - "chrono", - "crc", - "crossbeam-queue", - "either", - "event-listener", - "futures-core", - "futures-intrusive", - "futures-io", - "futures-util", - "hashbrown 0.16.1", - "hashlink", - "indexmap 2.14.0", - "log", - "memchr", - "percent-encoding", - "serde", - "serde_json", - "sha2 0.11.0", - "smallvec", - "thiserror 2.0.18", - "tracing", - "url", - "uuid", -] - [[package]] name = "sqlx-macros" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd2b84f2bc39a5705ef27ec785a11c934a41bbd4a24941e257927cddc26b60bf" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "proc-macro2", "quote", - "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sqlx-core", "sqlx-macros-core", "syn 2.0.117", ] @@ -9978,8 +10029,7 @@ dependencies = [ [[package]] name = "sqlx-macros-core" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb8d96de5fdc85a5c4ec813432b523ec637e80ba98f046555f75f7908ddac7c3" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "cfg-if 1.0.4", "dotenvy", @@ -9990,8 +10040,8 @@ dependencies = [ "quote", "serde", "serde_json", - "sha2 0.10.9", - "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sha2 0.11.0", + "sqlx-core", "sqlx-mysql", "sqlx-postgres", "sqlx-sqlite", @@ -10004,8 +10054,7 @@ dependencies = [ [[package]] name = "sqlx-mysql" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90b8020fe17c5f2c245bfa2505d7ef59c5604839527c740266ad2214acebea27" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "bitflags 2.13.0", "byteorder", @@ -10023,7 +10072,7 @@ dependencies = [ "serde", "sha1 0.11.0", "sha2 0.11.0", - "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sqlx-core", "thiserror 2.0.18", "tracing", "uuid", @@ -10032,8 +10081,7 @@ dependencies = [ [[package]] name = "sqlx-postgres" version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "atoi", "base64 0.22.1", @@ -10047,7 +10095,7 @@ dependencies = [ "futures-core", "futures-util", "hex", - "hkdf", + "hkdf 0.13.0", "hmac 0.13.0", "itoa", "log", @@ -10058,7 +10106,7 @@ dependencies = [ "serde_json", "sha2 0.11.0", "smallvec", - "sqlx-core 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sqlx-core", "stringprep", "thiserror 2.0.18", "tracing", @@ -10069,7 +10117,7 @@ dependencies = [ [[package]] name = "sqlx-sqlite" version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=94aafe3a68884d923b0798a767c8d7f6cfda89d2#94aafe3a68884d923b0798a767c8d7f6cfda89d2" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "atoi", "chrono", @@ -10084,7 +10132,7 @@ dependencies = [ "log", "percent-encoding", "serde", - "sqlx-core 0.9.0 (git+https://github.com/launchbadge/sqlx?rev=94aafe3a68884d923b0798a767c8d7f6cfda89d2)", + "sqlx-core", "thiserror 2.0.18", "tracing", "url", @@ -11656,6 +11704,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webp" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c071456adef4aca59bf6a583c46b90ff5eb0b4f758fc347cea81290288f37ce1" +dependencies = [ + "libwebp-sys", +] + [[package]] name = "webpki-root-certs" version = "1.0.10" @@ -12036,11 +12093,11 @@ dependencies = [ [[package]] name = "windows-sys" -version = "0.60.2" +version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets 0.53.5", + "windows-targets 0.52.6", ] [[package]] @@ -12076,30 +12133,13 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", + "windows_i686_gnullvm", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link 0.2.1", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - [[package]] name = "windows-threading" version = "0.1.0" @@ -12130,12 +12170,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -12148,12 +12182,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -12166,24 +12194,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -12196,12 +12212,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -12214,12 +12224,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -12232,12 +12236,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -12250,12 +12248,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winnow" version = "0.7.15" @@ -12291,8 +12283,8 @@ dependencies = [ "log", "serde", "thiserror 2.0.18", - "windows 0.62.2", - "windows-core 0.62.2", + "windows 0.61.3", + "windows-core 0.61.2", ] [[package]] @@ -12360,6 +12352,16 @@ dependencies = [ "rustix", ] +[[package]] +name = "xdg-home" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "xet-client" version = "1.6.0" @@ -12555,6 +12557,38 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +dependencies = [ + "async-broadcast", + "async-process", + "async-recursion", + "async-trait", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix 0.29.0", + "ordered-stream", + "rand 0.8.6", + "serde", + "serde_repr", + "sha1 0.10.6", + "static_assertions", + "tracing", + "uds_windows", + "windows-sys 0.52.0", + "xdg-home", + "zbus_macros 4.4.0", + "zbus_names 3.0.0", + "zvariant 4.2.0", +] + [[package]] name = "zbus" version = "5.19.0" @@ -12585,9 +12619,9 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow 1.0.3", - "zbus_macros", - "zbus_names", - "zvariant", + "zbus_macros 5.19.0", + "zbus_names 4.3.4", + "zvariant 5.15.0", ] [[package]] @@ -12597,8 +12631,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" dependencies = [ "keyring-core", - "secret-service", - "zbus", + "secret-service 5.2.0", + "zbus 5.19.0", +] + +[[package]] +name = "zbus_macros" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.117", + "zvariant_utils 2.1.0", ] [[package]] @@ -12611,9 +12658,20 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.3", - "zbus_names", - "zvariant", - "zvariant_utils", + "zbus_names 4.3.4", + "zvariant 5.15.0", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zbus_names" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +dependencies = [ + "serde", + "static_assertions", + "zvariant 4.2.0", ] [[package]] @@ -12624,7 +12682,7 @@ checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" dependencies = [ "serde", "winnow 1.0.3", - "zvariant", + "zvariant 5.15.0", ] [[package]] @@ -12783,6 +12841,19 @@ dependencies = [ "zune-core", ] +[[package]] +name = "zvariant" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +dependencies = [ + "endi", + "enumflags2", + "serde", + "static_assertions", + "zvariant_derive 4.2.0", +] + [[package]] name = "zvariant" version = "5.15.0" @@ -12794,8 +12865,21 @@ dependencies = [ "serde", "winnow 1.0.3", "zcheapstr", - "zvariant_derive", - "zvariant_utils", + "zvariant_derive 5.15.0", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zvariant_derive" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.117", + "zvariant_utils 2.1.0", ] [[package]] @@ -12808,7 +12892,18 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.3", - "zvariant_utils", + "zvariant_utils 4.2.0", +] + +[[package]] +name = "zvariant_utils" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 5541985154e..5f1bb3d11f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,13 +58,12 @@ tower = { version = "0.5", features = ["timeout", "util", "limit"] } tower-http = { version = "0.6", features = ["trace", "cors", "compression-gzip", "limit", "timeout", "fs"] } # Database -sqlx = { version = "0.9", features = [ +sqlx = { version = "=0.9.0", features = [ "runtime-tokio", "tls-rustls", "postgres", "uuid", "chrono", "json" ] } # Redis -redis = { version = "1.0", features = ["tokio-comp", "connection-manager", "tokio-rustls-comp"] } -deadpool-redis = { version = "0.23", features = ["rt_tokio_1"] } +redis = { version = "1.0", features = ["tokio-comp", "tokio-rustls-comp"] } # Kubernetes (buzz-backend-kubernetes provider). No `ring` feature here: the # process-level CryptoProvider is installed explicitly at startup, matching @@ -104,6 +103,7 @@ anyhow = "1" # Utilities uuid = { version = "1", features = ["v4", "serde"] } chrono = { version = "0.4", features = ["serde"] } +httpdate = "1" # JWT / JWS verification (NIP-FI federated identity assertions) jsonwebtoken = { version = "10.4.0", default-features = false, features = ["aws_lc_rs"] } @@ -159,6 +159,10 @@ buzz-ws-client = { path = "crates/buzz-ws-client" } buzz-relay-mesh = { path = "crates/buzz-relay-mesh" } buzz-datastore-tracing = { path = "crates/buzz-datastore-tracing" } +[profile.release] +lto = "thin" +codegen-units = 4 + # CI profile — builds the relay for desktop e2e. Dependencies keep full # release optimization (warm from main's cache; they carry the runtime hot # path: tokio/sqlx/axum). Workspace crates build at opt-level 1 — enough for @@ -168,6 +172,7 @@ buzz-datastore-tracing = { path = "crates/buzz-datastore-tracing" } [profile.ci] inherits = "release" lto = false +codegen-units = 16 opt-level = 1 [profile.ci.package."*"] @@ -194,8 +199,29 @@ strip = true # allowlist for the auth token). Revert to crates.io once #449 lands upstream. [patch.crates-io] aws-creds = { git = "https://github.com/tlongwell-block/rust-s3", rev = "c9fce3620dd434c1f810101d672cf384268dbb0f" } -# MeshLLM 0.76 uses rusqlite 0.40 / libsqlite3-sys 0.38. SQLx 0.9.0's -# optional SQLite driver still caps libsqlite3-sys below 0.38, which Cargo -# resolves even though Buzz only enables PostgreSQL. Pin the merged upstream -# compatibility fix until it is released: https://github.com/transact-rs/sqlx/pull/4402 -sqlx-sqlite = { git = "https://github.com/launchbadge/sqlx", rev = "94aafe3a68884d923b0798a767c8d7f6cfda89d2" } +# SQLx: pin every crate together; these crates share types. This unreleased +# revision includes the whole-return deadline from the open upstream PR #4407 +# and retains the fixes below. Return to a released version once it includes +# all three fixes: +# - https://github.com/transact-rs/sqlx/pull/4407: bound the entire return to +# the pool, including the release hook and SQLx ping, to five seconds. Silent +# sockets must release their pool permits so new connections can replace them. +# - https://github.com/transact-rs/sqlx/pull/4394: a `BEGIN` whose future is +# dropped before Postgres answers no longer returns its pooled connection +# still inside the transaction. 0.9.0 queues no `ROLLBACK` for it, so the +# next borrower runs inside the leftover transaction (`25001`, then `25P02` +# once a statement in it fails). +# - https://github.com/transact-rs/sqlx/pull/4402: MeshLLM 0.76 uses +# libsqlite3-sys 0.38, which 0.9.0's optional SQLite driver rejects; Cargo +# resolves it even though Buzz only enables PostgreSQL. +# The exact version prevents lockfile updates from selecting a newer unpatched +# release. Renovate updates are disabled for these crates; CI checks this pin +# with scripts/check-sqlx-pin.py. Update that policy only after verifying all +# three fixes in the replacement release. +sqlx = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-core = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-macros = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-macros-core = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-mysql = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-postgres = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-sqlite = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } diff --git a/Dockerfile b/Dockerfile index 02446e144f8..39692acac92 100644 --- a/Dockerfile +++ b/Dockerfile @@ -124,6 +124,7 @@ COPY web/package.json web/ COPY admin-web/package.json admin-web/ RUN pnpm install --frozen-lockfile --filter buzz-web --filter buzz-admin-web COPY web/ web/ +COPY previews/invite-video/buzz-invite-loop.mp4 previews/invite-video/buzz-invite-poster.png previews/invite-video/ COPY admin-web/ admin-web/ RUN pnpm -C web build && pnpm -C admin-web build diff --git a/Dockerfile.loadgen b/Dockerfile.loadgen new file mode 100644 index 00000000000..181b28fa9e8 --- /dev/null +++ b/Dockerfile.loadgen @@ -0,0 +1,37 @@ +# syntax=docker/dockerfile:1.7 +# +# Relay load generator image — published as ghcr.io/block/buzz-loadgen. +# Runs `buzz-loadgen` (crates/buzz-test-client, see perf/LOADGEN.md), for +# example as a Kubernetes Indexed Job with one `run --shard i/n` per pod. +# +# Multi-arch is produced by building this file on native amd64 and arm64 +# runners (see .github/workflows/loadgen-image.yml). Keep both bases pinned to +# manifest-list digests so either architecture resolves to immutable bytes. +FROM rust:1.98-alpine3.22@sha256:a1796ca6fa216d6727b5f61c69e4c665b120b1a4dcb969639e2f25f1ed309456 AS builder + +RUN apk add --no-cache \ + build-base \ + cmake \ + musl-dev \ + perl \ + pkgconf +WORKDIR /build +COPY . . +# --help proves the stripped binary starts on each native architecture. +RUN cargo build --locked --release -p buzz-test-client --bin buzz-loadgen \ + && strip target/release/buzz-loadgen \ + && target/release/buzz-loadgen --help >/dev/null + +FROM alpine:3.22@sha256:14358309a308569c32bdc37e2e0e9694be33a9d99e68afb0f5ff33cc1f695dce + +LABEL org.opencontainers.image.source="https://github.com/block/buzz" + +# Numeric UID/GID so Kubernetes runAsNonRoot can verify the user. +RUN apk add --no-cache ca-certificates \ + && addgroup -g 10001 loadgen \ + && adduser -D -H -u 10001 -G loadgen loadgen + +COPY --from=builder --chmod=0755 /build/target/release/buzz-loadgen /usr/local/bin/buzz-loadgen + +USER 10001:10001 +ENTRYPOINT ["/usr/local/bin/buzz-loadgen"] diff --git a/Dockerfile.sprig b/Dockerfile.sprig index a2867f53d03..a8ca3b7bce3 100644 --- a/Dockerfile.sprig +++ b/Dockerfile.sprig @@ -16,6 +16,10 @@ RUN apk add --no-cache \ protoc WORKDIR /build COPY . . +# GCC's outlined ARM64 atomics require libgcc helpers that Rust's static musl +# link does not provide (notably __aarch64_ldadd4_sync in vendored D-Bus). +# Emit baseline ARM64 atomics inline; cc-rs applies this only to that target. +ENV CFLAGS_aarch64_unknown_linux_musl="-mno-outline-atomics" RUN cargo build --locked --profile sprig -p sprig \ && strip target/sprig/sprig diff --git a/Justfile b/Justfile index 8e197c9a8cb..1833926ebee 100644 --- a/Justfile +++ b/Justfile @@ -409,8 +409,10 @@ test-unit: cargo nextest run -p buzz-auth --test mesh_jwks_proxy cargo nextest run -p buzz-audit --lib # Cross-pod disconnect payload tests (NIP-FI and community archive - # fence); all infra-free. - cargo nextest run -p buzz-pubsub --lib -E 'test(/^conn_control::tests::/)' + # fence), the shared Redis connection's timeout bounds (loopback + # fake peers), and the full-queue retain (no Redis dialed); all + # infra-free. Keep the Cargo fallback in step. + cargo nextest run -p buzz-pubsub --lib -E 'test(/^conn_control::tests::/) + test(/^connection::tests::/) + test(=tests::queue_full_retain_does_not_wait_and_schedules_reconciliation)' # buzz-auth NIP-FI verifier doctests. The sealed-authority # `compile_fail` doctests prove the default-feature public API alone # cannot forge the issuer→JWKS authority; nextest does not run @@ -424,6 +426,8 @@ test-unit: # never dialed). Keep the Cargo fallback in step. cargo nextest run -p buzz-relay-mesh cargo nextest run -p buzz-cli + cargo nextest run -p buzz-ws-client + cargo nextest run -p buzz-pairing-cli # buzz-sdk builder/validation unit tests: pure event-builder and input # validation (e.g. the canvas writer-discipline/skew guard and the # canvas_write_survived predicate), no infra. `--lib` runs all unit @@ -431,6 +435,9 @@ test-unit: # invocation hits. Enumerated explicitly because nothing in CI runs # `cargo test --workspace` — membership buys clippy/check, not tests. cargo nextest run -p buzz-sdk --lib + # buzz-workflow parser, cron, condition and denial-logging unit tests + # (infra-free). Its ignored Postgres cases run in the PostgreSQL lane. + cargo nextest run -p buzz-workflow --lib # buzz-acp owns the relay-to-agent trust boundary. Run its tests here so # forged relay events cannot regain a path into agent routing unnoticed. cargo nextest run -p buzz-acp @@ -444,6 +451,10 @@ test-unit: # #[ignore]d, so --lib runs only the infra-free set. Without this gate a # stray file in migrations/ or a broken lint ships green. cargo nextest run -p buzz-db --lib + # buzz-search unit tests: pure query-builder and cancel-outcome checks + # (no infra). Its Postgres suite runs in the PostgreSQL lane. Keep + # scripts/run-tests.sh in step. + cargo nextest run -p buzz-search --lib # buzz-db source-policy tests: infra-free scans of the crate sources # that enforce the event-write admission chokepoint, metric/provenance # contracts, and their fixtures. They live in an integration-test @@ -462,7 +473,7 @@ test-unit: # parser, validation, and propagation-evidence tests, and the partition # audit outcome contract, NIP-FI policy/backfill, and user-deletion intake. cargo nextest run -p buzz-admin \ - -E 'test(storage_snapshot) + test(/^communities::tests::/) + test(/^tests::communities_/) + test(=tests::partition_audit_outcomes_keep_their_json_names_and_exit_codes) + test(/^nip_fi::tests::/) + test(/^user_deletions::tests::/)' + -E 'test(storage_snapshot) + test(/^communities::tests::/) + test(/^tests::communities_/) + test(=tests::partition_audit_outcomes_keep_their_json_names_and_exit_codes) + test(/^nip_fi::tests::/) + test(/^nip_fi_policy::tests::/) + test(/^user_deletions::tests::/)' # Multi-tenant conformance gate (buzz-conformance): the independent # replay checker + golden fixtures. No infra — pure in-process trace # replay — so it belongs in the unit job. Run all targets (lib + the @@ -507,7 +518,8 @@ test-unit: # #[ignore]d Postgres suites — so these non-ignored tests ran in no lane # and a red one could ship green (exactly how a broken admin test slipped # past every gate once). Scoped to api::admin, not the whole buzz-relay - # --lib, because api::media has non-ignored tests that require Postgres. + # --lib, because much of handlers::req has non-ignored tests that require + # Postgres. # DB-backed api::admin tests are #[ignore]d and run in the PostgreSQL # lane; the non-ignored ones reject before touching the database. Any # new non-ignored test here must stay DB-free: without a database, a @@ -529,9 +541,15 @@ test-unit: # exact name for the same reason: the rest of handlers::req needs a DB. # The third clause adds the NIP-FI HTTP ingress and its router/config # neighbours: nip_fi_http, nip_fi_config, nip_fi_resolver (snapshot - # resolver and its WS/HTTP/audio router tests), router, api::parse_query_tests, - # the profile search request bounds (api::profiles), and the Git - # transport off_mode_precedence_tests. All are infra-free + # resolver and its WS/HTTP/audio router tests), router, api::parse_query_tests, api::db_read_error_tests, + # the profile search request bounds (api::profiles), the per-user + # search cap (api::bridge::search_slots), the Git transport + # off_mode_precedence_tests, and the git object-store + # client and conformance-probe tests (api::git::store::tests and + # ::fault_probe, which serves a fake S3 on loopback; the live-MinIO + # ::probe module stays opt-in), and the git push publish decision + # (api::git::cas_publish::tests and transport::track_c_tests, whose + # Postgres/MinIO cases are #[ignore]d). All are infra-free # and finish in well under a second with no DATABASE_URL, so none wait # out the sqlx acquire timeout. `--bin buzz-relay` adds main.rs's # `tests::` module (JWKS refresh cadence) and `composition_tests::` @@ -544,8 +562,12 @@ test-unit: # All four modules are infra-free; config parses env into a struct and # never connects. # `^config::` is anchored so it does not also select nip_fi_config. + # subscription::tests covers the in-memory registry and its fan-out + # indexes; it is infra-free. handlers::multinode_fanout::tests covers + # cross-node fan-out ordering and drops; its hung-delivery case fakes a + # database that never answers on loopback, and none use DATABASE_URL. cargo nextest run -p buzz-relay --lib --bin buzz-relay \ - -E 'test(/^api::admin::/) + test(/^push_runtime::/) + test(/^operator_listener::tests::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^handlers::system_channels::tests::/) + test(/^nip11::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_core::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_config::tests::/) + test(/^nip_fi_resolver::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + test(/^api::profiles::/) + test(/^api::git::transport::off_mode_precedence_tests::/) + test(/^audio::join::tests::/) + test(/^audio::handler::tests::/) + test(/^nip_fi_gate::tests::/) + test(/^nip_fi_session::tests::/) + test(/^nip_fi_shadow::tests::/) + test(/^nip_fi_shadow_session::tests::/) + test(/^startup_steps::tests::/) + test(/^mesh_boot::tests::/) + test(/^telemetry::tests::/) + test(/^config::tests::/) + test(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + test(=state::tests::periodic_revalidation_disconnects_inside_the_fenced_callback) + test(=state::tests::bare_community_disconnect_fails_closed_when_the_fence_is_unavailable) + test(=connection::tests::send_loop_sends_policy_close_when_community_is_archived) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=handlers::req::tests::timed_out_historical_read_deregisters_before_closed) + test(=handlers::req::tests::superseded_timeout_leaves_replacement_intact) + test(=handlers::req::tests::search_claim_retires_live_and_yields_to_replacement) + test(=handlers::req::tests::concurrent_claims_and_stale_teardowns_keep_the_last_owner) + test(=handlers::req::tests::timeout_closed_is_emitted_before_a_replacement_can_claim) + test(=handlers::req::tests::revoke_then_replacement_keeps_replacement_whole) + test(=handlers::req::tests::claims_after_connection_cleanup_are_refused) + test(=handlers::req::tests::dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::count_fallback_covers_filters_that_can_match_private_deletions) + test(=handlers::req::tests::group_state_t_and_creator_tags_reach_sql_only_for_group_state_kinds) + test(=api::bridge::postgres_tests::bridge_search_mode_extension_accepts_prefix_snake_or_camel_case) + test(=api::bridge::postgres_tests::bridge_search_sort_extension_selects_newest_only_when_named) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/) + test(/^env_filter_tests::/)) - test(/^tests::postgres_tests::/))' + -E 'test(/^api::media_access::tests::/) + test(/^handlers::media_access::tests::/) + test(/^subscription::tests::/) + test(/^handlers::multinode_fanout::tests::/) + test(/^api::admin::/) + test(/^access::tests::/) + test(/^api::git::transport::access_log_tests::/) + test(=api::bridge::postgres_tests::nip98_replay_check_logs_only_its_refusal) + test(=api::bridge::postgres_tests::warn_only_artifact_read_lines_keep_the_filter_summary) + test(=connection::tests::close_totals_count_frames_the_writer_flushed) + test(=connection::tests::dispatcher_counts_each_req_and_count_frame_once) + test(=handlers::req::tests::unqueued_eose_logs_aborted_not_served) + test(=api::bridge::postgres_tests::reject_code_keeps_only_a_known_prefix) + test(=api::bridge::postgres_tests::nip98_replay_check_fails_closed_when_guard_errors) + test(=api::bridge::postgres_tests::verify_bridge_auth_rejects_nip98_event_signed_for_wrong_communitys_host) + test(=api::bridge::postgres_tests::verify_bridge_auth_can_require_payload_tag_for_json_body_endpoints) + test(=api::bridge::postgres_tests::verify_bridge_auth_accepts_nip98_event_signed_for_matching_host) + test(=api::bridge::postgres_tests::moderation_read_query_bearing_nip98_event_verifies_with_matching_query) + test(=api::bridge::postgres_tests::moderation_read_query_bearing_nip98_event_rejected_against_bare_path) + test(=api::bridge::postgres_tests::moderation_read_audit_query_bearing_nip98_event_verifies) + test(=api::bridge::postgres_tests::moderation_read_restricted_no_query_still_verifies) + test(=connection::tests::aborting_lifecycle_owner_is_drop_safe) + test(=connection::tests::shutdown_terminalizes_auth_stalled_on_database_before_late_success) + test(=connection::terminal_close_delivery_tests::upgrade_would_deny_line_without_auth_logs_absent_at_close) + test(=handlers::event::tests::observer_owner_cache_is_scoped_to_community) + test(=state::tests::shared_counter_between_direct_and_fanout) + test(=connection::tests::startup_cancellation_writes_one_close_line) + test(=connection::tests::connection_limit_refusal_writes_one_close_line) + test(=connection::tests::dropped_authenticated_handler_writes_one_close_line) + test(=connection::tests::missed_pongs_close_with_their_reason_and_count) + test(=connection::tests::client_reply_to_a_jittered_restart_closes_as_shutdown) + test(=connection::tests::client_close_racing_a_policy_disconnect_keeps_the_policy_reason) + test(=connection::tests::server_close_reason_ranks_shutdown_policy_then_cancellation) + test(=connection::tests::auth_timeout_after_a_rejected_auth_closes_as_auth_failed) + test(=connection::tests::close_totals_count_a_batch_flushed_by_the_drain_after_cancellation) + test(=connection::tests::close_totals_skip_a_frame_the_socket_rejects) + test(=connection::tests::close_totals_skip_frames_stranded_by_a_failed_flush) + test(=connection::tests::read_before_login_logs_one_denial_from_the_handler) + test(=connection::tests::read_refused_by_a_full_handler_semaphore_logs_one_denial) + test(=connection::tests::saturated_handler_write_line_records_whether_its_ok_was_queued) + test(=connection::tests::read_refused_by_unavailable_admission_logs_one_denial) + test(=handlers::auth::tests::repeat_auth_after_a_terminal_logs_one_denial) + test(=nip_fi_upgrade::tests::deny_protected_logs_one_denied_auth_line) + test(=api::bridge::moderation_refusal_tests::moderation_lookup_failure_is_unavailable) + test(/^push_runtime::/) + test(/^operator_listener::tests::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^handlers::coalesced_refresh::tests::/) + test(/^handlers::system_channels::tests::/) + test(/^nip11::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_core::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_policy::tests::/) + test(/^nip_fi_config::tests::/) + test(/^nip_fi_resolver::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + test(/^api::db_read_error_tests::/) + test(/^api::profiles::/) + test(/^api::bridge::search_slots::tests::/) + test(/^api::git::transport::off_mode_precedence_tests::/) + test(/^api::git::store::tests::/) + test(/^api::git::store::fault_probe::/) + test(/^api::git::cas_publish::tests::/) + test(/^api::git::transport::track_c_tests::/) + test(/^audio::join::tests::/) + test(/^audio::handler::tests::/) + test(/^nip_fi_gate::tests::/) + test(/^nip_fi_session::tests::/) + test(/^nip_fi_shadow::tests::/) + test(/^nip_fi_shadow_session::tests::/) + test(/^startup_steps::tests::/) + test(/^mesh_boot::tests::/) + test(/^telemetry::tests::/) + test(/^config::tests::/) + test(=state::tests::accessible_channel_invalidation_is_scoped_to_community) + test(=state::tests::accessible_channels_join_member_and_open_halves) + test(=state::tests::channel_deleted_invalidation_is_scoped_to_community) + test(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + test(=state::tests::periodic_revalidation_disconnects_inside_the_fenced_callback) + test(=state::tests::bare_community_disconnect_fails_closed_when_the_fence_is_unavailable) + test(=connection::tests::send_loop_sends_policy_close_when_community_is_archived) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=handlers::req::tests::timed_out_historical_read_deregisters_before_closed) + test(=handlers::req::tests::superseded_timeout_leaves_replacement_intact) + test(=handlers::req::tests::search_claim_retires_live_and_yields_to_replacement) + test(=handlers::req::tests::failed_search_closes_without_eose_or_trying_later_filters) + test(=handlers::req::tests::concurrent_claims_and_stale_teardowns_keep_the_last_owner) + test(=handlers::req::tests::timeout_closed_is_emitted_before_a_replacement_can_claim) + test(=handlers::req::tests::revoke_then_replacement_keeps_replacement_whole) + test(=handlers::req::tests::revoke_of_a_replaced_holder_spares_the_pending_replacement) + test(=handlers::req::tests::superseded_or_closed_requests_cannot_claim) + test(=connection::tests::close_fences_a_req_whose_handler_has_not_run) + test(=connection::tests::only_the_newest_same_id_req_answers) + test(=handlers::req::tests::claims_after_connection_cleanup_are_refused) + test(=handlers::req::tests::dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::revoke_dropped_terminal_frame_cancels_connection) + test(=handlers::req::tests::count_fallback_covers_filters_that_can_match_private_deletions) + test(=handlers::req::tests::count_fallback_fetches_one_extra_candidate) + test(=handlers::req::tests::group_state_t_and_creator_tags_reach_sql_only_for_group_state_kinds) + test(=handlers::req::tests::empty_filter_sets_match_nothing_in_sql) + test(=api::bridge::postgres_tests::bridge_search_mode_extension_accepts_prefix_snake_or_camel_case) + test(=api::bridge::postgres_tests::bridge_search_sort_extension_selects_newest_only_when_named) + test(=api::invites::postgres_tests::restriction_tests::postgres_tests::destructive_fixture_rejects_shared_database_urls) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/) + test(/^env_filter_tests::/)) - test(/^tests::postgres_tests::/))' # Note on audio::join::tests scope: the full suite is infra-free (no DB, # no Redis). The infra-free audio/FI regression witnesses — bootstrap # ordering barrier, CommitConfirmed arm, pending-close invisibility, @@ -595,6 +617,7 @@ test-unit: + test(=connection::terminal_close_delivery_tests::blocked_frame_handler_does_not_hold_socket_open) + test(=connection::terminal_close_delivery_tests::refused_bootstrap_holds_connection_slot_until_socket_ends) + test(=connection::terminal_close_delivery_tests::stalled_bootstrap_holds_connection_slot) + + test(=connection::terminal_close_delivery_tests::bootstrap_admits_from_the_cached_community_answer) + test(=connection::terminal_close_delivery_tests::peer_wait_replies_to_client_initiated_close) + test(=handlers::auth::tests::b2_pre_cancelled_connection_never_becomes_authenticated) + test(=handlers::auth::tests::fi_ban_check_error_emits_terminal_authorization_unavailable) @@ -623,9 +646,27 @@ test-unit: + test(=state::tests::nip_fi_disconnect_does_not_close_different_pubkey_audio_socket) + test(=state::tests::nip_fi_disconnect_does_not_close_unproven_audio_socket) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + + test(=state::tests::enforce_end_is_recorded_only_by_the_winning_terminal) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=state::tests::manager_disconnect_sets_reason_enqueues_frame_then_cancels) + test(/^api::nip_fi::/)' + # Public invite metadata and HTTP media delivery are infra-free. + cargo nextest run -p buzz-relay --lib -E 'test(/invite_preview/)' + # Invitation drain/cutoff boundary contracts are infra-free. + cargo nextest run -p buzz-relay --lib -E 'test(/^invite_token::/) + test(/^config::invite_cutoff_tests::/)' + # Runtime concurrency caps: the flag controller, provider selection and + # the AUTH shed through handle_auth, whose stub database refuses at + # once. Infra-free. Keep scripts/run-tests.sh in step. + cargo nextest run -p buzz-relay --lib -E 'test(/^concurrency_limits::tests::/) + test(/^feature_flags::tests::/) + test(=handlers::auth::tests::auth_cap_sheds_a_verified_login_with_a_bare_close)' + # Relay read caches: the admitted-connection index, the shared-read + # gates (open set, restriction, tenant host), the community-active + # cache, tenant host cache, the + # overlong-host rejection and the ban disconnect's restriction-cache + # drop. Infra-free; the + # database URL refuses at once. Keep scripts/run-tests.sh in step. + cargo nextest run -p buzz-relay --lib -E 'test(=state::tests::admitted_index_follows_every_key_change) + test(/^shared_reads::tests::/) + test(/^membership_cache::tests::/) + test(/^community_active::tests::/) + test(=state::tests::concurrent_open_channel_misses_share_the_in_flight_read) + test(=state::tests::concurrent_restriction_and_host_misses_share_the_in_flight_read) + test(=tenant::tests::app_state_resolver_serves_fresh_cached_hosts_only) + test(=tenant::tests::an_overlong_host_fails_closed_before_the_resolver) + test(=state::tests::disconnect_drops_the_cached_restriction_row)' + # Retain partially consumed mesh receives across housekeeping ticks. + cargo nextest run -p buzz-relay --lib -E 'test(=mesh_boot::tests::demo_echo_retains_pending_receive_across_housekeeping_ticks)' # boot_lifecycle spawns the real relay binary and asserts its startup # lifecycle, including that buzz_startup_phase_* reaches /metrics. Its # non-ignored tests need no Postgres or Redis; the Postgres cases are @@ -636,6 +677,9 @@ test-unit: # relay events and agent prompts. They are infra-free; ignored lifecycle # tests remain excluded and run in their dedicated integration lanes. cargo nextest run -p buzz-acp --lib + # Load generator scenario, identity, shard and stats unit tests; all + # infra-free. Keep scripts/run-tests.sh in step. + cargo nextest run -p buzz-test-client --lib -E 'test(/^loadgen::/)' else ./scripts/run-tests.sh unit fi @@ -644,6 +688,11 @@ test-unit: test-integration: ./scripts/run-tests.sh integration +# Enforce-mode upload/publication/read journey (requires PostgreSQL and Redis). +# Uses the isolated PostgreSQL runner, including CLI edits and the target index. +test-media-access: + ./scripts/postgres-test-run.sh -p buzz-relay -p buzz-db --lib -E 'test(/^api::media_access_postgres_tests::/) | test(effective_edit_uses_target_index) | test(historical_edit_preflight)' + # Regenerate the model-capability normative corpus from the production Rust # resolver. The corpus is a golden snapshot, never hand-edited: this runs the # `#[ignore]`d writer test in buzz-agent, which serializes `resolve()` over the @@ -914,7 +963,7 @@ staging *ARGS: bootstrap _ensure-sidecar-stubs chmod +x "desktop/src-tauri/binaries/${bin}-${TARGET}" done cd {{desktop_dir}} - export BUZZ_RELAY_URL="wss://buzz.test.blockstaging.build" + export BUZZ_RELAY_URL="wss://buzz.block.builderlabstaging.xyz" source ../scripts/instance-env.sh # Ctrl+C kills the Tauri app before its in-process sweep finishes, leaking # agent workers. Reap this instance's agents on exit as a backstop. @@ -1025,8 +1074,8 @@ mobile-check: # Run mobile tests mobile-test: /bin/bash ./scripts/test-mobile-gateway-recipes.sh - unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}} && flutter test --dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example - unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}} && flutter test test/shared/push/push_unconfigured_build_test.dart + unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}} && flutter test + unset GIT_DIR GIT_WORK_TREE; cd {{mobile_dir}}/packages/buzz_secp256k1 && dart pub get && dart test # Regenerate the emoji dataset asset from desktop's emoji-mart install. # Output is committed — rerun after bumping @emoji-mart/data. diff --git a/NOSTR.md b/NOSTR.md index 507923d70c9..a6836b6dd2d 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -50,14 +50,14 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \ | **Reactions (kind:7)** | ✅ | Standard NIP-25; channel derived from target event's `#e` tag (client `#h` ignored) | | **Deletions (kind:5)** | ✅ | Standard NIP-09; self-authored only. `#h` optional, `#e` required | | **User profiles (kind:0)** | ✅ | NIP-01 metadata; synced to users table (display_name, avatar, about, NIP-05). NIP-05 handles must canonicalize to this relay's domain — off-domain or invalid handles are silently cleared. If a NIP-05 handle collides with another user's (UNIQUE constraint), the handle is skipped but other profile fields (display_name, avatar, about) are still synced. | -| **Group creation (kind:9007)** | ✅ | NIP-29; include `name` tag, optional `visibility`, `channel_type`, label `t` and `unlisted` tags | -| **Add user (kind:9000)** | ✅ | Open: any user, subject to target's `channel_add_policy` (`owner_only`/`nobody` can block). Private: owner/admin only. Self-add bypasses agent policy but not private-channel auth. A guest cannot add anyone. A new member with no role tag gets the channel's `join_role`; a non-member adding themselves may ask for `join_role` or a lower role. One event may name up to 100 people: one `p` tag each, with an optional role as the `p` tag's third element (NIP-29), falling back to the event's `role` tag. Each person is checked and added on their own. When the event names several people, the OK message is `members: ` followed by JSON listing the non-empty `added`, `updated` (role changed), `already_member` and `rejected` (`[{"reason", "pubkeys"}]`) results. The event is refused only when it is malformed or nobody it names may be added; then one person keeps the single-add error, and several get `invalid: members: {…}`. A resent event returns `duplicate:` without results; to retry an `error:` rejection, send a new event. Re-adding someone at their current role posts no second `member_joined` notice. | +| **Group creation (kind:9007)** | ✅ | NIP-29; include an `h` tag with the new channel id and a `name` tag, optional `visibility`, `channel_type`, label `t` and `unlisted` tags. The relay refuses a 9007 without `h`. It refuses a listed channel (open, not unlisted, stream or forum) whose name another listed channel already has, ignoring case and including archived ones: `invalid: an open channel named "" already exists`. | +| **Add user (kind:9000)** | ✅ | Open: any user, subject to target's `channel_add_policy` (`owner_only`/`nobody` can block). Private: owner/admin only. Self-add bypasses agent policy but not private-channel auth. A guest cannot add anyone. A new member with no role tag gets the channel's `join_role`; a non-member adding themselves may ask for `join_role` or a lower role. One event may name up to 100 people: one `p` tag each, with an optional role as the `p` tag's third element (NIP-29), falling back to the event's `role` tag. Each person is checked and added on their own. When the event names several people, the OK message is `members: ` followed by JSON listing the non-empty `added`, `updated` (role changed), `already_member` and `rejected` (`[{"reason", "pubkeys"}]`) results. The event is refused only when it is malformed or nobody it names may be added; then one person keeps the single-add error, and several get `invalid: members: {…}`. The event and its membership changes are stored together, so an `error:` rejection stores nothing and the same event can be resent; a resent stored event returns `duplicate:` without results. Re-adding someone at their current role posts no second `member_joined` notice. | | **Remove user (kind:9001)** | ✅ | Self-remove allowed (with last-owner guard). Removing others: owner/admin only. | -| **Edit group metadata (kind:9002)** | ✅ | `name`/`about`/label `t`/`visibility`/`ttl`/`archived`/`join_role`/`unlisted` tags: owner/admin. `topic`/`purpose` tags: any member except a guest. Buzz applies 9002 as a partial update: an absent tag leaves that setting unchanged. | +| **Edit group metadata (kind:9002)** | ✅ | `name`/`about`/label `t`/`visibility`/`ttl`/`archived`/`join_role`/`unlisted` tags: owner/admin. `topic`/`purpose` tags: any member except a guest. `auto_join` tag: relay owner/admin (see [Default channels](#default-channels)). A relay operator may also send a 9002 that changes only `name` on a listed channel, archived ones included, whatever its channel role, so that duplicate names can be repaired; the channel stays archived. The relay refuses a `name`, `visibility` or `unlisted` change that leaves a listed channel with a name another listed channel already has: `invalid: an open channel named "" already exists`. Buzz applies 9002 as a partial update: an absent tag leaves that setting unchanged. | | **Admin delete event (kind:9005)** | ✅ | Event author can always delete own. Otherwise owner/admin required. Target must be in same channel. | | **Group deletion (kind:9008)** | ✅ | Owner only. | | **Leave group (kind:9022)** | ✅ | Any member. Last-owner guard prevents orphaned groups. | -| **Group metadata (kind:39000)** | ✅ | Relay-signed; always `d`, `name`, `t`, `P`, `created_at`, `join_role`; `public` or `private`; `restricted` and `closed` per the access flags below; `unlisted` when the channel is unlisted; `about` only if description non-empty; `hidden` for DM channels and private system channels | +| **Group metadata (kind:39000)** | ✅ | Relay-signed; always `d`, `name`, `t`, `P`, `created_at`, `join_role`; `public` or `private`; `restricted` and `closed` per the access flags below; `unlisted` when the channel is unlisted; `about` only if description non-empty; `hidden` for DM channels and private system channels; `auto_join` while the channel is a default channel | | **Unlisted channels** | ✅ | kind:9002 `["unlisted", "true"\|"false"]`, owner/admin, or at creation on kind:9007. An unlisted open channel is left out of every read that does not name it, for non-members: channel lists, kind:39000 without `#d`, messages, COUNT, NIP-50 search and artifact queries. Naming it by `#h` (or `#d` on 39000–39003) reads it, and kind:9021 joins it, as for any open channel. See [Unlisted channels](#unlisted-channels). | | **Group admins (kind:39001)** | ✅ | Relay-signed; `d`, channel type `t` and creator `P` tags + `p` tags with roles (`owner`, `admin`) | | **Group members (kind:39002)** | ✅ | Relay-signed; `d`, channel type `t` and creator `P` tags + `p` tags for all members | @@ -72,7 +72,7 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \ | **NIP-10 threads** | ✅ | WS-submitted replies with `["e","","","reply"]` tags create `thread_metadata` atomically. Visible in REST thread queries. Unknown parents rejected. | | **NIP-17 DMs (gift wrap)** | ✅ | kind:1059 accepted with ephemeral signing keys. Stored community-globally (`channel_id=None` inside the connected community). Delivered via `#p`-filtered subscriptions. Not indexed in search. | | **DM discovery** | ✅ | DM creation emits kind:39000 (with `hidden` tag) + kind:44100 membership notifications. NIP-29 clients discover DMs via standard group discovery flow. | -| **Join request (kind:9021)** | ✅ | Open channels only. Adds the joiner with the channel's `join_role` (`member` by default), emits system message + group discovery events + kind:44100 membership notification. Private channels rejected at ingest. | +| **Join request (kind:9021)** | ✅ | Open channels only. Adds the joiner with the channel's `join_role` (`member` by default), emits system message + group discovery events + kind:44100 membership notification. Private channels rejected at ingest. The same body joins new community members to [default channels](#default-channels). | | **Edits (kind:40003)** | ⚠️ | Works on the wire but Buzz-only — no standard NIP-29 client renders these | | **Rich content (kind:40002)** | ⚠️ | Works on the wire but Buzz-only — no standard NIP-29 client renders these | @@ -192,6 +192,68 @@ and join it, but it does not show up for people who are not members. channel as unlisted. - Unlisted is not an access control. Anyone with the id can read the channel. +### Default channels + +A community's owners and admins can mark a channel as a **default channel**: +one the relay joins every new community member into. The setting is +`auto_join` on the channel. + +- Only a *relay* owner or admin (the NIP-43 roster role, not a channel role) + can change it, with kind:9002 `["auto_join", "true"]` or + `["auto_join", "false"]`. The actor need not be a member of the channel. + A missing tag means "no change". +- It is accepted only on a `stream` channel the event leaves open, and `true` + also needs it unarchived. `false` is refused on a private channel too: the + actor need not be a member, so neither value may write into a channel they + cannot read. The relay decides this in the same transaction as the other + kind:9002 changes, so one event may open a channel and flag it. Making a + flagged channel private or archiving it is allowed and leaves the stored + value in place; to take a private channel out of the defaults, clear the + flag before making it private or once it is open again. +- kind:39000 carries a bare `["auto_join"]` tag only while the setting is + effective: set, open and unarchived. What the event says is what the relay + does, so a client never has to combine the flag with the access flags. +- Nothing is a default channel until someone asks for it: new channels and + existing channels start with `auto_join` off. `buzz channels update + --channel --auto-join true` sets it. + +Every change is announced by one kind:40099 `auto_join_changed` system +message in the channel. + +When someone becomes a community member (an invite claim or a kind:9030 add) +the relay joins them to every effective default channel as a self-join: the +body of kind:9021, so the channel's `join_role` applies and the channel gets +its `member_joined` kind:40099, kind:39002 and kind:44100. There is no cap on +how many channels that is: whatever carries the kind:39000 tag is joined, and +the work a new member costs grows with the number of channels an owner or +admin flags. On a community that requires relay membership, the relay does +this once, at that moment, and never again on login or reconnect, so a later +kind:9022 leave stands. A kind:9030 add is +made by someone else, so the new member's `channel_add_policy` applies first, +as it would to that actor's kind:9000: if it refuses them, no default channel +is joined. The claim response waits for the joins, and a claimer who +disconnects before it arrives does not cut them short. A channel that fails +to join, or an add the member's policy refuses, is logged and counted +(`buzz_auto_join_failures_total`), not retried: the kind:39000 tag is the +record a client reconciles against. That includes a channel archived or made +private while the join runs: the membership write decides both again under +the channel's locks, so the member is not added and nothing is announced. +`buzz-admin add-member` writes the roster row only and +does not join default channels. + +A community that does not require relay membership has no roster insert to +join people at, so there the relay joins a person when it admits their +WebSocket AUTH, after the OK, to every effective default channel they have +never been a member of. "Never a member" is the channel's own membership +history: a kind:9022 leave or a kind:9001 removal keeps the row, so the +person is not joined back, and a new device or another relay pod finds the +row and does nothing. The check runs again under the channel's membership +lock, so two admissions of the same person join them once. A channel flagged +later is joined on each person's next admission. Agents are skipped: an AUTH +with a NIP-OA owner, a NIP-FI agent token, or a stored agent owner joins +nothing. A membership write that fails leaves no row, so the next admission +tries that channel again. + ### Group Discovery The relay emits NIP-29 group state events when channels are created, updated, or membership changes. @@ -201,7 +263,7 @@ All discovery events include a `d` tag set to the channel UUID (NIP-29 addressab | Kind | Tags | Content | |------|------|---------| -| **39000** | `d=`, `name`, `t=`, `P=`, `created_at=`, `join_role` (always); `public` or `private`; `restricted` (private channels, and `join_role=guest`); `closed` (private channels only); `unlisted` (unlisted channels); `about` (if description non-empty); `hidden` (DM channels and private system channels) | Group metadata. The access flags follow the channel settings (see [Announce channels](#announce-channels)). | +| **39000** | `d=`, `name`, `t=`, `P=`, `created_at=`, `join_role` (always); `public` or `private`; `restricted` (private channels, and `join_role=guest`); `closed` (private channels only); `unlisted` (unlisted channels); `about` (if description non-empty); `hidden` (DM channels and private system channels); `auto_join` (open, unarchived channels with the setting on, see [Default channels](#default-channels)) | Group metadata. The access flags follow the channel settings (see [Announce channels](#announce-channels)). | | **39001** | `d=`, `t=`, `P=`, `p` tags with role label (`owner`, `admin`) | Admin list | | **39002** | `d=`, `t=`, `P=`, `p` tags for all members | Member list | @@ -267,7 +329,9 @@ nak req -k 39002 --tag "d=" --auth --sec ws://localhost: > **Note:** Channel-scoped storage means live global subscriptions (`{kinds:[39000]}`) won't > receive these via fan-out. Clients discover groups via historical REQ queries. Live push for -> open-channel discovery is a future enhancement. +> open-channel discovery is a future enhancement. A group-state filter that names channels by +> `#d` (`{kinds:[39000], "#d":[]}`) does receive later replacements for the named +> channels it may read, after EOSE. ### Membership Notifications @@ -297,6 +361,51 @@ nak req -k 44100 -k 44101 --tag "p=" \ --auth --sec ws://localhost:3000 ``` +### Workflow Owner Attribution + +A workflow message is a kind:9 event that the relay signs and marks with +`["buzz:workflow", "true"]`. Its first `p` tag is `["p", , "", "owner"]`, +which names the workflow's owner for display. This tag is attribution, not a +mention, so `#p` filters do not match it. This is a deliberate exception to +NIP-01, applied to live subscriptions, history and push leases alike, so a +bounded `#p:[me]` read returns the messages that really mention you. A +workflow that mentions its owner also carries a plain `["p", ]`, which +`#p` matches as usual. To find a workflow's messages by owner, read the tags +of the channel's messages: `buzz:workflow-owner` also names the owner. A +marked `p` tag on any other event, for example a kind:39002 member list role, +matches `#p` normally. See `docs/buzz-push.md` for the push rules. + +### Workflow Mentions + +A workflow message may carry `["buzz:workflow-mention", ]` tags. Each +one names a channel member whom the workflow's owner named in the stored text of +the step, as opposed to text substituted into it when the step ran. The relay adds +a plain `["p", ]` for every member that the rendered text mentions, and a +`buzz:workflow-mention` tag only for members that the stored text also names. + +A `buzz:workflow-mention` tag is the relay's statement that the message may +direct the named agent on the owner's behalf. An agent acts on a workflow +message only if all of these hold: + +- the message is signed by the relay key that the active community advertises; +- a `buzz:workflow-mention` tag names the agent; +- the workflow principal that `buzz:workflow-owner` names passes the receiving + client's rule for whom the agent accepts work from: its owner, or an agent + that its owner has attested. + +`buzz:workflow-owner` is attribution. It does not by itself authorize anything. +A plain `p` tag on a workflow message notifies the member but does not direct +an agent. + +A relay may leave out `buzz:workflow-mention` tags under a policy. The message +still posts with its `p` tags, and an agent that no tag names does not act on +it. A relay's NIP-11 document MUST carry `workflow_agent_mentions`: `"any"` +when every run may carry the tags, or `"owner"` when only runs the workflow's +owner or a timer started, on a definition of only `send_message` and `delay` +steps, carry them; a client MUST treat a missing field as an older relay whose +policy is unknown. For Buzz's owner-only agent mentions, see +[docs/operator-workflow-agent-mentions.md](docs/operator-workflow-agent-mentions.md). + ### Sending Messages ```bash diff --git a/PLANS/REPLICA_FULL_READ_ROUTING_DESIGN.md b/PLANS/REPLICA_FULL_READ_ROUTING_DESIGN.md index c64d7e048b2..ad38f558042 100644 --- a/PLANS/REPLICA_FULL_READ_ROUTING_DESIGN.md +++ b/PLANS/REPLICA_FULL_READ_ROUTING_DESIGN.md @@ -14,8 +14,12 @@ routing**: the read may be served from a read replica when `RoutePredicate::for_query` derives from the query shape. The seam fails closed to the writer on replica errors, with one deliberate exception: a statement cancelled by `statement_timeout` (SQLSTATE `57014`) is surfaced rather than -re-run, because the writer would run the same slow statement. It is a genuine -no-op until the budget is configured (`crates/buzz-db/src/lib.rs`). +re-run, because the writer would run the same slow statement. A busy reader +is the other exception: a subscription-history read that cannot get a reader +connection within its bounded wait is rejected as retryable instead of moving +to the writer, and history reads are capped per pod below the reader pool +size (`Db::route_read`). It is a genuine no-op until the budget is configured +(`crates/buzz-db/src/lib.rs`). ## Routing rule @@ -55,7 +59,7 @@ in `crates/buzz-relay/src/api/bridge.rs` (`extract_consistency`). Rows below are every `query_events_routed` / `query_events_routed_bounded` call site at head, plus the writer-pinned canvas row this change adds. (The `count` and feed routed families — `count_events_routed`, -`get_events_by_ids_routed`, `query_feed_*_routed`, and the `get_channel_window` +`get_events_by_ids_at_routed`, `query_feed_*_routed`, and the `get_channel_window` cursor/head reads — are all display or bounded-count surfaces on the routed path; they carry their own soundness notes at their definitions in `crates/buzz-db/src/lib.rs` and are out of scope for this table.) diff --git a/README.md b/README.md index fdf475da40c..9845b5c02b8 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,18 @@ Yes, it's another AI-adjacent developer tool. We're sorry. The difference is wha --- +## Where to find things + +Buzz's open-source code lives in two repositories. The desktop app has its own; the relay and the mobile client are here. + +| Component | Home | +|---|---| +| Desktop app | [block/buzz-app](https://github.com/block/buzz-app) | +| Mobile client (iOS + Android) | This repo, in [`mobile/`](mobile/) | +| Relay | This repo, in [`crates/buzz-relay/`](crates/buzz-relay/) | + +--- + ## A look inside @@ -118,7 +130,7 @@ Agents are part of the room, not haunted cron jobs. | ✅ Works today | 🚧 Being wired up | 💭 Strong opinions, pending code | |---|---|---| | Relay, channels, threads, DMs, canvases, media, search, audit log | Mobile clients (iOS + Android, Flutter) | Web-of-trust reputation across relays | -| Desktop app (Tauri + React) | Workflow approval gates (infra exists, glue still drying) | Push notifications | +| Desktop app (in [block/buzz-app](https://github.com/block/buzz-app)) | Workflow approval gates (infra exists, glue still drying) | Push notifications | | `buzz-cli` (agent-first, JSON in / JSON out) + ACP harness (Goose, Codex, Claude Code) | Huddle lifecycle events | Culture features | | YAML workflows: message / reaction / schedule / webhook triggers | | | | Git events (NIP-34: patches, repo announcements, status) | | | @@ -134,21 +146,9 @@ New to Buzz? Pick the path that matches you. ### I just want to try the app -Grab a packaged build from the [latest release](https://github.com/block/buzz/releases/latest): - -| Platform | File | -|---|---| -| macOS (Apple Silicon) | `Buzz__aarch64.dmg` | -| macOS (Intel) | `Buzz__x64.dmg` | -| Linux (x86_64) | `Buzz__amd64.AppImage` or `Buzz__amd64.deb` | -| Windows (x64) | `Buzz__x64-setup_alpha-unsigned.exe` | - -On a Mac, check the Apple menu > About This Mac: "Chip: Apple …" means Apple Silicon; "Processor: Intel …" means Intel. - -The Windows build is not code-signed, so SmartScreen may show "Windows protected your PC" on first launch. If available, click **More info**, then **Run anyway**. +The desktop app lives in [block/buzz-app](https://github.com/block/buzz-app). Head there to install, build, or run it. - -By default the app connects to `ws://localhost:3000`. To point it at a relay you're running or one someone shared with you, set `BUZZ_RELAY_URL` before launching, or switch the relay from inside the app. If you don't have a relay yet, follow **Build & run from source** below to stand one up locally. +Need a relay for it to connect to? Deploy a hosted one, or follow **Quick start** below to stand one up locally. ### I want my own hosted relay @@ -158,20 +158,20 @@ To run a relay for your team without managing servers, you can deploy one to Rai See [here](https://engineering.block.xyz/blog/run-your-own-buzz-relay) for details. -### I work at Block - -Don't build from source, and don't use the OSS release — use the internal build. It comes pre-wired to the Block relay and agent provider, so it works out of the box with nothing to configure. +### I want to run the relay from source -Download the latest build from [`squareup/buzz-releases` releases](https://github.com/squareup/buzz-releases/releases/latest) and install it. +See **Quick start** below — this is the developer / self-host path. -### I want to build & run from source +### I want to work on the mobile app -See **Quick start** below — this is the developer / self-host path. +The Flutter client is in [`mobile/`](mobile/). See [mobile/README.md](mobile/README.md) for setup and run instructions. --- ## Quick start +This stands up the relay locally. For the desktop app, see [block/buzz-app](https://github.com/block/buzz-app); for the mobile app, see [mobile/README.md](mobile/README.md). + You'll need [Docker](https://docs.docker.com/get-docker/) and [Hermit](https://cashapp.github.io/hermit/) (or Rust 1.88+, Node 24+, pnpm 10+, `just`). **Once:** @@ -186,12 +186,10 @@ just setup && just build **Every day:** ```bash . ./bin/activate-hermit -just dev # starts the relay + desktop app together +just relay # starts the relay (and its Docker services if needed) ``` -Relay on `ws://localhost:3000`. Desktop app pops up. You're in. - -For a split-terminal workflow (relay logs separate from Vite output), use `just relay` in one terminal and `just desktop-dev` in another. +Relay on `ws://localhost:3000`. You're in. Want a single-node / VPS relay instead of the local-dev stack? Use the production Compose bundle in [`deploy/compose/`](deploy/compose/README.md) (`docker compose` + Postgres, Redis, MinIO, optional Caddy/TLS). The root [`docker-compose.yml`](docker-compose.yml) is for day-to-day development only. @@ -215,7 +213,7 @@ If you'd rather point buzz at a different bash-compatible shell, set `BUZZ_SHELL ┌─────────────────────────────────────────────────────────────────────────┐ │ Clients │ │ Human client AI agent CLI / scripts │ -│ (Buzz desktop) (Goose, Codex, ...) (buzz-cli, agents) │ +│ (desktop, mobile) (Goose, Codex, ...) (buzz-cli, agents) │ │ │ ┌──────────────┐ │ │ │ │ │ buzz-acp │ │ │ │ │ │ (ACP ↔ MCP) │ │ │ @@ -236,7 +234,7 @@ If you'd rather point buzz at a different bash-compatible shell, set `BUZZ_SHELL └──────────────┘ ``` -A Rust workspace of focused crates. Single source of truth: the relay. See [ARCHITECTURE.md](ARCHITECTURE.md) for the full breakdown. +A Rust workspace of focused crates. Single source of truth: the relay. The human clients are the desktop app in [block/buzz-app](https://github.com/block/buzz-app) and the mobile app in [`mobile/`](mobile/). See [ARCHITECTURE.md](ARCHITECTURE.md) for the full breakdown.
Crate map @@ -275,11 +273,11 @@ All defaults work out of the box. Override via `.env`. Full reference in [`.env. Common dev commands ```bash -just setup # Docker, migrations, desktop deps +just setup # Docker, migrations, JS deps just relay # Run the relay -just dev # Run the desktop app +just mobile-dev # Run the mobile app in an iOS Simulator just build # Build the Rust workspace -just check # fmt + clippy + desktop check +just check # Lint, formatting, and repo policy checks just test-unit # Unit tests (no infra required) just test # Full suite (starts services if needed) just ci # Everything CI runs diff --git a/RELEASING.md b/RELEASING.md index 6c7e2779ff8..bf3262d5d87 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -12,8 +12,9 @@ with an optional stable source branch: The lanes version independently. Desktop reads its manifests, relay reads its crate manifest, and mobile derives both source and marketing version from the -exact candidate tag. The mobile handoff to the private `buzz-releases` pipeline -remains manual because OSS CI cannot trigger private CI. +exact candidate tag. Mobile candidate tags are pushed by a human release +manager, not by CI or a GitHub App. The handoff to the private `buzz-releases` +pipeline remains manual because OSS CI cannot trigger private CI. ## Quick Start @@ -33,6 +34,7 @@ just release-relay just release-relay 0.4.0 # Publish the next mobile candidate from the exact current remote main commit +# (requires bypass of the mobile tag ruleset, see Mobile below) scripts/mobile-release.sh candidate 0.5.0 ``` @@ -49,6 +51,20 @@ or mobile GitHub Release. ### Desktop +Repository admins can manually validate an existing candidate with: + +```sh +gh workflow run desktop-release-candidate.yml --repo block/buzz --ref main -f version=0.5.3 +``` + +This checks out `version-bump/0.5.3` and runs the same immutable-candidate +validator as the PR check. Dispatch from `main`; both the original caller and +anyone rerunning the workflow must currently have repository admin permission. +GitHub allows users with write access to dispatch workflows, but this workflow +fails their manual runs before checkout. Permission lookup failures also stop +the run. Manual validation does not create a candidate, publish a release, or +replace the required checks on the candidate PR. + 1. Run `just release-desktop ` from a clean, up-to-date `main` checkout. The script creates one deterministic candidate commit and records both its frozen base and the verified prior release ledger in candidate metadata. @@ -88,8 +104,11 @@ prior release's recorded squash commit; tag ancestry is deliberately irrelevant. `debug-0.3.0` and `debug-latest`) for native profiling. The ordinary tags remain stripped and are the default for deployments that do not need it. -Every push to `main` continues to publish the rolling relay `:main` and -`:sha-<7>` tags, plus matching `:debug-main` and `:debug-sha-<7>` variants. +Every push to `main` that changes the image build context continues to +publish the rolling relay `:main` and `:sha-<7>` tags, plus matching +`:debug-main` and `:debug-sha-<7>` variants. Pushes that only touch paths +`.dockerignore` excludes (such as `desktop/`, `mobile/` and `docs/`) publish +nothing. ### Mobile @@ -98,11 +117,20 @@ Every push to `main` continues to publish the rolling relay `:main` and `scripts/mobile-release.sh candidate X.Y.Z`. The script resolves and fetches a snapshot of `origin/main`, derives the next number from exact remote tags for that marketing version, and publishes an annotated - `mobile-vX.Y.Z-rc.N` tag there through the dedicated `buzz-release-bot` - GitHub App. It never uses the operator's checked-out commit and never moves - an existing candidate. To select a historical commit, add `--commit FULL_SHA`. - Both operator and publisher require that commit to be in the selected source - branch's history. Later branch advances do not change or invalidate the tag. + `mobile-vX.Y.Z-rc.N` tag at that snapshot with `git tag -a` (your own tag + signing configuration applies) and pushes exactly that one tag to `origin`. + The push is allowed only because you are a bypass actor of the dedicated + mobile tag ruleset [`26588677`](https://github.com/block/buzz/rules/26588677) + for `refs/tags/mobile-*`; bypass is granted to the mobile release managers. + The `buzz-release-bot` App and its key are not involved in mobile. The script never uses the operator's + checked-out commit and never moves an existing candidate. To select a + historical commit, add `--commit FULL_SHA`. The script requires that commit + to be in the selected source branch's history. Later branch advances do not + change or invalidate the tag. If the push is rejected and origin has no + such tag, the script deletes the local tag and fails; check that you are a + bypass actor of the ruleset. If the candidate may already be on GitHub, the + script keeps the local tag and says so: use the published tag rather than + rerunning. 2. **Build the exact tag.** Enter the candidate tag as `mobile_ref` in the private Buzz mobile Buildkite pipeline. OSS CI deliberately cannot trigger that private pipeline. The tag supplies both source commit and release @@ -130,12 +158,13 @@ scripts/mobile-release.sh candidate 0.25.0 --source-branch mobile-v0.25 The branch must match the marketing version's major and minor components: `mobile-v0.25` accepts 0.25.x, but rejects 0.26.x and 1.25.x. Without the option, -the source remains `main`. Both the operator and publisher validate the source; +the source remains `main`. The script validates the source; a missing branch or a commit outside its history fails rather than falling back -to `main`. `--commit FULL_SHA` also works with a stable source branch, whose -review and check protections remain required. -The GitHub workflow itself continues to run from reviewed `main`. The private -pipeline still builds only the resulting immutable candidate tag. +to `main`. `--commit FULL_SHA` also works with a stable source branch. Its +review and check protections bind everyone except the mobile release managers, +who bypass them: a release manager can push an unreviewed commit to a stable +branch and tag it as a candidate. +The private pipeline still builds only the resulting immutable candidate tag. For the October 2026 stabilization period, all distributed mobile builds, including Company Portal dogfood builds, must come from `mobile-v0.25` until @@ -301,10 +330,13 @@ host's Wayland/GStreamer/graphics stack and requires GLib >= 2.72 - The Default `main` ruleset configured for squash-only merging, strict required checks, stale-review dismissal, and the **Desktop Release Candidate** check - Release tag ruleset [`14378754`](https://github.com/block/buzz/rules/14378754) - active for `desktop-v*` and `mobile-v*`, with creation, update, deletion, and + active for all tags (`~ALL`), with creation, update, deletion, and non-fast-forward protections and `buzz-release-bot` as its sole always-bypass - actor -- The `buzz-release-bot` App credentials configured for GitHub Actions + actor. It must exclude `refs/tags/mobile-*`: rulesets stack, so otherwise it + rejects release managers' mobile tag pushes. `scripts/mobile-release.sh` + checks that exclusion before tagging. +- The `buzz-release-bot` App credentials configured for GitHub Actions (desktop, + relay, and chart lanes only; mobile does not use them) - The following **GitHub Actions variables and secrets** configured for the desktop release lane: @@ -318,21 +350,26 @@ host's Wayland/GStreamer/graphics stack and requires GLib >= 2.72 | `TAURI_SIGNING_PRIVATE_KEY` | Secret | Tauri updater private key | | `TAURI_SIGNING_PRIVATE_KEY_PASSWORD` | Secret | Password for the private key | -Mobile candidate publication requires workflow-dispatch access and the existing -release App because strict tag protection denies direct human creation. The App -must be installed on `block/buzz`, have Contents write and Metadata read, and -retain an `always` bypass on the immutable `mobile-v*` tag rules. It does not -require GitHub Releases permissions or repository Administration permission. -Stable sources additionally require active branch ruleset `19321162` covering -`refs/heads/mobile-v*`, with no exclusions or bypass actors, deletion and -force-push prevention, at least one approval, stale-approval dismissal, last-push -approval, resolved review threads, and strict required `Mobile` and `DCO Check` -checks. An administrator must configure and audit the empty bypass list; GitHub -hides that list from non-admin tokens. Both operator and publisher verify the -public policy and their effective lack of branch bypass on every publication. -The publisher validates the App token's effective -`current_user_can_bypass` value rather than reading the ruleset's hidden bypass -actor list. +Mobile candidate publication requires being a bypass actor of the mobile tag +ruleset [`26588677`](https://github.com/block/buzz/rules/26588677) ("Restrict +Mobile Tags"), recorded as `MOBILE_RELEASE_TAG_RULESET_ID` in +`scripts/release-rulesets.sh`. Bypass is granted to the mobile release +managers. The ruleset must be active for `refs/tags/mobile-*` (or the narrower +`refs/tags/mobile-v*`), with creation, update, deletion, and non-fast-forward +protections and no exclusions. The `buzz-release-bot` App must not be a bypass +actor. On every publication the script checks the public policy and that the +caller's effective `current_user_can_bypass` is `always`; GitHub hides the bypass +actor list from non-admin tokens, so an administrator audits that list. +Stable sources additionally require active branch ruleset +[`19321162`](https://github.com/block/buzz/rules/19321162) covering +`refs/heads/mobile-v*`, with no exclusions, deletion and force-push prevention, +at least one approval, stale-approval dismissal, last-push approval, resolved +review threads, and strict required `Mobile` and `DCO Check` checks. The mobile +release managers are also its bypass actors, so they can publish from a stable +branch; the ruleset still forces review and checks on everyone else. Because of +that bypass, a release manager can push an unreviewed commit to a stable branch +and publish it as a candidate; nothing else enforces review for them. The script +verifies the public policy on every publication but does not check bypass. --- @@ -362,9 +399,9 @@ its own exact tag. ### The source branch advances during candidate publication -Publication remains pinned to the selected SHA. The publisher verifies that it -is an ancestor of a resolved source-branch snapshot, then creates and verifies -an immutable annotated tag for that exact SHA. The operator verifies the tag, +Publication remains pinned to the selected SHA. The script verifies that it +is an ancestor of a resolved source-branch snapshot, then creates, pushes, and +verifies an immutable annotated tag for that exact SHA. It verifies the tag, not the branch's later tip. A newer commit does not require retrying or creating another candidate. Missing or unverifiable ancestry still fails closed. @@ -376,9 +413,10 @@ increasing remote identities. ### A mobile candidate publication is rejected by repository rules -Confirm `buzz-release-bot` remains the sole always-bypass actor for the active -`mobile-v*` ruleset and that its Actions credentials are available. Do not grant -direct human creation or weaken update or deletion protection. Existing +Confirm you are a bypass actor of the active mobile tag ruleset `26588677` +(the mobile release managers). The script removes its local tag after a rejected +push, so retry after an administrator fixes your access. Do not add yourself to +the bypass list, grant the App bypass, or weaken update or deletion protection. Existing candidate tags must remain immutable. ### Auto-updater reports "no update available" diff --git a/TESTING.md b/TESTING.md index d939265c414..0a7acf817e1 100644 --- a/TESTING.md +++ b/TESTING.md @@ -146,6 +146,88 @@ backgrounded or you lost the terminal: `pkill -f buzz-relay`. Leaving it running will collide with the next reviewer who follows this doc on the same machine. +### Invitation compatibility and revocation + +New invitations are durable v2 bearers. A community ban permanently revokes +outstanding v2 invitations issued by that principal or its recorded agents. +Unban does not restore them; an unrestricted issuer can mint new invitations. +Existing durable rows default to legacy admission. Until the separately +reviewed historical repair processes them, any retained `community_bans` row +for a canonical issuer or its currently recorded owner permanently revokes a +legacy row, including expired, lifted, and timeout-only restrictions. The +repair clears that legacy marker after deciding the row's historical state. +Afterward, only an active ban permanently revokes it; timeouts and mutes block +claims only while active. New mints explicitly mark their rows as protocol +native. Audit and action records alone do not establish enforcement. +An issuer or verified owner timeout also blocks claims on existing invitations +while it lasts, without durable revocation. Claims resume after timeout expiry. +Claim credentials are verified without user writes. Successful claims commit +verified ownership with membership, policy evidence, and v2 consumption. +Rejected claims create no users or owner links. +Minting with a verified owner that differs from an agent's recorded owner +returns HTTP 403 `invite_owner_mismatch`; a storage failure while establishing +that link remains HTTP 503. Web, desktop, and mobile claim errors explain +`invite_restricted` as a restriction on the claiming account, or on the account +that owns it, in this community: contact a community administrator, or retry +after a temporary restriction ends. An issuer restriction returns +`invite_invalid`, so a claim never reveals the issuer's moderation state. +`invite_owner_mismatch` asks for the correct account or owner identity. Neither +error suggests a fresh link as a workaround, and neither automatically retries. +Claim and mint restriction reads use the writer inside a transaction serialized +with community restriction and agent-owner writes. Admission committed first +precedes the ban; a ban committed first prevents subsequent admission. Restriction +lookup failures deny admission, and onboarding does not require prior membership. + +Legacy v1 bearers contain no issuer identity. Unset `BUZZ_INVITE_V1_INVALID_AFTER` +preserves their natural expiry and claimant restriction checks, but cannot revoke +an individual legacy issuer's bearers. Drain for at most 30 days from the last +possible v1 issuance across **all serving and rollback versions**; do not use merge +time as the start. Full issuer-revocation coverage requires completing that drain +or an explicitly approved compatibility scope decision. + +Operators may set `BUZZ_INVITE_V1_INVALID_AFTER` to an absolute UTC RFC3339 +whole-second timestamp (for example `2026-12-01T00:00:00Z`). v1 verification +rejects at and after that instant, never extends bearer expiry, and leaves v2 +unchanged. Invalid or empty values fail configuration. Apply the same setting to +all serving pods and retain it on compatible rollbacks; rolling back to a version +without this setting's enforcement restores legacy acceptance until natural expiry. +This change does not choose or deploy a cutoff. + +The historical maintenance companion must be separately reviewed and approved +**before deploying this core change**. Both steps belong to the same controlled +rollout: leaving unrepaired rows serving indefinitely would extend historical +restriction rejection until their repair. Migration 0075 is schema-only: it adds +`revoked_at` and `legacy_admission` without rewriting existing invite rows. +Reconcile any previously applied invitation migration version with the schema +and migration history before applying it. + +There is no invitation-maintenance feature switch. Operators must prevent +invitation mint/claim, ban lifts, and **new timeout/mute restrictions** throughout +the drain/repair interval, including signed events, HTTP, administrative tools, +background jobs and direct writers. If this cannot be enforced for every writer +with existing operational controls, use a maintenance window: remove public +traffic, stop all relay instances and other writers, drain in-flight work and +verify no old writer remains. Keep them stopped while applying schema 0075 and +running the separately approved repair with its isolated operator connection. +Prepare only new-code instances; do not reopen traffic or restart other writers +until repair validation succeeds. Readers that may run before repair must use +new code, which rejects historical restrictions lazily on unrepaired legacy rows. + +The repair must report zero unrepaired invites in active communities and an +idempotent second run before reopening. Review every skipped/fenced community; +keep it closed until it is active and repaired, then recheck zero before admitting +traffic. After repair, timeouts/mutes only block temporarily; active bans still +revoke permanently. A rollback to code that ignores `revoked_at` requires +invitation admission paused, using the same traffic/writer controls if needed. +It also requires `BUZZ_AUTO_MIGRATE` off: with auto-migration on (the Helm +default), the old binary fails at startup with SQLx `VersionMissing(75)`. See +[docs/database.md](docs/database.md) Rule 5. +Legacy owner attribution uses the agent's currently recorded +`agent_owner_pubkey`; deleting an owner user row out of band clears that link +through its foreign key, so a later repair cannot recover the former +relationship. Reconcile before any external user-row cleanup that could erase +this provenance. + ### 4. Smoke test the CLI against the relay End-to-end: generate an identity, create a channel, post a message, read it @@ -190,7 +272,7 @@ relay key for authoritative replacement: ```bash export PATH="$PWD/target/release:$PATH" -export DATABASE_URL="postgres://buzz:buzz_dev@localhost:5432/buzz_roster_e2e" +export DATABASE_URL="${DATABASE_URL:?set an isolated local PostgreSQL URL}" export BUZZ_RELAY_URL="http://localhost:3030" # match the relay from step 3 export RELAY_URL="ws://localhost:3030" export BUZZ_RELAY_PRIVATE_KEY="" @@ -331,12 +413,13 @@ out of the box with `just setup` or `just relay`. Common overrides: | `BUZZ_HEALTH_PORT` | `8080` | `/_liveness`, `/_readiness` | | `BUZZ_METRICS_PORT` | `9102` | Prometheus `/metrics` | | `RELAY_URL` | `ws://localhost:3000` | Advertised in NIP-11 / NIP-42 challenges. **Note: no `BUZZ_` prefix.** | -| `DATABASE_URL` | `postgres://buzz:buzz_dev@localhost:5432/buzz` | | +| `DATABASE_URL` | Local PostgreSQL database `buzz` (development default) | | | `REDIS_URL` | `redis://localhost:6379` | | | `BUZZ_REQUIRE_AUTH_TOKEN` | `false` | When true, REST requires NIP-98 (no `X-Pubkey` fallback) | | `BUZZ_REQUIRE_RELAY_MEMBERSHIP` | `false` | When true, only pubkeys in `relay_members` can connect | | `BUZZ_DRAIN_JITTER_MS` | `0` (off) | Per-connection upper bound, in ms, for the random delay before each live WebSocket gets its `1012 Service Restart` close on graceful shutdown. `0` closes every socket at once (the previous behavior). A positive value spreads closes uniformly over `[1, value]` ms to avoid a reconnect thundering herd on rolling deploys. Values above `20000` are capped to `20000` (`MAX_DRAIN_JITTER_MS`) to leave close-frame delivery headroom under the relay's 30s hard-drain timeout. Empty or whitespace-only is treated as unset (off); a non-integer fails startup loudly. | | `BUZZ_AUDIT_ENABLED` | `true` | Tamper-evident event/media audit log. Set `false`/`0`/`off` to skip its DB pool and writes. Does not disable the separate moderation audit trail. | +| `BUZZ_WORKFLOW_AGENT_MENTIONS` | `any` | `owner` turns on owner-only agent mentions: only runs the owner or a timer started can direct agents. Any value other than `any` or `owner` fails startup. See [docs/operator-workflow-agent-mentions.md](docs/operator-workflow-agent-mentions.md). | | `BUZZ_AUTO_MIGRATE` | `false` | Opt in with `true`/`1`/`yes`/`on` to run embedded SQLx migrations on relay startup | | `RELAY_OWNER_PUBKEY` | unset | Bootstrapped as `owner` in `relay_members` at first start | | `BUZZ_ALLOW_NIP_OA_AUTH` | `false` | Enable NIP-OA owner attestation for membership | diff --git a/VISION_MOBILE.md b/VISION_MOBILE.md index c397d05535c..8a43969b043 100644 --- a/VISION_MOBILE.md +++ b/VISION_MOBILE.md @@ -17,7 +17,7 @@ When writing a spec or implementing significant changes or tests, check them for Mobile and desktop follow shared rules for behavior such as channel ordering, unread state, and autocomplete. Presentation and interaction should suit each platform. -The desktop implementation is a reference we can use to inform defining those rules, but it contains bugs and unintended behavior and is not itself the specification. Written intent takes priority over implementation precedent. A clearer vision or spec developed for mobile can establish the intended shared behavior for desktop too. +The legacy `desktop/` app in this repository will soon be superseded by [block/buzz-app](https://github.com/block/buzz-app). Never use it as an implementation or design reference for mobile. Written intent takes priority over implementation precedent. A clearer vision or spec developed for mobile can establish the intended shared behavior for desktop too. ## Architecture diff --git a/admin-web/package.json b/admin-web/package.json index 3f3eeebd875..647cd4b8829 100644 --- a/admin-web/package.json +++ b/admin-web/package.json @@ -20,7 +20,7 @@ "react-dom": "^19.1.0" }, "devDependencies": { - "@playwright/test": "^1.58.2", + "@playwright/test": "^1.65.0", "@testing-library/jest-dom": "^6.9.1", "@testing-library/react": "^16.3.2", "@types/react": "^19.1.8", diff --git a/bin/.flutter-3.47.7.pkg b/bin/.flutter-3.47.9.pkg similarity index 100% rename from bin/.flutter-3.47.7.pkg rename to bin/.flutter-3.47.9.pkg diff --git a/bin/dart b/bin/dart index 28f286c9c66..bac562fb5ac 120000 --- a/bin/dart +++ b/bin/dart @@ -1 +1 @@ -.flutter-3.47.7.pkg \ No newline at end of file +.flutter-3.47.9.pkg \ No newline at end of file diff --git a/bin/flutter b/bin/flutter index 28f286c9c66..bac562fb5ac 120000 --- a/bin/flutter +++ b/bin/flutter @@ -1 +1 @@ -.flutter-3.47.7.pkg \ No newline at end of file +.flutter-3.47.9.pkg \ No newline at end of file diff --git a/crates/buzz-acp/TESTING.md b/crates/buzz-acp/TESTING.md index 528bac21384..14483809003 100644 --- a/crates/buzz-acp/TESTING.md +++ b/crates/buzz-acp/TESTING.md @@ -40,6 +40,52 @@ BUZZ_TEST_PI_ACP=/absolute/buzz-pi-acp/dist/index.js \ cargo test -p buzz-acp real_pi_preserves -- --ignored ``` +## Observer retention measurement + +The observer has deterministic regression tests for replay byte/count limits, +oversized payloads and envelopes, and a stalled live subscriber. Run them with: + +```sh +cargo test -p buzz-acp --lib observer::tests -- --test-threads=1 +``` + +An ignored local probe measures the actual `ObserverHandle::emit`, `snapshot` +and broadcast paths without a relay or agent. It defaults to the #7987 workload: +1,000 events with a 1 MiB ASCII string each and a subscriber that does not drain +until after emission. It prints JSON with `emitMs`, replay/live serialized byte +totals and event counts, and the subscriber's lag count. + +```sh +cargo test --release -p buzz-acp --lib observer::tests::retention_probe -- \ + --exact --ignored --nocapture + +# Small-event throughput control, including ordinary count-based eviction: +BUZZ_OBSERVER_PROBE_EVENTS=10000 BUZZ_OBSERVER_PROBE_BYTES=1024 \ + cargo test --release -p buzz-acp --lib observer::tests::retention_probe -- \ + --exact --ignored --nocapture +``` + +Use fresh processes, the same profile and workload, an idle machine, and repeated +alternating baseline/candidate runs for timing comparisons. There is no timing +threshold. `emitMs` includes payload construction and excludes the later snapshot +and receive/serialization measurement. Serialized byte totals are not heap/RSS +measurements. On macOS, `/usr/bin/time -l` around the test executable printed by +`cargo test --release -p buzz-acp --lib --no-run` can additionally measure peak +RSS; do not time Cargo compilation as part of the memory workload. The probe's +snapshot and receive measurements allocate their own copies, so its peak RSS +includes measurement overhead. + +Replay keeps the newest suffix within both 1,000 events and 4 MiB of serialized +JSON. Events are fitted with the existing relay payload elision before either +store retains them. Large-payload preparation and snapshot copies stay outside +the replay lock. Publication finalizes the sequence and timestamp together, and +byte accounting uses that finalized envelope. The live ring preserves its requested 1,000-event capacity +(Tokio rounds it to 1,024 slots); its per-event relay-size cap bounds retained +serialized JSON to less than 64 MiB. These are JSON budgets, not exact allocator +limits. Oversized telemetry carries the existing elision markers; an envelope +that cannot fit even after payload elision is dropped with a warning and sequence +gap. A lagging receiver continues to report its dropped-event count. + ## Git bootstrap `cargo test -p buzz-acp --test git_bootstrap` starts the actual harness with a @@ -59,3 +105,42 @@ Goose and uses its provider to invoke the native developer shell. Both operate only on temporary local repositories, verify commit/tag signatures and identity, check unrelated-remote credential scoping, and assert keyfile removal. They do not replace authenticated relay clone/push/readback testing. + +## Observer performance measurement + +An ignored local probe exercises the production publish queue and its JSON +fitter. The default workload is 200 events, each with 1 MiB across 64 string +leaves. It prints elapsed milliseconds and retained queue bytes/events; there +is no timing threshold or additional CI job. + +```sh +cargo test --release -p buzz-acp --lib observer::perf_tests::publish_queue_probe -- \ + --exact --ignored --nocapture + +# Under-budget control: +BUZZ_OBSERVER_PROBE_EVENTS=10000 BUZZ_OBSERVER_PROBE_BYTES=1024 \ + BUZZ_OBSERVER_PROBE_FIELDS=1 \ + cargo test --release -p buzz-acp --lib observer::perf_tests::publish_queue_probe -- \ + --exact --ignored --nocapture +``` + +Elapsed time includes cloning the template payload and queue ingestion; it +excludes template construction and later publication/encryption. Use release +builds, fresh processes, identical workloads, and repeated alternating runs +when comparing revisions. Queue bytes are serialized JSON, not heap or RSS. + +## Observer frame packing measurement + +To isolate frame packing, the drain probe queues 10,000 small events before +starting its clock, then packs every event into frames. It checks complete FIFO +delivery, frame byte limits and empty byte accounting, and reports elapsed +milliseconds and frame count. `BUZZ_OBSERVER_PROBE_EVENTS` changes the count; +the workload must fit the existing queue budget. + +```sh +cargo test --release -p buzz-acp --lib observer::packing_tests::publish_queue_drain_probe -- \ + --exact --ignored --nocapture +``` + +This measures packing only, excluding ingestion, publish pacing, encryption, +relay delivery and rendering. It does not estimate overall app latency. diff --git a/crates/buzz-acp/src/acp.rs b/crates/buzz-acp/src/acp.rs index 72f9d8d91f5..79453929003 100644 --- a/crates/buzz-acp/src/acp.rs +++ b/crates/buzz-acp/src/acp.rs @@ -873,12 +873,16 @@ impl AcpClient { /// Emit a semantic event to the local observer feed, if enabled. pub fn observe(&self, kind: impl Into, payload: serde_json::Value) { + self.observe_with(kind, || payload); + } + + fn observe_with(&self, kind: impl Into, payload: impl FnOnce() -> serde_json::Value) { if let Some(observer) = &self.observer { observer.emit( kind, self.observer_agent_index, &self.observer_context, - payload, + payload(), ); } } @@ -1443,7 +1447,7 @@ impl AcpClient { .await .map_err(|_| AcpError::WriteTimeout(WRITE_TIMEOUT))? .map_err(AcpError::Io)?; - self.observe("acp_write", value.clone()); + self.observe_with("acp_write", || value.clone()); Ok(()) } @@ -1616,7 +1620,7 @@ impl AcpClient { continue; } }; - self.observe("acp_read", msg.clone()); + self.observe_with("acp_read", || msg.clone()); // Check if this is a response to our expected request (has matching id // AND no `method` field — a `method` field means it's an agent-initiated @@ -2089,7 +2093,7 @@ impl AcpClient { continue; } }; - self.observe("acp_read", msg.clone()); + self.observe_with("acp_read", || msg.clone()); clock.on_activity(Instant::now()); @@ -6173,6 +6177,8 @@ mod tests { let mut client = spawn_script(r#"while IFS= read -r line; do printf '%s\n' "$line"; done"#).await; let mut stdin = client.stdin.take().expect("test stdin"); + // Raw wire payload copies must be lazy when observation is disabled. + client.observe_with("acp_read", || panic!("disabled observer copied payload")); let observer = ObserverHandle::in_process(); let mut events = observer.subscribe(); client.set_observer(Some(observer), 0); @@ -6215,6 +6221,10 @@ mod tests { ); if let Ok(event) = events.try_recv() { assert_eq!(event.kind, "acp_read"); + assert_eq!( + event.payload, + serde_json::from_str::(&frame).unwrap() + ); break; } assert!( diff --git a/crates/buzz-acp/src/lib.rs b/crates/buzz-acp/src/lib.rs index 8e9ad2aa285..fc1dc0b68bc 100644 --- a/crates/buzz-acp/src/lib.rs +++ b/crates/buzz-acp/src/lib.rs @@ -1345,8 +1345,7 @@ impl ObserverPublishQueue { // Pre-trim at enqueue so (a) byte accounting reflects what will ship // and (b) one oversized leaf cannot force every frame it touches into // whole-envelope elision downstream. - fit_observer_event_to_budget(&mut event); - let bytes = serialized_len(&event); + let bytes = fit_observer_event_to_budget(&mut event); self.pending_bytes += bytes; self.events.push_back((bytes, source_events, event)); } @@ -1429,21 +1428,29 @@ impl ObserverPublishQueue { let channel = self.events.front()?.2.channel_id.clone(); let mut picked: Vec = Vec::new(); + let mut picked_bytes = 0; let mut kept: VecDeque<(usize, u64, observer::ObserverEvent)> = VecDeque::with_capacity(self.events.len()); let mut gathering = true; while let Some((bytes, source_events, event)) = self.events.pop_front() { if gathering && event.channel_id == channel { - picked.push(event); - if picked.len() > 1 - && serialized_len(&batch_envelope(&picked)) > OBSERVER_FRAME_MAX_LEN + // The empty envelope already includes the array brackets. + // Add cached event sizes and one comma per preceding event; + // only the newest event's envelope metadata needs measuring. + if !picked.is_empty() + && serialized_len(&empty_batch_envelope(&event)) + + picked_bytes + + bytes + + picked.len() + > OBSERVER_FRAME_MAX_LEN { // Frame full: the overflow event stays queued and leads // its channel's next slot. - let event = picked.pop().expect("len > 1"); kept.push_back((bytes, source_events, event)); gathering = false; } else { + picked.push(event); + picked_bytes += bytes; self.pending_bytes -= bytes; } } else { @@ -1477,6 +1484,12 @@ fn batch_envelope(events: &[observer::ObserverEvent]) -> observer::ObserverEvent let last = events .last() .expect("batch envelope needs at least 1 event"); + let mut envelope = empty_batch_envelope(last); + envelope.payload["events"] = serde_json::to_value(events).unwrap_or_default(); + envelope +} + +fn empty_batch_envelope(last: &observer::ObserverEvent) -> observer::ObserverEvent { observer::ObserverEvent { seq: last.seq, timestamp: last.timestamp.clone(), @@ -1486,9 +1499,7 @@ fn batch_envelope(events: &[observer::ObserverEvent]) -> observer::ObserverEvent session_id: last.session_id.clone(), turn_id: last.turn_id.clone(), started_at: last.started_at.clone(), - payload: serde_json::json!({ - "events": serde_json::to_value(events).unwrap_or_default(), - }), + payload: serde_json::json!({ "events": [] }), } } @@ -1760,7 +1771,7 @@ const OBSERVER_LEAF_RETAIN_BYTES: usize = 3_000; /// rejects plaintext over 65_536 - 128 bytes (its `MAX_SUPPORTED_PLAINTEXT_SIZE`), /// tighter than buzz-core's 65_535 `OBSERVER_MAX_PLAINTEXT_LEN`, so frames fitted /// to 65_535 failed with "NIP-44 error: message too long" and were dropped. -const OBSERVER_FRAME_MAX_LEN: usize = 65_536 - 128; +pub(crate) const OBSERVER_FRAME_MAX_LEN: usize = 65_536 - 128; /// Trim an oversized observer telemetry frame so its SERIALIZED form fits under /// `OBSERVER_FRAME_MAX_LEN`, instead of dropping the whole frame (silent @@ -1768,44 +1779,55 @@ const OBSERVER_FRAME_MAX_LEN: usize = 65_536 - 128; /// byte-identical. /// /// The cap is measured in SERIALIZED bytes (JSON escaping makes serialized -/// length differ from raw), so the stop condition is always a full reserialize -/// of the whole frame: that counts the envelope, the variable `Option` -/// IDs, and any elision markers exactly. No separate margin constant is needed. +/// length differ from raw). For small leaves, subtract the old serialized +/// size and add the replacement's size. JSON delimiters and the envelope stay +/// unchanged, so this accounting is exact. For a dominant leaf, recount the +/// fitted frame instead of traversing the large original leaf again. /// /// Termination is provable: each iteration elides the largest string leaf that -/// would STRICTLY shrink the serialized frame, then reserializes. Shrinkability -/// is re-evaluated against each leaf's CURRENT value, so a leaf already at its -/// retained floor can never be re-elided — the loop strictly decreases the -/// serialized length each pass and is bounded by the leaf count. When no leaf -/// can shrink the frame and it still overflows, the payload is replaced with a -/// tiny stub, which trivially fits. Monotone decrease, bounded below by the stub. +/// would STRICTLY shrink the serialized frame, then updates its size. +/// Shrinkability is re-evaluated against each leaf's CURRENT value: a shorter +/// removed-byte count can shorten an existing marker once more. Every pass +/// strictly decreases serialized length, so the loop terminates. When no leaf +/// can shrink the frame and it still overflows, replace the payload with a +/// small stub. Callers must still reject an oversized metadata envelope. /// -/// **Signature choice (`&mut`, double-serialize accepted):** on the common -/// under-budget path this serializes the frame once to decide it fits, then -/// `encrypt_observer_payload` serializes it again — one extra `to_string` of an -/// already-small frame. Reusing that string would mean changing buzz-core's -/// `encrypt_observer_payload` signature or adding a parallel encrypt path; both -/// are out of this change's scope (buzz-core stays untouched). The clean `&mut` -/// signature with one cheap redundant serialize is the deliberate tradeoff. -fn fit_observer_event_to_budget(event: &mut observer::ObserverEvent) { - if serialized_len(event) <= OBSERVER_FRAME_MAX_LEN { - return; - } - - // Raw size of the payload we are about to trim, captured before mutation so - // the stub's `originalBytes` reports source bytes discarded, not serialized - // overflow — consistent with the per-leaf marker's raw byte count. - let original_payload_bytes = serde_json::to_string(&event.payload) - .map(|s| s.len()) - .unwrap_or(0); - - // Elide the largest shrinkable leaf, reserialize, repeat. Each successful - // elision strictly shrinks the serialized frame, and a floored leaf can - // never be re-elided, so the loop is bounded by the leaf count. +/// Returns the fitted serialized size so retention can account for bytes +/// without another traversal. Counting writes avoid allocating a second copy +/// of a potentially multi-megabyte source frame just to measure its size. +fn fit_observer_event_to_budget(event: &mut observer::ObserverEvent) -> usize { + let mut bytes = serialized_len(event); + if bytes <= OBSERVER_FRAME_MAX_LEN { + return bytes; + } + + // Derive the original payload size from the measured frame and its small + // envelope, avoiding a second traversal of the oversized source payload. + // JSON null occupies four bytes in the temporary envelope. + let payload = event.payload.take(); + let envelope_bytes = serialized_len(event).saturating_sub(4); + event.payload = payload; + let original_payload_bytes = bytes.saturating_sub(envelope_bytes); + + // Each successful elision strictly shrinks the serialized frame, so the + // loop terminates even when a shortened marker permits another elision. while let Some(leaf) = largest_shrinkable_leaf(&mut event.payload) { - elide_leaf(leaf); - if serialized_len(event) <= OBSERVER_FRAME_MAX_LEN { - return; + // A JSON string uses at most six bytes per source byte (\u0000), + // plus quotes. Use deltas only when even that upper bound is small + // relative to the frame; otherwise recount the now-smaller frame. + let leaf_bound = leaf + .as_str() + .map_or(0, |s| s.len().saturating_mul(6).saturating_add(2)); + if leaf_bound < bytes / 2 { + let old_leaf_bytes = serialized_len(leaf); + elide_leaf(leaf); + bytes = bytes - old_leaf_bytes + serialized_len(leaf); + } else { + elide_leaf(leaf); + bytes = serialized_len(event); + } + if bytes <= OBSERVER_FRAME_MAX_LEN { + return bytes; } } @@ -1815,10 +1837,27 @@ fn fit_observer_event_to_budget(event: &mut observer::ObserverEvent) { "elided": format!("{} payload too large", event.kind), "originalBytes": original_payload_bytes, }); + serialized_len(event) } -fn serialized_len(event: &observer::ObserverEvent) -> usize { - serde_json::to_string(event).map(|s| s.len()).unwrap_or(0) +fn serialized_len(value: &impl serde::Serialize) -> usize { + let mut counter = ObserverByteCounter(0); + serde_json::to_writer(&mut counter, value) + .map(|()| counter.0) + .unwrap_or(usize::MAX) +} + +struct ObserverByteCounter(usize); + +impl std::io::Write for ObserverByteCounter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 = self.0.saturating_add(bytes.len()); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } } /// Find the longest string leaf that would STRICTLY shrink if elided, returning @@ -10997,626 +11036,7 @@ mod observer_snapshot_race_tests { } #[cfg(test)] -mod observer_publish_queue_tests { - use super::*; - - fn event(seq: u64, kind: &str, channel: Option<&str>) -> observer::ObserverEvent { - observer::ObserverEvent { - seq, - timestamp: format!("2026-04-29T04:00:{:02}Z", seq.min(59)), - kind: kind.to_string(), - agent_index: Some(0), - channel_id: channel.map(ToOwned::to_owned), - session_id: Some("session-1".to_string()), - turn_id: Some("turn-1".to_string()), - started_at: None, - payload: serde_json::json!({ "seq": seq }), - } - } - - fn queue_of(events: Vec) -> ObserverPublishQueue { - let mut queue = ObserverPublishQueue::default(); - for event in events { - queue.ingest(event); - } - queue - } - - /// Collect every frame the queue will produce, one publish slot at a time. - fn drain_frames(queue: &mut ObserverPublishQueue) -> Vec { - let mut frames = Vec::new(); - while !queue.is_empty() { - frames.push(queue.next_frame().expect("queue not empty")); - } - frames - } - - /// Inner seqs of a frame, whether it is an envelope or an unwrapped - /// singleton. - fn frame_seqs(frame: &observer::ObserverEvent) -> Vec { - match frame.payload.get("events").and_then(|v| v.as_array()) { - Some(inner) => inner.iter().map(|e| e["seq"].as_u64().unwrap()).collect(), - None => vec![frame.seq], - } - } - - /// Retained bytes computed by WALKING the entries, independently of the - /// queue's own accumulator. Cap regressions must assert on this, not on - /// `total_pending_bytes()` — asserting the counter against itself passed - /// while the process retained ~2x the budget (Sami/Max round 3: each - /// pending coalescer entry holds the first chunk's text twice, in the - /// serialized skeleton AND the extracted `text` copy). - fn walked_retained_bytes(queue: &ObserverPublishQueue) -> usize { - let fifo: usize = queue - .events - .iter() - .map(|(_, _, event)| serialized_len(event)) - .sum(); - let coalescer: usize = queue - .coalescer - .pending - .iter() - .map(|pending| serialized_len(&pending.event) + pending.text.len()) - .sum(); - fifo + coalescer - } - - /// The walker above is itself an instrument, and every cap test asks it - /// only for `<= CAP` — a blinded walker (missing an arm, or returning 0) - /// would satisfy all of them while hiding exactly the 2x overshoot it was - /// added to catch (Sami round 5, M17-M20). Pin it two-sided: it must SEE - /// the double retention, and it must agree with the accumulator EXACTLY - /// while both stores are non-empty — neither may drift. - #[test] - fn walked_retained_bytes_agrees_with_the_accumulator_exactly() { - fn chunk(seq: u64, message_id: &str, text: &str) -> observer::ObserverEvent { - let mut e = event(seq, "acp_read", Some("chan-a")); - e.payload = serde_json::json!({ - "jsonrpc": "2.0", - "method": "session/update", - "params": { - "sessionId": "session-1", - "update": { - "sessionUpdate": "agent_message_chunk", - "messageId": message_id, - "content": { "type": "text", "text": text }, - }, - }, - }); - e - } - - let text = "w".repeat(7_000); - let mut queue = ObserverPublishQueue::default(); - // One pending chunk: its text lives in the serialized skeleton AND - // the extracted copy, so a walker blind to either arm reads short. - queue.ingest(chunk(1, "message-a", &text)); - assert!( - walked_retained_bytes(&queue) >= 2 * text.len(), - "the walker must SEE the first chunk's text twice \ - (skeleton + extracted copy), got {}", - walked_retained_bytes(&queue) - ); - - // Populate BOTH stores: the non-chunk event flushes message-a into - // the FIFO and queues itself; fresh pending keys (plus a same-key - // append) rebuild the coalescer side. - queue.ingest(event(2, "tool_call", Some("chan-a"))); - queue.ingest(chunk(3, "message-b", &text)); - queue.ingest(chunk(4, "message-b", &text)); - queue.ingest(chunk(5, "message-c", &text)); - assert!( - !queue.events.is_empty() && !queue.coalescer.pending.is_empty(), - "both arms must be non-empty for the agreement check to bind" - ); - assert_eq!( - queue.total_pending_bytes(), - walked_retained_bytes(&queue), - "accumulator and entry-walk must agree exactly: neither may drift" - ); - } - - /// Two or more pending events for one channel ship as a single batch - /// envelope whose payload carries every inner event in arrival order. - #[test] - fn multiple_events_ship_as_one_envelope_in_order() { - let mut queue = queue_of(vec![ - event(1, "turn_started", Some("chan-a")), - event(2, "acp_read", Some("chan-a")), - event(3, "acp_write", Some("chan-a")), - ]); - - let frame = queue.next_frame().expect("one frame"); - assert!(queue.is_empty(), "one channel, one publish slot"); - assert_eq!(frame.kind, OBSERVER_BATCH_KIND); - assert_eq!(frame.seq, 3, "envelope mirrors the last inner event"); - assert_eq!(frame_seqs(&frame), [1, 2, 3], "arrival order preserved"); - let inner = frame.payload["events"].as_array().expect("events array"); - assert_eq!(inner[1]["kind"], "acp_read", "inner events keep their kind"); - } - - /// A single pending event is published unwrapped — no envelope, so - /// consumers that predate batching still understand quiet periods. - #[test] - fn a_single_event_stays_unwrapped() { - let mut queue = queue_of(vec![event(7, "turn_started", Some("chan-a"))]); - let frame = queue.next_frame().expect("one frame"); - assert!(queue.is_empty()); - assert_eq!(frame.kind, "turn_started"); - assert_eq!(frame.seq, 7); - } - - /// An empty queue yields no frame — a tick with nothing pending must not - /// publish anything. - #[test] - fn empty_queue_yields_no_frame() { - let mut queue = ObserverPublishQueue::default(); - assert!(queue.next_frame().is_none()); - assert!(queue.is_empty()); - } - - /// Frames never mix channels, and each channel's events keep their FIFO - /// order. Gathering is QUEUE-WIDE: the front event's channel collects its - /// events from anywhere in the queue (that is what keeps the drain rate - /// in bytes per slot under interleaving), so cross-channel frame order - /// MAY differ from arrival order — but a null-channel event is a barrier - /// nothing gathers across. - #[test] - fn frames_never_mix_channels_and_gather_queue_wide() { - let mut queue = queue_of(vec![ - event(1, "acp_read", Some("chan-a")), - event(2, "acp_write", Some("chan-a")), - event(3, "acp_read", Some("chan-b")), - event(4, "acp_read", Some("chan-a")), - event(5, "acp_read", None), - ]); - - let frames = drain_frames(&mut queue); - assert_eq!( - frames.len(), - 3, - "gathered: [1,2,4]@a, [3]@b, [5]@None — one frame each" - ); - for frame in &frames { - let channels: HashSet> = match frame.payload.get("events") { - Some(serde_json::Value::Array(inner)) => inner - .iter() - .map(|e| e["channelId"].as_str().map(ToOwned::to_owned)) - .collect(), - _ => std::iter::once(frame.channel_id.clone()).collect(), - }; - assert_eq!(channels.len(), 1, "a frame never mixes channels"); - } - assert_eq!( - frame_seqs(&frames[0]), - [1, 2, 4], - "chan-a gathers queue-wide, FIFO within the channel" - ); - assert_eq!(frames[0].channel_id.as_deref(), Some("chan-a")); - assert_eq!(frames[1].kind, "acp_read", "singleton stays unwrapped"); - assert_eq!(frames[1].channel_id.as_deref(), Some("chan-b")); - assert_eq!(frames[2].channel_id, None); - } - - /// A NULL-channel event is a barrier: channel events queued BEHIND it - /// must not gather into a frame ahead of it, so causally-global events - /// (`agent_panic`-class) keep their exact order against every channel. - /// The null event itself ships only its contiguous front run. - #[test] - fn null_channel_events_are_gather_barriers() { - let mut queue = queue_of(vec![ - event(1, "acp_read", Some("chan-a")), - event(2, "acp_read", Some("chan-b")), - event(3, "agent_panic", None), - event(4, "acp_write", Some("chan-a")), - ]); - - let frames = drain_frames(&mut queue); - let published: Vec> = frames.iter().map(frame_seqs).collect(); - assert_eq!( - published, - [vec![1], vec![2], vec![3], vec![4]], - "seq 4 must not gather past the null barrier into frame 1" - ); - } - - /// The drain-rate regression Sami measured: with two channels strictly - /// alternating, a front-run packer degrades to ONE event per slot - /// (~275 B/s regardless of the 64KB frame budget). Queue-wide gathering - /// must drain an interleaved backlog in ~ceil(events / per-frame-fit) - /// slots per channel, not one slot per event. - #[test] - fn interleaved_channels_drain_at_bytes_per_slot_not_events_per_slot() { - let mut events = Vec::new(); - for i in 0..100u64 { - events.push(event(2 * i + 1, "acp_read", Some("chan-a"))); - events.push(event(2 * i + 2, "acp_read", Some("chan-b"))); - } - let mut queue = queue_of(events); - - let frames = drain_frames(&mut queue); - assert!( - frames.len() <= 4, - "200 tiny alternating events must gather into a few full frames, \ - got {} (front-run packing would need 200 slots)", - frames.len() - ); - for frame in &frames { - assert!(serialized_len(frame) <= OBSERVER_FRAME_MAX_LEN); - } - // Within each channel, FIFO order survives the gather. - let mut seqs_a = Vec::new(); - let mut seqs_b = Vec::new(); - for frame in &frames { - match frame.channel_id.as_deref() { - Some("chan-a") => seqs_a.extend(frame_seqs(frame)), - Some("chan-b") => seqs_b.extend(frame_seqs(frame)), - other => panic!("unexpected channel {other:?}"), - } - } - assert!(seqs_a.windows(2).all(|w| w[0] < w[1]), "chan-a FIFO"); - assert!(seqs_b.windows(2).all(|w| w[0] < w[1]), "chan-b FIFO"); - assert_eq!(seqs_a.len() + seqs_b.len(), 200, "nothing lost"); - } - - /// A same-channel backlog that cannot fit one 64KB frame splits across - /// SUCCESSIVE publish slots — never multiple frames from one slot — with - /// every frame under the cap and no event lost or reordered. - #[test] - fn oversized_backlogs_split_across_publish_slots_under_the_cap() { - let big_text = "x".repeat(30_000); - let mut queue = queue_of( - (1..=6) - .map(|seq| { - let mut e = event(seq, "acp_read", Some("chan-a")); - e.payload = serde_json::json!({ "seq": seq, "text": big_text }); - e - }) - .collect(), - ); - - let frames = drain_frames(&mut queue); - assert!( - frames.len() > 1, - "six 30KB events cannot fit one 64KB frame" - ); - let mut seen = Vec::new(); - for frame in &frames { - assert!( - serialized_len(frame) <= OBSERVER_FRAME_MAX_LEN, - "every emitted frame must fit the plaintext cap" - ); - seen.extend(frame_seqs(frame)); - } - assert_eq!( - seen, - [1, 2, 3, 4, 5, 6], - "no event lost or reordered by splitting" - ); - } - - /// The queue preserves the coalescer's ordering rule: a non-chunk event - /// force-flushes pending chunk text ahead of itself, so merged chunks can - /// never leapfrog a tool call that arrived after them. - #[test] - fn non_chunk_events_flush_pending_chunks_ahead_of_themselves() { - fn chunk(seq: u64, text: &str) -> observer::ObserverEvent { - let mut e = event(seq, "acp_read", Some("chan-a")); - e.payload = serde_json::json!({ - "params": { "update": { - "sessionUpdate": "agent_message_chunk", - "messageId": "m1", - "content": { "text": text }, - }} - }); - e - } - - let mut queue = ObserverPublishQueue::default(); - queue.ingest(chunk(1, "hello ")); - queue.ingest(chunk(2, "world")); - queue.ingest(event(3, "tool_call", Some("chan-a"))); - - let frame = queue.next_frame().expect("one frame"); - assert!(queue.is_empty()); - let inner = frame.payload["events"].as_array().expect("batch of 2"); - assert_eq!(inner.len(), 2, "two chunks coalesce into one event"); - assert_eq!( - inner[0]["payload"]["params"]["update"]["content"]["text"], "hello world", - "chunk text merged before the tool call" - ); - assert_eq!(inner[1]["kind"], "tool_call"); - assert!(inner[0]["seq"].as_u64() < inner[1]["seq"].as_u64()); - } - - /// Chunks still pending inside the coalescer (no non-chunk flushed them) - /// are picked up by the publish slot itself, not stranded. - #[test] - fn a_publish_slot_flushes_pending_coalesced_chunks() { - let mut e = event(1, "acp_read", Some("chan-a")); - e.payload = serde_json::json!({ - "params": { "update": { - "sessionUpdate": "agent_message_chunk", - "messageId": "m1", - "content": { "text": "buffered" }, - }} - }); - let mut queue = ObserverPublishQueue::default(); - queue.ingest(e); - assert!(!queue.is_empty(), "pending chunk counts as queued work"); - - let frame = queue.next_frame().expect("chunk must ship"); - assert!(queue.is_empty()); - assert_eq!( - frame.payload["params"]["update"]["content"]["text"], - "buffered" - ); - } - - /// Sami's ceiling assertion: when sustained input outruns the one-frame - /// drain budget for longer than the queue's byte budget, the OLDEST events - /// drop with accounting — never silently — and everything that survives - /// publishes in order with nothing else lost. - #[test] - fn over_budget_floods_drop_oldest_with_accounting() { - let big_text = "y".repeat(10_000); - let total = 500usize; // ~5MB of ~10KB events > 4MiB budget - let mut queue = ObserverPublishQueue::default(); - for seq in 1..=total as u64 { - let mut e = event(seq, "acp_read", Some("chan-a")); - e.payload = serde_json::json!({ "seq": seq, "text": big_text }); - queue.ingest(e); - } - - assert!( - queue.dropped_events > 0, - "a 5MB backlog must overflow the 4MiB budget" - ); - assert!( - walked_retained_bytes(&queue) <= OBSERVER_PENDING_QUEUE_MAX_BYTES, - "eviction must restore the byte budget (entry-walked), got {}", - walked_retained_bytes(&queue) - ); - - let frames = drain_frames(&mut queue); - let published: Vec = frames.iter().flat_map(frame_seqs).collect(); - let expected: Vec = (queue.dropped_events + 1..=total as u64).collect(); - assert_eq!( - published, expected, - "exactly the oldest `dropped_events` events are missing; the rest \ - publish in order" - ); - assert_eq!( - published.len() as u64 + queue.dropped_events, - total as u64, - "accounting: published + dropped == ingested" - ); - } - - /// Max's coalescer-bypass regression: a flood of chunks with DISTINCT - /// messageIds never flushes on its own, so every chunk sits in the - /// coalescer's pending buffer. TRUE retained bytes — walked from the - /// entries, never the queue's own accumulator — MUST respect the byte - /// budget with event-level drop accounting. Pre-fix this retained ~25MB - /// against the 4 MiB cap with `pending_bytes == 0` and zero drops; the - /// round-3 refinement (Sami/Max) caught the accumulator itself reading - /// under cap while true retention was 1.99x over. - #[test] - fn distinct_key_chunk_floods_are_bounded_by_the_byte_budget() { - let big_text = "z".repeat(50_000); - let total = 500u64; // ~25MB pending chunk text vs a 4MiB budget - let mut queue = ObserverPublishQueue::default(); - for seq in 1..=total { - let mut e = event(seq, "acp_read", Some("chan-a")); - e.payload = serde_json::json!({ - "jsonrpc": "2.0", - "method": "session/update", - "params": { - "sessionId": "session-1", - "update": { - "sessionUpdate": "agent_message_chunk", - "messageId": format!("message-{seq}"), - "content": { "type": "text", "text": big_text }, - }, - }, - }); - queue.ingest(e); - } - - let walked = walked_retained_bytes(&queue); - assert!( - walked <= OBSERVER_PENDING_QUEUE_MAX_BYTES, - "TRUE retained bytes (walked from entries) must respect the cap, \ - got {walked}" - ); - assert!( - queue.total_pending_bytes() >= walked, - "the accumulator must never under-count true retention \ - (accumulator {} < walked {walked})", - queue.total_pending_bytes() - ); - assert!( - queue.dropped_events > 0, - "a ~25MB distinct-key chunk flood must record drops" - ); - // Event-level accounting: everything that survives publishes, and - // survivors + dropped == ingested. - let frames = drain_frames(&mut queue); - let survived: u64 = frames.iter().map(|f| frame_seqs(f).len() as u64).sum(); - assert_eq!( - survived + queue.dropped_events, - total, - "accounting: published + dropped == ingested" - ); - // The survivors are the NEWEST events (drop-oldest). - let last_frame_seqs = frame_seqs(frames.last().expect("frames")); - assert_eq!(*last_frame_seqs.last().expect("seqs"), total); - } - - /// Max's merged-chunk accounting regression: one coalescer entry can - /// represent MANY generated observer events (same-messageId chunks merge - /// in place), so evicting it must charge every merged source event to - /// `dropped_events`, not 1 per retained entry. Pre-fix, evicting an entry - /// that merged 50 chunks recorded `dropped_events == 1` and 49 generated - /// events vanished from the accounting. - #[test] - fn evicting_a_merged_chunk_entry_accounts_every_source_event() { - fn chunk(seq: u64, message_id: &str, text: &str) -> observer::ObserverEvent { - let mut e = event(seq, "acp_read", Some("chan-a")); - e.payload = serde_json::json!({ - "jsonrpc": "2.0", - "method": "session/update", - "params": { - "sessionId": "session-1", - "update": { - "sessionUpdate": "agent_message_chunk", - "messageId": message_id, - "content": { "type": "text", "text": text }, - }, - }, - }); - e - } - - let mut queue = ObserverPublishQueue::default(); - // 50 × 1KB chunks under ONE messageId merge into a single pending - // coalescer entry — the oldest item anywhere in the queue. - let merged_text = "m".repeat(1_000); - let merged_sources = 50u64; - for seq in 1..=merged_sources { - queue.ingest(chunk(seq, "message-merged", &merged_text)); - } - // Flood with distinct-key 50KB chunks until the byte budget evicts - // the oldest entries — the merged entry goes first. - let flood_text = "f".repeat(50_000); - let flood = 100u64; - for seq in 1..=flood { - queue.ingest(chunk( - merged_sources + seq, - &format!("message-{seq}"), - &flood_text, - )); - } - - assert!( - walked_retained_bytes(&queue) <= OBSERVER_PENDING_QUEUE_MAX_BYTES, - "eviction must restore the byte budget (entry-walked), got {}", - walked_retained_bytes(&queue) - ); - let frames = drain_frames(&mut queue); - assert!( - !frames - .iter() - .flat_map(frame_seqs) - .any(|seq| seq <= merged_sources), - "the merged entry (globally oldest) must have been evicted" - ); - // Every survivor is an unmerged distinct-key chunk (1 source each), - // so source-event accounting must close exactly: the merged entry's - // eviction charges all 50 sources. - let survived: u64 = frames.iter().map(|f| frame_seqs(f).len() as u64).sum(); - assert_eq!( - survived + queue.dropped_events, - merged_sources + flood, - "accounting: published sources + dropped sources == ingested" - ); - } - - /// Sami's M13 / Max's forced-flush probe: the OTHER eviction arm. A - /// merged entry FLUSHED into the publish FIFO (by a non-chunk event) must - /// still charge every absorbed source on eviction — the FIFO stores the - /// per-entry count precisely so the ledger survives flush. The - /// coalescer-side regression above never exercises this arm; mutating the - /// FIFO eviction to `dropped += 1` survived all 687 tests until this one. - #[test] - fn evicting_a_flushed_merged_entry_from_the_fifo_accounts_every_source_event() { - fn chunk(seq: u64, message_id: &str, text: &str) -> observer::ObserverEvent { - let mut e = event(seq, "acp_read", Some("chan-a")); - e.payload = serde_json::json!({ - "jsonrpc": "2.0", - "method": "session/update", - "params": { - "sessionId": "session-1", - "update": { - "sessionUpdate": "agent_message_chunk", - "messageId": message_id, - "content": { "type": "text", "text": text }, - }, - }, - }); - e - } - - let mut queue = ObserverPublishQueue::default(); - // 50 × 1KB chunks merge under one messageId in the coalescer… - let merged_text = "m".repeat(1_000); - let merged_sources = 50u64; - for seq in 1..=merged_sources { - queue.ingest(chunk(seq, "message-merged", &merged_text)); - } - // …then a non-chunk event force-flushes the merged entry into the - // publish FIFO. From here eviction happens on the FIFO arm. - queue.ingest(event(merged_sources + 1, "tool_call", Some("chan-a"))); - assert!( - queue.coalescer.pending.is_empty(), - "the non-chunk event must have flushed the merged entry" - ); - assert_eq!( - queue.events.front().expect("flushed entry queued").1, - merged_sources, - "the FIFO front must carry the merged source count" - ); - - // Distinct-key flood forces byte-budget eviction of the FIFO front. - let flood_text = "f".repeat(50_000); - let flood = 100u64; - for seq in 1..=flood { - queue.ingest(chunk( - merged_sources + 1 + seq, - &format!("message-{seq}"), - &flood_text, - )); - } - - assert!( - walked_retained_bytes(&queue) <= OBSERVER_PENDING_QUEUE_MAX_BYTES, - "eviction must restore the byte budget (entry-walked), got {}", - walked_retained_bytes(&queue) - ); - let frames = drain_frames(&mut queue); - assert!( - !frames - .iter() - .flat_map(frame_seqs) - .any(|seq| seq <= merged_sources), - "the flushed merged entry (globally oldest) must have been evicted" - ); - // Ledger in source units: survivors are unmerged (1 source each), the - // evicted merged FIFO entry must charge all 50 sources. - let survived: u64 = frames.iter().map(|f| frame_seqs(f).len() as u64).sum(); - let ingested = merged_sources + 1 + flood; - assert_eq!( - survived + queue.dropped_events, - ingested, - "accounting: published sources + dropped sources == ingested" - ); - } - - /// Under the byte budget the queue is lossless: every ingested event - /// publishes exactly once. - #[test] - fn under_budget_backlogs_are_lossless() { - let mut queue = queue_of( - (1..=200) - .map(|seq| event(seq, "acp_read", Some("chan-a"))) - .collect(), - ); - let frames = drain_frames(&mut queue); - let published: Vec = frames.iter().flat_map(frame_seqs).collect(); - assert_eq!(published, (1..=200).collect::>()); - assert_eq!(queue.dropped_events, 0); - } -} +mod observer_publish_queue_tests; #[cfg(test)] mod observer_publish_cadence_tests { @@ -16382,6 +15802,38 @@ mod observer_payload_trim_tests { 20_000, "the smaller leaf is left untouched once the frame fits" ); + + // Many escaped leaves exercise incremental size accounting; enough + // shrink to fit while untouched leaves and section order survive. + for text in ["x", "\n\"\\", "🐝\u{0}"] { + let leaf = format!( + "{}{}{}", + "x".repeat(3_000), + text.repeat(4_000), + "y".repeat(3_000) + ); + let mut event = event_with_payload( + "acp_read", + serde_json::json!({"items": vec![leaf.clone(); 9], "small": "keep"}), + ); + let fitted_bytes = fit_observer_event_to_budget(&mut event); + assert_eq!(fitted_bytes, serialized(&event).len()); + assert!(fitted_bytes <= OBSERVER_FRAME_MAX_LEN); + let items = event.payload["items"] + .as_array() + .expect("trimmed sections survive"); + assert_eq!(items.len(), 9); + assert_eq!(event.payload["small"], "keep"); + let mut saw_untouched = false; + for item in items { + if item == &leaf { + saw_untouched = true; + } else { + assert!(!saw_untouched, "equal-size leaves elide in traversal order"); + assert!(item.as_str().unwrap().contains("…[elided")); + } + } + } } #[test] @@ -16433,6 +15885,19 @@ mod observer_payload_trim_tests { "fell back to the stub" ); assert!(event.payload.get("originalBytes").is_some()); + + // An escaped leaf just above its retained floor is small relative to + // a non-shrinkable numeric array. Delta accounting must include the + // replacement, or it would incorrectly accept this oversized frame. + let mut event = event_with_payload( + "acp_read", + serde_json::json!({"numbers": vec![0; 18_500], "edge": "\u{0}".repeat(6_100)}), + ); + let original_payload_bytes = serialized_len(&event.payload); + let fitted_bytes = fit_observer_event_to_budget(&mut event); + assert_eq!(fitted_bytes, serialized(&event).len()); + assert!(fitted_bytes <= OBSERVER_FRAME_MAX_LEN); + assert_eq!(event.payload["originalBytes"], original_payload_bytes); } #[test] diff --git a/crates/buzz-acp/src/observer.rs b/crates/buzz-acp/src/observer.rs index 7029e5af6d5..1dc94dcc02f 100644 --- a/crates/buzz-acp/src/observer.rs +++ b/crates/buzz-acp/src/observer.rs @@ -15,7 +15,15 @@ use std::{ use serde::Serialize; use tokio::sync::broadcast; +#[cfg(test)] +mod packing_tests; +#[cfg(test)] +mod perf_tests; +#[cfg(test)] +mod tests; + const OBSERVER_BUFFER_CAP: usize = 1_000; +const OBSERVER_REPLAY_MAX_BYTES: usize = 4 * 1024 * 1024; /// Best-effort metadata attached to observer events. #[derive(Clone, Debug, Default)] @@ -37,17 +45,25 @@ pub struct ObserverHandle { } struct ObserverInner { + // Fit events before either buffer retains them. Tokio rounds 1,000 slots + // up to 1,024, so the per-event cap bounds live JSON below 64 MiB. tx: broadcast::Sender, - buffer: Mutex>, + buffer: Mutex, seq: AtomicU64, } +#[derive(Default)] +struct ReplayBuffer { + events: VecDeque<(usize, Arc)>, + bytes: usize, +} + fn new_observer_handle() -> ObserverHandle { let (tx, _) = broadcast::channel(OBSERVER_BUFFER_CAP); ObserverHandle { inner: Arc::new(ObserverInner { tx, - buffer: Mutex::new(VecDeque::with_capacity(OBSERVER_BUFFER_CAP)), + buffer: Mutex::new(ReplayBuffer::default()), seq: AtomicU64::new(1), }), } @@ -89,18 +105,24 @@ impl ObserverHandle { self.inner.tx.subscribe() } - /// Return the current replay buffer. + /// Return the newest events within the 1,000-event and 4 MiB JSON budgets. pub fn snapshot(&self) -> Vec { - match self.inner.buffer.lock() { - Ok(buffer) => buffer.iter().cloned().collect(), + // Pin the replay window under the lock, then copy JSON after releasing it. + let events: Vec<_> = match self.inner.buffer.lock() { + Ok(buffer) => buffer + .events + .iter() + .map(|(_, event)| event.clone()) + .collect(), Err(error) => { tracing::warn!(target: "observer", "observer replay buffer lock poisoned: {error}"); Vec::new() } - } + }; + events.into_iter().map(|event| (*event).clone()).collect() } - /// Emit a local observer event. + /// Emit a local observer event, fitting telemetry before retaining it. pub fn emit( &self, kind: impl Into, @@ -108,9 +130,9 @@ impl ObserverHandle { context: &ObserverContext, payload: serde_json::Value, ) { - let event = ObserverEvent { - seq: self.inner.seq.fetch_add(1, Ordering::Relaxed), - timestamp: chrono::Utc::now().to_rfc3339(), + let mut event = ObserverEvent { + seq: self.inner.seq.load(Ordering::Relaxed), + timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Nanos, false), kind: kind.into(), agent_index, channel_id: context.channel_id.clone(), @@ -120,17 +142,49 @@ impl ObserverHandle { payload, }; - match self.inner.buffer.lock() { - Ok(mut buffer) => { - if buffer.len() >= OBSERVER_BUFFER_CAP { - buffer.pop_front(); - } - buffer.push_back(event.clone()); - } + // Fit and copy before locking so large inputs do not stall other + // emitters. Fixed timestamp precision keeps metadata width stable; + // account for the final publication metadata below without a JSON walk. + let prepared_metadata_bytes = event.seq.to_string().len() + event.timestamp.len(); + let mut bytes = super::fit_observer_event_to_budget(&mut event); + let prepared_within_budget = bytes <= super::OBSERVER_FRAME_MAX_LEN; + let mut replay = event.clone(); + let mut buffer = match self.inner.buffer.lock() { + Ok(buffer) => buffer, Err(error) => { tracing::warn!(target: "observer", "observer replay buffer lock poisoned: {error}"); + return; } + }; + // Assign both fields with publication: desktop sorts by timestamp, + // and the publisher deduplicates snapshots by sequence high-water mark. + event.seq = self.inner.seq.fetch_add(1, Ordering::Relaxed); + event.timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Nanos, false); + bytes = + bytes - prepared_metadata_bytes + event.seq.to_string().len() + event.timestamp.len(); + if prepared_within_budget && bytes > super::OBSERVER_FRAME_MAX_LEN { + // A sequence-width boundary can grow a frame prepared just below + // the cap. Only an already-bounded frame can need this final fit. + bytes = super::fit_observer_event_to_budget(&mut event); + replay = event.clone(); + } + if bytes > super::OBSERVER_FRAME_MAX_LEN { + tracing::warn!(target: "observer", seq = event.seq, bytes, dropped = 1, + "observer envelope exceeds byte budget; dropped event"); + return; + } + replay.seq = event.seq; + replay.timestamp.clone_from(&event.timestamp); + while buffer.events.len() >= OBSERVER_BUFFER_CAP + || buffer.bytes + bytes > OBSERVER_REPLAY_MAX_BYTES + { + let Some((old_bytes, _)) = buffer.events.pop_front() else { + break; + }; + buffer.bytes -= old_bytes; } + buffer.bytes += bytes; + buffer.events.push_back((bytes, Arc::new(replay))); let _ = self.inner.tx.send(event); } diff --git a/crates/buzz-acp/src/observer/packing_tests.rs b/crates/buzz-acp/src/observer/packing_tests.rs new file mode 100644 index 00000000000..c16a4578637 --- /dev/null +++ b/crates/buzz-acp/src/observer/packing_tests.rs @@ -0,0 +1,56 @@ +use super::*; +use serde_json::json; + +/// Measure packing separately from ingestion, with no timing gate. +#[test] +#[ignore = "manual observer packing measurement"] +fn publish_queue_drain_probe() { + let count: usize = std::env::var("BUZZ_OBSERVER_PROBE_EVENTS") + .unwrap_or_else(|_| "10000".into()) + .parse() + .unwrap(); + let mut queue = crate::ObserverPublishQueue::default(); + for seq in 1..=count as u64 { + queue.ingest(ObserverEvent { + seq, + timestamp: "2026-11-01T00:00:00Z".into(), + kind: "marker".into(), + agent_index: Some(0), + channel_id: Some("channel".into()), + session_id: Some("session".into()), + turn_id: Some("turn".into()), + started_at: None, + payload: json!({"text": "hello 🐝\n\"world\"", "seq": seq}), + }); + } + assert_eq!(queue.events.len(), count, "workload must fit the queue"); + let start = std::time::Instant::now(); + let mut frames = Vec::new(); + while let Some(frame) = queue.next_frame() { + frames.push(frame); + } + let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0; + let seqs: Vec<_> = frames + .iter() + .flat_map(|frame| { + frame.payload["events"].as_array().map_or_else( + || vec![frame.seq], + |events| { + events + .iter() + .map(|event| event["seq"].as_u64().unwrap()) + .collect() + }, + ) + }) + .collect(); + assert_eq!(seqs, (1..=count as u64).collect::>()); + assert!(frames + .iter() + .all(|frame| crate::serialized_len(frame) <= crate::OBSERVER_FRAME_MAX_LEN)); + assert_eq!(queue.pending_bytes, 0); + println!( + "{}", + json!({"events": count, "frames": frames.len(), "elapsedMs": elapsed_ms}) + ); +} diff --git a/crates/buzz-acp/src/observer/perf_tests.rs b/crates/buzz-acp/src/observer/perf_tests.rs new file mode 100644 index 00000000000..e76b5c6b8c3 --- /dev/null +++ b/crates/buzz-acp/src/observer/perf_tests.rs @@ -0,0 +1,136 @@ +use super::*; +use serde_json::json; +use tokio::sync::broadcast::error::TryRecvError; + +struct SlowKind { + started: std::sync::mpsc::Sender<()>, + resume: std::sync::mpsc::Receiver<()>, +} + +impl From for String { + fn from(kind: SlowKind) -> Self { + kind.started.send(()).unwrap(); + kind.resume.recv().unwrap(); + "slow".into() + } +} + +#[test] +fn concurrent_emitters_keep_live_and_replay_sequence_order() { + let observer = ObserverHandle::in_process(); + let mut live = observer.subscribe(); + let context = context_for_turn( + None, + Some("session".into()), + "turn".into(), + "2026-11-01T00:00:00Z".into(), + ); + // Keep the payload below the frame cap so this checks ordering separately + // from the retention suite's oversized-payload fitting cases. + let payload = json!({"text":"hello 🐝\n\"world\"", "body":"x".repeat(40_000)}); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let (observer_ref, context_ref, payload_ref) = (&observer, &context, &payload); + let (mut handoff_live, mut handoff_snapshot) = std::thread::scope(move |scope| { + scope.spawn(move || { + observer_ref.emit( + SlowKind { + started: started_tx, + resume: resume_rx, + }, + Some(0), + context_ref, + payload_ref.clone(), + ) + }); + // Pause one real emit during preparation, then let another publish. + // No timing assertion: the channel controls this interleaving exactly. + started_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap(); + observer_ref.emit("fast", Some(1), context_ref, payload_ref.clone()); + let handoff_live = observer_ref.subscribe(); + let snapshot = observer_ref.snapshot(); + resume_tx.send(()).unwrap(); + (handoff_live, snapshot) + }); + let snapshot = observer.snapshot(); + assert_eq!(snapshot.len(), 2); + for (index, kind) in ["fast", "slow"].into_iter().enumerate() { + let event = live.try_recv().unwrap(); + assert_eq!(event.seq, index as u64 + 1); + assert_eq!(event.kind, kind); + assert!(chrono::DateTime::parse_from_rfc3339(&event.timestamp).is_ok()); + assert_eq!(event.payload, payload); + assert_eq!(event.session_id, context.session_id); + assert_eq!(event.turn_id, context.turn_id); + assert_eq!(event.started_at, context.started_at); + assert_eq!( + serde_json::to_value(&event).unwrap(), + serde_json::to_value(&snapshot[index]).unwrap() + ); + } + assert!(matches!(live.try_recv(), Err(TryRecvError::Empty))); + let high_water = handoff_snapshot.last().map_or(0, |event| event.seq); + while let Ok(event) = handoff_live.try_recv() { + if event.seq > high_water { + handoff_snapshot.push(event); + } + } + assert_eq!( + serde_json::to_value(&handoff_snapshot).unwrap(), + serde_json::to_value(&snapshot).unwrap(), + "snapshot/live handoff must neither skip nor duplicate the slow event" + ); + for n in 0..1_010 { + observer.emit("marker", None, &context, json!({"n":n})); + } + let snapshot = observer.snapshot(); + assert_eq!(snapshot.len(), 1_000); + assert_eq!(snapshot.first().unwrap().payload["n"], 10); + assert_eq!(snapshot.last().unwrap().payload["n"], 1_009); +} + +/// Local measurement only: the production publish queue, with no timing gate. +#[test] +#[ignore = "manual observer fitting measurement"] +fn publish_queue_probe() { + let count: usize = std::env::var("BUZZ_OBSERVER_PROBE_EVENTS") + .unwrap_or_else(|_| "200".into()) + .parse() + .unwrap(); + let payload_bytes: usize = std::env::var("BUZZ_OBSERVER_PROBE_BYTES") + .unwrap_or_else(|_| "1048576".into()) + .parse() + .unwrap(); + let fields: usize = std::env::var("BUZZ_OBSERVER_PROBE_FIELDS") + .unwrap_or_else(|_| "64".into()) + .parse() + .unwrap(); + assert!(fields > 0); + let mut template = ObserverEvent { + seq: 0, + timestamp: "2026-11-01T00:00:00Z".into(), + kind: "acp_read".into(), + agent_index: None, + channel_id: None, + session_id: None, + turn_id: None, + started_at: None, + payload: json!({"body": (0..fields).map(|n| + "x".repeat(payload_bytes / fields + usize::from(n < payload_bytes % fields)) + ).collect::>() }), + }; + let mut queue = crate::ObserverPublishQueue::default(); + let start = std::time::Instant::now(); + for n in 0..count { + template.seq = n as u64 + 1; + queue.ingest(template.clone()); + } + let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0; + println!( + "{}", + json!({"events": count, "payloadBytes": payload_bytes, "fields": fields, + "elapsedMs": elapsed_ms, "queuedEvents": queue.events.len(), "queuedBytes": queue.pending_bytes}) + ); +} diff --git a/crates/buzz-acp/src/observer/tests.rs b/crates/buzz-acp/src/observer/tests.rs new file mode 100644 index 00000000000..c105ac86065 --- /dev/null +++ b/crates/buzz-acp/src/observer/tests.rs @@ -0,0 +1,322 @@ +use super::*; +use crate::OBSERVER_FRAME_MAX_LEN; +use serde_json::json; +use tokio::sync::broadcast::error::TryRecvError; + +const REPLAY_MAX_BYTES: usize = 4 * 1024 * 1024; + +fn bytes(event: &ObserverEvent) -> usize { + serde_json::to_vec(event).unwrap().len() +} + +#[test] +fn small_events_preserve_payload_context_and_count_limited_replay() { + let observer = ObserverHandle::in_process(); + let mut live = observer.subscribe(); + let context = context_for_turn( + Some(uuid::Uuid::new_v4()), + Some("session".into()), + "turn".into(), + "2026-11-01T00:00:00Z".into(), + ); + let payload = json!({"text": "hello 🐝\n\"world\"", "count": 3}); + observer.emit("turn_started", Some(2), &context, payload.clone()); + let first = live.try_recv().unwrap(); + assert_eq!(first.payload, payload); + assert_eq!(first.kind, "turn_started"); + assert_eq!(first.agent_index, Some(2)); + assert_eq!(first.channel_id, context.channel_id); + assert_eq!(first.session_id, context.session_id); + assert_eq!(first.turn_id, context.turn_id); + assert_eq!(first.started_at, context.started_at); + assert_eq!(first.seq, 1); + assert_eq!( + serde_json::to_value(&first).unwrap(), + serde_json::to_value(&observer.snapshot()[0]).unwrap() + ); + + for n in 0..1_020 { + observer.emit("marker", None, &context, json!({"n": n})); + } + let snapshot = observer.snapshot(); + assert_eq!(snapshot.len(), 1_000); + assert_eq!(snapshot.first().unwrap().payload["n"], 20); + assert_eq!(snapshot.last().unwrap().payload["n"], 1_019); +} + +#[test] +fn replay_evicts_oldest_by_serialized_bytes_and_remains_usable() { + let observer = ObserverHandle::in_process(); + let context = ObserverContext::default(); + // Individually under the frame cap, collectively beyond the replay budget. + // Escaping makes the wire size substantially larger than the raw strings. + for n in 0..180 { + observer.emit( + "acp_read", + None, + &context, + json!({"n": n, "text": "\n🐝".repeat(8_000)}), + ); + } + let snapshot = observer.snapshot(); + let retained: usize = snapshot.iter().map(bytes).sum(); + assert!(retained <= REPLAY_MAX_BYTES, "retained {retained} bytes"); + assert!(snapshot.len() < 180); + assert_eq!(snapshot.last().unwrap().payload["n"], 179); + assert!(snapshot + .windows(2) + .all(|pair| pair[1].seq == pair[0].seq + 1)); + // Eviction is greedy, keeping the largest newest suffix that fits. + assert!(retained + bytes(snapshot.first().unwrap()) > REPLAY_MAX_BYTES); + drop(snapshot); + + observer.emit("turn_completed", None, &context, json!({"done": true})); + let snapshot = observer.snapshot(); + assert_eq!(snapshot.last().unwrap().kind, "turn_completed"); + assert!(snapshot.iter().map(bytes).sum::() <= REPLAY_MAX_BYTES); +} + +#[test] +fn oversized_payloads_are_fitted_before_replay_and_stalled_broadcast() { + let observer = ObserverHandle::in_process(); + let mut live = observer.subscribe(); + let context = context_for(None, Some("session".into()), Some("turn".into())); + // Exercise a string leaf, structure that cannot be leaf-trimmed, and large + // object keys. Both consumers must see the same bounded representation. + let payloads = [ + json!({"body": "🐝\n".repeat(40_000)}), + json!(vec![0; 80_000]), + json!({"x".repeat(100_000): "value"}), + ]; + let original_sizes: Vec<_> = payloads + .iter() + .map(|payload| serde_json::to_vec(payload).unwrap().len()) + .collect(); + for payload in payloads { + observer.emit("acp_read", Some(0), &context, payload); + } + let snapshot = observer.snapshot(); + assert_eq!(snapshot.len(), 3); + for (replay, original_size) in snapshot.into_iter().zip(original_sizes) { + let event = live.try_recv().unwrap(); + assert!(bytes(&event) <= OBSERVER_FRAME_MAX_LEN); + assert_eq!( + serde_json::to_value(&event).unwrap(), + serde_json::to_value(&replay).unwrap() + ); + assert_eq!(event.session_id, context.session_id); + assert_eq!(event.turn_id, context.turn_id); + assert!(serde_json::to_string(&event.payload) + .unwrap() + .contains("elided")); + if let Some(original_bytes) = event.payload.get("originalBytes") { + assert_eq!(original_bytes, original_size); + } + } +} + +#[test] +fn stalled_subscriber_has_a_bounded_recent_window_and_reports_lag() { + let observer = ObserverHandle::in_process(); + let mut live = observer.subscribe(); + for n in 0..1_100 { + observer.emit( + "acp_read", + None, + &ObserverContext::default(), + json!({"n": n, "body": "x".repeat(70_000)}), + ); + } + // Tokio rounds the 1,000 requested slots up to 1,024. Even a subscriber + // that never drains must not keep raw oversized events in those slots. + let mut lagged = 0; + let mut received = Vec::new(); + loop { + match live.try_recv() { + Ok(event) => received.push(event), + Err(TryRecvError::Lagged(count)) => lagged += count, + Err(TryRecvError::Empty) => break, + Err(error) => panic!("unexpected receive error: {error}"), + } + } + assert!(lagged > 0); + assert_eq!(lagged as usize + received.len(), 1_100); + assert!(received.len() <= 1_024); + assert!(received + .iter() + .all(|event| bytes(event) <= OBSERVER_FRAME_MAX_LEN)); + assert!(received.iter().map(bytes).sum::() <= 1_024 * OBSERVER_FRAME_MAX_LEN); + assert_eq!(received.last().unwrap().payload["n"], 1_099); + assert!(received + .windows(2) + .all(|pair| pair[1].seq == pair[0].seq + 1)); +} + +#[test] +fn oversized_envelope_is_not_retained_and_later_events_still_deliver() { + let observer = ObserverHandle::in_process(); + let mut live = observer.subscribe(); + let context = context_for(None, Some("s".repeat(100_000)), None); + observer.emit("acp_read", None, &context, json!({"body": "small"})); + assert!(observer.snapshot().is_empty()); + assert!(matches!(live.try_recv(), Err(TryRecvError::Empty))); + observer.emit( + "turn_completed", + None, + &ObserverContext::default(), + json!({}), + ); + assert_eq!(live.try_recv().unwrap().seq, 2); + assert_eq!(observer.snapshot().len(), 1); +} + +#[test] +fn concurrent_emitters_keep_live_and_replay_sequence_order() { + let observer = ObserverHandle::in_process(); + let mut live = observer.subscribe(); + let start = std::sync::Barrier::new(4); + std::thread::scope(|scope| { + for producer in 0..4 { + let (observer, start) = (&observer, &start); + scope.spawn(move || { + start.wait(); + for n in 0..50 { + observer.emit( + "acp_read", None, &ObserverContext::default(), + json!({"producer": producer, "n": n, "body": "x".repeat(1_000 + producer * 40_000)}), + ); + } + }); + } + }); + let snapshot = observer.snapshot(); + assert_eq!(snapshot.len(), 200); + for (index, replay) in snapshot.iter().enumerate() { + let event = live.try_recv().unwrap(); + assert_eq!(event.seq, index as u64 + 1); + assert_eq!( + serde_json::to_value(&event).unwrap(), + serde_json::to_value(replay).unwrap() + ); + } + assert!(matches!(live.try_recv(), Err(TryRecvError::Empty))); +} + +#[test] +fn publication_metadata_growth_keeps_live_events_bounded() { + struct PausedKind { + ready: std::sync::mpsc::Sender<()>, + resume: std::sync::mpsc::Receiver<()>, + } + impl From for String { + fn from(kind: PausedKind) -> Self { + kind.ready.send(()).unwrap(); + kind.resume.recv().unwrap(); + "boundary".into() + } + } + let observer = ObserverHandle::in_process(); + let context = ObserverContext::default(); + for _ in 0..8 { + observer.emit("seed", None, &context, json!({})); + } + let mut live = observer.subscribe(); + let mut template = ObserverEvent { + seq: 9, + timestamp: "2000-01-01T00:00:00.000000000+00:00".into(), + kind: "boundary".into(), + agent_index: None, + channel_id: None, + session_id: None, + turn_id: None, + started_at: None, + payload: json!({"body":""}), + }; + template.payload = json!({"body":"x".repeat(OBSERVER_FRAME_MAX_LEN - bytes(&template))}); + assert_eq!(bytes(&template), OBSERVER_FRAME_MAX_LEN); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| { + observer.emit( + PausedKind { + ready: ready_tx, + resume: resume_rx, + }, + None, + &context, + template.payload.clone(), + ); + }); + ready_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap(); + observer.emit("fast", None, &context, json!({})); + resume_tx.send(()).unwrap(); + }); + let fast = live.try_recv().unwrap(); + let boundary = live.try_recv().unwrap(); + assert_eq!((fast.seq, boundary.seq), (9, 10)); + assert_eq!(fast.kind, "fast"); + assert_eq!(boundary.kind, "boundary"); + assert!(bytes(&boundary) <= OBSERVER_FRAME_MAX_LEN); + assert_ne!(boundary.payload, template.payload); + let snapshot = observer.snapshot(); + assert_eq!( + serde_json::to_value(snapshot.last().unwrap()).unwrap(), + serde_json::to_value(boundary).unwrap() + ); + assert_eq!( + observer.inner.buffer.lock().unwrap().bytes, + snapshot.iter().map(bytes).sum::() + ); +} + +/// Local measurement only: no timing threshold and no relay or real agent. +#[test] +#[ignore = "manual observer retention and emit-time measurement"] +fn retention_probe() { + let count: usize = std::env::var("BUZZ_OBSERVER_PROBE_EVENTS") + .unwrap_or_else(|_| "1000".into()) + .parse() + .unwrap(); + let payload_bytes: usize = std::env::var("BUZZ_OBSERVER_PROBE_BYTES") + .unwrap_or_else(|_| "1048576".into()) + .parse() + .unwrap(); + let observer = ObserverHandle::in_process(); + let mut live = observer.subscribe(); + let body = "x".repeat(payload_bytes); + let start = std::time::Instant::now(); + for n in 0..count { + observer.emit( + "acp_read", + Some(0), + &ObserverContext::default(), + json!({"n": n, "body": body}), + ); + } + let emit_ms = start.elapsed().as_secs_f64() * 1_000.0; + let snapshot = observer.snapshot(); + let replay_events = snapshot.len(); + let replay_bytes: usize = snapshot.iter().map(bytes).sum(); + drop(snapshot); + let (mut live_events, mut live_bytes, mut lagged) = (0, 0, 0); + loop { + match live.try_recv() { + Ok(event) => { + live_events += 1; + live_bytes += bytes(&event); + } + Err(TryRecvError::Lagged(count)) => lagged += count, + Err(TryRecvError::Empty) => break, + Err(error) => panic!("unexpected receive error: {error}"), + } + } + println!( + "{}", + json!({"events": count, "payloadBytes": payload_bytes, "emitMs": emit_ms, + "replayEvents": replay_events, "replayBytes": replay_bytes, + "liveEvents": live_events, "liveBytes": live_bytes, "lagged": lagged}) + ); +} diff --git a/crates/buzz-acp/src/observer_publish_queue_tests.rs b/crates/buzz-acp/src/observer_publish_queue_tests.rs new file mode 100644 index 00000000000..490c1072a45 --- /dev/null +++ b/crates/buzz-acp/src/observer_publish_queue_tests.rs @@ -0,0 +1,679 @@ +use super::*; + +fn event(seq: u64, kind: &str, channel: Option<&str>) -> observer::ObserverEvent { + observer::ObserverEvent { + seq, + timestamp: format!("2026-04-29T04:00:{:02}Z", seq.min(59)), + kind: kind.to_string(), + agent_index: Some(0), + channel_id: channel.map(ToOwned::to_owned), + session_id: Some("session-1".to_string()), + turn_id: Some("turn-1".to_string()), + started_at: None, + payload: serde_json::json!({ "seq": seq }), + } +} + +fn queue_of(events: Vec) -> ObserverPublishQueue { + let mut queue = ObserverPublishQueue::default(); + for event in events { + queue.ingest(event); + } + queue +} + +/// Collect every frame the queue will produce, one publish slot at a time. +fn drain_frames(queue: &mut ObserverPublishQueue) -> Vec { + let mut frames = Vec::new(); + while !queue.is_empty() { + frames.push(queue.next_frame().expect("queue not empty")); + } + frames +} + +/// Inner seqs of a frame, whether it is an envelope or an unwrapped +/// singleton. +fn frame_seqs(frame: &observer::ObserverEvent) -> Vec { + match frame.payload.get("events").and_then(|v| v.as_array()) { + Some(inner) => inner.iter().map(|e| e["seq"].as_u64().unwrap()).collect(), + None => vec![frame.seq], + } +} + +/// Retained bytes computed by WALKING the entries, independently of the +/// queue's own accumulator. Cap regressions must assert on this, not on +/// `total_pending_bytes()` — asserting the counter against itself passed +/// while the process retained ~2x the budget (an earlier regression: each +/// pending coalescer entry holds the first chunk's text twice, in the +/// serialized skeleton AND the extracted `text` copy). +fn walked_retained_bytes(queue: &ObserverPublishQueue) -> usize { + let fifo: usize = queue + .events + .iter() + .map(|(_, _, event)| serialized_len(event)) + .sum(); + let coalescer: usize = queue + .coalescer + .pending + .iter() + .map(|pending| serialized_len(&pending.event) + pending.text.len()) + .sum(); + fifo + coalescer +} + +/// The walker above is itself an instrument, and every cap test asks it +/// only for `<= CAP` — a blinded walker (missing an arm, or returning 0) +/// would satisfy all of them while hiding exactly the 2x overshoot it was +/// added to catch. Pin it two-sided: it must SEE +/// the double retention, and it must agree with the accumulator EXACTLY +/// while both stores are non-empty — neither may drift. +#[test] +fn walked_retained_bytes_agrees_with_the_accumulator_exactly() { + fn chunk(seq: u64, message_id: &str, text: &str) -> observer::ObserverEvent { + let mut e = event(seq, "acp_read", Some("chan-a")); + e.payload = serde_json::json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "session-1", + "update": { + "sessionUpdate": "agent_message_chunk", + "messageId": message_id, + "content": { "type": "text", "text": text }, + }, + }, + }); + e + } + + let text = "w".repeat(7_000); + let mut queue = ObserverPublishQueue::default(); + // One pending chunk: its text lives in the serialized skeleton AND + // the extracted copy, so a walker blind to either arm reads short. + queue.ingest(chunk(1, "message-a", &text)); + assert!( + walked_retained_bytes(&queue) >= 2 * text.len(), + "the walker must SEE the first chunk's text twice \ + (skeleton + extracted copy), got {}", + walked_retained_bytes(&queue) + ); + + // Populate BOTH stores: the non-chunk event flushes message-a into + // the FIFO and queues itself; fresh pending keys (plus a same-key + // append) rebuild the coalescer side. + queue.ingest(event(2, "tool_call", Some("chan-a"))); + queue.ingest(chunk(3, "message-b", &text)); + queue.ingest(chunk(4, "message-b", &text)); + queue.ingest(chunk(5, "message-c", &text)); + assert!( + !queue.events.is_empty() && !queue.coalescer.pending.is_empty(), + "both arms must be non-empty for the agreement check to bind" + ); + assert_eq!( + queue.total_pending_bytes(), + walked_retained_bytes(&queue), + "accumulator and entry-walk must agree exactly: neither may drift" + ); +} + +/// Two or more pending events for one channel ship as a single batch +/// envelope whose payload carries every inner event in arrival order. +#[test] +fn multiple_events_ship_as_one_envelope_in_order() { + let mut queue = queue_of(vec![ + event(1, "turn_started", Some("chan-a")), + event(2, "acp_read", Some("chan-a")), + event(3, "acp_write", Some("chan-a")), + ]); + + let frame = queue.next_frame().expect("one frame"); + assert!(queue.is_empty(), "one channel, one publish slot"); + assert_eq!(frame.kind, OBSERVER_BATCH_KIND); + assert_eq!(frame.seq, 3, "envelope mirrors the last inner event"); + assert_eq!(frame_seqs(&frame), [1, 2, 3], "arrival order preserved"); + let inner = frame.payload["events"].as_array().expect("events array"); + assert_eq!(inner[1]["kind"], "acp_read", "inner events keep their kind"); +} + +/// A single pending event is published unwrapped — no envelope, so +/// consumers that predate batching still understand quiet periods. +#[test] +fn a_single_event_stays_unwrapped() { + let mut queue = queue_of(vec![event(7, "turn_started", Some("chan-a"))]); + let frame = queue.next_frame().expect("one frame"); + assert!(queue.is_empty()); + assert_eq!(frame.kind, "turn_started"); + assert_eq!(frame.seq, 7); +} + +/// An empty queue yields no frame — a tick with nothing pending must not +/// publish anything. +#[test] +fn empty_queue_yields_no_frame() { + let mut queue = ObserverPublishQueue::default(); + assert!(queue.next_frame().is_none()); + assert!(queue.is_empty()); +} + +/// Frames never mix channels, and each channel's events keep their FIFO +/// order. Gathering is QUEUE-WIDE: the front event's channel collects its +/// events from anywhere in the queue (that is what keeps the drain rate +/// in bytes per slot under interleaving), so cross-channel frame order +/// MAY differ from arrival order — but a null-channel event is a barrier +/// nothing gathers across. +#[test] +fn frames_never_mix_channels_and_gather_queue_wide() { + let mut queue = queue_of(vec![ + event(1, "acp_read", Some("chan-a")), + event(2, "acp_write", Some("chan-a")), + event(3, "acp_read", Some("chan-b")), + event(4, "acp_read", Some("chan-a")), + event(5, "acp_read", None), + ]); + + let frames = drain_frames(&mut queue); + assert_eq!( + frames.len(), + 3, + "gathered: [1,2,4]@a, [3]@b, [5]@None — one frame each" + ); + for frame in &frames { + let channels: HashSet> = match frame.payload.get("events") { + Some(serde_json::Value::Array(inner)) => inner + .iter() + .map(|e| e["channelId"].as_str().map(ToOwned::to_owned)) + .collect(), + _ => std::iter::once(frame.channel_id.clone()).collect(), + }; + assert_eq!(channels.len(), 1, "a frame never mixes channels"); + } + assert_eq!( + frame_seqs(&frames[0]), + [1, 2, 4], + "chan-a gathers queue-wide, FIFO within the channel" + ); + assert_eq!(frames[0].channel_id.as_deref(), Some("chan-a")); + assert_eq!(frames[1].kind, "acp_read", "singleton stays unwrapped"); + assert_eq!(frames[1].channel_id.as_deref(), Some("chan-b")); + assert_eq!(frames[2].channel_id, None); +} + +/// A NULL-channel event is a barrier: channel events queued BEHIND it +/// must not gather into a frame ahead of it, so causally-global events +/// (`agent_panic`-class) keep their exact order against every channel. +/// The null event itself ships only its contiguous front run. +#[test] +fn null_channel_events_are_gather_barriers() { + let mut queue = queue_of(vec![ + event(1, "acp_read", Some("chan-a")), + event(2, "acp_read", Some("chan-b")), + event(3, "agent_panic", None), + event(4, "acp_write", Some("chan-a")), + ]); + + let frames = drain_frames(&mut queue); + let published: Vec> = frames.iter().map(frame_seqs).collect(); + assert_eq!( + published, + [vec![1], vec![2], vec![3], vec![4]], + "seq 4 must not gather past the null barrier into frame 1" + ); +} + +/// The drain-rate regression: with two channels strictly +/// alternating, a front-run packer degrades to ONE event per slot +/// (~275 B/s regardless of the 64KB frame budget). Queue-wide gathering +/// must drain an interleaved backlog in ~ceil(events / per-frame-fit) +/// slots per channel, not one slot per event. +#[test] +fn interleaved_channels_drain_at_bytes_per_slot_not_events_per_slot() { + let mut events = Vec::new(); + for i in 0..100u64 { + events.push(event(2 * i + 1, "acp_read", Some("chan-a"))); + events.push(event(2 * i + 2, "acp_read", Some("chan-b"))); + } + let mut queue = queue_of(events); + + let frames = drain_frames(&mut queue); + assert!( + frames.len() <= 4, + "200 tiny alternating events must gather into a few full frames, \ + got {} (front-run packing would need 200 slots)", + frames.len() + ); + for frame in &frames { + assert!(serialized_len(frame) <= OBSERVER_FRAME_MAX_LEN); + } + // Within each channel, FIFO order survives the gather. + let mut seqs_a = Vec::new(); + let mut seqs_b = Vec::new(); + for frame in &frames { + match frame.channel_id.as_deref() { + Some("chan-a") => seqs_a.extend(frame_seqs(frame)), + Some("chan-b") => seqs_b.extend(frame_seqs(frame)), + other => panic!("unexpected channel {other:?}"), + } + } + assert!(seqs_a.windows(2).all(|w| w[0] < w[1]), "chan-a FIFO"); + assert!(seqs_b.windows(2).all(|w| w[0] < w[1]), "chan-b FIFO"); + assert_eq!(seqs_a.len() + seqs_b.len(), 200, "nothing lost"); +} + +/// A same-channel backlog that cannot fit one 64KB frame splits across +/// SUCCESSIVE publish slots — never multiple frames from one slot — with +/// every frame under the cap and no event lost or reordered. +#[test] +fn oversized_backlogs_split_across_publish_slots_under_the_cap() { + let big_text = "x".repeat(30_000); + let mut queue = queue_of( + (1..=6) + .map(|seq| { + let mut e = event(seq, "acp_read", Some("chan-a")); + e.payload = serde_json::json!({ "seq": seq, "text": big_text }); + e + }) + .collect(), + ); + + let frames = drain_frames(&mut queue); + assert!( + frames.len() > 1, + "six 30KB events cannot fit one 64KB frame" + ); + let mut seen = Vec::new(); + for frame in &frames { + assert!( + serialized_len(frame) <= OBSERVER_FRAME_MAX_LEN, + "every emitted frame must fit the plaintext cap" + ); + seen.extend(frame_seqs(frame)); + } + assert_eq!( + seen, + [1, 2, 3, 4, 5, 6], + "no event lost or reordered by splitting" + ); +} + +#[test] +fn batch_packing_matches_wire_bytes_at_the_exact_limit() { + for count in [2, 3, 16] { + for channel in [None, Some("channel\"🐝\n")] { + for delta in [-1isize, 0, 1] { + let mut events: Vec<_> = (0..count) + .map(|i| { + let mut e = event(9 + i, "marker", channel); + e.agent_index = (i % 2 == 0).then_some(123); + e.session_id = Some("session\"\\\n🐝".into()); + e.turn_id = None; + e.started_at = (i % 2 == 1).then(|| "2026-11-01T00:00:00Z".into()); + e.payload = serde_json::json!({"text": ""}); + e + }) + .collect(); + // Independent wire oracle, including the newest metadata, + // escaped strings, optional fields, array commas and UTF-8. + let wire_batch = |events: &[observer::ObserverEvent]| { + let mut value = serde_json::to_value(events.last().unwrap()).unwrap(); + value["kind"] = serde_json::json!("batch"); + value["payload"] = serde_json::json!({"events": events}); + value + }; + let overhead = serde_json::to_vec(&wire_batch(&events)).unwrap().len(); + let padding = (OBSERVER_FRAME_MAX_LEN as isize + delta) as usize - overhead; + events.last_mut().unwrap().payload["text"] = serde_json::json!("x".repeat(padding)); + let expected = wire_batch(&events); + assert_eq!( + serde_json::to_vec(&expected).unwrap().len(), + (OBSERVER_FRAME_MAX_LEN as isize + delta) as usize + ); + let mut queue = queue_of(events.clone()); + let frames = drain_frames(&mut queue); + assert_eq!(frames.len(), if delta <= 0 { 1 } else { 2 }); + if delta <= 0 { + assert_eq!(serde_json::to_value(&frames[0]).unwrap(), expected); + } + let mut delivered = Vec::new(); + for frame in frames { + assert!(serde_json::to_vec(&frame).unwrap().len() <= OBSERVER_FRAME_MAX_LEN); + if let Some(inner) = frame.payload["events"].as_array() { + delivered.extend(inner.iter().cloned()); + } else { + delivered.push(serde_json::to_value(frame).unwrap()); + } + } + assert_eq!( + delivered, + serde_json::to_value(events) + .unwrap() + .as_array() + .unwrap() + .clone() + ); + assert_eq!(queue.pending_bytes, 0); + } + } + } +} + +/// The queue preserves the coalescer's ordering rule: a non-chunk event +/// force-flushes pending chunk text ahead of itself, so merged chunks can +/// never leapfrog a tool call that arrived after them. +#[test] +fn non_chunk_events_flush_pending_chunks_ahead_of_themselves() { + fn chunk(seq: u64, text: &str) -> observer::ObserverEvent { + let mut e = event(seq, "acp_read", Some("chan-a")); + e.payload = serde_json::json!({ + "params": { "update": { + "sessionUpdate": "agent_message_chunk", + "messageId": "m1", + "content": { "text": text }, + }} + }); + e + } + + let mut queue = ObserverPublishQueue::default(); + queue.ingest(chunk(1, "hello ")); + queue.ingest(chunk(2, "world")); + queue.ingest(event(3, "tool_call", Some("chan-a"))); + + let frame = queue.next_frame().expect("one frame"); + assert!(queue.is_empty()); + let inner = frame.payload["events"].as_array().expect("batch of 2"); + assert_eq!(inner.len(), 2, "two chunks coalesce into one event"); + assert_eq!( + inner[0]["payload"]["params"]["update"]["content"]["text"], "hello world", + "chunk text merged before the tool call" + ); + assert_eq!(inner[1]["kind"], "tool_call"); + assert!(inner[0]["seq"].as_u64() < inner[1]["seq"].as_u64()); +} + +/// Chunks still pending inside the coalescer (no non-chunk flushed them) +/// are picked up by the publish slot itself, not stranded. +#[test] +fn a_publish_slot_flushes_pending_coalesced_chunks() { + let mut e = event(1, "acp_read", Some("chan-a")); + e.payload = serde_json::json!({ + "params": { "update": { + "sessionUpdate": "agent_message_chunk", + "messageId": "m1", + "content": { "text": "buffered" }, + }} + }); + let mut queue = ObserverPublishQueue::default(); + queue.ingest(e); + assert!(!queue.is_empty(), "pending chunk counts as queued work"); + + let frame = queue.next_frame().expect("chunk must ship"); + assert!(queue.is_empty()); + assert_eq!( + frame.payload["params"]["update"]["content"]["text"], + "buffered" + ); +} + +/// The queue ceiling assertion: when sustained input outruns the one-frame +/// drain budget for longer than the queue's byte budget, the OLDEST events +/// drop with accounting — never silently — and everything that survives +/// publishes in order with nothing else lost. +#[test] +fn over_budget_floods_drop_oldest_with_accounting() { + let big_text = "y".repeat(10_000); + let total = 500usize; // ~5MB of ~10KB events > 4MiB budget + let mut queue = ObserverPublishQueue::default(); + for seq in 1..=total as u64 { + let mut e = event(seq, "acp_read", Some("chan-a")); + e.payload = serde_json::json!({ "seq": seq, "text": big_text }); + queue.ingest(e); + } + + assert!( + queue.dropped_events > 0, + "a 5MB backlog must overflow the 4MiB budget" + ); + assert!( + walked_retained_bytes(&queue) <= OBSERVER_PENDING_QUEUE_MAX_BYTES, + "eviction must restore the byte budget (entry-walked), got {}", + walked_retained_bytes(&queue) + ); + + let frames = drain_frames(&mut queue); + let published: Vec = frames.iter().flat_map(frame_seqs).collect(); + let expected: Vec = (queue.dropped_events + 1..=total as u64).collect(); + assert_eq!( + published, expected, + "exactly the oldest `dropped_events` events are missing; the rest \ + publish in order" + ); + assert_eq!( + published.len() as u64 + queue.dropped_events, + total as u64, + "accounting: published + dropped == ingested" + ); +} + +/// The coalescer-bypass regression: a flood of chunks with DISTINCT +/// messageIds never flushes on its own, so every chunk sits in the +/// coalescer's pending buffer. TRUE retained bytes — walked from the +/// entries, never the queue's own accumulator — MUST respect the byte +/// budget with event-level drop accounting. Pre-fix this retained ~25MB +/// against the 4 MiB cap with `pending_bytes == 0` and zero drops; the +/// accounting refinement caught the accumulator itself reading +/// under cap while true retention was 1.99x over. +#[test] +fn distinct_key_chunk_floods_are_bounded_by_the_byte_budget() { + let big_text = "z".repeat(50_000); + let total = 500u64; // ~25MB pending chunk text vs a 4MiB budget + let mut queue = ObserverPublishQueue::default(); + for seq in 1..=total { + let mut e = event(seq, "acp_read", Some("chan-a")); + e.payload = serde_json::json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "session-1", + "update": { + "sessionUpdate": "agent_message_chunk", + "messageId": format!("message-{seq}"), + "content": { "type": "text", "text": big_text }, + }, + }, + }); + queue.ingest(e); + } + + let walked = walked_retained_bytes(&queue); + assert!( + walked <= OBSERVER_PENDING_QUEUE_MAX_BYTES, + "TRUE retained bytes (walked from entries) must respect the cap, \ + got {walked}" + ); + assert!( + queue.total_pending_bytes() >= walked, + "the accumulator must never under-count true retention \ + (accumulator {} < walked {walked})", + queue.total_pending_bytes() + ); + assert!( + queue.dropped_events > 0, + "a ~25MB distinct-key chunk flood must record drops" + ); + // Event-level accounting: everything that survives publishes, and + // survivors + dropped == ingested. + let frames = drain_frames(&mut queue); + let survived: u64 = frames.iter().map(|f| frame_seqs(f).len() as u64).sum(); + assert_eq!( + survived + queue.dropped_events, + total, + "accounting: published + dropped == ingested" + ); + // The survivors are the NEWEST events (drop-oldest). + let last_frame_seqs = frame_seqs(frames.last().expect("frames")); + assert_eq!(*last_frame_seqs.last().expect("seqs"), total); +} + +/// The merged-chunk accounting regression: one coalescer entry can +/// represent MANY generated observer events (same-messageId chunks merge +/// in place), so evicting it must charge every merged source event to +/// `dropped_events`, not 1 per retained entry. Pre-fix, evicting an entry +/// that merged 50 chunks recorded `dropped_events == 1` and 49 generated +/// events vanished from the accounting. +#[test] +fn evicting_a_merged_chunk_entry_accounts_every_source_event() { + fn chunk(seq: u64, message_id: &str, text: &str) -> observer::ObserverEvent { + let mut e = event(seq, "acp_read", Some("chan-a")); + e.payload = serde_json::json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "session-1", + "update": { + "sessionUpdate": "agent_message_chunk", + "messageId": message_id, + "content": { "type": "text", "text": text }, + }, + }, + }); + e + } + + let mut queue = ObserverPublishQueue::default(); + // 50 × 1KB chunks under ONE messageId merge into a single pending + // coalescer entry — the oldest item anywhere in the queue. + let merged_text = "m".repeat(1_000); + let merged_sources = 50u64; + for seq in 1..=merged_sources { + queue.ingest(chunk(seq, "message-merged", &merged_text)); + } + // Flood with distinct-key 50KB chunks until the byte budget evicts + // the oldest entries — the merged entry goes first. + let flood_text = "f".repeat(50_000); + let flood = 100u64; + for seq in 1..=flood { + queue.ingest(chunk( + merged_sources + seq, + &format!("message-{seq}"), + &flood_text, + )); + } + + assert!( + walked_retained_bytes(&queue) <= OBSERVER_PENDING_QUEUE_MAX_BYTES, + "eviction must restore the byte budget (entry-walked), got {}", + walked_retained_bytes(&queue) + ); + let frames = drain_frames(&mut queue); + assert!( + !frames + .iter() + .flat_map(frame_seqs) + .any(|seq| seq <= merged_sources), + "the merged entry (globally oldest) must have been evicted" + ); + // Every survivor is an unmerged distinct-key chunk (1 source each), + // so source-event accounting must close exactly: the merged entry's + // eviction charges all 50 sources. + let survived: u64 = frames.iter().map(|f| frame_seqs(f).len() as u64).sum(); + assert_eq!( + survived + queue.dropped_events, + merged_sources + flood, + "accounting: published sources + dropped sources == ingested" + ); +} + +/// The forced-flush probe covers the OTHER eviction arm. A +/// merged entry FLUSHED into the publish FIFO (by a non-chunk event) must +/// still charge every absorbed source on eviction — the FIFO stores the +/// per-entry count precisely so the ledger survives flush. The +/// coalescer-side regression above never exercises this arm; mutating the +/// FIFO eviction to `dropped += 1` survived all 687 tests until this one. +#[test] +fn evicting_a_flushed_merged_entry_from_the_fifo_accounts_every_source_event() { + fn chunk(seq: u64, message_id: &str, text: &str) -> observer::ObserverEvent { + let mut e = event(seq, "acp_read", Some("chan-a")); + e.payload = serde_json::json!({ + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "session-1", + "update": { + "sessionUpdate": "agent_message_chunk", + "messageId": message_id, + "content": { "type": "text", "text": text }, + }, + }, + }); + e + } + + let mut queue = ObserverPublishQueue::default(); + // 50 × 1KB chunks merge under one messageId in the coalescer… + let merged_text = "m".repeat(1_000); + let merged_sources = 50u64; + for seq in 1..=merged_sources { + queue.ingest(chunk(seq, "message-merged", &merged_text)); + } + // …then a non-chunk event force-flushes the merged entry into the + // publish FIFO. From here eviction happens on the FIFO arm. + queue.ingest(event(merged_sources + 1, "tool_call", Some("chan-a"))); + assert!( + queue.coalescer.pending.is_empty(), + "the non-chunk event must have flushed the merged entry" + ); + assert_eq!( + queue.events.front().expect("flushed entry queued").1, + merged_sources, + "the FIFO front must carry the merged source count" + ); + + // Distinct-key flood forces byte-budget eviction of the FIFO front. + let flood_text = "f".repeat(50_000); + let flood = 100u64; + for seq in 1..=flood { + queue.ingest(chunk( + merged_sources + 1 + seq, + &format!("message-{seq}"), + &flood_text, + )); + } + + assert!( + walked_retained_bytes(&queue) <= OBSERVER_PENDING_QUEUE_MAX_BYTES, + "eviction must restore the byte budget (entry-walked), got {}", + walked_retained_bytes(&queue) + ); + let frames = drain_frames(&mut queue); + assert!( + !frames + .iter() + .flat_map(frame_seqs) + .any(|seq| seq <= merged_sources), + "the flushed merged entry (globally oldest) must have been evicted" + ); + // Ledger in source units: survivors are unmerged (1 source each), the + // evicted merged FIFO entry must charge all 50 sources. + let survived: u64 = frames.iter().map(|f| frame_seqs(f).len() as u64).sum(); + let ingested = merged_sources + 1 + flood; + assert_eq!( + survived + queue.dropped_events, + ingested, + "accounting: published sources + dropped sources == ingested" + ); +} + +/// Under the byte budget the queue is lossless: every ingested event +/// publishes exactly once. +#[test] +fn under_budget_backlogs_are_lossless() { + let mut queue = queue_of( + (1..=200) + .map(|seq| event(seq, "acp_read", Some("chan-a"))) + .collect(), + ); + let frames = drain_frames(&mut queue); + let published: Vec = frames.iter().flat_map(frame_seqs).collect(); + assert_eq!(published, (1..=200).collect::>()); + assert_eq!(queue.dropped_events, 0); +} diff --git a/crates/buzz-acp/src/relay.rs b/crates/buzz-acp/src/relay.rs index 3afe9bc1579..cdb4c09150e 100644 --- a/crates/buzz-acp/src/relay.rs +++ b/crates/buzz-acp/src/relay.rs @@ -57,6 +57,14 @@ const WS_SEND_TIMEOUT_SECS: u64 = 10; const STABLE_CONNECTION_SECS: u64 = 60; /// Seconds subtracted from `since` on resubscribe to tolerate clock skew. pub(crate) const SINCE_SKEW_SECS: u64 = 5; +/// WebSocket close code 1001 (Going Away): the peer is shutting down. +const CLOSE_CODE_GOING_AWAY: u16 = 1001; +/// WebSocket close code 1012 (Service Restart): the relay pod is rolling. +const CLOSE_CODE_SERVICE_RESTART: u16 = 1012; +/// Upper bound of the uniform random wait before the first reconnect attempt +/// after a 1001/1012 close. The relay already spreads its own closes over ~10s +/// during a rolling deploy; this spreads the clients' arrival the same way. +const RESTART_RECONNECT_SPREAD: Duration = Duration::from_secs(10); /// Timeout for the NIP-42 auth handshake steps. /// /// Raised from 5s to 20s (≈2 RTTs at the observed 10s max round-trip on degraded @@ -125,6 +133,8 @@ use nostr::{Event, EventBuilder, Keys, Kind, RelayUrl, Tag}; use serde_json::{json, Value}; use tokio::sync::mpsc; use tokio::time::timeout; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::http::{header::USER_AGENT, HeaderValue}; use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream}; use tracing::{debug, info, warn}; use uuid::Uuid; @@ -1261,6 +1271,32 @@ struct BgState { /// the elevated rung it earned. Reset to 0 by the stability block once the /// connection has been up for `STABLE_CONNECTION_SECS`. backoff_step: usize, + /// Loss records (`channel_dropped_since` / `membership_dropped_since`) + /// that a REQ written on the CURRENT connection retired, keyed by + /// subscription ID. Writing a replay REQ retires its loss record, but the + /// replay only finished once that REQ reaches a counted EOSE, which removes + /// the entry. If the connection closes first, the record is restored, so + /// the next replay is still held at or before the loss whatever `last_seen` + /// says. Cleared on every close; it never outlives the connection, so on a + /// live connection overflow recovery behaves as before. + retired_loss_this_conn: HashMap, + /// Close code of the last WebSocket Close frame received, consumed by the + /// next reconnect to choose the first-attempt delay. + last_close_code: Option, + /// Subscription IDs a REQ was written for on the CURRENT connection. + /// Deliberately kept across unsubscribe: the wire ID is derived from the + /// channel, so a re-subscribe on the same socket reuses it and must count as + /// a second REQ (an EOSE for the old REQ may still be in flight). Cleared + /// only when the connection closes, so it is bounded by the IDs used on one + /// socket. + req_sent_this_conn: HashSet, + /// Subscription IDs whose REQ was written more than once on the CURRENT + /// connection. EOSE carries only the subscription ID, so an EOSE for the + /// superseded REQ cannot be told from one for its replacement; such a + /// subscription's EOSE never releases its retired loss record on this + /// connection. Like `req_sent_this_conn`, kept across unsubscribe and + /// cleared only on connection close. + superseded_this_conn: HashSet, } impl BgState { @@ -1289,6 +1325,10 @@ impl BgState { resubscribe_retry: HashSet::new(), connection_generation: 0, backoff_step: 0, + retired_loss_this_conn: HashMap::new(), + last_close_code: None, + req_sent_this_conn: HashSet::new(), + superseded_this_conn: HashSet::new(), } } @@ -1314,28 +1354,83 @@ impl BgState { /// Compute the `since` timestamp for a channel (re)subscribe. /// - /// Picks the earliest of `last_seen` and `channel_dropped_since` so - /// the replay window covers both successfully processed events and any - /// that were dropped due to queue pressure. Falls back to the per-channel - /// `subscribe_since` (set at first subscribe) or `startup_watermark`. + /// See [`resume_since`] for how `last_seen`, `channel_dropped_since` and + /// the per-channel `subscribe_since` / `startup_watermark` baseline combine. fn channel_since(&self, channel_id: &Uuid) -> Option { - let last_seen = self.last_seen.get(channel_id).copied(); - let dropped = self.channel_dropped_since.get(channel_id).copied(); - let since = match (last_seen, dropped) { - (Some(l), Some(d)) => Some(l.min(d)), - (Some(l), None) => Some(l), - (None, Some(d)) => Some(d), - (None, None) => self - .subscribe_since + resume_since( + self.subscribe_since .get(channel_id) .copied() .or(self.startup_watermark), - }; + self.last_seen.get(channel_id).copied(), + self.channel_dropped_since.get(channel_id).copied(), + ) // A replay cut off before its EOSE starts over from where it began. - since - .into_iter() - .chain(self.awaiting_eose.get(channel_id).copied()) - .min() + .into_iter() + .chain(self.awaiting_eose.get(channel_id).copied()) + .min() + } + + /// Compute the `since` timestamp for a membership notification (re)subscribe. + fn membership_since(&self) -> Option { + resume_since( + self.startup_watermark, + self.membership_last_seen, + self.membership_dropped_since, + ) + } + + /// `sub_id` reached EOSE on the current connection: its replay finished, + /// so the loss record its REQ retired is not restored on close. A + /// subscription whose REQ was re-sent on this connection is ignored: the + /// EOSE may belong to the superseded REQ, whose replacement (e.g. an + /// overflow-recovery replay) has not delivered its history yet. + fn note_eose(&mut self, sub_id: &str) { + if !self.superseded_this_conn.contains(sub_id) { + self.retired_loss_this_conn.remove(sub_id); + } + } + + /// A REQ was written for `sub_id`. A second REQ on the same connection + /// supersedes the first for the rest of that connection (see + /// `superseded_this_conn`). A caller that wrote a replay REQ retires the + /// subscription's loss record right after this, so the record is kept in + /// `retired_loss_this_conn` until the replay is known to have finished. + fn note_req_sent(&mut self, sub_id: &str) { + let loss = if sub_id == MEMBERSHIP_NOTIF_SUB_ID { + self.membership_dropped_since + } else { + channel_id_from_sub_id(sub_id) + .and_then(|channel_id| self.channel_dropped_since.get(&channel_id).copied()) + }; + if let Some(loss) = loss { + self.retired_loss_this_conn + .entry(sub_id.to_owned()) + .and_modify(|t| *t = (*t).min(loss)) + .or_insert(loss); + } + if !self.req_sent_this_conn.insert(sub_id.to_owned()) { + self.superseded_this_conn.insert(sub_id.to_owned()); + } + } + + /// The current connection closed: loss records retired by a replay that + /// never reached a counted EOSE are restored, merged by `min` with any + /// newer loss. Idempotent for the same outage. + fn note_connection_closed(&mut self) { + for (sub_id, loss) in std::mem::take(&mut self.retired_loss_this_conn) { + if sub_id == MEMBERSHIP_NOTIF_SUB_ID { + self.membership_dropped_since = + Some(self.membership_dropped_since.map_or(loss, |d| d.min(loss))); + } else if let Some(channel_id) = channel_id_from_sub_id(&sub_id) { + self.channel_dropped_since + .entry(channel_id) + .and_modify(|d| *d = (*d).min(loss)) + .or_insert(loss); + } + } + self.req_sent_this_conn.clear(); + self.superseded_this_conn.clear(); } /// Clear all per-channel state for a channel that is being unsubscribed. @@ -1349,6 +1444,11 @@ impl BgState { self.subscribe_since.remove(channel_id); self.awaiting_eose.remove(channel_id); self.channel_dropped_since.remove(channel_id); + // `req_sent_this_conn` / `superseded_this_conn` are intentionally NOT + // cleared: a re-subscribe on this socket reuses the wire ID, and an EOSE + // for the old REQ must not count for the new one. + self.retired_loss_this_conn + .remove(&channel_sub_id(*channel_id)); self.active_filters.remove(channel_id); self.rate_limited_pending.remove(channel_id); self.resubscribe_retry.remove(channel_id); @@ -1682,8 +1782,8 @@ async fn execute_connected_command( state.membership_resub_needed = true; return true; } - let since = state.membership_last_seen.or(state.startup_watermark); - let sent = send_membership_subscribe(ws, agent_pubkey_hex, since).await; + let since = state.membership_since(); + let sent = send_membership_subscribe(ws, state, agent_pubkey_hex, since).await; if sent { state.membership_resub_needed = false; if state.membership_last_seen.is_none() { @@ -1885,14 +1985,15 @@ async fn run_background_task( // recovery fires even when rate_limited_pending is empty. if state.check_rate_gate().is_none() { if state.membership_resub_needed && budget > 0 { - let replay_since = - match (state.membership_dropped_since, state.membership_last_seen) { - (Some(d), Some(l)) => Some(d.min(l)), - (Some(d), None) => Some(d), - (None, Some(l)) => Some(l), - (None, None) => state.startup_watermark, - }; - if send_membership_subscribe(&mut ws, &agent_pubkey_hex, replay_since).await { + let replay_since = state.membership_since(); + if send_membership_subscribe( + &mut ws, + &mut state, + &agent_pubkey_hex, + replay_since, + ) + .await + { state.membership_resub_needed = false; state.membership_dropped_since = None; budget = budget.saturating_sub(1); @@ -2394,6 +2495,7 @@ async fn handle_ws_message( } RelayMessage::Eose { subscription_id } => { debug!("EOSE for subscription {subscription_id}"); + state.note_eose(&subscription_id); if let Some(channel_id) = channel_id_from_sub_id(&subscription_id) { state.awaiting_eose.remove(&channel_id); } @@ -2488,14 +2590,9 @@ async fn handle_ws_message( return false; } } else if subscription_id == MEMBERSHIP_NOTIF_SUB_ID { - let since = - match (state.membership_dropped_since, state.membership_last_seen) { - (Some(d), Some(l)) => Some(d.min(l)), - (Some(d), None) => Some(d), - (None, Some(l)) => Some(l), - (None, None) => state.startup_watermark, - }; - let sent = send_membership_subscribe(ws, agent_pubkey_hex, since).await; + let since = state.membership_since(); + let sent = + send_membership_subscribe(ws, state, agent_pubkey_hex, since).await; if sent { // Success — subscription is live again. state.membership_dropped_since = None; @@ -2604,8 +2701,9 @@ async fn handle_ws_message( } true } - Message::Close(_) => { - debug!("relay sent Close frame"); + Message::Close(frame) => { + state.last_close_code = frame.as_ref().map(|f| u16::from(f.code)); + debug!(close_code = ?state.last_close_code, "relay sent Close frame"); false } // Binary, Pong, Frame — ignore @@ -2724,6 +2822,11 @@ async fn resubscribe_after_reconnect( is_fresh_connection: bool, ) -> ResubscribeResult { if is_fresh_connection { + // The previous socket is gone. The reconnect entry already closed it + // out, but a socket that died partway through an earlier resubscribe + // (`RetryConnection`) did not: restore the loss records its REQs + // retired before any `since` is computed. Idempotent otherwise. + state.note_connection_closed(); // These queues are derived from active subscription intent and rebuilt // below. The rate-limit gate is deliberately preserved: the relay's // shared admission counter survives socket replacement. @@ -2792,13 +2895,8 @@ async fn resubscribe_after_reconnect( { return ResubscribeResult::Shutdown; } - let replay_since = match (state.membership_dropped_since, state.membership_last_seen) { - (Some(d), Some(l)) => Some(d.min(l)), - (Some(d), None) => Some(d), - (None, Some(l)) => Some(l), - (None, None) => state.startup_watermark, - }; - let sent = send_membership_subscribe(ws, agent_pubkey_hex, replay_since).await; + let replay_since = state.membership_since(); + let sent = send_membership_subscribe(ws, state, agent_pubkey_hex, replay_since).await; if sent { state.membership_dropped_since = None; state.membership_resub_needed = false; @@ -3132,6 +3230,9 @@ async fn try_autonomous_reconnect( auth_tag: Option<&nostr::Tag>, ) -> ReconnectOutcome { state.requeue_observer_in_flight(); + if !prepare_reconnect(cmd_rx, state).await { + return ReconnectOutcome::Shutdown; + } // 5 attempts, up to 16s base backoff. Shares delay values with the // initial-connect retry in `HarnessRelay::connect()` (STARTUP_CONNECT_BACKOFFS) — // see its doc comment for how the two loops consume the array differently. @@ -3263,6 +3364,9 @@ async fn wait_for_reconnect( auth_tag: Option<&nostr::Tag>, ) -> ReconnectOutcome { state.requeue_observer_in_flight(); + if !prepare_reconnect(cmd_rx, state).await { + return ReconnectOutcome::Shutdown; + } if !skip_drain { // Drain commands until we get Reconnect (or Shutdown). // Other commands update state so reconnect reflects latest intent. @@ -3431,6 +3535,7 @@ async fn send_subscribe( Ok(text) => { match ws_send_timeout(ws, Message::Text(text.into()), WS_SEND_TIMEOUT_SECS).await { Ok(()) => { + state.note_req_sent(&sub_id); if let Some(since) = since { let floor = state.awaiting_eose.entry(channel_id).or_insert(since); *floor = (*floor).min(since); @@ -3462,6 +3567,7 @@ async fn send_subscribe( /// Returns `true` if the REQ was successfully written to the WebSocket. async fn send_membership_subscribe( ws: &mut WsStream, + state: &mut BgState, agent_pubkey_hex: &str, since: Option, ) -> bool { @@ -3489,6 +3595,7 @@ async fn send_membership_subscribe( Ok(text) => { match ws_send_timeout(ws, Message::Text(text.into()), WS_SEND_TIMEOUT_SECS).await { Ok(()) => { + state.note_req_sent(MEMBERSHIP_NOTIF_SUB_ID); debug!("subscribed to membership notifications (since={since_ts})"); true } @@ -3568,16 +3675,76 @@ pub(crate) fn parse_rate_limit_retry_secs(msg: &str) -> Option { after[..len].parse::().ok() } -/// Add ±20% jitter to a backoff duration using the nanosecond sub-second -/// component of the system clock as a cheap entropy source (no `rand` dep). +/// Uniform random sample in `[0, 1)` from the OS CSPRNG (via a v4 UUID, so no +/// extra dependency). Used for reconnect jitter so concurrent agents spread out. +fn random_unit_sample() -> f64 { + const MANTISSA_BITS: u32 = 53; + let (_, low) = Uuid::new_v4().as_u64_pair(); + (low & ((1u64 << MANTISSA_BITS) - 1)) as f64 / (1u64 << MANTISSA_BITS) as f64 +} + +/// Clamp an externally supplied sample into `[0, 1]`; non-finite values fall +/// back to the midpoint so `Duration::mul_f64` can never panic. +fn clamp_unit_sample(sample: f64) -> f64 { + if sample.is_finite() { + sample.clamp(0.0, 1.0) + } else { + 0.5 + } +} + +/// Add symmetric ±20% jitter to a backoff duration. fn jittered_duration(base: Duration) -> Duration { - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .subsec_nanos(); - // factor ∈ [0.8, 1.2) - let factor = 0.8 + (nanos as f64 / u32::MAX as f64) * 0.4; - base.mul_f64(factor) + jittered_duration_with(base, random_unit_sample()) +} + +/// Deterministic core of [`jittered_duration`]: `sample` in `[0, 1]` maps +/// linearly onto a factor in `[0.8, 1.2]`. +fn jittered_duration_with(base: Duration, sample: f64) -> Duration { + base.mul_f64(0.8 + clamp_unit_sample(sample) * 0.4) +} + +/// Delay before the first reconnect attempt after a close. +/// +/// A 1012 (Service Restart) or 1001 (Going Away) close means the relay pod is +/// rolling; every client of that pod is being closed within the same ~10s +/// window, so each waits a uniform random `sample * 10s` ("full jitter") to +/// spread its arrival. Any other close (or none) reconnects immediately, as +/// before. `sample` is in `[0, 1]` and is injected so callers can test this +/// without sleeping. +fn first_reconnect_delay(close_code: Option, sample: f64) -> Duration { + match close_code { + Some(CLOSE_CODE_SERVICE_RESTART | CLOSE_CODE_GOING_AWAY) => { + RESTART_RECONNECT_SPREAD.mul_f64(clamp_unit_sample(sample)) + } + _ => Duration::ZERO, + } +} + +/// Combine the replay inputs for one subscription into the `since` cursor +/// handed to `send_subscribe` (which subtracts [`SINCE_SKEW_SECS`] on the wire). +/// +/// - `base`: original replay floor (`subscribe_since` / startup watermark). +/// - `last_seen`: newest delivered event `created_at`. +/// - `dropped`: oldest event lost to backpressure; a recorded gap, so the +/// result never advances past it. +/// +/// The earlier of `last_seen` and `dropped`, else `base`. +fn resume_since(base: Option, last_seen: Option, dropped: Option) -> Option { + match (last_seen, dropped) { + (Some(l), Some(d)) => Some(l.min(d)), + (Some(l), None) => Some(l), + (None, Some(d)) => Some(d), + (None, None) => base, + } +} + +/// Bookkeeping at the top of every reconnect, returning the delay to wait +/// before the first attempt: restores loss records whose replay never finished +/// on the connection that just closed, and consumes its close code. +fn begin_reconnect(state: &mut BgState, sample: f64) -> Duration { + state.note_connection_closed(); + first_reconnect_delay(state.last_close_code.take(), sample) } /// Classify a `RelayError` as a DNS resolution failure. @@ -3633,8 +3800,18 @@ async fn dns_flat_sleep( state: &mut BgState, duration: Duration, ) -> bool { - let jittered = jittered_duration(duration); - let deadline = tokio::time::Instant::now() + jittered; + shutdown_aware_sleep(cmd_rx, state, jittered_duration(duration)).await +} + +/// Shutdown-aware sleep for exactly `duration`. Non-Shutdown commands received +/// meanwhile are applied to state without resetting the deadline. Returns +/// `false` if the task should shut down. +async fn shutdown_aware_sleep( + cmd_rx: &mut mpsc::Receiver, + state: &mut BgState, + duration: Duration, +) -> bool { + let deadline = tokio::time::Instant::now() + duration; let sleep = tokio::time::sleep_until(deadline); tokio::pin!(sleep); loop { @@ -3650,6 +3827,21 @@ async fn dns_flat_sleep( } } +/// Reconnect entry shared by `try_autonomous_reconnect` and +/// `wait_for_reconnect`: runs [`begin_reconnect`] with the real RNG, +/// then waits out the first-attempt delay. Returns `false` on shutdown. +async fn prepare_reconnect(cmd_rx: &mut mpsc::Receiver, state: &mut BgState) -> bool { + let delay = begin_reconnect(state, random_unit_sample()); + if delay.is_zero() { + return true; + } + info!( + "relay closed the connection for restart — waiting {:.1}s before reconnecting", + delay.as_secs_f64() + ); + shutdown_aware_sleep(cmd_rx, state, delay).await +} + /// Extract a channel UUID from the h tag of a Nostr event. fn extract_h_tag_uuid(event: &nostr::Event) -> Option { event.tags.iter().find_map(|tag| { @@ -4055,6 +4247,9 @@ where Err(last_err.unwrap_or(RelayError::ConnectionClosed)) } +/// `User-Agent` sent on every relay WebSocket upgrade. +const RELAY_USER_AGENT: &str = concat!("buzz-acp/", env!("CARGO_PKG_VERSION")); + /// Perform a single WebSocket connect + NIP-42 auth handshake. /// /// Returns `(ws, buffer)` on success. @@ -4067,7 +4262,14 @@ async fn do_connect( .parse::() .map_err(|e| RelayError::Http(format!("invalid relay URL: {e}")))?; - let (ws, _response) = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(parsed.as_str())) + let mut request = parsed + .as_str() + .into_client_request() + .map_err(|e| RelayError::WebSocket(Box::new(e)))?; + request + .headers_mut() + .insert(USER_AGENT, HeaderValue::from_static(RELAY_USER_AGENT)); + let (ws, _response) = tokio::time::timeout(CONNECT_TIMEOUT, connect_async(request)) .await .map_err(|_| RelayError::ConnectionClosed)? // timeout → treat as connection failure .map_err(|e| RelayError::WebSocket(Box::new(e)))?; @@ -4232,6 +4434,9 @@ mod recovery; #[cfg(test)] mod recovery_tests; +#[cfg(test)] +mod resume_tests; + #[cfg(test)] mod tests { use super::*; @@ -6366,6 +6571,34 @@ mod tests { /// WebSocket endpoint, and tungstenite returns `Error::Http` (non-101 /// response) or `Error::Url(UnsupportedUrlScheme)` depending on how far /// the handshake gets. Either way it must not be retried. + /// The upgrade `do_connect()` sends names buzz-acp and its version. + #[allow(clippy::result_large_err)] // tungstenite's handshake callback type + #[tokio::test] + async fn do_connect_sends_user_agent() { + use tokio_tungstenite::tungstenite::handshake::server::{Request, Response}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut received = None; + let _ws = tokio_tungstenite::accept_hdr_async( + stream, + |request: &Request, response: Response| { + received = request.headers().get(USER_AGENT).cloned(); + Ok(response) + }, + ) + .await + .unwrap(); + received + }); + // The server hangs up after the upgrade, so the AUTH handshake fails. + let _ = do_connect(&url, &nostr::Keys::generate(), None).await; + assert_eq!(server.await.unwrap().unwrap(), RELAY_USER_AGENT); + assert!(RELAY_USER_AGENT.starts_with("buzz-acp/")); + } + #[tokio::test] async fn do_connect_wrong_scheme_is_terminal() { let keys = nostr::Keys::generate(); diff --git a/crates/buzz-acp/src/relay/recovery.rs b/crates/buzz-acp/src/relay/recovery.rs index 62da119a4be..d04c83e166b 100644 --- a/crates/buzz-acp/src/relay/recovery.rs +++ b/crates/buzz-acp/src/relay/recovery.rs @@ -44,13 +44,8 @@ pub(super) async fn recover_one( } } } else { - let since = match (state.membership_dropped_since, state.membership_last_seen) { - (Some(d), Some(l)) => Some(d.min(l)), - (Some(d), None) => Some(d), - (None, Some(l)) => Some(l), - (None, None) => state.startup_watermark, - }; - if send_membership_subscribe(ws, agent_pubkey_hex, since).await { + let since = state.membership_since(); + if send_membership_subscribe(ws, state, agent_pubkey_hex, since).await { state.membership_dropped_since = None; } } diff --git a/crates/buzz-acp/src/relay/resume_tests.rs b/crates/buzz-acp/src/relay/resume_tests.rs new file mode 100644 index 00000000000..7ff47e904b2 --- /dev/null +++ b/crates/buzz-acp/src/relay/resume_tests.rs @@ -0,0 +1,884 @@ +//! Replay cursor (gap retention across a dropped socket) and reconnect +//! spreading. +//! +//! Pure decisions are table-tested; the wiring (EOSE handling, close-code +//! capture, the reconnect entry, REQ `since` on the wire) is driven through the +//! production functions the reconnect path actually calls. No relay service. +use super::tests::{next_test_frame, seed_test_subscription, test_channel_filter, test_ws_pair}; +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, CloseFrame}; + +#[test] +fn resume_since_table_over_input_combinations() { + // (name, base, last_seen, dropped, expected) + #[allow(clippy::type_complexity)] + let cases: &[(&str, Option, Option, Option, Option)] = &[ + ("nothing", Some(1000), None, None, Some(1000)), + ("no baseline", None, None, None, None), + ("events", Some(1000), Some(2000), None, Some(2000)), + ("gap only", Some(1000), None, Some(1500), Some(1500)), + ( + "gap before events", + Some(1000), + Some(2000), + Some(1500), + Some(1500), + ), + ( + "events before gap", + Some(1000), + Some(2000), + Some(2500), + Some(2000), + ), + ]; + for (name, base, last_seen, dropped, expected) in cases { + assert_eq!( + resume_since(*base, *last_seen, *dropped), + *expected, + "{name}" + ); + } +} + +#[test] +fn jitter_maps_sample_onto_symmetric_twenty_percent_band() { + let base = Duration::from_secs(100); + for (sample, expected_ms) in [ + (0.0, 80_000), + (0.25, 90_000), + (0.5, 100_000), + (0.75, 110_000), + (1.0, 120_000), + (-3.0, 80_000), + (7.0, 120_000), + (f64::NAN, 100_000), + ] { + assert_eq!( + jittered_duration_with(base, sample).as_millis(), + expected_ms, + "sample {sample}" + ); + } +} + +#[test] +fn production_jitter_spans_the_whole_band() { + let base = Duration::from_secs(100); + let draws: Vec<_> = (0..400).map(|_| jittered_duration(base)).collect(); + assert!(draws + .iter() + .all(|d| *d >= Duration::from_secs(80) && *d <= Duration::from_secs(120))); + // The old formula only produced 0.80x-0.89x. + assert!(draws.iter().any(|d| *d > Duration::from_secs(110))); + assert!(draws.iter().any(|d| *d < Duration::from_secs(90))); +} + +#[test] +fn first_reconnect_delay_table() { + let secs = Duration::from_secs; + let cases: &[(Option, f64, Duration)] = &[ + (Some(1012), 0.0, Duration::ZERO), + (Some(1012), 0.5, secs(5)), + (Some(1012), 1.0, secs(10)), + (Some(1012), 7.0, secs(10)), + (Some(1012), f64::NAN, secs(5)), + (Some(1001), 0.25, Duration::from_millis(2_500)), + // Other closes keep today's immediate first attempt. + (Some(1000), 0.5, Duration::ZERO), + (Some(1006), 0.5, Duration::ZERO), + (Some(1011), 0.5, Duration::ZERO), + (None, 0.5, Duration::ZERO), + ]; + for (code, sample, expected) in cases { + assert_eq!( + first_reconnect_delay(*code, *sample), + *expected, + "{code:?} sample {sample}" + ); + } +} + +#[tokio::test] +async fn close_frame_code_is_captured_by_the_message_handler() { + let (mut client, _server) = test_ws_pair().await; + let (event_tx, _event_rx) = mpsc::channel(1); + let (control_tx, _control_rx) = mpsc::channel(1); + let mut state = BgState::new(); + for (frame, expected) in [ + ( + Some(CloseFrame { + code: CloseCode::Restart, + reason: "".into(), + }), + Some(1012), + ), + ( + Some(CloseFrame { + code: CloseCode::Away, + reason: "".into(), + }), + Some(1001), + ), + (None, None), + ] { + let alive = handle_ws_message( + Message::Close(frame), + &mut client, + &event_tx, + &control_tx, + &mut state, + &Keys::generate(), + "ws://127.0.0.1:1", + "agent", + None, + ) + .await; + assert!(!alive, "a Close frame ends the connection"); + assert_eq!(state.last_close_code, expected); + } +} + +#[test] +fn begin_reconnect_consumes_the_close_code() { + let mut state = BgState::new(); + state.last_close_code = Some(1012); + assert_eq!(begin_reconnect(&mut state, 0.5), Duration::from_secs(5)); + // A later reconnect for an unrelated reason must not inherit the delay. + assert_eq!(begin_reconnect(&mut state, 0.5), Duration::ZERO); +} + +async fn deliver_eose(client: &mut WsStream, state: &mut BgState, sub_id: &str) { + let (event_tx, _event_rx) = mpsc::channel(1); + let (control_tx, _control_rx) = mpsc::channel(1); + let alive = handle_ws_message( + Message::Text(json!(["EOSE", sub_id]).to_string().into()), + client, + &event_tx, + &control_tx, + state, + &Keys::generate(), + "ws://127.0.0.1:1", + "agent", + None, + ) + .await; + assert!(alive); +} + +/// Wire `since` of a connected `SubscribeMembership` command for a membership +/// subscription with delivered progress at 4_000. +async fn subscribe_membership_wire_since(dropped: Option) -> u64 { + let (mut client, mut server) = test_ws_pair().await; + let mut state = BgState::new(); + state.startup_watermark = Some(1_000); + state.membership_last_seen = Some(4_000); + state.membership_dropped_since = dropped; + assert!( + execute_connected_command( + &mut client, + &mut state, + "agent", + RelayCommand::SubscribeMembership + ) + .await + ); + let req = next_test_frame(&mut server).await; + assert_eq!(req[1], MEMBERSHIP_NOTIF_SUB_ID); + req[2]["since"].as_u64().unwrap() +} + +#[tokio::test] +async fn subscribe_membership_command_uses_the_membership_cursor() { + // A recorded gap wins over delivered progress. + assert_eq!( + subscribe_membership_wire_since(Some(3_000)).await, + 3_000 - SINCE_SKEW_SECS + ); + assert_eq!( + subscribe_membership_wire_since(None).await, + 4_000 - SINCE_SKEW_SECS + ); +} + +#[tokio::test] +async fn removing_a_channel_clears_its_retired_loss() { + let (mut client, _server) = test_ws_pair().await; + let mut state = BgState::new(); + let channel = Uuid::new_v4(); + seed_test_subscription(&mut state, channel); + state.channel_dropped_since.insert(channel, 3_000); + let since = state.channel_since(&channel); + assert!( + send_subscribe( + &mut client, + &mut state, + channel, + "agent", + since, + &test_channel_filter() + ) + .await + ); + assert!(state + .retired_loss_this_conn + .contains_key(&channel_sub_id(channel))); + + apply_command_to_state( + &mut state, + RelayCommand::Unsubscribe { + channel_id: channel, + }, + ); + assert!(state.retired_loss_this_conn.is_empty()); + begin_reconnect(&mut state, 0.0); + assert!(state.channel_dropped_since.is_empty()); +} + +// -- Reconnect entry points, driven through the production functions -------- + +struct ReconnectHarness { + cmd_rx: mpsc::Receiver, + event_tx: mpsc::Sender>, + control_tx: mpsc::Sender, + keys: Keys, +} + +impl ReconnectHarness { + /// A harness whose command queue already holds `Shutdown`, so any wait + /// inside the reconnect path ends the call immediately. + async fn with_queued_shutdown() -> Self { + let (cmd_tx, cmd_rx) = mpsc::channel(4); + let (event_tx, _) = mpsc::channel(1); + let (control_tx, _) = mpsc::channel(1); + cmd_tx.send(RelayCommand::Shutdown).await.unwrap(); + Self { + cmd_rx, + event_tx, + control_tx, + keys: Keys::generate(), + } + } + + async fn autonomous(&mut self, ws: &mut WsStream, state: &mut BgState, url: &str) { + let outcome = try_autonomous_reconnect( + ws, + &mut self.cmd_rx, + state, + &self.keys, + url, + "agent", + &self.event_tx, + &self.control_tx, + None, + ) + .await; + assert!(matches!(outcome, ReconnectOutcome::Shutdown)); + } +} + +/// A relay URL nothing listens on: connects are refused immediately. +async fn refused_relay_url() -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + drop(listener); + format!("ws://{addr}") +} + +/// A TCP server that counts connections and hangs up immediately, so the +/// WebSocket handshake fails fast. +async fn counting_relay() -> (String, Arc, tokio::task::JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(AtomicUsize::new(0)); + let counter = accepted.clone(); + let task = tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + counter.fetch_add(1, Ordering::SeqCst); + drop(stream); + } + }); + (url, accepted, task) +} + +#[tokio::test] +async fn wait_for_reconnect_restores_a_retired_loss_too() { + let (mut dead, _dead_server) = test_ws_pair().await; + let mut state = BgState::new(); + let channel = Uuid::new_v4(); + seed_test_subscription(&mut state, channel); + state + .retired_loss_this_conn + .insert(channel_sub_id(channel), 3_000); + + let url = refused_relay_url().await; + let mut harness = ReconnectHarness::with_queued_shutdown().await; + let outcome = wait_for_reconnect( + &mut dead, + &mut harness.cmd_rx, + &mut state, + &harness.keys, + &url, + "agent", + &harness.event_tx, + &harness.control_tx, + true, + None, + ) + .await; + assert!(matches!(outcome, ReconnectOutcome::Shutdown)); + assert_eq!(state.channel_dropped_since.get(&channel), Some(&3_000)); +} + +#[tokio::test] +async fn restart_closes_delay_the_first_attempt_and_other_closes_do_not() { + for (close_code, expected_attempts) in [ + (Some(1012), 0), + (Some(1001), 0), + (Some(1000), 1), + (Some(1006), 1), + (None, 1), + ] { + let (mut dead, _server) = test_ws_pair().await; + let (url, accepted, relay) = counting_relay().await; + let mut state = BgState::new(); + state.last_close_code = close_code; + ReconnectHarness::with_queued_shutdown() + .await + .autonomous(&mut dead, &mut state, &url) + .await; + assert_eq!( + accepted.load(Ordering::SeqCst), + expected_attempts, + "close code {close_code:?}" + ); + relay.abort(); + } +} + +// -- Superseded-REQ EOSE ------------------------------------------------------ + +#[tokio::test] +async fn second_req_on_a_connection_supersedes_the_first_for_eose() { + let (mut client, _server) = test_ws_pair().await; + let mut state = BgState::new(); + let channel = Uuid::new_v4(); + seed_test_subscription(&mut state, channel); + let sub = channel_sub_id(channel); + for expect_released in [true, false] { + state.channel_dropped_since.insert(channel, 3_000); + let since = state.channel_since(&channel); + assert!( + send_subscribe( + &mut client, + &mut state, + channel, + "agent", + since, + &test_channel_filter() + ) + .await + ); + state.channel_dropped_since.remove(&channel); + deliver_eose(&mut client, &mut state, &sub).await; + assert_eq!( + !state.retired_loss_this_conn.contains_key(&sub), + expect_released + ); + } + // A new connection starts clean: its first REQ counts again. + begin_reconnect(&mut state, 0.0); + assert!(state.req_sent_this_conn.is_empty() && state.superseded_this_conn.is_empty()); +} + +fn tagged_event(channel: Uuid, created_at: u64) -> Event { + EventBuilder::new(Kind::Custom(9), format!("e{created_at}")) + .tags([Tag::parse(["h", &channel.to_string()]).unwrap()]) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(&Keys::generate()) + .unwrap() +} + +async fn deliver_event( + client: &mut WsStream, + state: &mut BgState, + tx: &mpsc::Sender>, + sub_id: &str, + event: &Event, +) { + let (control_tx, _control_rx) = mpsc::channel(1); + let alive = handle_ws_message( + Message::Text(json!(["EVENT", sub_id, event]).to_string().into()), + client, + tx, + &control_tx, + state, + &Keys::generate(), + "ws://127.0.0.1:1", + "agent", + None, + ) + .await; + assert!(alive); +} + +/// Drop the live socket the way the production loop does: through the real +/// autonomous reconnect entry (queued Shutdown, unreachable relay). +async fn lose_connection(state: &mut BgState) { + let (mut dead, _dead_server) = test_ws_pair().await; + let url = refused_relay_url().await; + ReconnectHarness::with_queued_shutdown() + .await + .autonomous(&mut dead, state, &url) + .await; +} + +/// Replay `state` on a fresh socket and return the `since` of the first REQ. +async fn first_replay_req(state: &mut BgState, expected_sub: &str) -> u64 { + let (mut client, mut server) = test_ws_pair().await; + let (_cmd_tx, mut cmd_rx) = mpsc::channel(1); + let result = resubscribe_after_reconnect(&mut client, &mut cmd_rx, state, "agent", true).await; + assert!(matches!(result, ResubscribeResult::Ok)); + let req = next_test_frame(&mut server).await; + assert_eq!(req[1], expected_sub); + req[2]["since"].as_u64().unwrap() +} + +#[tokio::test] +async fn delayed_eose_of_a_superseded_req_keeps_the_channel_overflow_floor() { + let (mut client, mut server) = test_ws_pair().await; + let mut state = BgState::new(); + let channel = Uuid::new_v4(); + seed_test_subscription(&mut state, channel); // base 1_000 + let sub = channel_sub_id(channel); + let (tx, mut rx) = mpsc::channel(2); + + // REQ #1 is on the wire; its EOSE is still in flight. + let since = state.channel_since(&channel); + assert!( + send_subscribe( + &mut client, + &mut state, + channel, + "agent", + since, + &test_channel_filter() + ) + .await + ); + assert_eq!(next_test_frame(&mut server).await[0], "REQ"); + + // History arrives faster than the consumer drains it: the third event + // overflows the queue and is recorded as lost. + for ts in [1_010, 1_020, 1_100] { + deliver_event( + &mut client, + &mut state, + &tx, + &sub, + &tagged_event(channel, ts), + ) + .await; + } + assert_eq!(state.channel_dropped_since[&channel], 1_100); + while rx.try_recv().is_ok() {} + // A newer event is delivered after the loss, so `last_seen` passes it. + deliver_event( + &mut client, + &mut state, + &tx, + &sub, + &tagged_event(channel, 1_200), + ) + .await; + assert_eq!(state.last_seen[&channel], 1_200); + while rx.try_recv().is_ok() {} + + // Overflow recovery writes REQ #2 and retires the loss floor on the write. + recovery::recover_one(&mut client, &mut state, &tx, "agent").await; + assert_eq!(next_test_frame(&mut server).await[0], "REQ"); + assert!(!state.channel_dropped_since.contains_key(&channel)); + + // The in-flight EOSE of REQ #1 lands, then the socket drops before REQ #2 + // has replayed the lost event. + deliver_eose(&mut client, &mut state, &sub).await; + lose_connection(&mut state).await; + + let since = first_replay_req(&mut state, &sub).await; + assert!( + since <= 1_100, + "replay must still cover the dropped event at 1100, got since={since}" + ); +} + +#[tokio::test] +async fn delayed_eose_of_a_superseded_req_keeps_the_membership_overflow_floor() { + let (mut client, mut server) = test_ws_pair().await; + let mut state = BgState::new(); + let channel = Uuid::new_v4(); + state.membership_sub_active = true; + state.startup_watermark = Some(1_000); + state.membership_last_seen = Some(1_000); + let (tx, mut rx) = mpsc::channel(2); + + let since = state.membership_since(); + assert!(send_membership_subscribe(&mut client, &mut state, "agent", since).await); + assert_eq!(next_test_frame(&mut server).await[0], "REQ"); + + for ts in [1_010, 1_020, 1_100] { + deliver_event( + &mut client, + &mut state, + &tx, + MEMBERSHIP_NOTIF_SUB_ID, + &tagged_event(channel, ts), + ) + .await; + } + assert_eq!(state.membership_dropped_since, Some(1_100)); + while rx.try_recv().is_ok() {} + deliver_event( + &mut client, + &mut state, + &tx, + MEMBERSHIP_NOTIF_SUB_ID, + &tagged_event(channel, 1_200), + ) + .await; + assert_eq!(state.membership_last_seen, Some(1_200)); + while rx.try_recv().is_ok() {} + + recovery::recover_one(&mut client, &mut state, &tx, "agent").await; + assert_eq!(next_test_frame(&mut server).await[0], "REQ"); + assert_eq!(state.membership_dropped_since, None); + + deliver_eose(&mut client, &mut state, MEMBERSHIP_NOTIF_SUB_ID).await; + lose_connection(&mut state).await; + + let since = first_replay_req(&mut state, MEMBERSHIP_NOTIF_SUB_ID).await; + assert!( + since <= 1_100, + "replay must still cover the dropped notification at 1100, got since={since}" + ); +} +// -- A gap replay that never reached EOSE keeps its floor ------------------- + +/// Reconnect, write the replay REQs, optionally deliver `newer` on that socket +/// (a partial replay), and drop the socket before any EOSE. +async fn replay_then_lose_before_eose( + state: &mut BgState, + sub: &str, + newer: Option<&Event>, +) -> u64 { + let (mut client, mut server) = test_ws_pair().await; + let (_cmd_tx, mut cmd_rx) = mpsc::channel(1); + let result = resubscribe_after_reconnect(&mut client, &mut cmd_rx, state, "agent", true).await; + assert!(matches!(result, ResubscribeResult::Ok)); + let req = next_test_frame(&mut server).await; + assert_eq!(req[1], sub); + if let Some(event) = newer { + let (tx, _rx) = mpsc::channel(8); + deliver_event(&mut client, state, &tx, sub, event).await; + } + lose_connection(state).await; + req[2]["since"].as_u64().unwrap() +} + +/// How a newer delivered event (`last_seen` past the loss) is mixed into +/// [`unfinished_gap_replay_keeps_its_floor`]. +#[derive(Clone, Copy)] +enum NewerEvent { + None, + /// Delivered before the loss is replayed: `last_seen` is already ahead. + BeforeReplay, + /// Delivered on the replay socket before it drops: a partial replay. + DuringReplay, +} + +/// The review's schedule: a subscription loses an event to backpressure, the +/// reconnect replay REQ correctly goes out below it (retiring the loss record), +/// and that socket drops before the replay's EOSE. A newer `last_seen` may not +/// skip the lost event on the next replay. Once a replay does reach EOSE, the +/// cursor moves past the gap again. +async fn unfinished_gap_replay_keeps_its_floor( + state: &mut BgState, + sub: &str, + channel: Uuid, + newer: NewerEvent, + record_loss: impl FnOnce(&mut BgState), + loss_recorded: impl Fn(&BgState) -> bool, +) { + const LOST: u64 = 3_000; + let newer_event = tagged_event(channel, 4_000); + let (mut live, _live_server) = test_ws_pair().await; + record_loss(state); + if matches!(newer, NewerEvent::BeforeReplay) { + let (tx, _rx) = mpsc::channel(8); + deliver_event(&mut live, state, &tx, sub, &newer_event).await; + } + lose_connection(state).await; + + let during = matches!(newer, NewerEvent::DuringReplay).then_some(&newer_event); + let first = replay_then_lose_before_eose(state, sub, during).await; + assert!(first <= LOST, "first replay since={first}"); + + for attempt in 0..2 { + let since = replay_then_lose_before_eose(state, sub, during).await; + assert!( + since <= LOST, + "replay {attempt} after an unfinished gap replay must still cover {LOST}, got since={since}" + ); + } + + // This time the replay reaches EOSE before the socket drops. + let (mut client, mut server) = test_ws_pair().await; + let (_cmd_tx, mut cmd_rx) = mpsc::channel(1); + let result = resubscribe_after_reconnect(&mut client, &mut cmd_rx, state, "agent", true).await; + assert!(matches!(result, ResubscribeResult::Ok)); + assert_eq!(next_test_frame(&mut server).await[1], sub); + assert!( + !loss_recorded(state), + "writing the replay retires the loss record" + ); + deliver_eose(&mut client, state, sub).await; + lose_connection(state).await; + assert!(!loss_recorded(state), "a finished replay is not restored"); + let since = first_replay_req(state, sub).await; + let progress = match newer { + NewerEvent::None => 1_000, + NewerEvent::BeforeReplay | NewerEvent::DuringReplay => 4_000, + }; + assert_eq!( + since, + progress - SINCE_SKEW_SECS, + "a completed replay must not keep the old floor" + ); +} + +const NEWER_EVENT_CASES: [NewerEvent; 3] = [ + NewerEvent::None, + NewerEvent::BeforeReplay, + NewerEvent::DuringReplay, +]; + +#[tokio::test] +async fn unfinished_channel_gap_replay_keeps_its_floor() { + for newer in NEWER_EVENT_CASES { + let mut state = BgState::new(); + let channel = Uuid::new_v4(); + seed_test_subscription(&mut state, channel); // base 1_000 + unfinished_gap_replay_keeps_its_floor( + &mut state, + &channel_sub_id(channel), + channel, + newer, + |state| { + state.channel_dropped_since.insert(channel, 3_000); + }, + |state| state.channel_dropped_since.contains_key(&channel), + ) + .await; + } +} + +#[tokio::test] +async fn unfinished_membership_gap_replay_keeps_its_floor() { + for newer in NEWER_EVENT_CASES { + let mut state = BgState::new(); + state.membership_sub_active = true; + state.startup_watermark = Some(1_000); + state.membership_last_seen = Some(1_000); + unfinished_gap_replay_keeps_its_floor( + &mut state, + MEMBERSHIP_NOTIF_SUB_ID, + Uuid::new_v4(), + newer, + |state| state.membership_dropped_since = Some(3_000), + |state| state.membership_dropped_since.is_some(), + ) + .await; + } +} +/// Write the reconnect replay on a fresh socket, leaving the connection open, +/// and return the socket pair with the first REQ's `since`. +async fn open_replay( + state: &mut BgState, + sub: &str, +) -> (WsStream, WebSocketStream, u64) { + let (mut client, mut server) = test_ws_pair().await; + let (_cmd_tx, mut cmd_rx) = mpsc::channel(1); + let result = resubscribe_after_reconnect(&mut client, &mut cmd_rx, state, "agent", true).await; + assert!(matches!(result, ResubscribeResult::Ok)); + let req = next_test_frame(&mut server).await; + assert_eq!(req[1], sub); + let since = req[2]["since"].as_u64().unwrap(); + (client, server, since) +} + +/// The loss record a gap-retention test drives: a channel's or the membership +/// subscription's. +#[derive(Clone, Copy)] +enum LossArm { + Channel(Uuid), + Membership, +} + +impl LossArm { + fn both() -> [Self; 2] { + [Self::Channel(Uuid::new_v4()), Self::Membership] + } + + fn sub(self) -> String { + match self { + Self::Channel(channel) => channel_sub_id(channel), + Self::Membership => MEMBERSHIP_NOTIF_SUB_ID.to_owned(), + } + } + + fn event(self, created_at: u64) -> Event { + match self { + Self::Channel(channel) => tagged_event(channel, created_at), + Self::Membership => tagged_event(Uuid::nil(), created_at), + } + } + + fn dropped(self, state: &BgState) -> Option { + match self { + Self::Channel(channel) => state.channel_dropped_since.get(&channel).copied(), + Self::Membership => state.membership_dropped_since, + } + } + + /// Delivered progress at 4_000 past a recorded loss at `lost`, the socket + /// already closed. + async fn progress_past_a_loss(self, lost: u64) -> BgState { + let mut state = BgState::new(); + match self { + Self::Channel(channel) => { + seed_test_subscription(&mut state, channel); // base 1_000 + state.last_seen.insert(channel, 4_000); + state.channel_dropped_since.insert(channel, lost); + } + Self::Membership => { + state.membership_sub_active = true; + state.startup_watermark = Some(1_000); + state.membership_last_seen = Some(4_000); + state.membership_dropped_since = Some(lost); + } + } + lose_connection(&mut state).await; + state + } + + /// Deliver `overflow` on `client` into `tx`, a consumer with room for two + /// events: the last one is dropped and recorded as a loss. + async fn overflow( + self, + client: &mut WsStream, + state: &mut BgState, + tx: &mpsc::Sender>, + overflow: [u64; 3], + ) { + for ts in overflow { + deliver_event(client, state, tx, &self.sub(), &self.event(ts)).await; + } + assert_eq!(self.dropped(state), Some(overflow[2])); + } +} + +/// A socket that dies partway through a resubscribe (`RetryConnection`) is +/// redialed by the reconnect loop without going back through the reconnect +/// entry. The next resubscribe must still restore the loss record the dead +/// socket's REQ retired, and that socket's first REQ must count its EOSE. +#[tokio::test] +async fn redial_after_a_failed_resubscribe_keeps_the_floor() { + const LOST: u64 = 3_000; + let arm = LossArm::Channel(Uuid::new_v4()); + let mut state = arm.progress_past_a_loss(LOST).await; + let sub = arm.sub(); + + let (_dead, _dead_server, first) = open_replay(&mut state, &sub).await; + assert!(first <= LOST, "first replay since={first}"); + assert_eq!(arm.dropped(&state), None); + + // That socket dies before EOSE and the loop redials straight into another + // resubscribe. + let (mut client, _server, second) = open_replay(&mut state, &sub).await; + assert!( + second <= LOST, + "redial after a failed resubscribe must still cover {LOST}, got since={second}" + ); + deliver_eose(&mut client, &mut state, &sub).await; + assert!( + !state.retired_loss_this_conn.contains_key(&sub), + "the redialed socket's REQ is not superseded by the dead socket's" + ); +} + +/// A new loss recorded while an unfinished replay is in flight merges with +/// the restored floor by `min`, and closing the same outage again changes +/// nothing. +#[tokio::test] +async fn loss_during_an_unfinished_replay_merges_with_the_restored_floor() { + const LOST: u64 = 3_000; + for arm in LossArm::both() { + for (overflow, expected) in [ + ([3_400, 3_450, 3_500], LOST), + ([2_400, 2_450, 2_500], 2_500), + ] { + let mut state = arm.progress_past_a_loss(LOST).await; + let sub = arm.sub(); + let (mut client, _server, since) = open_replay(&mut state, &sub).await; + assert!(since <= LOST); + let (tx, _rx) = mpsc::channel(2); + arm.overflow(&mut client, &mut state, &tx, overflow).await; + + lose_connection(&mut state).await; + assert_eq!(arm.dropped(&state), Some(expected)); + + // A repeated close for the same outage is a no-op. + begin_reconnect(&mut state, 0.0); + assert_eq!(arm.dropped(&state), Some(expected)); + + let since = first_replay_req(&mut state, &sub).await; + assert!( + since <= expected, + "replay must cover the earliest loss {expected}, got since={since}" + ); + } + } +} + +/// History replays newest first, so a loss recorded during the reconnect +/// replay can be older than the loss that replay retired. Overflow recovery's +/// second REQ on the same socket retires it too; if the socket drops before +/// EOSE, the older of the two retired losses is restored. +#[tokio::test] +async fn a_second_replay_on_one_socket_restores_the_older_retired_loss() { + const LOST: u64 = 3_000; + const OLDER: u64 = 2_500; + for arm in LossArm::both() { + let mut state = arm.progress_past_a_loss(LOST).await; + let sub = arm.sub(); + let (mut client, mut server, since) = open_replay(&mut state, &sub).await; + assert!(since <= LOST); + let (tx, mut rx) = mpsc::channel(2); + arm.overflow(&mut client, &mut state, &tx, [2_400, 2_450, OLDER]) + .await; + while rx.try_recv().is_ok() {} + + // Overflow recovery writes REQ #2 and retires the older loss on the write. + recovery::recover_one(&mut client, &mut state, &tx, "agent").await; + assert_eq!(next_test_frame(&mut server).await[1], sub.as_str()); + assert_eq!(arm.dropped(&state), None); + + lose_connection(&mut state).await; + assert_eq!(arm.dropped(&state), Some(OLDER)); + assert_eq!( + first_replay_req(&mut state, &sub).await, + OLDER - SINCE_SKEW_SECS + ); + } +} diff --git a/crates/buzz-acp/tests/run_task.rs b/crates/buzz-acp/tests/run_task.rs index fbea25692a1..c90227c78d7 100644 --- a/crates/buzz-acp/tests/run_task.rs +++ b/crates/buzz-acp/tests/run_task.rs @@ -3,7 +3,8 @@ use serde_json::{json, Value}; use std::{ fs, - io::Write, + io::{ErrorKind, Write}, + os::unix::{io::OwnedFd, net::UnixStream}, path::PathBuf, process::{Child, Command, Output, Stdio}, time::{Duration, Instant}, @@ -97,7 +98,8 @@ fn terminal(output: &Output, code: i32, status: &str) -> Value { assert_eq!( output.status.code(), Some(code), - "stderr={} stdout={}", + "exit={:?} stderr={} stdout={}", + output.status, String::from_utf8_lossy(&output.stderr), String::from_utf8_lossy(&output.stdout) ); @@ -419,6 +421,32 @@ fn deadline_covers_initialize_session_and_turn_and_cleans_descendants() { } } +fn backpressured_stdin() -> (UnixStream, UnixStream) { + let (reader, mut writer) = UnixStream::pair().unwrap(); + writer.set_nonblocking(true).unwrap(); + // Fill before spawning: the next write cannot finish until the runner reads + // stdin, which happens after signal registration. Keep below the task limit + // and leave the writer open so read_to_end still awaits EOF when cancelled. + let mut queued = 0; + loop { + match writer.write(b" ") { + Ok(0) => panic!("stdin fixture stopped accepting bytes"), + Ok(n) => { + queued += n; + assert!(queued < 1024 * 1024 - 1, "stdin fixture exceeds task limit"); + } + Err(error) if error.kind() == ErrorKind::Interrupted => continue, + Err(error) if error.kind() == ErrorKind::WouldBlock => break, + Err(error) => panic!("cannot fill stdin fixture: {error}"), + } + } + writer.set_nonblocking(false).unwrap(); + writer + .set_write_timeout(Some(Duration::from_secs(3))) + .unwrap(); + (reader, writer) +} + #[test] fn signals_cancel_startup_turn_and_pending_stdin_without_hanging() { use nix::{ @@ -435,9 +463,20 @@ fn signals_cancel_startup_turn_and_pending_stdin_without_hanging() { command .env("TASK_AGENT_MODE", mode) .args(["--no-memory", "--task", "-"]); + let mut held_stdin = if mode == "stdin" { + let (reader, writer) = backpressured_stdin(); + command.stdin(Stdio::from(OwnedFd::from(reader))); + Some(writer) + } else { + None + }; let mut child = command.spawn().unwrap(); - let held_stdin = if mode == "stdin" { - child.stdin.take() + if let Some(writer) = held_stdin.as_mut() { + if let Err(error) = writer.write_all(b" ") { + let status = child.try_wait(); + let _ = child.kill(); + panic!("{mode} never drained pending input: {error}; status={status:?}"); + } } else { child .stdin @@ -445,24 +484,34 @@ fn signals_cancel_startup_turn_and_pending_stdin_without_hanging() { .unwrap() .write_all(f.task().to_string().as_bytes()) .unwrap(); - None - }; - let until = Instant::now() + Duration::from_secs(3); - if mode == "stdin" { - std::thread::sleep(Duration::from_millis(250)); - } else { + let until = Instant::now() + Duration::from_secs(3); let method = if mode == "turn-hang" { "session/prompt" } else { "initialize" }; while !f.wire().iter().any(|v| v["method"] == method) { - assert!(Instant::now() < until); + if Instant::now() >= until { + let status = child.try_wait(); + let _ = child.kill(); + panic!("{mode} never reached {method}: status={status:?}"); + } std::thread::sleep(Duration::from_millis(10)); } } + eprintln!( + "cancelling case={mode} signal={signal:?} pid={}", + child.id() + ); kill(Pid::from_raw(child.id() as i32), signal).unwrap(); - terminal(&wait(child), code, "cancelled"); + let result = terminal(&wait(child), code, "cancelled"); + if mode == "stdin" { + assert!(result["taskId"].is_null()); + assert!( + f.wire().is_empty(), + "incomplete input must not start an agent" + ); + } drop(held_stdin); for frame in f.wire() { if let Some(pid) = frame["pid"].as_u64() { diff --git a/crates/buzz-admin/Cargo.toml b/crates/buzz-admin/Cargo.toml index d8d075a8b26..4d38d25582b 100644 --- a/crates/buzz-admin/Cargo.toml +++ b/crates/buzz-admin/Cargo.toml @@ -27,7 +27,9 @@ serde_json = { workspace = true } serde = { workspace = true } anyhow = { workspace = true } hex = { workspace = true } -deadpool-redis = { workspace = true } +base64 = { workspace = true } +reqwest = { workspace = true } +sha2 = { workspace = true } # Redis TLS (rediss://, e.g. ElastiCache) uses rustls, which needs a process # CryptoProvider installed at startup. The workspace redis TLS feature compiles # both aws-lc-rs and ring in transitively, so rustls can't auto-select one — we @@ -40,4 +42,6 @@ uuid = { workspace = true } clap = { version = "4", features = ["derive"] } [dev-dependencies] +axum = { workspace = true } +tempfile = "3" tokio = { workspace = true, features = ["test-util"] } diff --git a/crates/buzz-admin/src/communities.rs b/crates/buzz-admin/src/communities.rs index f8bcd7c015b..fe1fa3559ae 100644 --- a/crates/buzz-admin/src/communities.rs +++ b/crates/buzz-admin/src/communities.rs @@ -1,7 +1,7 @@ //! Reversible whole-community lifecycle commands. use anyhow::{Context, Result}; -use buzz_core::tenant::{normalize_host, relay_url_authority, TenantContext}; +use buzz_core::tenant::{normalize_host, relay_url_authority, TenantContext, MAX_HOST_LEN}; use buzz_db::{ArchivedCommunityRecord, UnarchivedCommunityRecord}; use buzz_pubsub::conn_control::ConnControl; use buzz_pubsub::PubSubManager; @@ -9,8 +9,6 @@ use clap::Subcommand; use serde_json::{json, Value}; use url::{Host, Url}; -const MAX_HOST_LEN: usize = 255; - /// Reversible community lifecycle actions. #[derive(Debug, Subcommand)] pub enum CommunitiesCommand { @@ -154,9 +152,8 @@ async fn unarchive( async fn publish_disconnect(tenant: &TenantContext, command: &ConnControl) -> Result { let redis_url = std::env::var("REDIS_URL").context("REDIS_URL is required")?; - let redis_pool = deadpool_redis::Config::from_url(&redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .context("Redis pool creation failed")?; + let redis_pool = + buzz_pubsub::redis_connection(&redis_url).context("Redis connection setup failed")?; let pubsub = PubSubManager::new(&redis_url, redis_pool) .await .context("PubSub init failed")?; diff --git a/crates/buzz-admin/src/main.rs b/crates/buzz-admin/src/main.rs index 13e7f6df82e..86551425fa0 100644 --- a/crates/buzz-admin/src/main.rs +++ b/crates/buzz-admin/src/main.rs @@ -22,6 +22,7 @@ mod communities; mod deletions; mod nip_fi; +mod nip_fi_policy; mod user_deletions; use std::future::Future; @@ -56,7 +57,9 @@ enum Command { /// /// Accepts a bech32 npub or 64-char hex pubkey. After inserting the DB row, /// publishes a kind:13534 membership roster via Redis so live clients see - /// the updated list immediately. + /// the updated list immediately. Does not join the member to the + /// community's default (`auto_join`) channels: the relay does that on an + /// invite claim or a kind:9030 add, which this command bypasses. AddMember { /// Nostr public key — bech32 npub or 64-char hex. #[arg(long)] @@ -122,6 +125,8 @@ enum Command { #[command(subcommand)] command: nip_fi::NipFiCommand, }, + /// Change or inspect a community stored NIP-FI requirement. + NipFiPolicy(nip_fi_policy::Args), /// Durable CLI-only whole-community deletion control plane. Deletions { #[command(subcommand)] @@ -211,6 +216,11 @@ async fn run(cli: Cli) -> Result { Command::Deletions { command } => deletions::run(command).await, Command::UserDeletions { command } => user_deletions::run(command).await, Command::NipFi { command } => nip_fi::run(command).await, + // Retain transport/file causes for this operator command without changing + // the diagnostics of other admin commands. Key parse errors are redacted. + Command::NipFiPolicy(args) => nip_fi_policy::run(args) + .await + .map_err(|e| anyhow::anyhow!("{e:#}")), Command::ReconcileChannels { channel, relay_key } => { reconcile_channels(channel, relay_key).await?; Ok(0) @@ -661,11 +671,8 @@ async fn connect_member_services() -> Result<(Db, Arc, Keys)> { let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://localhost:6379".to_string()); - let redis_pool = { - let cfg = deadpool_redis::Config::from_url(&redis_url); - cfg.create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .map_err(|e| anyhow::anyhow!("Redis pool creation failed: {e}"))? - }; + let redis_pool = buzz_pubsub::redis_connection(&redis_url) + .map_err(|e| anyhow::anyhow!("Redis connection setup failed: {e}"))?; let pubsub = Arc::new( PubSubManager::new(&redis_url, redis_pool) diff --git a/crates/buzz-admin/src/nip_fi.rs b/crates/buzz-admin/src/nip_fi.rs index 0fd62977bd0..dd9a4867eca 100644 --- a/crates/buzz-admin/src/nip_fi.rs +++ b/crates/buzz-admin/src/nip_fi.rs @@ -188,6 +188,10 @@ async fn unbind( { NipFiUnbind::Removed => true, NipFiUnbind::NotBound => false, + NipFiUnbind::RequiredIssuer => anyhow::bail!( + "refusing to remove the last NIP-FI issuer: this community requires NIP-FI; \ + bind a replacement first, or archive or delete the community to stop it logging in" + ), NipFiUnbind::LastIssuer => anyhow::bail!( "refusing to remove the community's last NIP-FI issuer: backfill would rebind it; \ bind a replacement first, or archive or delete the community to stop it logging in" @@ -273,11 +277,18 @@ mod postgres_tests { const ISS: &str = "https://issuer.example/api/goose"; + /// The production writer pool, with the connection budget of the sqlx + /// pools the other PostgreSQL tests use. The relay's 3 s acquire timeout + /// and two eager spare connections are sized for a warm relay pod, not for + /// the first wave of a test lane, where every worker clones its database + /// at once and a first connection can take longer than 3 s. async fn db() -> Db { let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") .unwrap_or_else(|_| DbConfig::default().database_url); Db::new(&DbConfig { database_url, + min_connections: 0, + acquire_timeout_secs: 30, ..DbConfig::default() }) .await diff --git a/crates/buzz-admin/src/nip_fi_policy.rs b/crates/buzz-admin/src/nip_fi_policy.rs new file mode 100644 index 00000000000..6b7e18276bf --- /dev/null +++ b/crates/buzz-admin/src/nip_fi_policy.rs @@ -0,0 +1,666 @@ +//! General stored community policy management with immutable saved intent. +use std::{ + io::Read, + path::{Path, PathBuf}, + time::Duration, +}; + +use anyhow::{ensure, Context, Result}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use clap::{Args as ClapArgs, Subcommand}; +use nostr::{EventBuilder, JsonUtil, Keys, Kind, Tag}; +use reqwest::{redirect::Policy, Method}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use url::Url; +use uuid::Uuid; + +const PATH: &str = "/operator/communities/nip-fi-policy"; +const MAX_BYTES: usize = 64 * 1024; + +/// Explicit operator destination and signing key for community policy management. +#[derive(Debug, ClapArgs)] +pub struct Args { + #[arg(long)] + origin: String, + #[arg(long)] + key_file: PathBuf, + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Apply a saved requires_nip_fi=true intent, or recover its acceptance. + Enable { + #[arg(long)] + request: PathBuf, + }, + /// Apply a saved requires_nip_fi=false intent, or recover its acceptance. + Disable { + #[arg(long)] + request: PathBuf, + }, + /// Read current preconditions by community/host, or a historical operation. + Status { + #[arg(long, conflicts_with_all = ["community_id", "host"])] + operation_id: Option, + #[arg(long, requires = "host")] + community_id: Option, + #[arg(long, requires = "community_id")] + host: Option, + }, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Request { + operation_id: Uuid, + community_id: Uuid, + expected_host: String, + actor_pubkey: String, + expected_owner_pubkey: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + expected_issuer: Option, + requires_nip_fi: bool, + expected_policy_generation: i64, + expected_requires_nip_fi: bool, +} + +impl Request { + fn validate(&self, desired: bool) -> Result<()> { + ensure!( + self.requires_nip_fi == desired, + "saved requires_nip_fi does not match the command" + ); + ensure!( + self.expected_policy_generation >= 0, + "generation must be nonnegative" + ); + ensure!( + if desired { + self.expected_issuer.as_ref().is_some_and(|s| !s.is_empty()) + } else { + self.expected_issuer.is_none() + }, + "enable requires expected_issuer; disable must omit it" + ); + ensure!( + !self.operation_id.is_nil() && !self.community_id.is_nil(), + "UUIDs must not be nil" + ); + let host = crate::communities::normalize_host_authority(&self.expected_host) + .map_err(anyhow::Error::msg)?; + ensure!( + host == self.expected_host && !host.contains(':'), + "expected_host must be canonical lowercase without a port or trailing dot" + ); + for key in [&self.actor_pubkey, &self.expected_owner_pubkey] { + ensure!( + key.len() == 64 + && key + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)), + "owner public keys must be 64 lowercase hex characters" + ); + } + Ok(()) + } +} + +fn read_bounded(path: &Path, limit: usize) -> Result> { + let mut bytes = Vec::new(); + std::fs::File::open(path) + .with_context(|| format!("cannot open {}", path.display()))? + .take((limit + 1) as u64) + .read_to_end(&mut bytes) + .with_context(|| format!("cannot read {}", path.display()))?; + ensure!(bytes.len() <= limit, "input file exceeds size limit"); + Ok(bytes) +} + +fn endpoint(origin: &str) -> Result { + let base = Url::parse(origin).context("invalid operator origin")?; + ensure!( + matches!(base.scheme(), "http" | "https") + && base.host_str().is_some() + && base.username().is_empty() + && base.password().is_none() + && base.path() == "/" + && base.query().is_none() + && base.fragment().is_none(), + "operator origin must be an HTTP(S) origin without credentials, path, query or fragment" + ); + Ok(base.join(PATH)?) +} + +fn authorization(keys: &Keys, method: &Method, url: &Url, body: Option<&[u8]>) -> Result { + let mut tags = vec![ + Tag::parse(["u", url.as_str()])?, + Tag::parse(["method", method.as_str()])?, + Tag::parse(["nonce", &Uuid::new_v4().to_string()])?, + ]; + if let Some(body) = body { + tags.push(Tag::parse(["payload", &hex::encode(Sha256::digest(body))])?); + } + let event = EventBuilder::new(Kind::HttpAuth, "") + .tags(tags) + .sign_with_keys(keys)?; + Ok(format!("Nostr {}", STANDARD.encode(event.as_json()))) +} + +/// Bounded, signed single call shared by the operator policy commands. +async fn signed_call(keys: &Keys, url: Url, body: Option>) -> Result { + let method = if body.is_some() { + Method::POST + } else { + Method::GET + }; + let auth = authorization(keys, &method, &url, body.as_deref())?; + let client = reqwest::Client::builder() + .redirect(Policy::none()) + .retry(reqwest::retry::never()) + .timeout(Duration::from_secs(30)) + .build()?; + let mut call = client.request(method, url).header("Authorization", auth); + if let Some(body) = body { + call = call.header("Content-Type", "application/json").body(body); + } + let mut response = call + .send() + .await + .context("unconfirmed: request failed; recover the same operation_id")?; + let status = response.status(); + let mut bytes = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .context("unconfirmed: response interrupted; recover the same operation_id")? + { + ensure!( + bytes.len() + chunk.len() <= MAX_BYTES, + "unconfirmed: response exceeds size limit" + ); + bytes.extend_from_slice(&chunk); + } + if !status.is_success() { + // Preserve known machine-readable codes, without echoing arbitrary response bodies. + let error = serde_json::from_slice::(&bytes).ok(); + let code = error.as_ref().and_then(|value| value["code"].as_str()); + let detail = match code { + Some( + code @ ("invalid_request" + | "community_not_found" + | "operation_not_found" + | "idempotency_conflict" + | "policy_conflict" + | "policy_generation_exhausted" + | "host_conflict" + | "owner_conflict" + | "lifecycle_conflict" + | "issuer_conflict" + | "upgrades_disabled" + | "authorization_unavailable"), + ) => code, + _ if error.is_none() => "non-JSON error response", + _ => "unrecognized error code", + }; + anyhow::bail!("operator API returned HTTP {} ({detail}); on policy_conflict re-read policy and use a new UUID; after response loss recover the same saved request and UUID", status.as_u16()); + } + // Print only structured relay output, never transport headers or signing material. + let receipt: Value = serde_json::from_slice(&bytes).with_context(|| { + format!( + "unconfirmed: invalid JSON response (HTTP {})", + status.as_u16() + ) + })?; + Ok(receipt) +} + +fn receipt_exit_code( + value: &Value, + id: Uuid, + operator: &str, + request: Option<&Request>, +) -> Result { + let receipt = &value["receipt"]; + ensure!( + receipt["operation_id"].as_str() == Some(id.to_string().as_str()) + && receipt["operator_pubkey"].as_str() == Some(operator) + && receipt["policy_generation"].as_i64().is_some_and(|g| g > 0) + && receipt["requires_nip_fi"].is_boolean(), + "unconfirmed: invalid policy receipt" + ); + if let Some(request) = request { + let expected = serde_json::to_value(request)?; + ensure!( + expected + .as_object() + .context("invalid saved request")? + .iter() + .all(|(key, v)| receipt[key] == *v), + "unconfirmed: receipt differs from saved intent" + ); + } + match ( + receipt["state"].as_str(), + receipt["requires_nip_fi"].as_bool(), + ) { + (Some("applied"), Some(false)) => Ok(0), + (Some("pending"), Some(true)) => Ok(10), + (Some("superseded"), _) => Ok(11), + (Some("unavailable"), _) => Ok(12), + _ => anyhow::bail!("unconfirmed: invalid policy state"), + } +} + +/// Execute one signed policy call; never change or automatically retry saved intent. +pub async fn run(args: Args) -> Result { + let request = match &args.command { + Command::Enable { request } | Command::Disable { request } => { + let saved: Request = serde_json::from_slice(&read_bounded(request, 64 * 1024)?)?; + saved.validate(matches!(args.command, Command::Enable { .. }))?; + Some(saved) + } + Command::Status { .. } => None, + }; + let mut url = endpoint(&args.origin)?; + if let Command::Status { + operation_id, + community_id, + host, + } = &args.command + { + match (operation_id, community_id, host) { + (Some(id), None, None) if !id.is_nil() => { + url.query_pairs_mut() + .append_pair("operation_id", &id.to_string()); + } + (None, Some(id), Some(host)) if !id.is_nil() => { + let canonical = crate::communities::normalize_host_authority(host) + .map_err(anyhow::Error::msg)?; + ensure!( + canonical == *host && !host.contains(':'), + "host must be canonical lowercase without a port" + ); + url.query_pairs_mut() + .append_pair("community_id", &id.to_string()) + .append_pair("expected_host", host); + } + _ => anyhow::bail!("status requires operation-id or community-id and host"), + } + } + // Validate the entire saved intent, including action, before touching the key. + let secret = read_bounded(&args.key_file, 1024)?; + let keys = std::str::from_utf8(&secret) + .ok() + .and_then(|s| Keys::parse(s.trim()).ok()) + .context("invalid operator key file")?; + let value = signed_call( + &keys, + url, + request.as_ref().map(serde_json::to_vec).transpose()?, + ) + .await?; + let code = if let Some(saved) = request.as_ref() { + receipt_exit_code( + &value, + saved.operation_id, + &keys.public_key().to_hex(), + Some(saved), + )? + } else if let Command::Status { + operation_id: Some(id), + .. + } = args.command + { + receipt_exit_code(&value, id, &keys.public_key().to_hex(), None)? + } else { + if let Command::Status { + community_id: Some(id), + host: Some(host), + .. + } = &args.command + { + ensure!( + value["community_id"].as_str() == Some(id.to_string().as_str()) + && value["expected_host"].as_str() == Some(host.as_str()) + && value["expected_policy_generation"] + .as_i64() + .is_some_and(|g| g >= 0) + && value["expected_requires_nip_fi"].is_boolean(), + "unconfirmed: invalid current policy" + ); + } + 0 + }; + let stored = value + .get("receipt") + .map_or(&value["expected_requires_nip_fi"], |r| { + &r["current_requires_nip_fi"] + }); + if stored.is_boolean() + && value["effective_required"].is_boolean() + && *stored != value["effective_required"] + { + eprintln!("Global mode makes effective_required differ from the stored requirement; inspect mode in the response."); + } + println!("{}", serde_json::to_string(&value)?); + Ok(code) +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::{routing::any, Json, Router}; + + fn saved(desired: bool) -> Request { + Request { + operation_id: Uuid::new_v4(), + community_id: Uuid::new_v4(), + expected_host: "team.communities.example.org".into(), + actor_pubkey: "a".repeat(64), + expected_owner_pubkey: "a".repeat(64), + expected_issuer: desired.then(|| "https://issuer.example.org".into()), + requires_nip_fi: desired, + expected_policy_generation: 0, + expected_requires_nip_fi: false, + } + } + + #[tokio::test] + async fn immutable_action_and_preconditions_are_checked_before_key_read() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("request.json"); + for (mut request, change, expected) in [ + (saved(true), 0, "does not match"), + (saved(false), 1, "generation"), + (saved(false), 2, "omit"), + (saved(false), 3, "canonical"), + ] { + match change { + 1 => request.expected_policy_generation = -1, + 2 => request.expected_issuer = Some("https://issuer.example.org".into()), + 3 => request.expected_host = "TEAM.communities.example.org".into(), + _ => (), + } + std::fs::write(&file, serde_json::to_vec(&request).unwrap()).unwrap(); + let error = run(Args { + origin: "http://127.0.0.1:1".into(), + key_file: dir.path().join("absent-key"), + command: Command::Disable { + request: file.clone(), + }, + }) + .await + .unwrap_err(); + assert!(error.to_string().contains(expected), "{error:#}"); + } + } + + #[derive(Clone)] + struct TestPolicy { + origin: String, + response: Value, + expected_body: Value, + host: String, + community_id: Uuid, + operation_id: Uuid, + desired: bool, + } + + async fn policy_test_handler( + axum::extract::State(policy): axum::extract::State, + method: Method, + uri: axum::http::Uri, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, + ) -> Json { + let encoded = headers["authorization"] + .to_str() + .unwrap() + .strip_prefix("Nostr ") + .unwrap(); + let event = String::from_utf8(STANDARD.decode(encoded).unwrap()).unwrap(); + let url = format!("{}{uri}", policy.origin); + buzz_auth::verify_nip98_event( + &event, + &url, + method.as_str(), + (method == Method::POST).then_some(body.as_ref()), + ) + .unwrap(); + if method == Method::POST { + assert_eq!( + serde_json::from_slice::(&body).unwrap(), + policy.expected_body + ); + assert!(buzz_auth::verify_nip98_event(&event, &url, "POST", Some(b"changed")).is_err()); + } else if uri.query().unwrap().starts_with("community_id=") { + assert_eq!( + uri.query(), + Some( + format!( + "community_id={}&expected_host={}", + policy.community_id, policy.host + ) + .as_str() + ) + ); + return Json(serde_json::json!({ + "community_id": policy.community_id, "expected_host": policy.host, + "expected_policy_generation": 1, "expected_requires_nip_fi": policy.desired, + "mode": "shadow", "effective_required": policy.desired, + })); + } else { + assert_eq!( + uri.query(), + Some(format!("operation_id={}", policy.operation_id).as_str()) + ); + assert!(buzz_auth::verify_nip98_event( + &event, + &format!("{}{PATH}", policy.origin), + "GET", + None + ) + .is_err()); + } + Json(policy.response) + } + + #[tokio::test] + async fn policy_commands_send_saved_action_and_recover_current_and_history() { + let keys = Keys::generate(); + let dir = tempfile::tempdir().unwrap(); + let key_file = dir.path().join("key"); + let file = dir.path().join("request.json"); + std::fs::write(&key_file, keys.secret_key().display_secret().to_string()).unwrap(); + for desired in [true, false] { + let saved = saved(desired); + let id = saved.operation_id; + let community_id = saved.community_id; + let host = saved.expected_host.clone(); + let mut receipt = serde_json::to_value(&saved).unwrap(); + receipt["operator_pubkey"] = keys.public_key().to_hex().into(); + receipt["policy_generation"] = 1.into(); + receipt["current_requires_nip_fi"] = desired.into(); + receipt["state"] = if desired { "pending" } else { "applied" }.into(); + let response = serde_json::json!({"receipt": receipt, "mode": "shadow", "effective_required": desired}); + std::fs::write(&file, serde_json::to_vec(&saved).unwrap()).unwrap(); + let expected_body = serde_json::to_value(&saved).unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let app = Router::new() + .route(PATH, any(policy_test_handler)) + .with_state(TestPolicy { + origin: origin.clone(), + response, + expected_body, + host, + community_id, + operation_id: id, + desired, + }); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let command = if desired { + Command::Enable { + request: file.clone(), + } + } else { + Command::Disable { + request: file.clone(), + } + }; + for command in [ + command, + Command::Status { + operation_id: Some(id), + community_id: None, + host: None, + }, + ] { + assert_eq!( + run(Args { + origin: origin.clone(), + key_file: key_file.clone(), + command + }) + .await + .unwrap(), + if desired { 10 } else { 0 } + ); + } + assert_eq!( + run(Args { + origin, + key_file: key_file.clone(), + command: Command::Status { + operation_id: None, + community_id: Some(community_id), + host: Some(saved.expected_host.clone()), + } + }) + .await + .unwrap(), + 0 + ); + server.abort(); + for (state, code) in [("superseded", 11), ("unavailable", 12)] { + let value = serde_json::json!({"receipt": {"operation_id":id,"operator_pubkey":keys.public_key().to_hex(),"policy_generation":1,"requires_nip_fi":desired,"state":state}}); + assert_eq!( + receipt_exit_code(&value, id, &keys.public_key().to_hex(), None).unwrap(), + code + ); + } + } + } + #[tokio::test] + async fn refuses_noncanonical_inputs_before_reading_key_or_sending_post() { + for (field, value) in [ + ("expected_host", "TEST.communities.example.org"), + ("expected_host", "test.communities.example.org."), + ("expected_host", "test.communities.example.org:443"), + ("expected_host", "https://test.communities.example.org"), + ("actor_pubkey", &"A".repeat(64)), + ("expected_owner_pubkey", &"A".repeat(64)), + ("actor_pubkey", &"a".repeat(63)), + ("expected_owner_pubkey", &"g".repeat(64)), + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("request.json"); + let mut input = serde_json::to_value(saved(true)).unwrap(); + input[field] = value.into(); + std::fs::write(&path, serde_json::to_vec(&input).unwrap()).unwrap(); + let error = run(Args { + origin: "http://127.0.0.1:1".into(), + key_file: dir.path().join("absent-key"), + command: Command::Enable { request: path }, + }) + .await + .unwrap_err(); + let message = format!("{error:#}"); + assert!( + message.contains("host") || message.contains("public keys"), + "{message}" + ); + assert!( + !message.contains("absent-key"), + "key read preceded validation: {message}" + ); + } + } + + #[tokio::test] + async fn error_responses_preserve_status_and_known_codes_without_echoing_bodies() { + use axum::http::StatusCode; + + for (status, body, expected) in [ + ( + 409, + r#"{"code":"owner_conflict","error":"private detail"}"#, + "owner_conflict", + ), + (409, r#"{"code":"issuer_conflict"}"#, "issuer_conflict"), + (409, r#"{"code":"host_conflict"}"#, "host_conflict"), + ( + 409, + r#"{"code":"idempotency_conflict"}"#, + "idempotency_conflict", + ), + (503, r#"{"code":"upgrades_disabled"}"#, "upgrades_disabled"), + ( + 502, + "private detail", + "non-JSON error response", + ), + ( + 409, + r#"{"code":"private detail"}"#, + "unrecognized error code", + ), + ] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let app = Router::new().route( + PATH, + any(move || async move { (StatusCode::from_u16(status).unwrap(), body) }), + ); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let dir = tempfile::tempdir().unwrap(); + let key_file = dir.path().join("key"); + let request_file = dir.path().join("request.json"); + let keys = Keys::generate(); + std::fs::write(&key_file, keys.secret_key().display_secret().to_string()).unwrap(); + std::fs::write(&request_file, serde_json::to_vec(&saved(true)).unwrap()).unwrap(); + let error = run(Args { + origin, + key_file, + command: Command::Enable { + request: request_file, + }, + }) + .await + .unwrap_err(); + let message = format!("{error:#}"); + assert!(message.contains(&format!("HTTP {status}")), "{message}"); + assert!(message.contains(expected), "{message}"); + assert!(!message.contains("private detail"), "{message}"); + assert!(!message.contains(&keys.secret_key().display_secret().to_string())); + server.abort(); + } + } + + #[test] + fn origin_cannot_select_a_different_path_or_embed_credentials() { + for origin in [ + "https://user:password@example.org", + "https://example.org/wrong", + "https://example.org/?q=x", + "https://example.org/#fragment", + "file:///tmp/key", + ] { + assert!(endpoint(origin).is_err(), "accepted {origin}"); + } + } +} diff --git a/crates/buzz-admin/tests/postgres_user_inventory.rs b/crates/buzz-admin/tests/postgres_user_inventory.rs index 2c53cb053db..d697f12d693 100644 --- a/crates/buzz-admin/tests/postgres_user_inventory.rs +++ b/crates/buzz-admin/tests/postgres_user_inventory.rs @@ -71,7 +71,7 @@ async fn cluster_global_inventory_cli_uses_only_existing_membership_tables() { for target in [community, participant_community] { for _ in 0..2 { let channel = Uuid::new_v4(); - sqlx::query("INSERT INTO channels (community_id, id, name, created_by) VALUES ($1, $2, 'inventory-test', decode($3, 'hex'))") + sqlx::query("INSERT INTO channels (community_id, id, name, created_by) VALUES ($1, $2, 'inventory-test-' || $2::uuid::text, decode($3, 'hex'))") .bind(target).bind(channel).bind(pubkey).execute(&mut *tx).await.unwrap(); sqlx::query("INSERT INTO channel_members (community_id, channel_id, pubkey) VALUES ($1, $2, decode($3, 'hex'))") .bind(target).bind(channel).bind(pubkey).execute(&mut *tx).await.unwrap(); diff --git a/crates/buzz-agent/tests/fake_llm.rs b/crates/buzz-agent/tests/fake_llm.rs index 86c469f982c..84dbf23c120 100644 --- a/crates/buzz-agent/tests/fake_llm.rs +++ b/crates/buzz-agent/tests/fake_llm.rs @@ -1521,17 +1521,33 @@ async fn steer_rejected_on_empty_prompt() { json!({"sessionId": sid, "expectedRunId": run_id, "prompt": []}), ) .await; - let mut saw_reject = false; + // The prompt runs in its own task while the steer is answered from the + // read loop, so the turn can finish before the steer is even read: wait + // for both responses in either order. + let (mut steer_reply, mut prompt_done) = (None, false); for _ in 0..40 { + if steer_reply.is_some() && prompt_done { + break; + } let v = h.recv().await; if v["id"] == json!(s_id) { - assert_eq!(v["error"]["code"], -32602, "empty prompt must be rejected"); - saw_reject = true; + steer_reply = Some(v); } else if v["id"] == json!(p_id) { - break; + prompt_done = true; } } - assert!(saw_reject, "empty steer prompt was not rejected"); + let steer_reply = steer_reply.expect("empty steer prompt got no response"); + assert_eq!( + steer_reply["error"]["code"], -32602, + "empty prompt must be rejected" + ); + // "no active run" and a run-id mismatch also answer -32602, and either can + // win if the turn ends first; the empty-prompt guard runs before both. + assert_eq!( + steer_reply["error"]["message"], "steer: prompt must not be empty", + "the empty-prompt guard must be what rejects the steer" + ); + assert!(prompt_done, "session/prompt did not finish"); h.shutdown().await; } diff --git a/crates/buzz-agent/tests/permission_boundary.rs b/crates/buzz-agent/tests/permission_boundary.rs index 2873ba14d6f..b7bfc5494e4 100644 --- a/crates/buzz-agent/tests/permission_boundary.rs +++ b/crates/buzz-agent/tests/permission_boundary.rs @@ -136,18 +136,16 @@ async fn drive( // Session init + call-log helpers // ───────────────────────────────────────────────────────────────────────────── -fn call_log_path(tag: &str) -> String { - let p = std::env::temp_dir().join(format!( - "buzz_perm_calllog_{tag}_{}_{:x}.log", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_nanos() - )); - let s = p.to_string_lossy().to_string(); - let _ = std::fs::remove_file(&s); - s +/// A fresh call-log path inside its own temp dir. Keep the returned `TempDir` +/// bound for the whole test: dropping it deletes the log, including when an +/// assertion panics. +fn call_log_path(tag: &str) -> (tempfile::TempDir, String) { + let dir = tempfile::Builder::new() + .prefix(&format!("buzz_perm_calllog_{tag}_")) + .tempdir() + .expect("create call-log temp dir"); + let path = dir.path().join("calls.log").to_string_lossy().into_owned(); + (dir, path) } /// Invoked tool names recorded by fake_mcp (bare names, one per `tools/call`). @@ -214,7 +212,7 @@ fn stop_reason(resp: &Value) -> String { /// the tally ends at one. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_allow_reaches_tool_exactly_once_and_not_before_approval() { - let log = call_log_path("allow"); + let (_log_dir, log) = call_log_path("allow"); let llm = spawn_capturing_llm(vec![shell_call("tc1"), openai_text("done")]).await; let mut h = Harness::spawn(&llm.url).await; let sid = init( @@ -250,7 +248,7 @@ async fn test_allow_reaches_tool_exactly_once_and_not_before_approval() { /// sees a permission-denied tool error (the turn continues to `end_turn`). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_reject_option_never_invokes_tool() { - let log = call_log_path("reject"); + let (_log_dir, log) = call_log_path("reject"); let llm = spawn_capturing_llm(vec![shell_call("tc1"), openai_text("understood")]).await; let mut h = Harness::spawn(&llm.url).await; let sid = init( @@ -321,7 +319,7 @@ async fn test_adversarial_outcomes_never_invoke_tool() { ]; for (tag, build) in shapes { - let log = call_log_path(tag); + let (_log_dir, log) = call_log_path(tag); let llm = spawn_capturing_llm(vec![shell_call("tc1"), openai_text("ok")]).await; let mut h = Harness::spawn(&llm.url).await; let sid = init( @@ -352,7 +350,7 @@ async fn test_adversarial_outcomes_never_invoke_tool() { /// waiter; the correct id then authorizes exactly once. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_stale_id_ignored_then_real_id_authorizes() { - let log = call_log_path("staleid"); + let (_log_dir, log) = call_log_path("staleid"); let llm = spawn_capturing_llm(vec![shell_call("tc1"), openai_text("done")]).await; let mut h = Harness::spawn(&llm.url).await; let sid = init( @@ -406,7 +404,7 @@ async fn test_stale_id_ignored_then_real_id_authorizes() { /// by staying silent, and cancellation must not depend on that answer. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_cancel_while_waiting_executes_nothing_without_client_answer() { - let log = call_log_path("cancelwait"); + let (_log_dir, log) = call_log_path("cancelwait"); let llm = spawn_capturing_llm(vec![shell_call("tc1"), openai_text("done")]).await; let mut h = Harness::spawn(&llm.url).await; let sid = init( @@ -452,7 +450,7 @@ async fn test_cancel_while_waiting_executes_nothing_without_client_answer() { /// proves only the allowed (second) call reached MCP — order-agnostic. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_crossed_parallel_decisions_authorize_only_matching_call() { - let log = call_log_path("crossed"); + let (_log_dir, log) = call_log_path("crossed"); // Two distinct registered tools so the call log distinguishes them by name. let llm = spawn_capturing_llm(vec![ openai_tool_calls(&[ @@ -547,7 +545,7 @@ async fn test_load_skill_emits_no_permission_request() { /// objects once, forcing a hook invocation the test can observe. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_stop_hook_reaches_mcp_without_permission_ask() { - let log = call_log_path("stophook"); + let (_log_dir, log) = call_log_path("stophook"); // Text turn triggers the _Stop gate → hook objects once → agent loops → // second text turn, hook silent → end_turn. No model-issued tool call. let llm = spawn_capturing_llm(vec![ @@ -599,7 +597,7 @@ async fn test_stop_hook_reaches_mcp_without_permission_ask() { /// with an end-to-end proof that the negotiated version reaches the wire. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_v2_negotiation_emits_v2_request_shape() { - let log = call_log_path("v2shape"); + let (_log_dir, log) = call_log_path("v2shape"); let llm = spawn_capturing_llm(vec![shell_call("tc1"), openai_text("done")]).await; let mut h = Harness::spawn(&llm.url).await; let sid = init( diff --git a/crates/buzz-agent/tests/regressions.rs b/crates/buzz-agent/tests/regressions.rs index a6feb989b6e..5d488d0dff9 100644 --- a/crates/buzz-agent/tests/regressions.rs +++ b/crates/buzz-agent/tests/regressions.rs @@ -1425,6 +1425,10 @@ async fn cancel_kills_inflight_tool_via_mcp_notification() { ]) .await; + // The agent stops buzz-dev-mcp with SIGKILL, so the server never deletes + // its own temp dirs. Point its TMPDIR at a dir this test owns and removes. + // Declared before `h` so it drops after the harness. + let dev_mcp_tmp = tempfile::TempDir::new().expect("create buzz-dev-mcp TMPDIR"); let mut h = Harness::spawn(&llm.url).await; let sid = init_session( &mut h, @@ -1432,7 +1436,7 @@ async fn cancel_kills_inflight_tool_via_mcp_notification() { "name": "dev", "command": &dev_mcp_bin, "args": [], - "env": [] + "env": [{"name": "TMPDIR", "value": dev_mcp_tmp.path()}] }]), ) .await; diff --git a/crates/buzz-audio-client/src/connection.rs b/crates/buzz-audio-client/src/connection.rs index 6413b41742b..21b4b22b02b 100644 --- a/crates/buzz-audio-client/src/connection.rs +++ b/crates/buzz-audio-client/src/connection.rs @@ -5,7 +5,12 @@ use serde_json::{json, Value}; use std::{collections::BTreeSet, future::Future, time::Duration}; use tokio_tungstenite::{ connect_async_tls_with_config, - tungstenite::{client::IntoClientRequest, protocol::WebSocketConfig, Message}, + tungstenite::{ + client::IntoClientRequest, + http::{header::USER_AGENT, HeaderValue}, + protocol::WebSocketConfig, + Message, + }, Connector, MaybeTlsStream, WebSocketStream, }; @@ -96,11 +101,15 @@ async fn control(socket: &mut AudioSocket) -> Result { } } +/// `User-Agent` sent on the upgrade unless the request already carries one. +const DEFAULT_USER_AGENT: &str = concat!("buzz-audio-client/", env!("CARGO_PKG_VERSION")); + /// Connect and authenticate using a host-provided asynchronous signer. /// /// The host validates the destination before calling, and constructs the NIP-42 /// event (including its exact relay tag) from the challenge. `request` is the -/// audio URL, or a request carrying host-supplied upgrade headers. No private key is +/// audio URL, or a request carrying host-supplied upgrade headers; without a +/// `User-Agent` it sends `buzz-audio-client/`. No private key is /// accepted. Dropping this future cancels connection/admission; the entire /// operation is bounded to 15 seconds, including signing. pub async fn connect( @@ -117,6 +126,13 @@ where let config = WebSocketConfig::default() .max_message_size(Some(65_536)) .max_frame_size(Some(65_536)); + let mut request = request + .into_client_request() + .map_err(|e| format!("audio WS connect failed: {e}"))?; + request + .headers_mut() + .entry(USER_AGENT) + .or_insert(HeaderValue::from_static(DEFAULT_USER_AGENT)); let (mut socket, _) = connect_async_tls_with_config(request, Some(config), false, connector) .await diff --git a/crates/buzz-audio-client/tests/connection.rs b/crates/buzz-audio-client/tests/connection.rs index 31e9cb66f5a..f4e010e59f6 100644 --- a/crates/buzz-audio-client/tests/connection.rs +++ b/crates/buzz-audio-client/tests/connection.rs @@ -149,7 +149,11 @@ async fn request_headers_reach_the_upgrade() { let (stream, _) = listener.accept().await.unwrap(); let (seen, header) = oneshot::channel(); let mut socket = accept_hdr_async(stream, |request: &Request, response: Response| { - let _ = seen.send(request.headers().get("authorization").cloned()); + let headers = request.headers(); + let _ = seen.send(( + headers.get("authorization").cloned(), + headers.get("user-agent").cloned(), + )); Ok(response) }) .await @@ -182,8 +186,11 @@ async fn request_headers_reach_the_upgrade() { }) .await .unwrap(); - assert_eq!( - server.await.unwrap().unwrap().to_str().unwrap(), - "Bearer upgrade-token" - ); + let (authorization, user_agent) = server.await.unwrap(); + assert_eq!(authorization.unwrap(), "Bearer upgrade-token"); + let user_agent = user_agent.unwrap(); + assert!(user_agent + .to_str() + .unwrap() + .starts_with("buzz-audio-client/")); } diff --git a/crates/buzz-auth/Cargo.toml b/crates/buzz-auth/Cargo.toml index 93833103dbc..bbb4330238f 100644 --- a/crates/buzz-auth/Cargo.toml +++ b/crates/buzz-auth/Cargo.toml @@ -17,6 +17,8 @@ jsonwebtoken = { version = "10.4.0", default-features = false, features = ["aws_ tokio = { workspace = true, features = ["test-util"] } [dependencies] +unicode-normalization = "0.1.25" +unicode-properties = { version = "0.1.4", default-features = false, features = ["general-category"] } buzz-core = { workspace = true } base64 = { workspace = true } chrono = { workspace = true } diff --git a/crates/buzz-auth/src/nip_fi/assertion.rs b/crates/buzz-auth/src/nip_fi/assertion.rs index 879734d22a8..7431b50c15d 100644 --- a/crates/buzz-auth/src/nip_fi/assertion.rs +++ b/crates/buzz-auth/src/nip_fi/assertion.rs @@ -117,6 +117,7 @@ impl fmt::Debug for RevalidationDependencies { #[derive(Clone, PartialEq, Eq)] pub struct VerifiedAssertion { identity: FederatedIdentity, + profile_assertion: Option, asserted_key: Option, owner: Option, capabilities: CanonicalCapabilities, @@ -147,6 +148,7 @@ impl VerifiedAssertion { ); Self { identity: FederatedIdentity { issuer, subject }, + profile_assertion: None, asserted_key, owner, capabilities, @@ -157,6 +159,19 @@ impl VerifiedAssertion { } } + /// Optional output-only evidence; absent for OAuth client-subject assertions. + pub fn profile_assertion(&self) -> Option<&super::public_profile::ProfileAssertion> { + self.profile_assertion.as_ref() + } + + pub(super) fn with_profile_assertion( + mut self, + value: Option, + ) -> Self { + self.profile_assertion = value; + self + } + /// The issuer-qualified identity. pub fn identity(&self) -> &FederatedIdentity { &self.identity @@ -268,6 +283,7 @@ impl VerifiedAssertion { subject: "test-subject".to_string(), }, asserted_key, + profile_assertion: None, owner: None, capabilities: CanonicalCapabilities::from_pairs(vec![]), authority_deadlines, diff --git a/crates/buzz-auth/src/nip_fi/config.rs b/crates/buzz-auth/src/nip_fi/config.rs index cfe98596703..08c01bb4077 100644 --- a/crates/buzz-auth/src/nip_fi/config.rs +++ b/crates/buzz-auth/src/nip_fi/config.rs @@ -84,7 +84,7 @@ pub(crate) const MAX_JTI_BYTES: usize = 512; /// type, which requires a `nostr_owner_pubkey` claim (a valid lowercase key /// distinct from the asserted key); a `nip-fi+jwt` or `at+jwt` token carrying /// `nostr_owner_pubkey` with any value, `null` included, is rejected. -pub(crate) const VERIFIER_CONTRACT_VERSION: u32 = 3; +pub(crate) const VERIFIER_CONTRACT_VERSION: u32 = 4; /// The transport-contract fingerprint folded into [`TransportContractId`]. /// **Bump on any change** to the client-attached parsing, attachment, @@ -391,6 +391,8 @@ pub struct IssuerPolicy { /// transport, refresh schedule, or hard-deadline rule changes the policy /// ID and invalidates all prepared evidence. jwks_source_contract: JwksSourceContract, + public_profile: bool, + public_issuer_label: Option, id: AssertionPolicyId, } @@ -502,6 +504,8 @@ impl IssuerPolicy { maximum_assertion_age_seconds, maximum_status_age_seconds, jwks_source_contract, + public_profile: false, + public_issuer_label: None, // Placeholder, overwritten from the fully built policy below. id: AssertionPolicyId([0u8; 32]), }; @@ -509,6 +513,14 @@ impl IssuerPolicy { Ok(policy) } + /// Bind output-only profile policy into prepared-evidence identity. + pub fn with_public_profile(mut self, enabled: bool, label: Option) -> Self { + self.public_profile = enabled; + self.public_issuer_label = label; + self.id = derive_assertion_policy_id(&self); + self + } + /// The policy ID an assertion verified for the community expecting /// `community_aud` carries: `H(base policy contract, community aud)`. The /// base contract already commits to the issuer. The verifier mints it @@ -679,6 +691,8 @@ fn derive_assertion_policy_id(policy: &IssuerPolicy) -> AssertionPolicyId { maximum_assertion_age_seconds, maximum_status_age_seconds, jwks_source_contract, + public_profile, + public_issuer_label, id: _, } = policy; let mut hasher = Sha256::new(); @@ -700,6 +714,15 @@ fn derive_assertion_policy_id(policy: &IssuerPolicy) -> AssertionPolicyId { ] { hasher.update((bound as u64).to_be_bytes()); } + hasher.update([u8::from(*public_profile)]); + hasher.update([u8::from(public_issuer_label.is_some())]); + hash_field( + &mut hasher, + public_issuer_label + .as_deref() + .unwrap_or_default() + .as_bytes(), + ); hash_field(&mut hasher, issuer.as_bytes()); hash_seq(&mut hasher, command_audiences.iter().map(String::as_bytes)); hash_field(&mut hasher, token_class.discriminant().as_bytes()); @@ -803,7 +826,7 @@ mod jwks_transport_identity_tests { assert_eq!( hex::encode(policy(contract).id().as_bytes()), - "29ecb98c34dc7574616d72caf1565cda35585a15f682f0d30f6c011342a555d8", + "41616c071239652badb7f75ea060f6ad20de4dee1af665d942b0fdee3dc32c0b", "public_https mode omits the mesh transport tag" ); } @@ -819,7 +842,7 @@ mod jwks_transport_identity_tests { assert_eq!( hex::encode(policy(contract).id().as_bytes()), - "da846eec66b2e084ac3557d8e5c2a3a2faf12946e965c82d2ef46f91b6fa014e", + "14f2cc8f50b6ce76008936321794642dfa1a79fa99150bff7f0f0479b5e7d06f", "mesh transport is part of policy identity" ); } diff --git a/crates/buzz-auth/src/nip_fi/mod.rs b/crates/buzz-auth/src/nip_fi/mod.rs index f580ad089d8..f558028b4e9 100644 --- a/crates/buzz-auth/src/nip_fi/mod.rs +++ b/crates/buzz-auth/src/nip_fi/mod.rs @@ -18,6 +18,7 @@ pub mod deny_map; pub mod discovery; pub mod jwks; pub mod provision; +pub mod public_profile; pub mod startup; pub mod verifier; diff --git a/crates/buzz-auth/src/nip_fi/public_profile.rs b/crates/buzz-auth/src/nip_fi/public_profile.rs new file mode 100644 index 00000000000..76938908671 --- /dev/null +++ b/crates/buzz-auth/src/nip_fi/public_profile.rs @@ -0,0 +1,150 @@ +//! Optional, output-only NIP-FI name claims. Never used for authorization. + +use serde::{Deserialize, Serialize}; +use unicode_properties::{GeneralCategory, UnicodeGeneralCategory}; + +/// The names an issuer explicitly authorizes the relay to publish. +#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct PublicProfile { + /// NFC display text, bounded to 64 Unicode scalar values. + pub display_name: String, + /// Lowercase ASCII handle. + pub username: String, + /// Optional full name, with the same Unicode and length bounds as display text. + #[serde( + default, + deserialize_with = "optional_full_name", + skip_serializing_if = "Option::is_none" + )] + pub full_name: Option, +} + +fn optional_full_name<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + String::deserialize(deserializer).map(Some) +} + +impl std::fmt::Debug for PublicProfile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("PublicProfile([REDACTED])") + } +} + +impl PublicProfile { + /// Malformed optional claims are absent, never an admission error. + pub fn from_json(value: &str) -> Option { + let profile: Self = serde_json::from_str(value).ok()?; + (valid_display_name(&profile.display_name) + && valid_username(&profile.username) + && profile.full_name.as_deref().is_none_or(valid_display_name)) + .then_some(profile) + } +} + +/// Validate the protocol's display-name and public-issuer-label text rules. +pub fn valid_display_name(value: &str) -> bool { + use GeneralCategory::{ + Control, Format, LineSeparator, ParagraphSeparator, PrivateUse, Surrogate, Unassigned, + }; + !value.is_empty() + && value.chars().count() <= 64 + && value.trim() == value + && unicode_normalization::is_nfc(value) + && !value.chars().any(|c| { + matches!( + c.general_category(), + Control + | Format + | Surrogate + | PrivateUse + | Unassigned + | LineSeparator + | ParagraphSeparator + ) + }) +} + +/// Validate a NIP-FI public username. +pub fn valid_username(value: &str) -> bool { + (1..=64).contains(&value.len()) + && value + .bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(&c)) +} + +/// Verified projection input, kept separate from authoritative capabilities. +#[derive(Clone, PartialEq, Eq)] +pub struct ProfileAssertion { + /// Authenticated assertion issuance time, including fractional seconds. + pub issued_at: chrono::DateTime, + /// None for agents and malformed/missing human claims: publish nothing. + pub profile: Option, +} + +impl std::fmt::Debug for ProfileAssertion { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ProfileAssertion([REDACTED])") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn optional_full_name_is_validated_without_requiring_it_for_older_issuers() { + let profile = PublicProfile::from_json( + r#"{"display_name":"alice","username":"alice","full_name":"Alice Example"}"#, + ) + .unwrap(); + assert_eq!(profile.full_name.as_deref(), Some("Alice Example")); + for full_name in [ + serde_json::json!(null), + serde_json::json!(42), + serde_json::json!(""), + serde_json::json!(" A"), + serde_json::json!("A\nB"), + ] { + assert!(PublicProfile::from_json(&serde_json::json!({"display_name":"alice","username":"alice","full_name":full_name}).to_string()).is_none()); + } + } + + #[test] + fn claim_is_closed_and_unicode_rules_are_exact() { + for name in ["Alice", "Élodie", "李明", "🦀", &"a".repeat(64)] { + assert!(valid_display_name(name), "{name:?}"); + } + for name in [ + "", + " Alice", + "Alice\u{a0}", + "E\u{301}", + "a\n", + "a\u{200d}b", + "a\u{e000}", + "a\u{378}", + "a\u{2028}", + &"a".repeat(65), + ] { + assert!(!valid_display_name(name), "{name:?}"); + } + for value in [ + serde_json::json!(null), + serde_json::json!({"display_name":"Alice"}), + serde_json::json!({"display_name":"Alice","username":"Alice"}), + serde_json::json!({"display_name":"Alice","username":"alice","email":"private@example.com"}), + ] { + assert!(PublicProfile::from_json(&value.to_string()).is_none()); + } + assert!(PublicProfile::from_json( + r#"{"display_name":"Alice","display_name":"Bob","username":"alice"}"# + ) + .is_none()); + assert!(PublicProfile::from_json( + &serde_json::json!({"display_name":"Alice","username":"alice.s_1-"}).to_string() + ) + .is_some()); + } +} diff --git a/crates/buzz-auth/src/nip_fi/startup/mod.rs b/crates/buzz-auth/src/nip_fi/startup/mod.rs index 967d6c3719a..403de76dbdf 100644 --- a/crates/buzz-auth/src/nip_fi/startup/mod.rs +++ b/crates/buzz-auth/src/nip_fi/startup/mod.rs @@ -29,6 +29,23 @@ pub enum NipFiMode { } impl NipFiMode { + /// Enforce stored community requirements only in Shadow; Off disables FI. + /// Repair mode remains unconditional. + pub const fn with_requirement(self, required: bool) -> Self { + if self.denies_unconditionally() { + self + } else if self.observes_only() && required { + Self::Enforce + } else { + self + } + } + + /// Fail closed when a dependency needed to decide policy is unavailable. + pub const fn unavailable() -> Self { + Self::DenyProtected + } + /// NIP-FI is disabled. pub const fn is_off(self) -> bool { matches!(self, Self::Off) diff --git a/crates/buzz-auth/src/nip_fi/startup/tests.rs b/crates/buzz-auth/src/nip_fi/startup/tests.rs index 123289ee189..4cb89441b0a 100644 --- a/crates/buzz-auth/src/nip_fi/startup/tests.rs +++ b/crates/buzz-auth/src/nip_fi/startup/tests.rs @@ -247,3 +247,26 @@ fn mode_predicates_separate_evaluation_from_authority() { assert_eq!(mode.observes_only(), evaluates && !restricts, "{mode:?}"); } } + +#[test] +fn community_requirements_follow_relay_mode() { + for stored in [false, true] { + assert_eq!(NipFiMode::Off.with_requirement(stored), NipFiMode::Off); + assert_eq!( + NipFiMode::Shadow.with_requirement(stored), + if stored { + NipFiMode::Enforce + } else { + NipFiMode::Shadow + } + ); + assert_eq!( + NipFiMode::Enforce.with_requirement(stored), + NipFiMode::Enforce + ); + assert_eq!( + NipFiMode::DenyProtected.with_requirement(stored), + NipFiMode::DenyProtected + ); + } +} diff --git a/crates/buzz-auth/src/nip_fi/verifier.rs b/crates/buzz-auth/src/nip_fi/verifier.rs index daa91f29405..ee5ba161396 100644 --- a/crates/buzz-auth/src/nip_fi/verifier.rs +++ b/crates/buzz-auth/src/nip_fi/verifier.rs @@ -458,6 +458,45 @@ impl FederatedAssertionVerifier { return Err(VerifierError::StatusWitnessUnavailable); } + // This optional evidence has no effect on admission or capabilities. + // Agents carry no profile, OAuth client subjects carry no evidence. + let profile_eligible = match policy.token_class() { + TokenClass::DedicatedNipFi => true, + TokenClass::AccessTokenAtJwt { subject_class } => { + subject_class.classify( + claims + .get(subject_class.marker_claim()) + .and_then(Value::as_str), + ) == Some(SubjectClass::ResourceOwner) + } + }; + let profile_assertion = if profile_eligible { + Some(super::public_profile::ProfileAssertion { + issued_at: parse_numeric_date(&claims["iat"])?, + profile: if owner.is_some() { + None + } else { + token + .split('.') + .nth(1) + .and_then(|segment| base64url_decode(segment).ok()) + .and_then(|bytes| { + serde_json::from_slice::< + std::collections::HashMap>, + >(&bytes) + .ok() + }) + .and_then(|raw| { + raw.get("nostr_public_profile").and_then(|value| { + super::public_profile::PublicProfile::from_json(value.get()) + }) + }) + }, + }) + } else { + None + }; + Ok(VerifiedAssertion::seal( policy.issuer().to_owned(), subject, @@ -473,7 +512,8 @@ impl FederatedAssertionVerifier { key_set.hard_deadline, token.to_owned(), ), - )) + ) + .with_profile_assertion(profile_assertion)) } fn unverified_issuer(&self, token: &str) -> Result { diff --git a/crates/buzz-auth/src/nip_fi/verifier/tests.rs b/crates/buzz-auth/src/nip_fi/verifier/tests.rs index 8912e653c1b..c5cafbcfa50 100644 --- a/crates/buzz-auth/src/nip_fi/verifier/tests.rs +++ b/crates/buzz-auth/src/nip_fi/verifier/tests.rs @@ -19,11 +19,7 @@ use jsonwebtoken::{Algorithm, EncodingKey, Header}; use serde_json::{json, Value}; // A fixed P-256 test key (PKCS#8 PEM) and its public JWK coordinates. -const TEST_EC_PKCS8_PEM: &str = "-----BEGIN PRIVATE KEY-----\n\ -MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\n\ -WZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\n\ -zhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n\ ------END PRIVATE KEY-----\n"; +const TEST_EC_PKCS8_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\nWZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\nzhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n-----END PRIVATE KEY-----\n"; // sadscan:disable np.pem.1 kingfisher.privkey.2 -- unchanged public ES256 test fixture const TEST_JWK_X: &str = "RW-mZ7H5Kjjl8hIY9ygUKYRiheL02s4Xm22r22dWaJI"; const TEST_JWK_Y: &str = "WqQXVwaD6NM7us40BUTNe9dRa1XoJ0NX6vJuJWYU_bA"; const TEST_KID: &str = "test-key-1"; @@ -46,11 +42,7 @@ fn test_jwks_contract() -> crate::nip_fi::jwks::JwksSourceContract { // A second, independent P-256 key: issuer B's real signing key, used to prove // that a token signed by B and claiming `iss=A` cannot mint an A identity. -const TEST_EC_PKCS8_PEM_B: &str = "-----BEGIN PRIVATE KEY-----\n\ -MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKcmDf3+zDWyC96/X\n\ -Gv8aYK552uF5aE6nXKzxAfl4fSWhRANCAATf0ccbp1c4mMd6WvSuliv5ZAS8iIWL\n\ -Ne2tqOfFa0hRpa41DANab1/EuDGi7PtIo8xSYwkaoib1MAJlfLvRMjQA\n\ ------END PRIVATE KEY-----\n"; +const TEST_EC_PKCS8_PEM_B: &str = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKcmDf3+zDWyC96/X\nGv8aYK552uF5aE6nXKzxAfl4fSWhRANCAATf0ccbp1c4mMd6WvSuliv5ZAS8iIWL\nNe2tqOfFa0hRpa41DANab1/EuDGi7PtIo8xSYwkaoib1MAJlfLvRMjQA\n-----END PRIVATE KEY-----\n"; // sadscan:disable np.pem.1 kingfisher.privkey.2 -- unchanged public ES256 test fixture const TEST_JWK_X_B: &str = "39HHG6dXOJjHelr0rpYr-WQEvIiFizXtrajnxWtIUaU"; const TEST_JWK_Y_B: &str = "rjUMA1pvX8S4MaLs-0ijzFJjCRqiJvUwAmV8u9EyNAA"; @@ -2123,3 +2115,44 @@ fn community_binding_rejects_empty_parts() { CommunityBindingError::EmptyIssuers ); } + +#[test] +fn public_profile_is_output_only_and_malformed_claims_do_not_deny() { + // FI-TRACE-PUBLIC-PROFILE-MALFORMED and FI-TRACE-PUBLIC-PROFILE-SCOPE. + let verifier = verifier_with(dedicated_policy(ISSUER)); + let community = CommunityBinding::new(AUDIENCE.into(), vec![ISSUER.into()]).unwrap(); + for profile in [ + json!(null), + json!("Alice"), + json!({"display_name":"Alice"}), + json!({"display_name":"Alice","username":"Alice"}), + json!({"display_name":"Alice","username":"alice","email":"private"}), + ] { + let token = mint( + Some("nip-fi+jwt"), + TEST_KID, + json!({"sub":"user", "nostr_public_profile": profile}), + ); + let verified = verifier.verify(&token, &community).unwrap(); + assert!(verified.profile_assertion().unwrap().profile.is_none()); + assert!(verified.capabilities().is_empty()); + } + let token = mint( + Some("nip-fi+jwt"), + TEST_KID, + json!({"sub":"user", "nostr_public_profile":{"display_name":"Alice","username":"alice"}}), + ); + let verified = verifier.verify(&token, &community).unwrap(); + assert_eq!( + verified + .profile_assertion() + .unwrap() + .profile + .as_ref() + .unwrap() + .display_name, + "Alice" + ); + assert!(verified.capabilities().is_empty()); + assert!(!format!("{verified:?}").contains("Alice")); +} diff --git a/crates/buzz-cli/Cargo.toml b/crates/buzz-cli/Cargo.toml index 59d1bb2cee6..fa08534db8b 100644 --- a/crates/buzz-cli/Cargo.toml +++ b/crates/buzz-cli/Cargo.toml @@ -40,6 +40,7 @@ uuid = { workspace = true } # RFC3339 observer timestamps for owner-reviewed agent draft requests chrono = { workspace = true } +httpdate = { workspace = true } # Typed event builders for all write operations buzz-sdk = { workspace = true } @@ -86,10 +87,24 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std" # Random number generation — full jitter for exponential backoff in with_retry rand = { workspace = true } +[target.'cfg(unix)'.dependencies] +# getuid for the desktop provider's same-user check +libc = "0.2" + +# OS keychain for paired desktop-provider tokens (never a file) +[target.'cfg(target_os = "macos")'.dependencies] +keyring = { version = "=3.6.3", default-features = false, features = ["apple-native"] } + +[target.'cfg(target_os = "linux")'.dependencies] +keyring = { version = "=3.6.3", default-features = false, features = ["sync-secret-service", "crypto-rust", "vendored"] } + [dev-dependencies] # Scratch files for channel-templates.json fixtures in tests tempfile = "3" # Minimal HTTP test server for retry/policy integration tests axum = { workspace = true } +# A raw WebSocket relay for NIP-FI close-classification tests +tokio-tungstenite = { workspace = true } +futures-util = { workspace = true } # `test-util` enables paused-time control for deterministic timeout tests tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] } diff --git a/crates/buzz-cli/README.md b/crates/buzz-cli/README.md index c610a65ab11..6824fe0a9f0 100644 --- a/crates/buzz-cli/README.md +++ b/crates/buzz-cli/README.md @@ -20,6 +20,45 @@ export BUZZ_PRIVATE_KEY="nsec1..." buzz channels list ``` +### Which credentials are used + +The CLI uses the first of these that is configured: + +1. **An explicit key** (`--private-key` or `BUZZ_PRIVATE_KEY`), with the + headless NIP-FI settings below when they are set. +2. **The Buzz desktop** (macOS and Linux), through a token it gave this + process or one saved by `buzz auth desktop pair`. The desktop signs and + supplies NIP-FI evidence itself; headless NIP-FI settings are ignored, with + a warning naming them. + +With neither, commands fail with an `auth_error`. + +### Federated identity (NIP-FI) + +A relay that enforces federated identity also needs an identity assertion on +every protected request (`docs/nips/NIP-FI.md`). Give the CLI your NIP-FA +adapter session and it requests one; the adapter mints it +(`docs/nips/NIP-FA.md` §Relay assertion). The CLI caches the assertion for the +process, requests a new one shortly before it expires, and sends it as +`Nostr-Federated-Identity` on HTTP requests and the WebSocket upgrade. + +The session is a human sign-in for your own key: the adapter issues +assertions only for the key bound to the signed-in user. It is not an agent +grant, and it cannot authorize an agent key. + +```bash +export BUZZ_PRIVATE_KEY="nsec1..." +export BUZZ_FEDERATED_IDENTITY_ADAPTER="https://adapter.example" +export BUZZ_FEDERATED_IDENTITY_TOKEN="..." # your adapter session token; env only, never a flag +buzz channels list +``` + +The token goes only to the adapter, never through a redirect, and never into +output. Adapter outages (network errors, 429, 5xx) are retried a bounded number +of times and then fail as a retryable `adapter_error` before anything reaches +the relay; an adapter refusal is an `auth_error` and is not retried. On relays without NIP-FI, leave both unset: nothing changes. An +enforcing relay's `401` without them is an `auth_error` naming both settings. + ## Usage All output is JSON on stdout. Errors are JSON on stderr. Exit codes: 0=ok, 1=user error, 2=network, 3=auth, 4=other, 5=write conflict. @@ -33,19 +72,24 @@ buzz messages send --channel --content "Hello" buzz messages send --channel --content "Reply" --reply-to --broadcast buzz messages send --channel --content - < message.md # read body from stdin buzz messages send --channel --content-file message.md # UTF-8 file; use on Windows (PowerShell pipes drop non-ASCII) +buzz messages send --channel --content "Decision: ship" --from-thread # desktop "Send to channel" buzz messages get --channel --limit 20 buzz messages thread --channel --event buzz messages thread --link 'buzz://message?channel=&id=&thread=' buzz messages search --query "architecture" buzz messages search --author --since +buzz messages search --author --before --before-id --limit 100 # next older page buzz messages edit --event --content "Updated text" buzz messages delete --event +buzz messages report --event --reason spam --note "why" # to moderators only +buzz messages report --pubkey --reason impersonation # Diffs buzz messages send-diff --channel --diff - --repo https://github.com/org/repo --commit abc123 < diff.patch # Channels buzz channels list +buzz channels unread # unread counts from your synced read state (read-only) buzz channels create --name "my-channel" --type stream --visibility open buzz channels join --channel buzz channels topic --channel --topic "New topic" @@ -54,6 +98,10 @@ buzz channels topic --channel --topic "New topic" buzz reactions add --event --emoji "👍" buzz reactions get --event +# Huddles (read-only) +buzz huddles list --channel --active # huddles with state and start/end times +buzz huddles participants --channel --huddle + # GIFs (requires relay to advertise buzz-gif / KLIPY) buzz gifs search # trending GIFs buzz gifs search --query "celebration" # search GIFs @@ -72,7 +120,10 @@ buzz users get --pubkey --pubkey # batch (max 200) buzz users get --name Honey --owner me # exact-name lookup in your managed agents buzz users set-presence --status online buzz users set-status --text "heads down on the CLI" --emoji "🚀" +buzz users set-status --text "lunch" --emoji "🥪" --expires 1h # clears itself; also a unix time buzz users set-status --clear # remove your status +buzz users status # your visible status: [{pubkey, text, emoji, expires_at, updated_at}] +buzz users status --pubkey # repeatable, max 100; expired or cleared users are omitted # DMs buzz dms open --pubkey @@ -91,6 +142,23 @@ buzz messages vote --event --direction up buzz canvas get --channel buzz canvas set --channel --content "# Welcome" +# Sidebar sections (your own sidebar, synced with Buzz desktop) +buzz sidebar sections create --name "Engineering" --icon "🛠" +buzz sidebar sections move --section "Engineering" --channel --channel +buzz sidebar sections list + +# Sidebar sort modes (alpha or recent per group) +buzz sidebar sort set --group dms --mode recent +buzz sidebar sort set --group "Engineering" --mode recent +buzz sidebar sort reset --group section: +buzz sidebar sort list + +# Sidebar stars, mutes, and project pins +buzz sidebar stars add --channel --channel +buzz sidebar mutes remove --channel +buzz sidebar projects add --project 30621:: +buzz sidebar stars list + # Agent Memory (NIP-AE) buzz mem ls buzz mem get @@ -107,6 +175,34 @@ buzz repos protect remove --id my-repo --ref refs/heads/main buzz channels list | jq '.[].name' ``` +`sidebar sections` edits the signing identity's own sidebar. Each command is +one read and one publish, so a multi-channel `move` lands together. `--section` +takes a section id or a unique section name. A repeated command prints +`"message": "unchanged"` and publishes nothing. Concurrent edits from another +CLI run or another client can overwrite each other, and the last publish wins. + +`sidebar stars`, `sidebar mutes`, and `sidebar projects` edit the other synced +sidebar lists the same way: one head read and one publish per command, and +`"message": "unchanged"` when nothing changes. `remove` keeps a `false` entry +(as desktop does) so the change syncs; removing an id that is not set changes +nothing. Stars and mutes keep the newest 500 entries; a command that would +evict its own ids fails. Project addresses are `30621::`. +Pass the same ids in any case; channel UUIDs and project owners are stored in +lowercase. If the relay reports a newer update (exit 5), run the command again. + +`sidebar sort` sets how one sidebar group orders its channels: `alpha` (name, +the default) or `recent` (last message, newest first). `--group` takes +`starred`, `channels`, `forums`, `dms`, `section:` (an exact live id), or a +section name (or bare id). A fixed group name wins over a section with the same name. `sort list` +prints `{"default": "alpha", "groups": {: }}` with only the groups +that have a mode set. `sort reset` writes a `null` register that returns the +group to the default; resetting a group with no register changes nothing. A +write is one sort-head read and one publish; a section name also reads your +sections. Desktop keeps a deleted section's `section:` mode, and so does the +CLI: it still shows in `sort list`, `sort set` refuses it, and `sort reset +--group section:` clears it. The sidebar keeps at most 104 sort modes +(stale keys count), and a command that would pass that fails. + `protect set` replaces every existing rule for the exact ref pattern. Any constraint omitted from the command is removed. `protect list` reports malformed stored rules in `validation_error` so an owner can remove and repair them. @@ -125,12 +221,14 @@ The table below mirrors that tree for readers who are not at a terminal. | | `send-diff` | Send a code diff with metadata | | | `edit` | Edit a message you sent | | | `delete` | Delete a message | +| | `report` | Report a message or user to community moderators (NIP-56); reasons: `illegal`, `nudity`, `malware`, `spam`, `impersonation`, `profanity`, `other` | | | `get` | List messages in a channel | | | `thread` | Get a message thread | | | `search` | Full-text search, filterable by author | | | `vote` | Vote on a forum post | | `channels` | `list` | List channels | | | `get` | Get channel details | +| | `unread` | Unread counts per channel (read-only) | | | `create` | Create a channel | | | `update` | Update channel name/description | | | `topic` | Set channel topic | @@ -145,9 +243,24 @@ The table below mirrors that tree for readers who are not at a terminal. | | `remove-member` | Remove a member | | `canvas` | `get` | Get channel canvas | | | `set` | Set channel canvas | +| `sidebar` | `sections list` | List your sections and their channels | +| | `sections create` | Create a section at the end of your sidebar | +| | `sections update` | Rename a section or change its icon | +| | `sections delete` | Delete a section | +| | `sections reorder` | Put sections in order | +| | `sections move` | Move one or more channels into a section | +| | `sections unassign` | Return channels to the default channel list | +| | `sort list` | List the groups with a sort mode | +| | `sort set` | Sort a group by `alpha` or `recent` | +| | `sort reset` | Return a group to the default sort | +| | `stars list` / `add` / `remove` | List, star, or unstar channels | +| | `mutes list` / `add` / `remove` | List, mute, or unmute channels | +| | `projects list` / `add` / `remove` | List, pin, or unpin sidebar projects | | `reactions` | `add` | React to a message | | | `remove` | Remove a reaction | | | `get` | List reactions | +| `huddles` | `list` | List a channel's huddles (read-only) | +| | `participants` | Show who is in a huddle (read-only) | | `gifs` | `search` | Search or browse trending GIFs (requires relay buzz-gif support) | | | `share` | Report a selected GIF to the provider's Recents | | `dms` | `list` | List DM conversations | @@ -157,7 +270,8 @@ The table below mirrors that tree for readers who are not at a terminal. | | `set-profile` | Update your profile | | | `presence` | Get presence status | | | `set-presence` | Set presence status | -| | `set-status` | Set or clear your NIP-38 profile status | +| | `set-status` | Set or clear your NIP-38 profile status; `--expires` takes a unix time or `30m`/`2h`/`1d`/`1w` | +| | `status` | Read NIP-38 statuses (default: yours); expired or cleared are omitted | | `workflows` | `list` | List workflows | | | `get` | Get workflow definition | | | `create` | Create a workflow | @@ -189,6 +303,17 @@ The table below mirrors that tree for readers who are not at a terminal. | | `patch` | Apply unified diff to memory value | | | `rm` | Publish a tombstone to delete memory | +## Huddles + +`huddles list` and `huddles participants` rebuild huddle state from the relay-signed lifecycle +events (kinds 48100–48103) with the same rules as the desktop app. They never join, start, or end +a huddle. Each scans at most 5000 newest events of the channel. If older events may be missing, +`complete` is `false` and `truncated` is `true`. A huddle with no end event is `active`, then +`stale` once its start is over an hour old; desktop shows `stale` as ended. The relay's liveness +snapshots are not served over HTTP, so `liveness_checked` is always `false`. +Rosters come from the relay's join and leave events only. Desktop's roster view also lists the +creator from the start event; the CLI lists the creator once the relay records their join. + ## Architecture ``` @@ -197,6 +322,9 @@ buzz [flags] ├─ main.rs ──▶ commands/*.rs ──▶ client.rs ──▶ Buzz Relay REST API │ (clap) (handlers) (reqwest) │ + ├─ credentials.rs (identity, signer, NIP-FI evidence; every request + │ is authorized through client.rs `authorize`) + ├─ federated_identity.rs (NIP-FA adapter session → NIP-FI assertion) ├─ validate.rs (UUID, hex, content size, percent-encode) └─ error.rs (CliError → JSON stderr + exit code) diff --git a/crates/buzz-cli/TESTING.md b/crates/buzz-cli/TESTING.md index b9b83c34981..2581071bb2f 100644 --- a/crates/buzz-cli/TESTING.md +++ b/crates/buzz-cli/TESTING.md @@ -104,6 +104,13 @@ cargo clippy -p buzz-cli -- -D warnings # Expected: zero warnings ``` +When `desktop/src/features/huddle/lib/huddlePresence.ts` changes, also replay the huddle fixtures +through desktop's tracker (run `pnpm install --frozen-lockfile` in `desktop/` first): + +```bash +node --import ./desktop/test-loader.mjs --experimental-strip-types crates/buzz-cli/tests/huddle_interop.mjs +``` + --- ## 6. Live Testing — Command by Command @@ -228,6 +235,9 @@ buzz messages search --query "CLI test" --limit 5 | jq . # messages edit buzz messages edit --event "$EVENT_ID" --content "Edited by CLI test" | jq . +# Explicit removal stays removed in a subsequent text edit. +buzz messages edit --event "$EVENT_ID" --content "Remove attached files" --clear-attachments | jq . +buzz messages edit --event "$EVENT_ID" --content "Still no attachments" | jq . # messages delete buzz messages delete --event "$REPLY_ID" | jq . diff --git a/crates/buzz-cli/src/agent_management.rs b/crates/buzz-cli/src/agent_management.rs index e5f25130694..54708af764d 100644 --- a/crates/buzz-cli/src/agent_management.rs +++ b/crates/buzz-cli/src/agent_management.rs @@ -1,9 +1,10 @@ //! Owner-reviewed agent draft requests published through Buzz observer frames. -use buzz_core::observer::{encrypt_observer_payload, OBSERVER_FRAME_TELEMETRY}; -use nostr::{Event, Keys, PublicKey}; +use buzz_core::observer::{OBSERVER_FRAME_TELEMETRY, OBSERVER_MAX_PLAINTEXT_LEN}; +use nostr::{Event, PublicKey}; use serde::Serialize; +use crate::credentials::Credentials; use crate::error::CliError; const AGENT_REQUEST_KIND: &str = "agent_management_request"; @@ -99,8 +100,8 @@ fn optional(value: Option, label: &str) -> Result, CliErr value.map(|value| required(value, label, 300)).transpose() } -fn build( - keys: &Keys, +async fn build( + credentials: &Credentials, owner: &PublicKey, channel_id: String, request_kind: &'static str, @@ -123,17 +124,23 @@ fn build( request, }, }; - let encrypted = encrypt_observer_payload(keys, owner, &payload) - .map_err(|error| CliError::Other(format!("could not encrypt draft request: {error}")))?; - let event = buzz_sdk::build_agent_observer_frame( + let plaintext = serde_json::to_string(&payload) + .map_err(|error| CliError::Other(format!("could not encode draft request: {error}")))?; + if plaintext.len() > OBSERVER_MAX_PLAINTEXT_LEN { + return Err(CliError::Usage(format!( + "draft request is too large: {} bytes (max {OBSERVER_MAX_PLAINTEXT_LEN})", + plaintext.len() + ))); + } + let encrypted = credentials.nip44_encrypt(owner, &plaintext).await?; + let builder = buzz_sdk::build_agent_observer_frame( &owner.to_hex(), - &keys.public_key().to_hex(), + &credentials.public_key().to_hex(), OBSERVER_FRAME_TELEMETRY, &encrypted, ) - .map_err(|error| CliError::Other(format!("could not build draft request: {error}")))? - .sign_with_keys(keys) - .map_err(|error| CliError::Other(format!("could not sign draft request: {error}")))?; + .map_err(|error| CliError::Other(format!("could not build draft request: {error}")))?; + let event = credentials.sign(builder).await?; Ok(BuiltDraftRequest { event, request_id, @@ -141,8 +148,8 @@ fn build( }) } -pub fn build_create( - keys: &Keys, +pub(crate) async fn build_create( + credentials: &Credentials, owner: &PublicKey, draft: CreateAgentDraft, ) -> Result { @@ -155,17 +162,18 @@ pub fn build_create( system_prompt: required(draft.system_prompt, "system prompt", MAX_PROMPT_CHARS)?, }; build( - keys, + credentials, owner, channel_id, AGENT_REQUEST_KIND, "create", request, ) + .await } -pub fn build_update( - keys: &Keys, +pub(crate) async fn build_update( + credentials: &Credentials, owner: &PublicKey, draft: UpdateAgentDraft, ) -> Result { @@ -206,17 +214,18 @@ pub fn build_update( )); } build( - keys, + credentials, owner, channel_id, AGENT_REQUEST_KIND, "update", request, ) + .await } -pub fn build_project_channel( - keys: &Keys, +pub(crate) async fn build_project_channel( + credentials: &Credentials, owner: &PublicKey, draft: CreateProjectChannelDraft, ) -> Result { @@ -242,28 +251,30 @@ pub fn build_project_channel( template_name: optional(draft.template_name, "template")?, }; build( - keys, + credentials, owner, home_channel_id, PROJECT_CHANNEL_REQUEST_KIND, "create", request, ) + .await } #[cfg(test)] mod tests { use super::*; use buzz_core::observer::{decrypt_observer_payload, OBSERVER_AGENT_TAG, OBSERVER_FRAME_TAG}; + use nostr::Keys; const CHANNEL: &str = "7c07e659-3610-42f4-9a5e-1e9973c09da9"; - #[test] - fn create_is_owner_encrypted_and_matches_desktop_contract() { + #[tokio::test] + async fn create_is_owner_encrypted_and_matches_desktop_contract() { let agent = Keys::generate(); let owner = Keys::generate(); let built = build_create( - &agent, + &Credentials::from_keys(agent.clone()), &owner.public_key(), CreateAgentDraft { channel_id: CHANNEL.into(), @@ -271,6 +282,7 @@ mod tests { system_prompt: "Find sources.".into(), }, ) + .await .unwrap(); assert_eq!(built.event.kind.as_u16(), 24_200); @@ -306,10 +318,10 @@ mod tests { assert!(payload["payload"]["request"].get("respondTo").is_none()); } - #[test] - fn update_requires_a_change() { + #[tokio::test] + async fn update_requires_a_change() { let error = build_update( - &Keys::generate(), + &Credentials::from_keys(Keys::generate()), &Keys::generate().public_key(), UpdateAgentDraft { channel_id: CHANNEL.into(), @@ -322,14 +334,15 @@ mod tests { respond_to: None, }, ) + .await .unwrap_err(); assert!(error.to_string().contains("at least one field")); } - #[test] - fn create_rejects_invalid_channel() { + #[tokio::test] + async fn create_rejects_invalid_channel() { let error = build_create( - &Keys::generate(), + &Credentials::from_keys(Keys::generate()), &Keys::generate().public_key(), CreateAgentDraft { channel_id: "general".into(), @@ -337,16 +350,17 @@ mod tests { system_prompt: "Help".into(), }, ) + .await .unwrap_err(); assert!(error.to_string().contains("invalid channel UUID")); } - #[test] - fn project_channel_request_is_owner_encrypted() { + #[tokio::test] + async fn project_channel_request_is_owner_encrypted() { let agent = Keys::generate(); let owner = Keys::generate(); let built = build_project_channel( - &agent, + &Credentials::from_keys(agent.clone()), &owner.public_key(), CreateProjectChannelDraft { home_channel_id: CHANNEL.into(), @@ -357,6 +371,7 @@ mod tests { template_name: Some("Release team".into()), }, ) + .await .unwrap(); let payload: serde_json::Value = decrypt_observer_payload(&owner, &built.event).unwrap(); diff --git a/crates/buzz-cli/src/cached_assertion.rs b/crates/buzz-cli/src/cached_assertion.rs new file mode 100644 index 00000000000..b3d0fcd962c --- /dev/null +++ b/crates/buzz-cli/src/cached_assertion.rs @@ -0,0 +1,135 @@ +//! The one cached NIP-FI assertion an evidence link holds for its relay, +//! shared by the headless adapter session and the Buzz desktop link: one +//! `exp` parser and one refresh rule. + +use tokio::sync::Mutex; + +use crate::error::CliError; + +/// Refresh at least this long before expiry. +const REFRESH_MARGIN_SECS: u64 = 30; + +/// An evidence link's current assertion, or its answer that it has none. +#[derive(Default)] +pub(crate) struct CachedAssertion(Mutex, u64)>>); + +impl CachedAssertion { + /// The cached answer until its refresh point, else `fetch`'s. A fetched + /// assertion must be a compact JWS with an `exp`; `None` is kept until + /// the next command. Concurrent callers share one fetch. + pub(crate) async fn get(&self, fetch: F) -> Result, CliError> + where + F: std::future::Future, CliError>>, + { + let mut cached = self.0.lock().await; + if let Some((assertion, refresh)) = cached.as_ref() { + if unix_now() < *refresh { + return Ok(assertion.clone()); + } + } + let assertion = fetch.await?; + let refresh = match assertion.as_deref() { + Some(jws) => refresh_at( + unix_now(), + jws_exp(jws).ok_or_else(|| { + CliError::Auth("the evidence source returned an unreadable assertion".into()) + })?, + ), + None => u64::MAX, + }; + *cached = Some((assertion.clone(), refresh)); + Ok(assertion) + } +} + +/// Refresh at the earlier of half-life and [`REFRESH_MARGIN_SECS`] before +/// `exp`; when that margin is already past, at half-life, so a short-lived +/// assertion is not fetched again on every request. +pub(crate) fn refresh_at(now: u64, exp: u64) -> u64 { + let half_life = now + exp.saturating_sub(now) / 2; + match exp.saturating_sub(REFRESH_MARGIN_SECS) { + early if early > now => early.min(half_life), + _ => half_life, + } +} + +/// The `exp` claim of a structurally valid compact JWS: three non-empty +/// unpadded base64url segments, a JSON-object header naming `alg`, and a +/// JSON-object payload with an integer `exp`. The relay verifies the +/// signature; the CLI only refuses output it could not present or refresh. +pub(crate) fn jws_exp(token: &str) -> Option { + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; + let mut segments = token.split('.'); + let (Some(header), Some(payload), Some(signature), None) = ( + segments.next(), + segments.next(), + segments.next(), + segments.next(), + ) else { + return None; + }; + let json = |segment: &str| -> Option> { + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(segment).ok()?).ok() + }; + if signature.is_empty() || URL_SAFE_NO_PAD.decode(signature).is_err() { + return None; + } + json(header)?.get("alg")?.as_str()?; + json(payload)?.get("exp")?.as_u64() +} + +pub(crate) fn unix_now() -> u64 { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + #[cfg(test)] + let now = test_clock::FROZEN.with(std::cell::Cell::get).unwrap_or(now) + + test_clock::SKEW.with(std::cell::Cell::get); + now +} + +/// A clock tests move forward instead of sleeping. Per thread, so it moves +/// only for the test (and its current-thread runtime) that advances it. +#[cfg(test)] +pub(crate) mod test_clock { + thread_local! { + pub(super) static FROZEN: std::cell::Cell> = const { std::cell::Cell::new(None) }; + pub(super) static SKEW: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + /// Pin this thread's clock to `at`, so reads on either side of a + /// wall-clock second boundary agree; `advance` still moves it. + pub(crate) fn freeze(at: u64) { + FROZEN.with(|frozen| frozen.set(Some(at))); + } + pub(crate) fn advance(secs: u64) { + SKEW.with(|skew| skew.set(skew.get() + secs)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refresh_is_at_the_earlier_of_half_life_and_the_margin() { + assert_eq!(refresh_at(1_000, 1_300), 1_150, "long-lived: half-life"); + assert_eq!(refresh_at(1_000, 1_060), 1_030); + assert_eq!(refresh_at(1_000, 1_040), 1_010, "short-lived: the margin"); + assert_eq!(refresh_at(1_000, 1_020), 1_010, "margin past: half-life"); + assert_eq!(refresh_at(1_000, 1_001), 1_000); + } + + #[test] + fn jws_exp_needs_a_compact_jws_with_alg_and_exp() { + let payload = "eyJleHAiOjE3OTAwMDAzMDB9"; // {"exp":1790000300} + let header = "eyJhbGciOiJFUzI1NiJ9"; // {"alg":"ES256"} + assert_eq!( + jws_exp(&format!("{header}.{payload}.c2ln")), + Some(1_790_000_300) + ); + assert_eq!(jws_exp(&format!("e30.{payload}.c2ln")), None, "no alg"); + assert_eq!(jws_exp(&format!("{header}.{payload}")), None); + assert_eq!(jws_exp(&format!("{header}.{payload}.c2ln.x")), None); + } +} diff --git a/crates/buzz-cli/src/client.rs b/crates/buzz-cli/src/client.rs index 28197f3923e..9749c0ece14 100644 --- a/crates/buzz-cli/src/client.rs +++ b/crates/buzz-cli/src/client.rs @@ -1,13 +1,20 @@ use std::future::Future; use std::time::Duration; -use base64::engine::general_purpose::STANDARD as B64; use base64::Engine; -use nostr::{EventBuilder, JsonUtil, Keys, Kind, Tag}; +use nostr::{EventBuilder, JsonUtil, Kind, PublicKey, Tag}; use sha2::{Digest, Sha256}; +use crate::credentials::{ + Credentials, FEDERATED_IDENTITY_ADAPTER_ENV, FEDERATED_IDENTITY_TOKEN_ENV, +}; use crate::error::CliError; +/// NIP-FI assertion header (`docs/nips/NIP-FI.md` §Client-attached transport). +const FEDERATED_IDENTITY_HEADER: &str = "Nostr-Federated-Identity"; +/// `User-Agent` sent on every WebSocket upgrade. +const USER_AGENT: &str = concat!("buzz-cli/", env!("CARGO_PKG_VERSION")); + /// Descriptor returned by the relay after a successful upload. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct BlobDescriptor { @@ -60,8 +67,9 @@ pub fn build_imeta_tag(d: &BlobDescriptor) -> Vec { tag } -/// MIME types accepted for upload. -const ALLOWED_MIMES: &[&str] = &[ +/// MIME types the relay stores as inline media; everything else is a generic +/// file it validates, stores and serves as a download. +const MEDIA_MIMES: &[&str] = &[ "image/jpeg", "image/png", "image/gif", @@ -75,39 +83,8 @@ const MAX_IMAGE_BYTES: u64 = 50 * 1024 * 1024; /// Maximum file size for video uploads (500 MB). const MAX_VIDEO_BYTES: u64 = 500 * 1024 * 1024; -/// Sign a NIP-98 HTTP auth event (kind:27235) and return the Authorization header value. -/// -/// The event includes: -/// - `u` tag: the full request URL -/// - `method` tag: HTTP method (GET, POST, PUT, DELETE) -/// - `payload` tag: SHA-256 hex of the request body (if present) -fn sign_nip98( - keys: &Keys, - method: &str, - url: &str, - body: Option<&[u8]>, -) -> Result { - let mut tags = vec![ - Tag::parse(["u", url]).map_err(|e| CliError::Other(format!("tag error: {e}")))?, - Tag::parse(["method", method]).map_err(|e| CliError::Other(format!("tag error: {e}")))?, - // Nonce prevents replay rejection for rapid-fire requests with identical bodies. - Tag::parse(["nonce", &uuid::Uuid::new_v4().to_string()]) - .map_err(|e| CliError::Other(format!("tag error: {e}")))?, - ]; - if let Some(b) = body { - let hash = hex::encode(Sha256::digest(b)); - tags.push( - Tag::parse(["payload", &hash]) - .map_err(|e| CliError::Other(format!("tag error: {e}")))?, - ); - } - let event = EventBuilder::new(Kind::Custom(27235), "") - .tags(tags) - .sign_with_keys(keys) - .map_err(|e| CliError::Other(format!("NIP-98 signing failed: {e}")))?; - let json = event.as_json(); - Ok(format!("Nostr {}", B64.encode(json.as_bytes()))) -} +/// Maximum file size for generic file uploads (100 MB), the relay's default. +const MAX_FILE_BYTES: u64 = 100 * 1024 * 1024; fn relay_server_tag(relay_url: &str) -> Option { let authority = buzz_core::tenant::relay_url_authority(relay_url); @@ -119,6 +96,14 @@ fn relay_server_tag(relay_url: &str) -> Option { } /// Maximum number of attempts per request (initial attempt + two retries). +/// The WebSocket connect and upgrade, before any NIP-42 wait. +const WS_CONNECT_TIMEOUT: Duration = Duration::from_secs(15); +/// Connections a WebSocket publish may open to complete NIP-42 sign-in. +const WS_SIGN_IN_ATTEMPTS: u32 = 3; +/// Times an HTTP proof is signed while its NIP-FI assertion keeps expiring. +const AUTHORIZE_ROUNDS: u32 = 3; +/// How old an HTTP proof may be when sent, well inside the relay's 60 s. +const PROOF_MAX_AGE_SECS: u64 = 30; const RETRY_MAX_ATTEMPTS: u32 = 3; /// Base sleep durations for full-jitter exponential backoff. @@ -252,7 +237,7 @@ fn is_safe_media_path_segment(sha256_ext: &str) -> bool { match segments.as_slice() { [hash] => is_lower_hex_sha256(hash), [hash, ext] => is_lower_hex_sha256(hash) && is_safe_media_ext(ext), - [hash, "thumb", "jpg"] => is_lower_hex_sha256(hash), + [hash, "thumb", "webp" | "jpg"] => is_lower_hex_sha256(hash), _ => false, } } @@ -284,7 +269,7 @@ fn media_url_from_input(relay_url: &str, input: &str) -> Result Result Result Result { - use base64::engine::general_purpose::URL_SAFE_NO_PAD; - use nostr::Timestamp; - - let now = Timestamp::now().as_secs(); - let exp_str = (now + 60).to_string(); - let domain = relay_server_tag(media_url) - .ok_or_else(|| CliError::Usage(format!("invalid media URL: {media_url}")))?; - let tags = vec![ - Tag::parse(["t", "get"]).map_err(|e| CliError::Other(e.to_string()))?, - Tag::parse(["expiration", &exp_str]).map_err(|e| CliError::Other(e.to_string()))?, - Tag::parse(["server", &domain]).map_err(|e| CliError::Other(e.to_string()))?, - ]; - - let auth_event = EventBuilder::new(Kind::from(24242), "Get media") - .tags(tags) - .sign_with_keys(keys) - .map_err(|e| CliError::Other(format!("signing failed: {e}")))?; - - Ok(format!( - "Nostr {}", - URL_SAFE_NO_PAD.encode(auth_event.as_json().as_bytes()) - )) +/// Blossom (BUD-01) `t=get` proof for `media_url`, scoped to its server. +fn blossom_get_event(media_url: &str) -> Result { + blossom_event( + "get", + None, + relay_server_tag(media_url) + .ok_or_else(|| CliError::Usage(format!("invalid media URL: {media_url}")))?, + "Get media", + ) } -fn sign_blossom_upload( - keys: &Keys, - sha256: &str, - _mime: &str, - relay_url: &str, -) -> Result { - use base64::engine::general_purpose::URL_SAFE_NO_PAD; - use nostr::Timestamp; - - let now = Timestamp::now().as_secs(); - let exp_str = (now + 60).to_string(); - let domain = relay_server_tag(relay_url) - .ok_or_else(|| CliError::Usage(format!("invalid relay URL: {relay_url}")))?; - - let tags = vec![ - Tag::parse(["t", "upload"]).map_err(|e| CliError::Other(e.to_string()))?, - Tag::parse(["x", sha256]).map_err(|e| CliError::Other(e.to_string()))?, - Tag::parse(["expiration", &exp_str]).map_err(|e| CliError::Other(e.to_string()))?, - Tag::parse(["server", &domain]).map_err(|e| CliError::Other(e.to_string()))?, - ]; - - let auth_event = EventBuilder::new(Kind::from(24242), "Upload file") - .tags(tags) - .sign_with_keys(keys) - .map_err(|e| CliError::Other(format!("signing failed: {e}")))?; +/// Blossom (BUD-02) `t=upload` proof for blob `sha256` on this relay. +fn blossom_upload_event(sha256: &str, relay_url: &str) -> Result { + blossom_event( + "upload", + Some(sha256), + relay_server_tag(relay_url) + .ok_or_else(|| CliError::Usage(format!("invalid relay URL: {relay_url}")))?, + "Upload file", + ) +} - Ok(format!( - "Nostr {}", - URL_SAFE_NO_PAD.encode(auth_event.as_json().as_bytes()) - )) +fn blossom_event( + verb: &str, + sha256: Option<&str>, + server: String, + content: &str, +) -> Result { + let exp = (nostr::Timestamp::now().as_secs() + 60).to_string(); + let tag = |parts: &[&str]| { + Tag::parse(parts.iter().copied()).map_err(|e| CliError::Other(e.to_string())) + }; + let mut tags = vec![tag(&["t", verb])?]; + if let Some(sha256) = sha256 { + tags.push(tag(&["x", sha256])?); + } + tags.push(tag(&["expiration", &exp])?); + tags.push(tag(&["server", &server])?); + Ok(EventBuilder::new(Kind::from(24242), content).tags(tags)) } #[cfg(test)] @@ -446,19 +415,12 @@ mod media_download_tests { #[test] fn media_get_auth_header_is_server_scoped() { - let keys = Keys::generate(); + let keys = nostr::Keys::generate(); let hash = "a".repeat(64); - let header = sign_blossom_get( - &keys, - &format!("https://relay.example:443/media/{hash}.jpg"), - ) - .unwrap(); - let encoded = header.strip_prefix("Nostr ").unwrap(); - let json = base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(encoded) + let event = blossom_get_event(&format!("https://relay.example:443/media/{hash}.jpg")) + .unwrap() + .sign_with_keys(&keys) .unwrap(); - let event = nostr::Event::from_json(std::str::from_utf8(&json).unwrap()).unwrap(); - event.verify().unwrap(); assert_eq!(event.kind, Kind::from(24242)); let tags: Vec> = event @@ -490,8 +452,21 @@ mod media_download_tests { } } -const QUERY_PAGE_SIZE: u32 = 500; +pub(crate) const QUERY_PAGE_SIZE: u32 = 500; + +/// The most pages one limited query reads before failing, so a relay that +/// never runs out of events to skip cannot keep a command running forever. +pub(crate) const MAX_QUERY_PAGES: usize = 100; + +fn stalled_query(detail: &str) -> CliError { + CliError::Relay { + status: 200, + body: format!("query pagination stopped: {detail}"), + } +} +/// Move the composite cursor to the page's last event, failing unless it +/// lands strictly older than the current cursor. fn advance_query_cursor( filter: &mut serde_json::Value, page: &[serde_json::Value], @@ -508,19 +483,67 @@ fn advance_query_cursor( .and_then(serde_json::Value::as_str) .filter(|id| id.len() == 64 && id.chars().all(|c| c.is_ascii_hexdigit())) .ok_or_else(|| CliError::Other("query event missing valid id".into()))?; + if let (Some(until), Some(before_id)) = ( + filter.get("until").and_then(serde_json::Value::as_u64), + filter.get("before_id").and_then(serde_json::Value::as_str), + ) { + // The relay pages newest first, equal timestamps by ascending id: + // the next page lies at `created_at < until`, or at `until` past `before_id`. + let older = created_at < until + || (created_at == until && id.to_ascii_lowercase() > before_id.to_ascii_lowercase()); + if !older { + return Err(stalled_query( + "the relay did not move the cursor to older events", + )); + } + } filter["until"] = serde_json::json!(created_at); filter["before_id"] = serde_json::json!(id); Ok(()) } +/// How a protected relay request proves key possession in `Authorization`. +enum Proof<'a> { + /// NIP-98 over the request method, URL and body. + Nip98 { + method: &'a str, + url: &'a str, + body: Option<&'a [u8]>, + }, + /// Blossom kind-24242 upload proof for blob `sha256`. + BlossomUpload { sha256: &'a str }, + /// Blossom kind-24242 read proof for `url`. + BlossomGet { url: &'a str }, +} + +impl<'a> Proof<'a> { + fn post(url: &'a str, body: &'a [u8]) -> Self { + Self::Nip98 { + method: "POST", + url, + body: Some(body), + } + } +} + pub struct BuzzClient { http: reqwest::Client, relay_url: String, // base URL, no trailing slash, e.g. "https://relay.buzz.place" - keys: Keys, - /// Optional NIP-OA auth tag injected into every signed event. - auth_tag: Option, - /// Raw JSON of the auth tag for the `x-auth-tag` HTTP header. - auth_tag_json: Option, + /// The configured URL as a WebSocket URL, path and trailing slash kept, + /// as NIP-42 AUTH must name it. + ws_url: String, + /// Identity, signer, NIP-OA auth tag and NIP-FI evidence source. + credentials: Credentials, + /// Whether any request has carried a NIP-FI assertion, for error hints. + assertion_sent: std::sync::atomic::AtomicBool, +} + +/// A credential header value, marked sensitive so `Debug` output redacts it. +fn sensitive(value: String) -> Result { + let mut value = reqwest::header::HeaderValue::try_from(value) + .map_err(|_| CliError::Auth("credential is not a valid header value".into()))?; + value.set_sensitive(true); + Ok(value) } impl BuzzClient { @@ -533,29 +556,34 @@ impl BuzzClient { /// - `BUZZ_TIMEOUT_SECS` — per-request total timeout (default 30 s) /// /// A value of zero for either variable is treated as invalid and falls back to the default. - pub fn new( - relay_url: String, - keys: Keys, - auth_tag: Option, - auth_tag_json: Option, - ) -> Result { + /// A client for the relay at `relay_url`, as configured. + pub fn new(relay_url: String, credentials: Credentials) -> Result { let http = reqwest::Client::builder() + // Never replay credentials to a redirect target: reqwest strips + // `Authorization` across origins but not `x-auth-tag` or the + // NIP-FI assertion. A 3xx surfaces as a relay error instead. + .redirect(reqwest::redirect::Policy::none()) .timeout(env_duration_secs("BUZZ_TIMEOUT_SECS", 30)) .connect_timeout(env_duration_secs("BUZZ_CONNECT_TIMEOUT_SECS", 15)) .build() .map_err(|e| CliError::Other(e.to_string()))?; Ok(Self { http, - relay_url, - keys, - auth_tag, - auth_tag_json, + ws_url: to_ws_url(&relay_url), + relay_url: normalize_relay_url(&relay_url), + credentials, + assertion_sent: Default::default(), }) } - /// Get the keypair. - pub fn keys(&self) -> &Keys { - &self.keys + /// The public key this client acts as. + pub fn public_key(&self) -> PublicKey { + self.credentials.public_key() + } + + /// The credentials this client acts with. + pub fn credentials(&self) -> &Credentials { + &self.credentials } /// Get the relay base URL. @@ -569,9 +597,9 @@ impl BuzzClient { /// The auth tag is `["auth", owner_pubkey, conditions, sig]`; the /// owner pubkey lives at index 1. pub fn auth_tag_owner_hex(&self) -> Option { - self.auth_tag - .as_ref() - .map(|t| t.as_slice()) + self.credentials + .auth_tag() + .map(|t| t.tag.as_slice()) .and_then(|slice| slice.get(1).cloned()) } @@ -580,23 +608,21 @@ impl BuzzClient { /// All event creation should go through this method to ensure consistent /// auth tag injection. Callers MUST NOT add `auth` tags to the builder /// before calling this method. - pub fn sign_event(&self, builder: EventBuilder) -> Result { - let builder = if let Some(ref tag) = self.auth_tag { - builder.tags([tag.clone()]) - } else { - builder + pub async fn sign_event(&self, builder: EventBuilder) -> Result { + let auth_tag = self.credentials.auth_tag(); + let builder = match auth_tag { + Some(tag) => builder.tags([tag.tag.clone()]), + None => builder, }; - let event = builder - .sign_with_keys(&self.keys) - .map_err(|e| CliError::Other(format!("signing failed: {e}")))?; + let event = self.credentials.sign(builder).await?; - // Enforce: auth tags may only come from self.auth_tag injection. + // Enforce: auth tags may only come from the credentials' auth tag. let auth_count = event .tags .iter() .filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("auth")) .count(); - let expected = if self.auth_tag.is_some() { 1 } else { 0 }; + let expected = if auth_tag.is_some() { 1 } else { 0 }; if auth_count != expected { return Err(CliError::Other(format!( "event has {auth_count} auth tags — expected {expected}; \ @@ -607,11 +633,137 @@ impl BuzzClient { Ok(event) } - /// Attach the `x-auth-tag` header if configured (NIP-OA relay membership delegation). - fn with_auth_tag(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder { - match self.auth_tag_json { - Some(ref json) => req.header("x-auth-tag", json), - None => req, + /// The one place protected relay requests get their credentials: + /// `proof` in `Authorization`, the NIP-OA `x-auth-tag` (relay membership + /// delegation) when configured, and the NIP-FI `Nostr-Federated-Identity` + /// assertion when an evidence source is configured. Called once per + /// attempt so every retry carries a fresh proof. + async fn authorize( + &self, + req: reqwest::RequestBuilder, + proof: Proof<'_>, + ) -> Result { + // Evidence first: a refresh may wait out adapter retries, and the + // proof must be signed after it, just before sending, to stay fresh. + // Signing may wait out throttling in turn, so evidence that is due + // for refresh by then is fetched again, and the proof re-signed when + // the assertion changed or that fetch aged the proof. + let mut assertion = self.evidence().await?; + let mut round = 1; + let authorization = loop { + // The proof is dated before signing, which may be held for long. + let signed_at = crate::cached_assertion::unix_now(); + let authorization = self.proof(&proof).await?; + let current = self.evidence().await?; + let age = crate::cached_assertion::unix_now().saturating_sub(signed_at); + if current == assertion && age < PROOF_MAX_AGE_SECS { + break authorization; + } + if round == AUTHORIZE_ROUNDS { + return Err(CliError::Unavailable( + "the NIP-FI assertion kept expiring while the proof was signed".into(), + )); + } + (assertion, round) = (current, round + 1); + }; + let mut req = req.header(reqwest::header::AUTHORIZATION, sensitive(authorization)?); + if let Some(tag) = self.credentials.auth_tag() { + req = req.header("x-auth-tag", sensitive(tag.json.clone())?); + } + if let Some(assertion) = assertion { + req = req.header( + FEDERATED_IDENTITY_HEADER, + sensitive(format!("Bearer {assertion}"))?, + ); + } + Ok(req) + } + + /// `proof`, signed now, as an `Authorization` value. + async fn proof(&self, proof: &Proof<'_>) -> Result { + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + Ok(match *proof { + Proof::Nip98 { method, url, body } => { + format!("Nostr {}", self.credentials.nip98(method, url, body).await?) + } + Proof::BlossomUpload { sha256 } => { + let event = self + .credentials + .sign(blossom_upload_event(sha256, &self.relay_url)?) + .await?; + format!( + "Nostr {}", + URL_SAFE_NO_PAD.encode(event.as_json().as_bytes()) + ) + } + Proof::BlossomGet { url } => { + let event = self.credentials.sign(blossom_get_event(url)?).await?; + format!( + "Nostr {}", + URL_SAFE_NO_PAD.encode(event.as_json().as_bytes()) + ) + } + }) + } + + /// The WebSocket upgrade headers: the CLI's `User-Agent`, and the NIP-FI + /// assertion when there is an evidence source. + async fn upgrade_headers(&self) -> Result { + let mut headers = buzz_ws_client::HeaderMap::new(); + headers.insert( + "user-agent", + buzz_ws_client::HeaderValue::from_static(USER_AGENT), + ); + if let Some(assertion) = self.evidence().await? { + let mut value = + buzz_ws_client::HeaderValue::from_str(&format!("Bearer {assertion}")) + .map_err(|_| CliError::Auth("assertion is not a valid header value".into()))?; + value.set_sensitive(true); + headers.insert(FEDERATED_IDENTITY_HEADER, value); + } + Ok(headers) + } + + /// The NIP-FI assertion for this relay, noting that one was sent. + async fn evidence(&self) -> Result, CliError> { + let assertion = self.credentials.evidence().await?; + if assertion.is_some() { + self.assertion_sent + .store(true, std::sync::atomic::Ordering::Relaxed); + } + Ok(assertion) + } + + /// Map a non-2xx relay response to a `CliError`. + /// + /// The relay's `{"error": …}` / `{"message": …}` field becomes the + /// message. A 401 without a NIP-FI evidence source names the settings, + /// since an enforcing relay answers every request that way. + fn relay_error(&self, status: u16, body: String) -> CliError { + let message = extract_relay_message_field(&body).unwrap_or(body); + let message = message.trim_end().to_owned(); + let sent = self + .assertion_sent + .load(std::sync::atomic::Ordering::Relaxed); + let desktop = self.credentials.is_desktop(); + if status == 401 && !sent && desktop { + return CliError::Auth(format!( + "relay requires authentication ({message}); if it enforces federated identity \ + (NIP-FI), the Buzz desktop has no assertion for this relay: sign in to this \ + community in Buzz, then retry" + )); + } + if status == 401 && !sent && !self.credentials.has_evidence_source() { + return CliError::Auth(format!( + "relay requires authentication ({message}); if it enforces federated identity \ + (NIP-FI), set {FEDERATED_IDENTITY_TOKEN_ENV} to your own NIP-FA sign-in session \ + (a human session for this key, not an agent grant) and \ + {FEDERATED_IDENTITY_ADAPTER_ENV} to its adapter, which mints the assertion" + )); + } + CliError::Relay { + status, + body: message, } } @@ -676,16 +828,38 @@ impl BuzzClient { } async fn query_pages( + &self, + filter: serde_json::Value, + limit: Option, + ) -> Result, CliError> { + self.query_pages_keeping(filter, limit, None).await + } + + /// Like `query_pages`, but with `keep`, only events it accepts count + /// toward `limit`: paging continues past the ones it drops, always in + /// full pages, for at most `MAX_QUERY_PAGES` pages. + async fn query_pages_keeping( &self, mut filter: serde_json::Value, limit: Option, + keep: Option<&dyn Fn(&serde_json::Value) -> bool>, ) -> Result, CliError> { let mut events = Vec::new(); + let mut pages = 0; while limit.is_none_or(|limit| events.len() < limit as usize) { - let page_limit = limit - .map(|limit| (limit as usize - events.len()).min(QUERY_PAGE_SIZE as usize)) - .unwrap_or(QUERY_PAGE_SIZE as usize); + if keep.is_some() && pages == MAX_QUERY_PAGES { + return Err(stalled_query(&format!( + "read {MAX_QUERY_PAGES} pages without reaching the end of the results" + ))); + } + pages += 1; + let page_limit = match (limit, keep) { + (Some(limit), None) => { + (limit as usize - events.len()).min(QUERY_PAGE_SIZE as usize) + } + _ => QUERY_PAGE_SIZE as usize, + }; filter["limit"] = serde_json::json!(page_limit); let raw = self.query(&filter).await?; @@ -696,15 +870,30 @@ impl BuzzClient { if !done { advance_query_cursor(&mut filter, &page)?; } - events.extend(page); + events.extend(page.into_iter().filter(|e| keep.is_none_or(|keep| keep(e)))); if done { break; } } + if let Some(limit) = limit { + events.truncate(limit as usize); + } Ok(events) } + /// Query up to `limit` historical events that `keep` accepts, paging past + /// the rest until the limit is met or the history runs out. + pub async fn query_paginated_keeping( + &self, + filter: serde_json::Value, + limit: u32, + keep: impl Fn(&serde_json::Value) -> bool, + ) -> Result, CliError> { + self.query_pages_keeping(filter, Some(limit), Some(&keep)) + .await + } + /// Query up to `limit` historical events, following the relay bridge's /// composite `(until, before_id)` cursor across bounded result pages. pub async fn query_paginated( @@ -750,16 +939,17 @@ impl BuzzClient { /// Used only for NIP-IA identity archive/unarchive requests (kind /// 9035/9036), whose optional `auth` tag is a *content-level* /// owner-of-agent attestation about the *target* identity — unrelated to - /// this client's own NIP-OA membership delegation (`self.auth_tag`, + /// this client's own NIP-OA membership delegation (the credentials' auth tag, /// which [`sign_event`] injects into every other event and which /// `submit_event` separately attaches via the `x-auth-tag` HTTP header). /// Routing an identity archive request through `sign_event` would either /// silently drop the caller's owner attestation or double up an /// unrelated tag. - pub fn sign_event_unchecked(&self, builder: EventBuilder) -> Result { - builder - .sign_with_keys(&self.keys) - .map_err(|e| CliError::Other(format!("signing failed: {e}"))) + pub async fn sign_event_unchecked( + &self, + builder: EventBuilder, + ) -> Result { + self.credentials.sign(builder).await } /// GET a public, unauthenticated relay endpoint (e.g. the NIP-11 `/info` @@ -796,17 +986,16 @@ impl BuzzClient { let body = body.clone(); let url = url.clone(); async move { - let auth = sign_nip98(&self.keys, "POST", &url, Some(&body))?; - let resp = self - .with_auth_tag( + let req = self + .authorize( self.http .post(&url) - .header("Authorization", auth) .header("Content-Type", "application/json") - .body(body), + .body(body.clone()), + Proof::post(&url, &body), ) - .send() .await?; + let resp = req.send().await?; self.handle_response(resp).await } }) @@ -826,17 +1015,16 @@ impl BuzzClient { let body = body.clone(); let url = url.clone(); async move { - let auth = sign_nip98(&self.keys, "POST", &url, Some(&body))?; - let resp = self - .with_auth_tag( + let req = self + .authorize( self.http .post(&url) - .header("Authorization", auth) .header("Content-Type", "application/json") - .body(body), + .body(body.clone()), + Proof::post(&url, &body), ) - .send() .await?; + let resp = req.send().await?; self.handle_response(resp).await } }) @@ -854,11 +1042,17 @@ impl BuzzClient { self.with_retry_body(|| { let url = url.clone(); async move { - let auth = sign_nip98(&self.keys, "GET", &url, None)?; - let resp = self - .with_auth_tag(self.http.get(&url).header("Authorization", auth)) - .send() + let req = self + .authorize( + self.http.get(&url), + Proof::Nip98 { + method: "GET", + url: &url, + body: None, + }, + ) .await?; + let resp = req.send().await?; self.handle_response(resp).await } }) @@ -884,17 +1078,16 @@ impl BuzzClient { let body_bytes = body_bytes.clone(); let url = url.clone(); async move { - let auth = sign_nip98(&self.keys, "POST", &url, Some(&body_bytes))?; - let resp = self - .with_auth_tag( + let req = self + .authorize( self.http .post(&url) - .header("Authorization", auth) .header("Content-Type", "application/json") - .body(body_bytes), + .body(body_bytes.clone()), + Proof::post(&url, &body_bytes), ) - .send() .await?; + let resp = req.send().await?; // 204 No Content: return empty string rather than failing on // an empty body that cannot be parsed as JSON. if resp.status() == reqwest::StatusCode::NO_CONTENT { @@ -915,29 +1108,27 @@ impl BuzzClient { ) -> Result { let url = format!("{}{path}", self.relay_url); let body = serde_json::to_vec(body).map_err(|e| CliError::Other(e.to_string()))?; - let auth = sign_nip98(&self.keys, "POST", &url, Some(&body))?; let unknown = |detail: String| CliError::DeliveryUnknown(detail); let http = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .timeout(env_duration_secs("BUZZ_TIMEOUT_SECS", 30)) .connect_timeout(env_duration_secs("BUZZ_CONNECT_TIMEOUT_SECS", 15)) .build()?; - let response = self - .with_auth_tag( + let req = self + .authorize( http.post(&url) - .header("Authorization", auth) .header("Content-Type", "application/json") - .body(body), + .body(body.clone()), + Proof::post(&url, &body), ) - .send() - .await - .map_err(|e| { - if e.is_connect() || e.is_builder() { - CliError::Network(e) - } else { - unknown(e.to_string()) - } - })?; + .await?; + let response = req.send().await.map_err(|e| { + if e.is_connect() || e.is_builder() { + CliError::Network(e) + } else { + unknown(e.to_string()) + } + })?; let status = response.status(); let body = response.text().await.map_err(|e| unknown(e.to_string()))?; let message = extract_relay_message_field(&body).unwrap_or_else(|| body.clone()); @@ -948,10 +1139,7 @@ impl BuzzClient { return Err(unknown(format!("HTTP {}: {message}", status.as_u16()))); } if !status.is_success() { - return Err(CliError::Relay { - status: status.as_u16(), - body: message, - }); + return Err(self.relay_error(status.as_u16(), body)); } Ok(body) } @@ -989,18 +1177,17 @@ impl BuzzClient { // Re-sign NIP-98 each attempt: the nonce tag generates a fresh // event ID, keeping retries safe against the relay's replay guard. - let auth = sign_nip98(&self.keys, "POST", &url, Some(&body))?; - let send_result: Result = self - .with_auth_tag( + let req = self + .authorize( self.http .post(&url) - .header("Authorization", auth) .header("Content-Type", "application/json") .body(body.clone()), + Proof::post(&url, &body), ) - .send() - .await - .map_err(CliError::from); + .await?; + let send_result: Result = + req.send().await.map_err(CliError::from); match send_result { Err(e) => { @@ -1086,26 +1273,7 @@ impl BuzzClient { })?; // Map the body through handle_response's error logic inline. if !resp_was_success(status) { - let message = serde_json::from_str::(&body_text) - .ok() - .and_then(|v| { - v.get("error") - .or_else(|| v.get("message")) - .and_then(|m| m.as_str()) - .map(str::to_string) - }) - .unwrap_or(body_text); - let message = if status == 403 && std::env::var("BUZZ_AUTH_TAG").is_ok() { - format!( - "{message} (BUZZ_AUTH_TAG is set — it may be stale or revoked; try unsetting it)" - ) - } else { - message - }; - return Err(CliError::Relay { - status, - body: message, - }); + return Err(self.relay_error(status, body_text)); } return Ok(body_text); } @@ -1134,25 +1302,36 @@ impl BuzzClient { serde_json::to_vec(&event) .map_err(|e| CliError::Other(format!("event serialization failed: {e}")))?, ); + // Whether any attempt reached the relay without an authoritative + // answer. A later failure, even one before sending, cannot clear it. + let maybe_delivered = std::sync::atomic::AtomicBool::new(false); let result = self .with_retry_body(|| { let body = body.clone(); let url = url.clone(); + let maybe_delivered = &maybe_delivered; async move { // Re-sign NIP-98 each attempt: the nonce tag generates a fresh // event ID, keeping retries safe against the relay's replay guard. - let auth = sign_nip98(&self.keys, "POST", &url, Some(&body))?; - let resp = self - .with_auth_tag( + let req = self + .authorize( self.http .post(&url) - .header("Authorization", auth) .header("Content-Type", "application/json") - .body(body), + .body(body.clone()), + Proof::post(&url, &body), ) - .send() .await?; - self.handle_response(resp).await + let sent = match req.send().await { + Ok(resp) => self.handle_response(resp).await, + Err(e) => Err(e.into()), + }; + if let Err(ref e) = sent { + if is_stored_event_exhaustion_ambiguous(e) { + maybe_delivered.store(true, std::sync::atomic::Ordering::Relaxed); + } + } + sent } }) .await; @@ -1162,7 +1341,13 @@ impl BuzzClient { // Connect failures stay Network (retryable:true) — definitively never received. // Canonical pre-ingest 429 (Relay{429}) stays retryable — definitively not stored. if let Err(ref e) = result { - if is_stored_event_exhaustion_ambiguous(e) { + // Once an attempt may have been stored, no later answer settles + // the outcome, except a canvas 409, which the canvas command + // resolves by looking the canvas up. + let settled = matches!(e, CliError::Relay { status: 409, body } if body.contains("canvas changed")); + if is_stored_event_exhaustion_ambiguous(e) + || (maybe_delivered.load(std::sync::atomic::Ordering::Relaxed) && !settled) + { let kind_u16 = event.kind.as_u16(); return Err(CliError::DeliveryUnknown(format!( "stored event (kind {kind_u16}) outcome unknown after all attempts: {e}" @@ -1179,15 +1364,70 @@ impl BuzzClient { /// `buzz_ws_client::publish_event` which handles connect, NIP-42 auth, /// EVENT send, OK wait, and graceful close. pub async fn publish_ephemeral_event(&self, event: nostr::Event) -> Result { - let ws_url = to_ws_url(&self.relay_url); - // Hard cap — inner wait ceilings sum to 70 s; connect time and network RTT are - // additional overhead absorbed by this budget. - // See buzz_ws_client::{AUTH_CHALLENGE_TIMEOUT_SECS, AUTH_OK_TIMEOUT_SECS, - // PUBLISH_OK_TIMEOUT_SECS} for the inner ceilings. - let ok = - buzz_ws_client::publish_event(&ws_url, event, &self.keys, self.auth_tag.as_ref(), 75) - .await - .map_err(|e| CliError::Other(e.to_string()))?; + let ws_url = &self.ws_url; + // Two kinds of deadline: each network phase is capped as a whole, + // writes included (the connect below, then buzz_ws_client's challenge, + // AUTH, EVENT and close phases), and NIP-42 signing between them is + // bounded by the signer itself. A + // desktop provider may wait out throttling and hold `sign_event` for a + // person's decision, which no relay budget should cut short. + let signer = crate::credentials::CapturingSigner::new(&self.credentials); + let ws_error = |e: buzz_ws_client::WsClientError| match e.upgrade_rejection() { + // A denial decided on the upgrade is an HTTP response (NIP-FI). + Some((status, body)) => self.relay_error(status, body), + // A post-upgrade denial (e.g. a NIP-FI key mismatch) is a 1008 close. + None if matches!(e, buzz_ws_client::WsClientError::PolicyClose(_)) => { + CliError::Auth(e.to_string()) + } + None => CliError::Other(e.to_string()), + }; + // + // The relay closes a socket that has not signed in within seconds, + // so a slow or throttled sign-in signature reconnects and signs the + // new challenge, a bounded number of times, with current evidence: + // the old assertion may have expired meanwhile. A throttled sign-in + // is waited out between connections, never on one. EVENT, signed + // before any of this, is sent only once AUTH succeeds. + let mut attempt = 1; + let mut conn = loop { + let headers = self.upgrade_headers().await?; + let mut conn = tokio::time::timeout( + WS_CONNECT_TIMEOUT, + buzz_ws_client::NostrWsConnection::connect_with_headers(ws_url, headers), + ) + .await + .map_err(|_| CliError::Other("relay WebSocket connect timed out".into()))? + .map_err(ws_error)?; + let signed_in = conn + .authenticate(&signer, self.credentials.auth_tag().map(|t| &t.tag)) + .await; + let Err(e) = signed_in else { break conn }; + let failure = signer.take_failure(); + let lost = matches!( + e, + buzz_ws_client::WsClientError::ConnectionClosed + | buzz_ws_client::WsClientError::WebSocket(_) + ); + let (failure, wait) = failure.unzip(); + let wait = wait.flatten(); + let throttled = matches!(failure, Some(CliError::Throttled(_))); + let _ = conn.disconnect().await; + if !(lost || throttled) { + return Err(failure.unwrap_or_else(|| ws_error(e))); + } + if attempt == WS_SIGN_IN_ATTEMPTS { + return Err(failure.unwrap_or_else(|| { + CliError::Unavailable(format!( + "the relay closed the WebSocket before sign-in completed, \ + {WS_SIGN_IN_ATTEMPTS} times: {e}" + )) + })); + } + tokio::time::sleep(wait.unwrap_or_else(|| jitter_delay(attempt - 1))).await; + attempt += 1; + }; + let ok = conn.send_event(event).await.map_err(ws_error)?; + let _ = conn.disconnect().await; if !ok.accepted { return Err(CliError::Relay { @@ -1208,28 +1448,26 @@ impl BuzzClient { pub async fn upload_file(&self, file_path: &str) -> Result { // 1. Read file — validate it exists and is a regular file let metadata = std::fs::metadata(file_path) - .map_err(|e| CliError::Other(format!("cannot access {file_path}: {e}")))?; + .map_err(|e| CliError::Usage(format!("cannot access {file_path}: {e}")))?; if !metadata.is_file() { return Err(CliError::Usage(format!("{file_path} is not a file"))); } let bytes = std::fs::read(file_path) - .map_err(|e| CliError::Other(format!("failed to read {file_path}: {e}")))?; + .map_err(|e| CliError::Usage(format!("failed to read {file_path}: {e}")))?; // 2. Detect MIME from magic bytes let mime = infer::get(&bytes) .map(|t| t.mime_type().to_string()) .unwrap_or_else(|| "application/octet-stream".to_string()); - if !ALLOWED_MIMES.contains(&mime.as_str()) { - return Err(CliError::Usage(format!("unsupported file type: {mime}"))); - } - - // 3. Size check - let max = if mime.starts_with("video/") { + // 3. Size check. The relay decides which other types it accepts. + let max = if mime == "video/mp4" { MAX_VIDEO_BYTES - } else { + } else if MEDIA_MIMES.contains(&mime.as_str()) { MAX_IMAGE_BYTES + } else { + MAX_FILE_BYTES }; if bytes.len() as u64 > max { return Err(CliError::Usage(format!( @@ -1244,7 +1482,7 @@ impl BuzzClient { // 5. PUT request to the BUD-02 /upload endpoint with a generous timeout. // Auth is signed per attempt — matches the per-attempt signing pattern in download_media. - let upload_timeout = if mime.starts_with("video/") { + let upload_timeout = if max > MAX_IMAGE_BYTES { Duration::from_secs(600) } else { Duration::from_secs(120) @@ -1262,25 +1500,23 @@ impl BuzzClient { let mime = mime.clone(); let sha256 = sha256.clone(); async move { - let auth_header = - sign_blossom_upload(&self.keys, &sha256, &mime, &self.relay_url)?; - let resp = self - .with_auth_tag( + let req = self + .authorize( self.http .put(&url) .timeout(upload_timeout) - .header("Authorization", auth_header) .header("Content-Type", &mime) .header("X-SHA-256", &sha256) .body(upload_body), + Proof::BlossomUpload { sha256: &sha256 }, ) - .send() .await?; + let resp = req.send().await?; let status = resp.status(); if !status.is_success() { let s = status.as_u16(); let body = resp.text().await.unwrap_or_default(); - return Err(CliError::Relay { status: s, body }); + return Err(self.relay_error(s, body)); } resp.json::().await.map_err(CliError::from) } @@ -1309,23 +1545,22 @@ impl BuzzClient { let mime = mime.clone(); let sha256 = sha256.clone(); async move { - let auth_header = sign_blossom_upload(&self.keys, &sha256, &mime, &self.relay_url)?; - let resp = self - .with_auth_tag( + let req = self + .authorize( self.http .put(&legacy_url) .timeout(upload_timeout) - .header("Authorization", auth_header) .header("Content-Type", &mime) .header("X-SHA-256", &sha256) .body(upload_body), + Proof::BlossomUpload { sha256: &sha256 }, ) - .send() .await?; + let resp = req.send().await?; if !resp.status().is_success() { let status = resp.status().as_u16(); let body = resp.text().await.unwrap_or_default(); - return Err(CliError::Relay { status, body }); + return Err(self.relay_error(status, body)); } resp.json::().await.map_err(CliError::from) } @@ -1347,15 +1582,14 @@ impl BuzzClient { let url = url.clone(); let client = client.clone(); async move { - let auth_header = sign_blossom_get(&self.keys, &url)?; - let resp = self - .with_auth_tag(client.get(&url).header("Authorization", auth_header)) - .send() + let req = self + .authorize(client.get(&url), Proof::BlossomGet { url: &url }) .await?; + let resp = req.send().await?; if !resp.status().is_success() { let status = resp.status().as_u16(); let body = resp.text().await.unwrap_or_default(); - return Err(CliError::Relay { status, body }); + return Err(self.relay_error(status, body)); } resp.bytes().await.map_err(CliError::Network) } @@ -1367,28 +1601,7 @@ impl BuzzClient { if !resp.status().is_success() { let status = resp.status().as_u16(); let body = resp.text().await.unwrap_or_default(); - let message = serde_json::from_str::(&body) - .ok() - .and_then(|v| { - v.get("error") - .or_else(|| v.get("message")) - .and_then(|m| m.as_str()) - .map(|s| s.to_string()) - }) - .unwrap_or(body); - if status == 403 && std::env::var("BUZZ_AUTH_TAG").is_ok() { - let message = format!( - "{message} (BUZZ_AUTH_TAG is set — it may be stale or revoked; try unsetting it)" - ); - return Err(CliError::Relay { - status, - body: message, - }); - } - return Err(CliError::Relay { - status, - body: message, - }); + return Err(self.relay_error(status, body)); } Ok(resp.text().await?) } @@ -1754,8 +1967,15 @@ mod retry_policy_tests { } fn test_client(base_url: &str) -> BuzzClient { - let keys = Keys::generate(); - BuzzClient::new(base_url.to_string(), keys, None, None).unwrap() + BuzzClient::new( + base_url.to_string(), + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap() + } + + fn client_keys(client: &BuzzClient) -> Keys { + client.credentials().test_keys() } fn make_moderation_event(keys: &Keys, kind: u16) -> nostr::Event { @@ -1783,7 +2003,7 @@ mod retry_policy_tests { }) .await; let client = test_client(&url); - let event = make_moderation_event(client.keys(), 9040); + let event = make_moderation_event(&client_keys(&client), 9040); let err = client.submit_event(event).await.unwrap_err(); assert!( matches!(err, CliError::DeliveryUnknown(_)), @@ -1823,7 +2043,7 @@ mod retry_policy_tests { }) .await; let client = test_client(&url); - let event = make_moderation_event(client.keys(), 9041); + let event = make_moderation_event(&client_keys(&client), 9041); let t0 = std::time::Instant::now(); let result = client.submit_event(event).await; let elapsed = t0.elapsed(); @@ -1856,7 +2076,7 @@ mod retry_policy_tests { }) .await; let client = test_client(&url); - let event = make_moderation_event(client.keys(), 9040); + let event = make_moderation_event(&client_keys(&client), 9040); let err = client.submit_event(event).await.unwrap_err(); // Must be Relay(429), not DeliveryUnknown. @@ -1884,7 +2104,7 @@ mod retry_policy_tests { let (url, attempts) = test_server(|_n| (StatusCode::BAD_GATEWAY, "bad gateway".to_string())).await; let client = test_client(&url); - let event = make_moderation_event(client.keys(), 9042); + let event = make_moderation_event(&client_keys(&client), 9042); let err = client.submit_event(event).await.unwrap_err(); assert!( matches!(err, CliError::DeliveryUnknown(_)), @@ -1912,7 +2132,7 @@ mod retry_policy_tests { let base = format!("http://{addr}"); let client = test_client(&base); - let event = make_moderation_event(client.keys(), 9040); + let event = make_moderation_event(&client_keys(&client), 9040); let err = client.submit_event(event).await.unwrap_err(); // Must be Network (retryable), not DeliveryUnknown (retryable:false). assert!( @@ -1943,7 +2163,7 @@ mod retry_policy_tests { }) .await; let client = test_client(&url); - let event = make_stored_event(client.keys()); + let event = make_stored_event(&client_keys(&client)); let result = client.submit_event(event).await; assert!( result.is_ok(), @@ -2203,7 +2423,7 @@ mod retry_policy_tests { let base = format!("http://{addr}"); let client = test_client(&base); - let event = make_stored_event(client.keys()); + let event = make_stored_event(&client_keys(&client)); let result = client.submit_event(event).await; assert!( result.is_ok(), @@ -2365,7 +2585,7 @@ mod retry_policy_tests { let base = format!("http://{addr}"); let client = test_client(&base); - let event = make_stored_event(client.keys()); + let event = make_stored_event(&client_keys(&client)); let err = client.submit_event(event).await.unwrap_err(); // Final error must be DeliveryUnknown — relay may have accepted any attempt. @@ -2397,7 +2617,7 @@ mod retry_policy_tests { let (url, attempts) = test_server(|_n| (StatusCode::BAD_GATEWAY, "bad gateway".to_string())).await; let client = test_client(&url); - let event = make_stored_event(client.keys()); + let event = make_stored_event(&client_keys(&client)); let err = client.submit_event(event).await.unwrap_err(); assert!( @@ -2410,13 +2630,56 @@ mod retry_policy_tests { "all 3 attempts must fire before surfacing DeliveryUnknown" ); } + + /// The first send is stored but its answer is lost; the retry is then + /// refused before ingest. The refusal cannot undo the first send, so the + /// outcome stays unknown rather than a plain rejection. + #[tokio::test] + async fn a_403_after_a_lost_stored_send_stays_delivery_unknown() { + let (url, attempts) = test_server(|n| match n { + 1 => (StatusCode::BAD_GATEWAY, "bad gateway".to_string()), + _ => ( + StatusCode::FORBIDDEN, + r#"{"error":"restricted: not allowed"}"#.to_string(), + ), + }) + .await; + let client = test_client(&url); + let event = make_stored_event(&client_keys(&client)); + let err = client.submit_event(event).await.unwrap_err(); + + assert!(matches!(err, CliError::DeliveryUnknown(_)), "{err:?}"); + assert!(!crate::error::is_retryable_error(&err)); + assert_eq!(attempts.load(Ordering::SeqCst), 2, "no retry after the 403"); + } } #[cfg(test)] mod tests { + #[cfg(unix)] + #[tokio::test] + async fn an_unreadable_file_is_bad_input() { + use std::os::unix::fs::PermissionsExt; + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::set_permissions(file.path(), std::fs::Permissions::from_mode(0o000)).unwrap(); + let client = BuzzClient::new( + "http://127.0.0.1:9".into(), + crate::credentials::Credentials::from_keys(nostr::Keys::generate()), + ) + .unwrap(); + let err = client + .upload_file(file.path().to_str().unwrap()) + .await + .unwrap_err(); + assert!( + matches!(err, crate::error::CliError::Usage(ref m) if m.contains("failed to read")), + "{err:?}" + ); + } + use super::{ advance_query_cursor, create_response_with_id_if_accepted, extract_relay_response_field, - normalize_events, BuzzClient, + normalize_events, BuzzClient, Credentials, Proof, }; use nostr::{EventBuilder, Keys, Kind, Tag}; @@ -2536,21 +2799,19 @@ mod tests { (tag, json) } - #[test] - fn sign_event_unchecked_does_not_inject_ambient_auth_tag() { + #[tokio::test] + async fn sign_event_unchecked_does_not_inject_ambient_auth_tag() { let keys = Keys::generate(); let (auth_tag, auth_json) = make_auth_tag(); let client = BuzzClient::new( "https://test.relay".into(), - keys, - Some(auth_tag), - Some(auth_json), + Credentials::from_keys(keys).with_auth_tag(auth_tag, auth_json), ) .unwrap(); let builder = EventBuilder::new(Kind::Custom(9035), "archive").tags([Tag::parse(["-"]).unwrap()]); - let event = client.sign_event_unchecked(builder).unwrap(); + let event = client.sign_event_unchecked(builder).await.unwrap(); let auth_tags: Vec<_> = event .tags @@ -2564,15 +2825,13 @@ mod tests { ); } - #[test] - fn sign_event_unchecked_preserves_callers_content_auth_tag() { + #[tokio::test] + async fn sign_event_unchecked_preserves_callers_content_auth_tag() { let keys = Keys::generate(); let (auth_tag, auth_json) = make_auth_tag(); let client = BuzzClient::new( "https://test.relay".into(), - keys, - Some(auth_tag), - Some(auth_json), + Credentials::from_keys(keys).with_auth_tag(auth_tag, auth_json), ) .unwrap(); @@ -2586,7 +2845,7 @@ mod tests { let builder = EventBuilder::new(Kind::Custom(9035), "archive") .tags([Tag::parse(["-"]).unwrap(), content_auth]); - let event = client.sign_event_unchecked(builder).unwrap(); + let event = client.sign_event_unchecked(builder).await.unwrap(); let auth_tags: Vec<_> = event .tags @@ -2601,21 +2860,23 @@ mod tests { assert_eq!(auth_tags[0].as_slice()[1], "c".repeat(64)); } - #[test] - fn with_auth_tag_sets_header_when_configured() { + #[tokio::test] + async fn authorize_sets_auth_tag_header_when_configured() { let keys = Keys::generate(); let (auth_tag, auth_json) = make_auth_tag(); let client = BuzzClient::new( "https://test.relay".into(), - keys, - Some(auth_tag), - Some(auth_json.clone()), + Credentials::from_keys(keys).with_auth_tag(auth_tag, auth_json.clone()), ) .unwrap(); - let req = client.http.post("https://test.relay/events"); - let req = client.with_auth_tag(req); - let built = req.build().unwrap(); + let url = "https://test.relay/events"; + let built = client + .authorize(client.http.post(url), Proof::post(url, b"{}")) + .await + .unwrap() + .build() + .unwrap(); let header = built .headers() .get("x-auth-tag") @@ -2627,17 +2888,1413 @@ mod tests { ); } - #[test] - fn with_auth_tag_omits_header_when_not_configured() { - let keys = Keys::generate(); - let client = BuzzClient::new("https://test.relay".into(), keys, None, None).unwrap(); + #[tokio::test] + async fn authorize_omits_optional_headers_when_not_configured() { + let client = BuzzClient::new( + "https://test.relay".into(), + Credentials::from_keys(Keys::generate()), + ) + .unwrap(); - let req = client.http.post("https://test.relay/events"); - let req = client.with_auth_tag(req); - let built = req.build().unwrap(); + let url = "https://test.relay/events"; + let built = client + .authorize(client.http.post(url), Proof::post(url, b"{}")) + .await + .unwrap() + .build() + .unwrap(); + assert!(built.headers().get("authorization").is_some()); assert!( built.headers().get("x-auth-tag").is_none(), "x-auth-tag header must not be present when no auth tag is configured" ); + assert!( + built.headers().get("nostr-federated-identity").is_none(), + "no NIP-FI header without an evidence source" + ); + } +} + +/// NIP-FI evidence on every protected route (Review-Proven Rule #2: every +/// request path that carries auth is enumerated here, plus the WebSocket +/// upgrade). One mock origin serves both the NIP-FA adapter and the relay. +#[cfg(test)] +mod federated_identity_route_tests { + use std::sync::{Arc, Mutex}; + + use axum::extract::Request; + use axum::http::{HeaderMap, StatusCode}; + use axum::response::IntoResponse; + use nostr::{EventBuilder, Keys, Kind}; + + use super::BuzzClient; + use crate::credentials::Credentials; + use crate::error::CliError; + use crate::federated_identity::AdapterSession; + + use crate::federated_identity::test_support::{self, count, raw_adapter}; + + const HASH: &str = "4f2b5e7c1a9d3e6f8b0c2d4e6f8a0b1c3d5e7f9a1b3c5d7e9f0a2b4c6d8e0f1a"; + + #[derive(Default)] + struct Log { + mints: usize, + /// The last assertion the adapter issued. + assertion: String, + requests: Vec<(String, String, HeaderMap)>, + } + + /// Serve the adapter and relay on one loopback origin. Relay routes + /// answer `deny` when set, otherwise a plausible success; `PUT /upload` + /// is 404 so the legacy `/media/upload` fallback runs too. + async fn origin(deny: Option) -> (String, Arc>) { + let log: Arc> = Arc::default(); + let state = log.clone(); + let app = axum::Router::new() + .route( + "/v1/identity/assertions", + axum::routing::post({ + let log = log.clone(); + move |body: axum::body::Bytes| { + let log = log.clone(); + async move { + let req: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let pubkey = req["nostr_pubkey"].as_str().unwrap_or_default(); + let expires_at = nostr::Timestamp::now().as_secs() + 300; + let assertion = test_support::assertion(pubkey, expires_at); + let mut log = log.lock().unwrap(); + log.mints += 1; + log.assertion = assertion.clone(); + axum::Json(serde_json::json!({ + "assertion": assertion, + "nostr_pubkey": pubkey, + "expires_at": expires_at, + })) + } + } + }), + ) + .fallback(move |req: Request| { + let log = state.clone(); + async move { + let method = req.method().to_string(); + let path = req.uri().path().to_owned(); + log.lock().unwrap().requests.push(( + method.clone(), + path.clone(), + req.headers().clone(), + )); + if let Some(status) = deny { + return (status, r#"{"error":"authentication required"}"#).into_response(); + } + let body = match (method.as_str(), path.as_str()) { + ("PUT", "/upload") => return StatusCode::NOT_FOUND.into_response(), + // No WebSocket server: the test only needs the upgrade's headers. + ("GET", "/") => return StatusCode::FORBIDDEN.into_response(), + ("PUT", "/media/upload") => serde_json::json!({ + "url": format!("http://x/media/{HASH}.png"), + "sha256": HASH, + "size": 8, + "type": "image/png", + "uploaded": 0, + }) + .to_string(), + ("POST", "/query") => "[]".to_owned(), + ("POST", "/count") => r#"{"count":0}"#.to_owned(), + _ => r#"{"accepted":true}"#.to_owned(), + }; + (StatusCode::OK, body).into_response() + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (base, log) + } + + fn client(base: &str, evidence: bool) -> BuzzClient { + if evidence { + client_via(base, base) + } else { + BuzzClient::new(base.to_owned(), Credentials::from_keys(Keys::generate())).unwrap() + } + } + + /// A client for the relay at `relay` that mints from the adapter at `adapter`. + fn client_via(relay: &str, adapter: &str) -> BuzzClient { + let credentials = Credentials::from_keys(Keys::generate()) + .with_evidence(AdapterSession::new(adapter, "token", relay).unwrap()); + BuzzClient::new(relay.to_owned(), credentials).unwrap() + } + + /// Drive every protected request path once, ignoring results (the WS + /// publish fails by design once its upgrade headers are recorded). + async fn exercise_every_route(client: &BuzzClient) -> Vec> { + let keys = client.credentials().test_keys(); + let png = tempfile::Builder::new().suffix(".png").tempfile().unwrap(); + std::fs::write(png.path(), b"\x89PNG\r\n\x1a\n").unwrap(); + let filter = serde_json::json!({"kinds": [1]}); + let body = serde_json::json!({"k": "v"}); + let event = |kind: u16| { + EventBuilder::new(Kind::Custom(kind), "") + .sign_with_keys(&keys) + .unwrap() + }; + let mut results = vec![ + client.query(&filter).await, + client.query_multi(&[filter.clone(), filter.clone()]).await, + client.count(&filter).await, + client.get_authed("/api/get").await, + client.post_json_authed("/api/post", &body).await, + client.post_json_once_authed("/api/post-once", &body).await, + client.submit_event(event(1)).await, + client.submit_event(event(9041)).await, + client.publish_ephemeral_event(event(20001)).await, + ]; + results.push( + client + .upload_file(png.path().to_str().unwrap()) + .await + .map(|d| d.url), + ); + results.push( + client + .download_media(&format!("{HASH}.png")) + .await + .map(|_| String::new()), + ); + results + } + + /// Each `(method, path)` the CLI sends on a protected route. + const PROTECTED: &[(&str, &str)] = &[ + ("POST", "/query"), + ("POST", "/count"), + ("GET", "/api/get"), + ("POST", "/api/post"), + ("POST", "/api/post-once"), + ("POST", "/events"), + ("GET", "/"), + ("PUT", "/upload"), + ("PUT", "/media/upload"), + ]; + + fn covered(log: &Log) -> Vec<(String, String)> { + let mut seen: Vec<(String, String)> = log + .requests + .iter() + .map(|(m, p, _)| (m.clone(), p.clone())) + .collect(); + seen.sort(); + seen.dedup(); + seen + } + + /// The relay proof is signed after the assertion arrives, so a slow + /// mint (adapter retries can exceed NIP-98's 60 s window) cannot age it. + #[tokio::test] + async fn the_relay_proof_is_signed_after_a_slow_mint() { + use base64::Engine; + let minted_at: Arc> = Arc::default(); + let proofs: Arc>> = Arc::default(); + let app = axum::Router::new() + .route( + "/v1/identity/assertions", + axum::routing::post({ + let minted_at = minted_at.clone(); + move |body: axum::body::Bytes| { + let minted_at = minted_at.clone(); + async move { + tokio::time::sleep(std::time::Duration::from_millis(1200)).await; + let req: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let pubkey = req["nostr_pubkey"].as_str().unwrap_or_default(); + let now = nostr::Timestamp::now().as_secs(); + *minted_at.lock().unwrap() = now; + axum::Json(serde_json::json!({ + "assertion": test_support::assertion(pubkey, now + 300), + "nostr_pubkey": pubkey, + "expires_at": now + 300, + })) + } + } + }), + ) + .fallback({ + let proofs = proofs.clone(); + move |headers: HeaderMap| { + let proofs = proofs.clone(); + async move { + let auth = headers["authorization"].to_str().unwrap().to_owned(); + proofs.lock().unwrap().push(auth); + (StatusCode::OK, "{}") + } + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + client(&base, true).get_authed("/api/get").await.unwrap(); + + let proof = proofs.lock().unwrap()[0].clone(); + let json = base64::engine::general_purpose::STANDARD + .decode(proof.trim_start_matches("Nostr ")) + .unwrap(); + let event: nostr::Event = serde_json::from_slice(&json).unwrap(); + assert!( + event.created_at.as_secs() >= *minted_at.lock().unwrap(), + "the proof was signed before the assertion arrived" + ); + } + + #[tokio::test] + async fn every_protected_route_and_the_upgrade_carry_the_assertion() { + let (base, log) = origin(None).await; + let results = exercise_every_route(&client(&base, true)).await; + + let log = log.lock().unwrap(); + for (method, path) in PROTECTED { + assert!( + covered(&log).contains(&(method.to_string(), path.to_string())), + "{method} {path} was not exercised" + ); + } + assert!( + log.requests + .iter() + .any(|(_, p, _)| p.starts_with("/media/") && p != "/media/upload"), + "GET /media/ was not exercised" + ); + for (method, path, headers) in &log.requests { + assert_eq!( + headers + .get("nostr-federated-identity") + .and_then(|v| v.to_str().ok()), + Some(format!("Bearer {}", log.assertion).as_str()), + "{method} {path}" + ); + if path != "/" { + assert!( + headers + .get("authorization") + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("Nostr ")), + "{method} {path}: Authorization proof" + ); + } + } + assert_eq!(log.mints, 1, "one assertion serves the whole process"); + // Everything but the WS publish (no WS server) succeeds. + for (i, result) in results.iter().enumerate() { + if i != 8 { + assert!(result.is_ok(), "route {i}: {result:?}"); + } + } + } + + #[tokio::test] + async fn exempt_routes_and_relays_without_a_source_get_no_assertion() { + let (base, log) = origin(None).await; + let plain = client(&base, false); + exercise_every_route(&plain).await; + plain.get_public("/info").await.unwrap(); + + { + let log = log.lock().unwrap(); + assert_eq!(log.mints, 0); + assert!(log.requests.len() >= PROTECTED.len()); + for (method, path, headers) in &log.requests { + assert!( + headers.get("nostr-federated-identity").is_none(), + "{method} {path}" + ); + } + } + + // An exempt route never mints or presents evidence, even with a source. + let (base, log) = origin(None).await; + client(&base, true).get_public("/info").await.unwrap(); + let log = log.lock().unwrap(); + assert_eq!(log.mints, 0); + assert!(log.requests[0].2.get("nostr-federated-identity").is_none()); + } + + /// An enforcing relay's 401 with no evidence source names the settings, + /// on HTTP and on the WebSocket upgrade, and is not retried. + #[tokio::test] + async fn a_401_without_a_source_names_the_evidence_settings() { + let (base, log) = origin(Some(StatusCode::UNAUTHORIZED)).await; + let plain = client(&base, false); + let keys = plain.credentials().test_keys(); + let ws_event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&keys) + .unwrap(); + for err in [ + plain.query(&serde_json::json!({})).await.unwrap_err(), + plain.publish_ephemeral_event(ws_event).await.unwrap_err(), + ] { + assert!( + matches!(&err, CliError::Auth(m) + if m.contains("BUZZ_FEDERATED_IDENTITY_TOKEN") + && m.contains("BUZZ_FEDERATED_IDENTITY_ADAPTER")), + "{err:?}" + ); + } + assert_eq!(log.lock().unwrap().requests.len(), 2, "401 is not retried"); + + // With a source configured, a 401 is the relay's verdict, not a hint. + let (base, _) = origin(Some(StatusCode::UNAUTHORIZED)).await; + let err = client(&base, true) + .query(&serde_json::json!({})) + .await + .unwrap_err(); + assert!( + matches!(err, CliError::Relay { status: 401, .. }), + "{err:?}" + ); + } + + /// The paths a failed mint must stop before anything reaches the relay: + /// a read, a post-once write, a moderation command, a stored message + /// (`messages send`) and the WebSocket upgrade (`users set-presence`). + /// Returns each path's error and how many mints that one call made. + async fn every_path_once( + client: &BuzzClient, + mints: &std::sync::atomic::AtomicUsize, + ) -> Vec<(&'static str, CliError, usize)> { + let keys = client.credentials().test_keys(); + let event = |kind: u16| { + EventBuilder::new(Kind::Custom(kind), "hi") + .sign_with_keys(&keys) + .unwrap() + }; + let body = serde_json::json!({"k": "v"}); + let mut out = Vec::new(); + let mut record = |path, result: Result, before| { + out.push((path, result.unwrap_err(), count(mints) - before)); + }; + let before = count(mints); + record( + "read", + client.query(&serde_json::json!({"kinds": [1]})).await, + before, + ); + let before = count(mints); + record( + "post-once", + client.post_json_once_authed("/api/post-once", &body).await, + before, + ); + let before = count(mints); + record("moderation", client.submit_event(event(9041)).await, before); + let before = count(mints); + record("message", client.submit_event(event(9)).await, before); + let before = count(mints); + record( + "websocket", + client.publish_ephemeral_event(event(20001)).await, + before, + ); + out + } + + /// An adapter 500 or 503 is retried a bounded number of times on every + /// path, then fails as a retryable adapter error. Nothing reaches the + /// relay, so a message is never reported as possibly delivered. + #[tokio::test] + async fn adapter_5xx_is_retried_on_every_path_and_never_reaches_the_relay() { + for response in [test_support::HTTP_500, test_support::HTTP_503] { + let (relay, log) = origin(None).await; + let (adapter, mints) = raw_adapter(response).await; + let client = client_via(&relay, &adapter); + for (path, err, attempts) in every_path_once(&client, &mints).await { + assert!(matches!(err, CliError::Adapter(_)), "{path}: {err:?}"); + assert!(crate::error::is_retryable_error(&err), "{path}"); + assert_eq!(attempts, 3, "{path}: three mints, no more"); + } + assert!( + log.lock().unwrap().requests.is_empty(), + "the relay saw a request" + ); + } + } + + /// A first send whose outcome is lost, then an assertion refresh that + /// fails, is still possibly delivered: the adapter error must not invite + /// an outer re-sign. + #[tokio::test] + async fn a_refresh_failure_after_a_lost_send_stays_delivery_unknown() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mints = Arc::new(AtomicUsize::new(0)); + let sends = Arc::new(AtomicUsize::new(0)); + let app = axum::Router::new() + .route( + "/v1/identity/assertions", + axum::routing::post({ + let mints = mints.clone(); + move |body: axum::body::Bytes| { + let mints = mints.clone(); + async move { + if mints.fetch_add(1, Ordering::SeqCst) > 0 { + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + let req: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let pubkey = req["nostr_pubkey"].as_str().unwrap_or_default(); + let expires_at = nostr::Timestamp::now().as_secs() + 300; + axum::Json(serde_json::json!({ + "assertion": test_support::assertion(pubkey, expires_at), + "nostr_pubkey": pubkey, + "expires_at": expires_at, + })) + .into_response() + } + } + }), + ) + .fallback({ + let sends = sends.clone(); + move || { + let sends = sends.clone(); + async move { + sends.fetch_add(1, Ordering::SeqCst); + // The relay may have stored it; the proxy lost the answer + // after the assertion reached its refresh boundary. + crate::cached_assertion::test_clock::advance(300); + StatusCode::BAD_GATEWAY.into_response() + } + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let client = client_via(&base, &base); + let keys = client.credentials().test_keys(); + let event = EventBuilder::new(Kind::Custom(9), "hi") + .sign_with_keys(&keys) + .unwrap(); + let err = client.submit_event(event).await.unwrap_err(); + assert!(matches!(err, CliError::DeliveryUnknown(_)), "{err:?}"); + assert!(!crate::error::is_retryable_error(&err)); + assert_eq!( + sends.load(Ordering::SeqCst), + 1, + "one send reached the relay" + ); + assert_eq!( + mints.load(Ordering::SeqCst), + 4, + "one mint, then three failed refreshes" + ); + } + + /// A 403 whose body is cut off is one refusal on every path, not a + /// retryable network error, and nothing reaches the relay. + #[tokio::test] + async fn a_truncated_adapter_403_is_a_single_refusal_on_every_path() { + let (relay, log) = origin(None).await; + let (adapter, mints) = raw_adapter(test_support::TRUNCATED_403).await; + let client = client_via(&relay, &adapter); + for (path, err, attempts) in every_path_once(&client, &mints).await { + assert!(matches!(err, CliError::Auth(_)), "{path}: {err:?}"); + assert!(!crate::error::is_retryable_error(&err), "{path}"); + assert_eq!(attempts, 1, "{path}: one mint"); + } + assert!( + log.lock().unwrap().requests.is_empty(), + "the relay saw a request" + ); + } + + /// A relay redirect to another origin is never followed: the assertion, + /// proof and auth tag stay with the relay that was asked. + #[tokio::test] + async fn a_cross_origin_relay_redirect_is_not_followed() { + let (target, target_log) = origin(None).await; + let location = format!("{target}/query"); + let app = axum::Router::new().fallback(move || { + let location = location.clone(); + async move { (StatusCode::TEMPORARY_REDIRECT, [("location", location)]) } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + // Mint from the target origin's adapter so the client has an assertion to leak. + let client = client_via(&relay, &target); + let body = serde_json::json!({"k": "v"}); + for err in [ + client.query(&serde_json::json!({})).await.unwrap_err(), + client.get_authed("/api/get").await.unwrap_err(), + client + .post_json_authed("/api/post", &body) + .await + .unwrap_err(), + ] { + assert!( + matches!(err, CliError::Relay { status: 307, .. }), + "{err:?}" + ); + } + let log = target_log.lock().unwrap(); + assert_eq!(log.mints, 1); + assert!( + log.requests.is_empty(), + "redirect followed: {:?}", + covered(&log) + ); + } + + /// A WebSocket refused after NIP-42 with a policy close (a NIP-FI key + /// mismatch) is an auth error, exit 3, not a generic failure. + #[tokio::test] + async fn a_websocket_policy_close_is_an_auth_error() { + use futures_util::{SinkExt, StreamExt}; + use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, CloseFrame}; + use tokio_tungstenite::tungstenite::Message; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + ws.send(Message::Text(r#"["AUTH","challenge"]"#.into())) + .await + .unwrap(); + let _auth = ws.next().await; + let _ = ws + .send(Message::Close(Some(CloseFrame { + code: CloseCode::Policy, + reason: "auth-required: key mismatch".into(), + }))) + .await; + }); + let client = client(&relay, false); + let event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&client.credentials().test_keys()) + .unwrap(); + let err = client.publish_ephemeral_event(event).await.unwrap_err(); + assert!( + matches!(&err, CliError::Auth(m) if m.contains("key mismatch")), + "{err:?}" + ); + assert_eq!(crate::error::exit_code(&err), 3); + assert!(!crate::error::is_retryable_error(&err)); + } +} + +/// A desktop that stays `rate_limited`, or throttles and then holds a +/// signature, through every command path that signs or encrypts. +#[cfg(all(test, unix))] +mod desktop_throttle_tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + use nostr::{EventBuilder, Kind}; + + use super::ws_deadline_tests::ws_relay; + use super::BuzzClient; + use crate::desktop_provider::{tests as dp, Provider}; + use crate::error::CliError; + + /// A desktop holding `keys` that answers `rate_limited` to `throttled`. + async fn client(relay: &str, keys: &nostr::Keys, throttled: &'static str) -> BuzzClient { + let answer = dp::desktop_answers(keys.clone(), vec![relay.into()]); + let (endpoint, _) = dp::provider(move |version, request| { + if request["method"] == throttled { + return serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 1}); + } + answer(version, request) + }) + .await; + let provider = Provider::open(endpoint, "t".into(), false, relay) + .await + .unwrap() + .ok() + .unwrap(); + let credentials = crate::credentials::Credentials::from_desktop(provider) + .await + .unwrap(); + BuzzClient::new(relay.into(), credentials).unwrap() + } + + /// A desktop user's 401 and 403 hints name what they can act on in Buzz, + /// not the headless settings. + #[tokio::test] + async fn desktop_users_get_hints_for_the_desktop() { + let app = axum::Router::new().fallback(|req: axum::extract::Request| async move { + let status = if req.uri().path() == "/forbidden" { + 403 + } else { + 401 + }; + ( + axum::http::StatusCode::from_u16(status).unwrap(), + r#"{"error":"no"}"#, + ) + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let keys = nostr::Keys::generate(); + let owner = nostr::Keys::generate(); + let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &keys.public_key(), "").unwrap(); + let answer = dp::desktop_answers(keys.clone(), vec![relay.clone()]); + let (endpoint, _) = + dp::provider(move |version, request| match request["method"].as_str() { + Some("federated_identity") => serde_json::json!({"result": ""}), + Some("auth_tag") => serde_json::json!({"result": tag}), + Some("describe") => { + let mut described = answer(version, request); + let mut body: serde_json::Value = + serde_json::from_str(described["result"].as_str().unwrap()).unwrap(); + body["methods"] + .as_array_mut() + .unwrap() + .push("auth_tag".into()); + described["result"] = body.to_string().into(); + described + } + _ => answer(version, request), + }) + .await; + let provider = Provider::open(endpoint, "t".into(), false, &relay) + .await + .unwrap() + .ok() + .unwrap(); + let credentials = crate::credentials::Credentials::from_desktop(provider) + .await + .unwrap(); + let client = BuzzClient::new(relay, credentials).unwrap(); + + let err = client.get_authed("/api").await.unwrap_err(); + assert!( + matches!(&err, CliError::Auth(m) if m.contains("in Buzz")), + "{err:?}" + ); + let err = client.get_authed("/forbidden").await.unwrap_err(); + let text = err.to_string(); + assert!( + !text.contains("stale") && !text.contains("BUZZ_AUTH_TAG"), + "{text}" + ); + } + + /// A desktop holding `keys` whose assertions live `lifetime` s and + /// which answers `sign_event` with `sign` (`None`: sign it), logging the + /// sign-in challenges it signs. + async fn desktop( + relay: &str, + keys: &nostr::Keys, + assertion: impl Fn() -> String + Send + Sync + 'static, + sign: impl Fn(&nostr::UnsignedEvent) -> Option + Send + Sync + 'static, + ) -> (BuzzClient, super::ws_deadline_tests::Log) { + let signed: super::ws_deadline_tests::Log = Default::default(); + let log = signed.clone(); + let answer = dp::desktop_answers(keys.clone(), vec![relay.into()]); + let (endpoint, _) = + dp::provider(move |version, request| match request["method"].as_str() { + Some("federated_identity") => { + serde_json::json!({ "result": assertion() }) + } + Some("sign_event") => { + let unsigned = ::from_json( + request["params"][0].as_str().unwrap(), + ) + .unwrap(); + if let Some(refusal) = sign(&unsigned) { + return refusal; + } + if let Some(c) = unsigned.tags.find(nostr::TagKind::Challenge) { + log.lock().unwrap().push(c.content().unwrap().to_owned()); + } + answer(version, request) + } + _ => answer(version, request), + }) + .await; + let provider = Provider::open(endpoint, "t".into(), false, relay) + .await + .unwrap() + .ok() + .unwrap(); + let credentials = crate::credentials::Credentials::from_desktop(provider) + .await + .unwrap(); + (BuzzClient::new(relay.into(), credentials).unwrap(), signed) + } + + /// A desktop that throttles the first sign-in signature: the throttle is + /// waited out between connections, so only the live challenge is signed, + /// with a fresh assertion on the reconnect after the old one expired. + /// + /// The throttle is decided by call count, not by time since the test + /// started: on a loaded runner the desktop setup alone could outlast a + /// wall-clock throttle window, leaving nothing to wait out. The relay's + /// sign-in deadline is long for the same reason; the client drops the + /// throttled socket itself. + #[tokio::test] + async fn a_throttled_sign_in_reconnects_with_fresh_evidence() { + use super::ws_deadline_tests::deadline_relay; + let keys = nostr::Keys::generate(); + let (relay, conns, _, bearers) = deadline_relay(std::time::Duration::from_secs(5)).await; + let signs = AtomicUsize::new(0); + let (c, signed) = desktop(&relay, &keys, || dp::assertion(40), move |_| { + if signs.fetch_add(1, Ordering::SeqCst) == 0 { + crate::cached_assertion::test_clock::advance(60); + return Some( + serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 30}), + ); + } + None + }) + .await; + let event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&keys) + .unwrap(); + c.publish_ephemeral_event(event).await.unwrap(); + assert_eq!(conns.load(Ordering::SeqCst), 2); + assert_eq!( + *signed.lock().unwrap(), + ["c1"], + "the dead challenge is never signed" + ); + let bearers = bearers.lock().unwrap(); + assert_ne!( + bearers[0], bearers[1], + "the reconnect brings a fresh assertion" + ); + } + + /// An HTTP relay logging each request's NIP-FI assertion. + async fn logging_relay() -> (String, super::ws_deadline_tests::Log) { + let seen: super::ws_deadline_tests::Log = Default::default(); + let log = seen.clone(); + let app = axum::Router::new().fallback(move |headers: axum::http::HeaderMap| { + let bearer = headers["nostr-federated-identity"].to_str().unwrap(); + log.lock() + .unwrap() + .push(bearer.trim_start_matches("Bearer ").to_owned()); + async { axum::Json(serde_json::json!([])) } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (relay, seen) + } + + /// A NIP-98 signature that outlives the assertion is signed again after + /// fresh evidence, and goes out with both current. + #[tokio::test] + async fn a_slow_http_signature_goes_out_with_fresh_evidence() { + let (relay, seen) = logging_relay().await; + let signs = Arc::new(AtomicUsize::new(0)); + let n = signs.clone(); + let (c, _) = desktop( + &relay, + &nostr::Keys::generate(), + || dp::assertion(40), + move |_| { + if n.fetch_add(1, Ordering::SeqCst) == 0 { + crate::cached_assertion::test_clock::advance(60); + } + None + }, + ) + .await; + c.query(&serde_json::json!({})).await.unwrap(); + assert_eq!(signs.load(Ordering::SeqCst), 2, "the proof is signed again"); + let sent = crate::cached_assertion::jws_exp(&seen.lock().unwrap()[0]).unwrap(); + assert!( + sent > crate::cached_assertion::unix_now(), + "the assertion sent is current" + ); + } + + /// A post-sign refresh that waits and returns the same assertion still + /// gets a proof signed after it. + #[tokio::test] + async fn a_slow_refresh_of_the_same_assertion_re_signs_the_proof() { + let (relay, seen) = logging_relay().await; + let exp = crate::cached_assertion::unix_now() + 600; + let fetches = AtomicUsize::new(0); + let same = move || { + if fetches.fetch_add(1, Ordering::SeqCst) == 1 { + // The desktop waits out throttling before it answers. + crate::cached_assertion::test_clock::advance(45); + } + dp::assertion(exp - crate::cached_assertion::unix_now()) + }; + let signs = Arc::new(AtomicUsize::new(0)); + let n = signs.clone(); + let (c, _) = desktop(&relay, &nostr::Keys::generate(), same, move |_| { + if n.fetch_add(1, Ordering::SeqCst) == 0 { + crate::cached_assertion::test_clock::advance(310); + } + None + }) + .await; + c.query(&serde_json::json!({})).await.unwrap(); + assert_eq!( + signs.load(Ordering::SeqCst), + 2, + "the aged proof is signed again" + ); + assert_eq!(seen.lock().unwrap().len(), 1); + } + + /// A signature slower than a proof's lifetime is signed again even when + /// the evidence did not change. + #[tokio::test] + async fn a_slow_signature_with_unchanged_evidence_is_signed_again() { + let (relay, seen) = logging_relay().await; + let exp = crate::cached_assertion::unix_now() + 3600; + let signs = Arc::new(AtomicUsize::new(0)); + let n = signs.clone(); + let (c, _) = desktop( + &relay, + &nostr::Keys::generate(), + move || dp::assertion(exp - crate::cached_assertion::unix_now()), + move |_| { + if n.fetch_add(1, Ordering::SeqCst) == 0 { + crate::cached_assertion::test_clock::advance(65); + } + None + }, + ) + .await; + c.query(&serde_json::json!({})).await.unwrap(); + assert_eq!( + signs.load(Ordering::SeqCst), + 2, + "the stale proof is signed again" + ); + assert_eq!(seen.lock().unwrap().len(), 1); + } + + /// Evidence that keeps expiring while the proof is signed ends retryable + /// after three rounds, sending nothing. + #[tokio::test] + async fn evidence_that_keeps_expiring_ends_retryable() { + let (relay, seen) = logging_relay().await; + let signs = Arc::new(AtomicUsize::new(0)); + let n = signs.clone(); + let (c, _) = desktop( + &relay, + &nostr::Keys::generate(), + || dp::assertion(40), + move |_| { + n.fetch_add(1, Ordering::SeqCst); + crate::cached_assertion::test_clock::advance(60); + None + }, + ) + .await; + let err = c.query(&serde_json::json!({})).await.unwrap_err(); + assert!(matches!(err, CliError::Unavailable(_)), "{err:?}"); + assert_eq!(signs.load(Ordering::SeqCst), 3); + assert!(seen.lock().unwrap().is_empty()); + } + + /// An HTTP relay answering every query with no events. + async fn http_relay() -> String { + let app = axum::Router::new().fallback(|| async { axum::Json(serde_json::json!([])) }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + relay + } + + fn assert_throttled(err: CliError) { + assert!(matches!(err, CliError::Throttled(_)), "{err:?}"); + assert!(crate::error::is_retryable_error(&err)); + assert_eq!(crate::error::exit_code(&err), 2); + } + + #[tokio::test] + async fn persistent_throttling_is_retryable_on_every_signing_path() { + let keys = nostr::Keys::generate(); + let relay = http_relay().await; + let c = client(&relay, &keys, "sign_event").await; + + // NIP-98 on an ordinary request. + assert_throttled(c.query(&serde_json::json!({})).await.unwrap_err()); + // Event signing. + assert_throttled( + c.sign_event(EventBuilder::new(Kind::TextNote, "x")) + .await + .unwrap_err(), + ); + + // Memory encryption. + let c = client(&relay, &keys, "nip44_encrypt").await; + let owner = nostr::Keys::generate().public_key().to_hex(); + assert_throttled( + crate::commands::mem::cmd_set(&c, "mem/a", "v", Some(&owner), false) + .await + .unwrap_err(), + ); + } + + #[tokio::test] + async fn persistent_throttling_during_nip42_is_retryable() { + let keys = nostr::Keys::generate(); + let (relay, auths, events) = ws_relay().await; + let c = client(&relay, &keys, "sign_event").await; + let event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&keys) + .unwrap(); + assert_throttled(c.publish_ephemeral_event(event).await.unwrap_err()); + assert_eq!(auths.load(Ordering::SeqCst), 0); + assert_eq!(events.load(Ordering::SeqCst), 0); + } + + /// NIP-42 signing that is throttled, then held for a decision, completes + /// the publish: provider time is outside the relay's deadlines, and the + /// relay sees one AUTH and one EVENT. + #[tokio::test(flavor = "multi_thread")] + async fn a_throttled_then_held_nip42_signature_completes_without_replay() { + let keys = nostr::Keys::generate(); + let (relay, auths, events) = ws_relay().await; + let signs = Arc::new(AtomicUsize::new(0)); + let counted = signs.clone(); + let answer = dp::desktop_answers(keys.clone(), vec![relay.clone()]); + let (endpoint, _) = dp::provider(move |version, request| { + if request["method"] == "sign_event" { + if counted.fetch_add(1, Ordering::SeqCst) == 0 { + return serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 30}); + } + // Held for a person's decision. + std::thread::sleep(std::time::Duration::from_secs(2)); + } + answer(version, request) + }) + .await; + let provider = Provider::open(endpoint, "t".into(), false, &relay) + .await + .unwrap() + .ok() + .unwrap(); + let credentials = crate::credentials::Credentials::from_desktop(provider) + .await + .unwrap(); + let c = BuzzClient::new(relay, credentials).unwrap(); + let event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&keys) + .unwrap(); + c.publish_ephemeral_event(event).await.unwrap(); + assert_eq!(signs.load(Ordering::SeqCst), 2); + assert_eq!(auths.load(Ordering::SeqCst), 1); + assert_eq!(events.load(Ordering::SeqCst), 1); + } +} + +/// WebSocket publish deadlines, on a paused clock: a signer may take as long +/// as it needs, while each network phase, writes included, is capped. +#[cfg(test)] +mod ws_deadline_tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + use std::time::Duration; + + use futures_util::{SinkExt, StreamExt}; + use nostr::{Event, EventBuilder, Keys, Kind, NostrSigner, PublicKey, UnsignedEvent}; + use tokio_tungstenite::tungstenite::Message; + + use super::BuzzClient; + use crate::credentials::Credentials; + use crate::error::CliError; + + /// A WebSocket relay that sends a challenge, then OKs AUTH and one event. + /// Returns its URL and the count of AUTH and EVENT frames it received. + pub(super) async fn ws_relay() -> (String, Arc, Arc) { + let (auths, events) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0))); + let (a, e) = (auths.clone(), events.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let (a, e) = (a.clone(), e.clone()); + tokio::spawn(async move { + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + let _ = ws + .send(Message::Text(r#"["AUTH","challenge"]"#.into())) + .await; + while let Some(Ok(Message::Text(text))) = ws.next().await { + let frame: serde_json::Value = serde_json::from_str(&text).unwrap(); + let counter = if frame[0] == "AUTH" { &a } else { &e }; + counter.fetch_add(1, Ordering::SeqCst); + let ok = serde_json::json!(["OK", frame[1]["id"], true, ""]); + let _ = ws.send(Message::Text(ok.to_string().into())).await; + } + }); + } + }); + (relay, auths, events) + } + + /// Keys that take `delay` to sign, like a signer held for a decision. + /// The clock is paused only while signing (after the real connect), so + /// the delay passes at once unless an earlier timer fires first. + #[derive(Debug)] + struct Slow(Keys, Duration); + + /// Keys whose first signature takes `delay`, then sign at once. + #[derive(Debug)] + struct SlowFirst(Slow, std::sync::atomic::AtomicBool); + + impl NostrSigner for Slow { + fn backend(&self) -> nostr::signer::SignerBackend<'_> { + nostr::signer::SignerBackend::Custom("slow".into()) + } + fn get_public_key( + &self, + ) -> nostr::util::BoxedFuture<'_, Result> { + self.0.get_public_key() + } + fn sign_event( + &self, + unsigned: UnsignedEvent, + ) -> nostr::util::BoxedFuture<'_, Result> { + Box::pin(async move { + tokio::time::pause(); + tokio::time::sleep(self.1).await; + tokio::time::resume(); + self.0.sign_event(unsigned).await + }) + } + fn nip04_encrypt<'a>( + &'a self, + p: &'a PublicKey, + c: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + self.0.nip04_encrypt(p, c) + } + fn nip04_decrypt<'a>( + &'a self, + p: &'a PublicKey, + c: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + self.0.nip04_decrypt(p, c) + } + fn nip44_encrypt<'a>( + &'a self, + p: &'a PublicKey, + c: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + self.0.nip44_encrypt(p, c) + } + fn nip44_decrypt<'a>( + &'a self, + p: &'a PublicKey, + c: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + self.0.nip44_decrypt(p, c) + } + } + + impl NostrSigner for SlowFirst { + fn backend(&self) -> nostr::signer::SignerBackend<'_> { + self.0.backend() + } + fn get_public_key( + &self, + ) -> nostr::util::BoxedFuture<'_, Result> { + self.0.get_public_key() + } + fn sign_event( + &self, + unsigned: UnsignedEvent, + ) -> nostr::util::BoxedFuture<'_, Result> { + if self.1.swap(false, Ordering::SeqCst) { + self.0.sign_event(unsigned) + } else { + self.0 .0.sign_event(unsigned) + } + } + fn nip04_encrypt<'a>( + &'a self, + p: &'a PublicKey, + c: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + self.0.nip04_encrypt(p, c) + } + fn nip04_decrypt<'a>( + &'a self, + p: &'a PublicKey, + c: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + self.0.nip04_decrypt(p, c) + } + fn nip44_encrypt<'a>( + &'a self, + p: &'a PublicKey, + c: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + self.0.nip44_encrypt(p, c) + } + fn nip44_decrypt<'a>( + &'a self, + p: &'a PublicKey, + c: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + self.0.nip44_decrypt(p, c) + } + } + + /// A relay that, like buzz-relay, drops a socket not signed in within + /// 5 s; otherwise as [`ws_relay`]. Returns its URL, its connection + /// count, and the challenges each AUTH answered. + /// A relay closing sockets not signed in within `deadline`: the + /// connection count, the challenges answered and each upgrade's NIP-FI + /// header. + #[allow(clippy::result_large_err)] // tungstenite's handshake callback type + pub(super) async fn deadline_relay(deadline: Duration) -> (String, Arc, Log, Log) { + let conns = Arc::new(AtomicUsize::new(0)); + let (answered, bearers): (Log, Log) = Default::default(); + let (n, log, seen) = (conns.clone(), answered.clone(), bearers.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let challenge = format!("c{}", n.fetch_add(1, Ordering::SeqCst)); + let (log, seen) = (log.clone(), seen.clone()); + tokio::spawn(async move { + let record = + |req: &tokio_tungstenite::tungstenite::handshake::server::Request, res| { + let bearer = req.headers().get("nostr-federated-identity"); + let bearer = bearer.map(|v| v.to_str().unwrap().to_owned()); + seen.lock().unwrap().push(bearer.unwrap_or_default()); + Ok(res) + }; + let mut ws = tokio_tungstenite::accept_hdr_async(stream, record) + .await + .unwrap(); + let hello = serde_json::json!(["AUTH", challenge]).to_string(); + let _ = ws.send(Message::Text(hello.into())).await; + let deadline = tokio::time::sleep(deadline); + tokio::pin!(deadline); + let mut authed = false; + loop { + let next = tokio::select! { + _ = &mut deadline, if !authed => return, + next = ws.next() => next, + }; + let Some(Ok(Message::Text(text))) = next else { + return; + }; + let frame: serde_json::Value = serde_json::from_str(&text).unwrap(); + if frame[0] == "AUTH" { + let tags = frame[1]["tags"].as_array().unwrap(); + let c = tags.iter().find(|t| t[0] == "challenge").unwrap(); + log.lock().unwrap().push(c[1].as_str().unwrap().to_owned()); + authed = true; + } + let ok = serde_json::json!(["OK", frame[1]["id"], true, ""]); + let _ = ws.send(Message::Text(ok.to_string().into())).await; + } + }); + } + }); + (relay, conns, answered, bearers) + } + + pub(super) type Log = Arc>>; + + /// Every upgrade names the CLI and its version. + #[tokio::test] + async fn upgrade_headers_carry_the_cli_user_agent() { + let keys = Keys::generate(); + let c = BuzzClient::new( + "http://127.0.0.1:1".into(), + Credentials::from_signer(Arc::new(keys.clone()), keys.public_key()), + ) + .unwrap(); + let headers = c.upgrade_headers().await.unwrap(); + assert_eq!(headers.get("user-agent").unwrap(), super::USER_AGENT); + assert!(super::USER_AGENT.starts_with("buzz-cli/")); + } + + /// A sign-in signature that comes back after the relay's 5 s deadline + /// reconnects and signs the new challenge, never the old one. + #[tokio::test] + async fn a_late_sign_in_reconnects_and_signs_the_new_challenge() { + let keys = Keys::generate(); + let (relay, conns, answered, _) = deadline_relay(Duration::from_secs(5)).await; + let signer = Arc::new(SlowFirst( + Slow(keys.clone(), Duration::from_secs(8)), + std::sync::atomic::AtomicBool::new(true), + )); + let c = + BuzzClient::new(relay, Credentials::from_signer(signer, keys.public_key())).unwrap(); + let event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&keys) + .unwrap(); + c.publish_ephemeral_event(event).await.unwrap(); + assert_eq!(conns.load(Ordering::SeqCst), 2); + assert_eq!( + *answered.lock().unwrap(), + ["c1"], + "only the new challenge is signed" + ); + } + + /// A signer that is always too slow ends retryable after the bound. + #[tokio::test] + async fn a_sign_in_always_too_late_ends_retryable() { + let keys = Keys::generate(); + let (relay, conns, ..) = deadline_relay(Duration::from_secs(5)).await; + let c = client(relay, &keys, Duration::from_secs(8)); + let event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&keys) + .unwrap(); + let err = c.publish_ephemeral_event(event).await.unwrap_err(); + assert!(crate::error::is_retryable_error(&err), "{err:?}"); + assert_eq!( + conns.load(Ordering::SeqCst), + super::WS_SIGN_IN_ATTEMPTS as usize + ); + } + + fn client(relay: String, keys: &Keys, delay: Duration) -> BuzzClient { + let signer = Arc::new(Slow(keys.clone(), delay)); + BuzzClient::new(relay, Credentials::from_signer(signer, keys.public_key())).unwrap() + } + + /// Signing held for 300 s, past the old 225 s single cap, still publishes, + /// once. + #[tokio::test] + async fn a_signature_held_past_every_relay_cap_still_publishes_once() { + let keys = Keys::generate(); + let (relay, auths, events) = ws_relay().await; + let c = client(relay, &keys, Duration::from_secs(300)); + let event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&keys) + .unwrap(); + let started = tokio::time::Instant::now(); + c.publish_ephemeral_event(event).await.unwrap(); + assert!(started.elapsed() >= Duration::from_secs(300)); + assert!( + started.elapsed() < Duration::from_secs(330), + "real time stays short" + ); + assert_eq!(auths.load(Ordering::SeqCst), 1); + assert_eq!(events.load(Ordering::SeqCst), 1); + } + + /// A relay that OKs AUTH and then stops reading stalls the EVENT write; + /// the publish fails within its phase cap and is not sent again. + #[tokio::test] + async fn a_stalled_event_write_fails_within_its_phase_cap() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(AtomicUsize::new(0)); + let count = accepted.clone(); + // The relay pauses the clock once it has OKed AUTH, so the EVENT + // phase runs on virtual time from that mark. + let authed = Arc::new(std::sync::Mutex::new(None)); + let mark = authed.clone(); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + count.fetch_add(1, Ordering::SeqCst); + let mark = mark.clone(); + tokio::spawn(async move { + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + let _ = ws + .send(Message::Text(r#"["AUTH","challenge"]"#.into())) + .await; + if let Some(Ok(Message::Text(text))) = ws.next().await { + let frame: serde_json::Value = serde_json::from_str(&text).unwrap(); + let ok = serde_json::json!(["OK", frame[1]["id"], true, ""]); + let _ = ws.send(Message::Text(ok.to_string().into())).await; + tokio::time::pause(); + *mark.lock().unwrap() = Some(tokio::time::Instant::now()); + } + // Hold the socket open without reading. + std::future::pending::<()>().await; + drop(ws); + }); + } + }); + let keys = Keys::generate(); + let c = BuzzClient::new(relay, Credentials::from_keys(keys.clone())).unwrap(); + let event = EventBuilder::new(Kind::Custom(20001), "x".repeat(32 * 1024 * 1024)) + .sign_with_keys(&keys) + .unwrap(); + // An unbounded write would wait here for the hour, not forever. + let err = tokio::time::timeout(Duration::from_secs(3600), c.publish_ephemeral_event(event)) + .await + .expect("the stalled write is bounded") + .unwrap_err(); + let stalled = authed.lock().unwrap().expect("AUTH was OKed").elapsed(); + // From the OK the client has at most the rest of the AUTH phase (the + // paused clock jumps to its read deadline before the OK is read) and + // the whole EVENT phase. + use buzz_ws_client::connection::{AUTH_OK_TIMEOUT_SECS, PUBLISH_OK_TIMEOUT_SECS}; + let cap = Duration::from_secs(AUTH_OK_TIMEOUT_SECS + 1 + PUBLISH_OK_TIMEOUT_SECS + 1); + assert!(stalled <= cap, "{stalled:?} {err:?}"); + assert!( + matches!(err, CliError::Other(ref m) if m.contains("Timeout")), + "{err:?}" + ); + assert_eq!(accepted.load(Ordering::SeqCst), 1); + } + + /// The NIP-42 AUTH event names the configured community URL, path and + /// trailing slash kept, as the relay checks it. + #[tokio::test] + async fn the_auth_event_names_the_relay_with_its_trailing_slash() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let named = Arc::new(std::sync::Mutex::new(None::)); + let log = named.clone(); + tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap(); + let _ = ws + .send(Message::Text(r#"["AUTH","challenge"]"#.into())) + .await; + while let Some(Ok(Message::Text(text))) = ws.next().await { + let frame: serde_json::Value = serde_json::from_str(&text).unwrap(); + if frame[0] == "AUTH" { + let relay = frame[1]["tags"] + .as_array() + .unwrap() + .iter() + .find(|t| t[0] == "relay") + .map(|t| t[1].as_str().unwrap().to_owned()); + *log.lock().unwrap() = relay; + } + let ok = serde_json::json!(["OK", frame[1]["id"], true, ""]); + let _ = ws.send(Message::Text(ok.to_string().into())).await; + } + }); + let keys = Keys::generate(); + let c = BuzzClient::new( + format!("http://{addr}/team/"), + Credentials::from_keys(keys.clone()), + ) + .unwrap(); + let event = EventBuilder::new(Kind::Custom(20001), "") + .sign_with_keys(&keys) + .unwrap(); + c.publish_ephemeral_event(event).await.unwrap(); + assert_eq!( + named.lock().unwrap().as_deref(), + Some(format!("ws://{addr}/team/").as_str()) + ); + } + + #[test] + fn auth_keeps_the_configured_relay_path() { + let client = BuzzClient::new( + "wss://host.example/team/".into(), + Credentials::from_keys(Keys::generate()), + ) + .unwrap(); + assert_eq!(client.ws_url, "wss://host.example/team/"); + assert_eq!(client.relay_url, "https://host.example/team"); } } diff --git a/crates/buzz-cli/src/commands/agents.rs b/crates/buzz-cli/src/commands/agents.rs index 568249d0829..9b98129254f 100644 --- a/crates/buzz-cli/src/commands/agents.rs +++ b/crates/buzz-cli/src/commands/agents.rs @@ -18,14 +18,15 @@ pub async fn dispatch(command: AgentsCmd, client: &BuzzClient) -> Result<(), Cli } => { let owner = require_owner(client)?; let built = build_create( - client.keys(), + client.credentials(), &owner, CreateAgentDraft { channel_id: channel, display_name, system_prompt: read_or_stdin(&system_prompt)?, }, - )?; + ) + .await?; let response = client.publish_ephemeral_event(built.event).await?; let mut output: serde_json::Value = serde_json::from_str(&response) .map_err(|e| CliError::Other(format!("invalid relay response: {e}")))?; @@ -55,7 +56,7 @@ pub async fn dispatch(command: AgentsCmd, client: &BuzzClient) -> Result<(), Cli } => { let owner = require_owner(client)?; let built = build_update( - client.keys(), + client.credentials(), &owner, UpdateAgentDraft { channel_id: channel, @@ -67,7 +68,8 @@ pub async fn dispatch(command: AgentsCmd, client: &BuzzClient) -> Result<(), Cli model, respond_to: respond_to.map(RespondToArg::to_wire), }, - )?; + ) + .await?; let response = client.publish_ephemeral_event(built.event).await?; let mut output: serde_json::Value = serde_json::from_str(&response) .map_err(|e| CliError::Other(format!("invalid relay response: {e}")))?; @@ -93,7 +95,7 @@ pub async fn dispatch(command: AgentsCmd, client: &BuzzClient) -> Result<(), Cli admin, } => { validate_hex64(&target_pubkey)?; - let signer_hex = client.keys().public_key().to_hex(); + let signer_hex = client.public_key().to_hex(); let auth = resolve_auth( client, &target_pubkey, @@ -110,7 +112,7 @@ pub async fn dispatch(command: AgentsCmd, client: &BuzzClient) -> Result<(), Cli auth.as_ref(), ) .map_err(|e| CliError::Usage(format!("invalid archive request: {e}")))?; - let event = client.sign_event_unchecked(builder)?; + let event = client.sign_event_unchecked(builder).await?; let event_id = event.id.to_hex(); client.submit_event(event).await?; println!( @@ -132,7 +134,7 @@ pub async fn dispatch(command: AgentsCmd, client: &BuzzClient) -> Result<(), Cli admin, } => { validate_hex64(&target_pubkey)?; - let signer_hex = client.keys().public_key().to_hex(); + let signer_hex = client.public_key().to_hex(); let auth = resolve_auth( client, &target_pubkey, @@ -148,7 +150,7 @@ pub async fn dispatch(command: AgentsCmd, client: &BuzzClient) -> Result<(), Cli auth.as_ref(), ) .map_err(|e| CliError::Usage(format!("invalid unarchive request: {e}")))?; - let event = client.sign_event_unchecked(builder)?; + let event = client.sign_event_unchecked(builder).await?; let event_id = event.id.to_hex(); client.submit_event(event).await?; println!( @@ -394,7 +396,7 @@ fn extract_owner_auth_tag(tags: &[serde_json::Value], signer_hex: &str) -> Optio /// normalize it to lowercase, so the archived-identities query filter and /// the author comparison in [`verify_archived_event`] agree regardless of /// the case the relay published `self` in. -fn normalize_relay_self_hex(self_hex: &str) -> Result { +pub(crate) fn normalize_relay_self_hex(self_hex: &str) -> Result { if self_hex.len() != 64 || !self_hex.chars().all(|c| c.is_ascii_hexdigit()) { return Err(CliError::Other(format!( "relay 'self' field is not a valid 64-hex pubkey: {self_hex}" @@ -889,7 +891,11 @@ mod tests { fn test_client(base_url: &str) -> crate::client::BuzzClient { let keys = nostr::Keys::generate(); - crate::client::BuzzClient::new(base_url.to_string(), keys, None, None).unwrap() + crate::client::BuzzClient::new( + base_url.to_string(), + crate::credentials::Credentials::from_keys(keys), + ) + .unwrap() } fn kind0_response(signer_hex: &str) -> String { diff --git a/crates/buzz-cli/src/commands/channel_unread.rs b/crates/buzz-cli/src/commands/channel_unread.rs new file mode 100644 index 00000000000..c4ba9df6816 --- /dev/null +++ b/crates/buzz-cli/src/commands/channel_unread.rs @@ -0,0 +1,730 @@ +//! `buzz channels unread` — per-channel unread counts from the synced NIP-RS +//! read state. Read-only: it never publishes. +//! +//! Counting follows desktop's `communityUnreadObserver.ts` +//! (`isUnreadExternalEvent`): an event is unread when it is not yours and is +//! newer than the greatest of the channel frontier, its `msg:` marker and, +//! for a non-broadcast reply, its `thread:` marker. Thread replies count. +//! Desktop's notification gate (participated/followed threads, muted channels, +//! hidden DMs) lives in desktop-local storage and is not applied here. + +use std::collections::HashMap; + +use buzz_core::kind::{ + KIND_FORUM_COMMENT, KIND_FORUM_POST, KIND_HUDDLE_STARTED, KIND_STREAM_MESSAGE, + KIND_STREAM_MESSAGE_V2, +}; +use serde_json::{json, Value}; + +use super::read_state::{self, ReadState}; +use crate::client::{extract_d_tag, extract_tag_value, BuzzClient}; +use crate::error::CliError; +use crate::validate::validate_uuid; + +const KIND_GROUP_METADATA: u32 = 39000; +const KIND_GROUP_MEMBERS: u32 = 39002; +const MEMBER_CHANNEL_LIMIT: u32 = 1000; + +/// Resource bounds of one run. +pub(crate) struct Bounds { + /// Most channels counted in one run. + pub max_channels: usize, + /// Most events read per channel; a channel that reaches it reports `capped`. + pub events_per_channel: u32, +} + +pub(crate) const BOUNDS: Bounds = Bounds { + max_channels: 200, + events_per_channel: 1000, +}; + +#[derive(Debug, PartialEq, Eq, serde::Serialize)] +pub(crate) struct ChannelUnread { + pub channel_id: String, + pub name: String, + pub last_read_at: Option, + pub unread_count: u32, + /// `unread_count` is a lower bound: the per-channel event cap was reached. + pub capped: bool, +} + +#[derive(Debug)] +pub(crate) struct Outcome { + pub channels: Vec, + /// Channels found but not counted because of `--limit`. + pub dropped: usize, + pub skipped_slots: Vec, +} + +struct Channel { + id: String, + name: String, + is_dm: bool, +} + +fn message_kinds(is_dm: bool) -> Vec { + let mut kinds = vec![ + KIND_STREAM_MESSAGE, + KIND_STREAM_MESSAGE_V2, + KIND_FORUM_POST, + KIND_FORUM_COMMENT, + ]; + if is_dm { + kinds.push(KIND_HUDDLE_STARTED); + } + kinds +} + +fn tags(event: &Value) -> impl Iterator> { + event + .get("tags") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|tag| tag.as_array()) + .map(|tag| tag.iter().map(|v| v.as_str().unwrap_or("")).collect()) +} + +/// The thread root a reply counts against, as desktop's `getThreadReference` +/// and `isBroadcastReply` resolve it. A broadcast reply has none. +fn thread_root(event: &Value) -> Option { + let mut broadcast = false; + let mut root = None; + let mut reply = None; + for tag in tags(event) { + match tag.as_slice() { + ["broadcast", "1", ..] => broadcast = true, + ["e", id, _, "root", ..] => { + root.get_or_insert(*id); + } + ["e", id, _, "reply", ..] => reply = Some(*id), + _ => {} + } + } + if broadcast { + return None; + } + let parent = reply?; + Some(root.unwrap_or(parent).to_string()) +} + +fn is_unread(event: &Value, me: &str, channel_read_at: Option, state: &ReadState) -> bool { + if event + .get("pubkey") + .and_then(Value::as_str) + .is_some_and(|p| p.eq_ignore_ascii_case(me)) + { + return false; + } + let id = event.get("id").and_then(Value::as_str).unwrap_or(""); + let created_at = event.get("created_at").and_then(Value::as_u64).unwrap_or(0); + let read_at = [ + channel_read_at, + state.frontier(&format!("msg:{id}")), + thread_root(event).and_then(|root| state.frontier(&format!("thread:{root}"))), + ] + .into_iter() + .flatten() + .max(); + read_at.is_none_or(|read_at| created_at > read_at) +} + +fn newest_by_d(events: Vec) -> HashMap { + let mut newest: HashMap = HashMap::new(); + for event in events { + let d = extract_d_tag(&event); + if d.is_empty() { + continue; + } + let at = |e: &Value| e.get("created_at").and_then(Value::as_u64).unwrap_or(0); + if newest.get(&d).is_none_or(|head| at(&event) > at(head)) { + newest.insert(d, event); + } + } + newest +} + +async fn member_channel_ids(client: &BuzzClient) -> Result, CliError> { + let filter = json!({ + "kinds": [KIND_GROUP_MEMBERS], + "#p": [client.public_key().to_hex()], + }); + let events = client + .query_all_bounded(filter, MEMBER_CHANNEL_LIMIT) + .await + .map_err(|e| match e { + CliError::Other(msg) => { + CliError::Other(format!("{msg}; name the channels with --channel instead")) + } + other => other, + })?; + let mut ids: Vec = events + .iter() + .map(extract_d_tag) + .filter(|id| !id.is_empty()) + .collect(); + ids.sort(); + ids.dedup(); + Ok(ids) +} + +async fn channel_metadata( + client: &BuzzClient, + ids: &[String], +) -> Result, CliError> { + if ids.is_empty() { + return Ok(HashMap::new()); + } + let filter = json!({"kinds": [KIND_GROUP_METADATA], "#d": ids}); + let events = client + .query_all_bounded(filter, MEMBER_CHANNEL_LIMIT) + .await?; + Ok(newest_by_d(events)) +} + +fn is_archived(metadata: &Value) -> bool { + tags(metadata).any(|t| t.as_slice() == ["archived", "true"]) +} + +async fn resolve_channels( + client: &BuzzClient, + requested: &[String], + limit: usize, +) -> Result<(Vec, usize), CliError> { + let explicit = !requested.is_empty(); + let ids = if explicit { + requested.to_vec() + } else { + member_channel_ids(client).await? + }; + let metadata = channel_metadata(client, &ids).await?; + let mut channels = Vec::new(); + for id in ids { + match metadata.get(&id) { + Some(meta) if !explicit && is_archived(meta) => {} + Some(meta) => channels.push(Channel { + name: extract_tag_value(meta, "name"), + is_dm: extract_tag_value(meta, "t") == "dm", + id, + }), + None if explicit => { + return Err(CliError::NotFound(format!("channel {id} not found"))); + } + None => channels.push(Channel { + name: String::new(), + is_dm: false, + id, + }), + } + } + channels.sort_by(|a, b| a.id.cmp(&b.id)); + let dropped = channels.len().saturating_sub(limit); + channels.truncate(limit); + Ok((channels, dropped)) +} + +async fn count_channel( + client: &BuzzClient, + channel: &Channel, + state: &ReadState, + bounds: &Bounds, +) -> Result { + let last_read_at = state.frontier(&channel.id); + let mut filter = json!({ + "kinds": message_kinds(channel.is_dm), + "#h": [channel.id], + }); + if let Some(read_at) = last_read_at { + filter["since"] = json!(read_at + 1); + } + let events = client + .query_paginated(filter, bounds.events_per_channel) + .await?; + let capped = events.len() >= bounds.events_per_channel as usize; + let me = client.public_key().to_hex(); + let unread = events + .iter() + .filter(|e| is_unread(e, &me, last_read_at, state)) + .count(); + Ok(ChannelUnread { + channel_id: channel.id.clone(), + name: channel.name.clone(), + last_read_at, + unread_count: u32::try_from(unread).unwrap_or(u32::MAX), + capped, + }) +} + +/// Compute unread counts for the user's channels, or for `requested` ones. +pub(crate) async fn unread( + client: &BuzzClient, + requested: &[String], + limit: Option, + bounds: &Bounds, +) -> Result { + let limit = match limit { + None => bounds.max_channels, + Some(0) => return Err(CliError::Usage("--limit must be at least 1".into())), + Some(n) if n as usize > bounds.max_channels => { + return Err(CliError::Usage(format!( + "--limit must be at most {}", + bounds.max_channels + ))); + } + Some(n) => n as usize, + }; + let mut requested: Vec = requested + .iter() + .map(|c| validate_uuid(c).map(|()| c.to_lowercase())) + .collect::>()?; + requested.sort(); + requested.dedup(); + if requested.len() > limit { + return Err(CliError::Usage(format!( + "{} channels given but at most {limit} can be counted per run", + requested.len() + ))); + } + + let state = read_state::fetch(client).await?; + let (channels, dropped) = resolve_channels(client, &requested, limit).await?; + let mut counted = Vec::with_capacity(channels.len()); + for channel in &channels { + counted.push(count_channel(client, channel, &state, bounds).await?); + } + counted.sort_by(|a, b| { + b.unread_count + .cmp(&a.unread_count) + .then_with(|| a.name.cmp(&b.name)) + .then_with(|| a.channel_id.cmp(&b.channel_id)) + }); + Ok(Outcome { + channels: counted, + dropped, + skipped_slots: state.skipped, + }) +} + +pub async fn cmd_unread( + client: &BuzzClient, + requested: &[String], + limit: Option, +) -> Result<(), CliError> { + let outcome = unread(client, requested, limit, &BOUNDS).await?; + if outcome.dropped > 0 { + eprintln!( + "{}", + json!({ + "warning": "channels_truncated", + "counted": outcome.channels.len(), + "dropped": outcome.dropped, + "message": "more channels than --limit; rerun with --channel to count the rest", + }) + ); + } + if !outcome.skipped_slots.is_empty() { + let slots: Vec = outcome + .skipped_slots + .iter() + .map(|s| json!({"d": s.d_tag, "v": s.version})) + .collect(); + eprintln!( + "{}", + json!({ + "warning": "read_state_slots_skipped", + "slots": slots, + "message": "written by a newer schema; counts may overstate unread", + }) + ); + } + let out = serde_json::to_string(&outcome.channels) + .map_err(|e| CliError::Other(format!("failed to encode unread counts: {e}")))?; + println!("{out}"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::commands::read_state::tests::{slot_event, snapshot_descriptor, snapshot_envelope}; + use axum::{body::Bytes, extract::State, routing::get, routing::post, Json, Router}; + use nostr::Keys; + use std::sync::{Arc, Mutex}; + use tokio::net::TcpListener; + + #[derive(Default)] + struct Relay { + events: Vec, + filters: Vec, + } + type Shared = Arc>; + + fn tag_values(filter: &Value, key: &str) -> Vec { + filter[key] + .as_array() + .map(|a| { + a.iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() + } + + fn matches(event: &Value, filter: &Value) -> bool { + let kinds: Vec = filter["kinds"] + .as_array() + .unwrap() + .iter() + .filter_map(Value::as_u64) + .collect(); + let has_tag = |name: &str, wanted: Vec| { + wanted.is_empty() + || tags(event).any(|t| { + t.first() == Some(&name) && wanted.iter().any(|w| t.get(1) == Some(&w.as_str())) + }) + }; + kinds.contains(&event["kind"].as_u64().unwrap()) + && filter["authors"] + .as_array() + .is_none_or(|a| a.iter().any(|x| x == &event["pubkey"])) + && event["created_at"].as_u64().unwrap() >= filter["since"].as_u64().unwrap_or(0) + && has_tag("h", tag_values(filter, "#h")) + && has_tag("d", tag_values(filter, "#d")) + && has_tag("p", tag_values(filter, "#p")) + && has_tag("t", tag_values(filter, "#t")) + } + + async fn fake_relay(relay: Shared) -> String { + let app = Router::new() + .route( + "/query", + post(|State(relay): State, body: Bytes| async move { + let filters: Vec = serde_json::from_slice(&body).unwrap(); + let [filter] = filters.as_slice() else { + panic!("one filter expected") + }; + let mut relay = relay.lock().unwrap(); + relay.filters.push(filter.clone()); + if filter.get("read_state_snapshot").is_some() { + let own: Vec = relay + .events + .iter() + .filter(|e| { + e["kind"] == 30078 && filter["authors"] == json!([e["pubkey"]]) + }) + .cloned() + .collect(); + let author = filter["authors"][0].as_str().unwrap(); + return Json(snapshot_envelope(author, own)); + } + let mut hits: Vec = relay + .events + .iter() + .filter(|e| matches(e, filter)) + .cloned() + .collect(); + hits.sort_by_key(|e| std::cmp::Reverse(e["created_at"].as_u64().unwrap())); + hits.truncate(filter["limit"].as_u64().unwrap() as usize); + Json(json!(hits)) + }), + ) + .route( + "/info", + get(|| async { Json(json!({"read_state_snapshot": snapshot_descriptor()})) }), + ) + .with_state(relay); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + struct World { + client: BuzzClient, + relay: Shared, + other: Keys, + counter: u64, + } + + const GEN: &str = "11111111-1111-4111-8111-111111111111"; + const DEV: &str = "22222222-2222-4222-8222-222222222222"; + const OLD: &str = "33333333-3333-4333-8333-333333333333"; + const NEW: &str = "44444444-4444-4444-8444-444444444444"; + + async fn world() -> World { + let relay = Shared::default(); + let url = fake_relay(relay.clone()).await; + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); + World { + client, + relay, + other: Keys::generate(), + counter: 0, + } + } + + impl World { + fn push(&self, event: Value) { + self.relay.lock().unwrap().events.push(event); + } + + fn signed(&self, keys: &Keys, kind: u16, tags: Vec, at: u64) -> Value { + let event = nostr::EventBuilder::new(nostr::Kind::Custom(kind), "x") + .tags(tags) + .custom_created_at(nostr::Timestamp::from(at)) + .sign_with_keys(keys) + .unwrap(); + serde_json::to_value(event).unwrap() + } + + fn member(&self, channel: &str) { + let me = self.client.public_key(); + let tags = vec![nostr::Tag::identifier(channel), nostr::Tag::public_key(me)]; + self.push(self.signed(&Keys::generate(), 39002, tags, 1)); + } + + fn channel(&self, id: &str, name: &str, extra: &[(&str, &str)]) { + let mut tags = vec![ + nostr::Tag::identifier(id), + nostr::Tag::parse(["name", name]).unwrap(), + ]; + tags.extend( + extra + .iter() + .map(|(k, v)| nostr::Tag::parse([*k, *v]).unwrap()), + ); + self.push(self.signed(&Keys::generate(), 39000, tags, 1)); + } + + fn say(&mut self, channel: &str, author: &Keys, at: u64, extra: &[Vec<&str>]) -> String { + self.counter += 1; + let mut tags = vec![nostr::Tag::parse(["h", channel]).unwrap()]; + tags.extend(extra.iter().map(|t| nostr::Tag::parse(t.clone()).unwrap())); + tags.push(nostr::Tag::parse(["nonce", &self.counter.to_string()]).unwrap()); + let event = self.signed(author, 9, tags, at); + let id = event["id"].as_str().unwrap().to_string(); + self.push(event); + id + } + + fn read_state(&self, slot: &str, contexts: Value, at: u64) { + let plaintext = json!({"v": 1, "client_id": slot, "contexts": contexts}).to_string(); + self.push(slot_event( + &self.client.credentials().test_keys(), + slot, + &plaintext, + at, + )); + } + + fn queries_for(&self, kind: u64) -> Vec { + self.relay + .lock() + .unwrap() + .filters + .iter() + .filter(|f| { + f["kinds"] + .as_array() + .is_some_and(|k| k.contains(&json!(kind))) + }) + .cloned() + .collect() + } + } + + fn by_id<'a>(out: &'a Outcome, id: &str) -> &'a ChannelUnread { + out.channels.iter().find(|c| c.channel_id == id).unwrap() + } + + #[tokio::test] + async fn counts_unread_with_desktop_rules() { + let mut w = world().await; + let me = w.client.credentials().test_keys(); + let other = w.other.clone(); + for (id, name) in [(GEN, "general"), (DEV, "dev"), (OLD, "old")] { + w.member(id); + w.channel(id, name, &[]); + } + w.member(NEW); + w.channel(NEW, "new", &[("archived", "true")]); + + // general: frontier 100 from slot a, raised to 150 by slot b (max-merge). + w.say(GEN, &other, 90, &[]); + w.say(GEN, &other, 120, &[]); + w.say(GEN, &other, 160, &[]); + w.say(GEN, &me, 170, &[]); + let marked = w.say(GEN, &other, 180, &[]); + let root = w.say(GEN, &other, 80, &[]); + let reply = w.say( + GEN, + &other, + 200, + &[vec!["e", &root, "", "root"], vec!["e", &root, "", "reply"]], + ); + let broadcast = w.say( + GEN, + &other, + 203, + &[ + vec!["e", &root, "", "root"], + vec!["e", &root, "", "reply"], + vec!["broadcast", "1"], + ], + ); + w.read_state("a", json!({GEN: 100, DEV: 5}), 1); + w.read_state( + "b", + json!({GEN: 150, format!("msg:{marked}"): 180, format!("thread:{root}"): 205}), + 2, + ); + // dev: never read, two from others, one of mine. + w.say(DEV, &other, 10, &[]); + w.say(DEV, &other, 11, &[]); + w.say(DEV, &me, 12, &[]); + // old: fully read. + w.say(OLD, &other, 50, &[]); + w.read_state("c", json!({OLD: 50}), 3); + let _ = (reply, broadcast); + + let out = unread(&w.client, &[], None, &BOUNDS).await.unwrap(); + + // 160 (> 150); 180 is covered by its msg marker; `reply` 200 is covered by + // thread:root 205; the broadcast reply 203 ignores the thread marker; 90/120 + // predate the frontier; mine is excluded. + assert_eq!(by_id(&out, GEN).unread_count, 2); + assert_eq!(by_id(&out, GEN).last_read_at, Some(150)); + assert_eq!(by_id(&out, DEV).unread_count, 2); + assert_eq!(by_id(&out, DEV).last_read_at, Some(5)); + assert_eq!(by_id(&out, OLD).unread_count, 0); + assert!( + out.channels.iter().all(|c| c.channel_id != NEW), + "archived is skipped" + ); + assert!(out.channels.iter().all(|c| !c.capped)); + assert_eq!(out.dropped, 0); + let order: Vec<_> = out.channels.iter().map(|c| c.name.as_str()).collect(); + assert_eq!( + order, + ["dev", "general", "old"], + "sorted by unread desc, then name" + ); + + // The production queries are bounded and scoped, not a firehose. + let reads = w.queries_for(9); + assert_eq!(reads.len(), 3); + for q in &reads { + assert!(q["limit"].as_u64().unwrap() <= u64::from(BOUNDS.events_per_channel)); + assert!(q["#h"].as_array().is_some_and(|h| h.len() == 1)); + } + let general_q = reads.iter().find(|q| q["#h"] == json!([GEN])).unwrap(); + assert_eq!( + general_q["since"], + json!(151), + "reads start after the frontier" + ); + let dev_q = reads.iter().find(|q| q["#h"] == json!([DEV])).unwrap(); + assert_eq!(dev_q["since"], json!(6)); + let state_qs = w.queries_for(30078); + assert_eq!(state_qs.len(), 1, "read state is one atomic snapshot"); + assert_eq!(state_qs[0]["read_state_snapshot"], json!(1)); + for paging in ["#t", "since", "until", "limit"] { + assert!(state_qs[0].get(paging).is_none(), "{paging}"); + } + } + + #[tokio::test] + async fn bounds_channels_and_events_and_says_so() { + let mut w = world().await; + let other = w.other.clone(); + for id in [GEN, DEV, OLD] { + w.member(id); + w.channel(id, id, &[]); + for at in 1..=4 { + w.say(id, &other, at, &[]); + } + } + let bounds = Bounds { + max_channels: 2, + events_per_channel: 3, + }; + + let out = unread(&w.client, &[], Some(2), &bounds).await.unwrap(); + assert_eq!((out.channels.len(), out.dropped), (2, 1)); + assert!(out.channels.iter().all(|c| c.capped && c.unread_count == 3)); + assert_eq!( + w.queries_for(9).len(), + 2, + "the dropped channel is never queried" + ); + + let err = unread(&w.client, &[], Some(3), &bounds).await.unwrap_err(); + assert!(matches!(err, CliError::Usage(_))); + let err = unread(&w.client, &[], Some(0), &bounds).await.unwrap_err(); + assert!(matches!(err, CliError::Usage(_))); + let all = [GEN, DEV, OLD].map(String::from); + let err = unread(&w.client, &all, None, &bounds).await.unwrap_err(); + assert!( + matches!(err, CliError::Usage(_)), + "explicit channels are never silently dropped" + ); + } + + #[tokio::test] + async fn explicit_channels_are_validated_and_must_exist() { + let mut w = world().await; + let other = w.other.clone(); + w.channel(GEN, "general", &[("archived", "true"), ("t", "dm")]); + w.say(GEN, &other, 5, &[]); + + let out = unread(&w.client, &[GEN.to_uppercase(), GEN.into()], None, &BOUNDS) + .await + .unwrap(); + assert_eq!( + out.channels.len(), + 1, + "case-insensitive dedupe; archived is allowed when named" + ); + assert_eq!(out.channels[0].unread_count, 1); + let queried = w.queries_for(9); + assert!( + queried[0]["kinds"] + .as_array() + .unwrap() + .contains(&json!(48100)), + "dm counts huddle starts" + ); + + let err = unread(&w.client, &["nope".into()], None, &BOUNDS) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_))); + let err = unread(&w.client, &[DEV.into()], None, &BOUNDS) + .await + .unwrap_err(); + assert!(matches!(err, CliError::NotFound(_))); + } + + #[tokio::test] + async fn an_unreadable_slot_fails_the_command_before_any_count() { + let w = world().await; + w.member(GEN); + w.channel(GEN, "general", &[]); + w.read_state("a", json!({GEN: 1}), 1); + w.push(slot_event( + &w.client.credentials().test_keys(), + "b", + "garbage", + 2, + )); + + let err = unread(&w.client, &[], None, &BOUNDS).await.unwrap_err(); + assert!(err.to_string().contains("unreadable"), "{err}"); + assert!(w.queries_for(9).is_empty()); + assert!(w.queries_for(39002).is_empty()); + } +} diff --git a/crates/buzz-cli/src/commands/channels.rs b/crates/buzz-cli/src/commands/channels.rs index e9425800cc0..eee7d4f797f 100644 --- a/crates/buzz-cli/src/commands/channels.rs +++ b/crates/buzz-cli/src/commands/channels.rs @@ -36,7 +36,7 @@ pub async fn cmd_list_channels( let effective_limit = limit.unwrap_or(500); let events = if member == Some(true) { // Step 1: find channel IDs where we're a member (kind:39002) - let my_pk = client.keys().public_key().to_hex(); + let my_pk = client.public_key().to_hex(); let member_filter = serde_json::json!({ "kinds": [39002], "#p": [my_pk], @@ -457,7 +457,7 @@ pub async fn cmd_restore_canvas( let builder = buzz_sdk::build_set_canvas_after_head(channel_uuid, &content, head_id, head_created_at) .map_err(|e| CliError::Other(format!("build_set_canvas failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let our_id = event.id.to_hex(); let submit_result = client.submit_event(event).await; @@ -733,7 +733,7 @@ pub async fn cmd_create_channel( ) .map_err(|e| CliError::Other(format!("build_create_channel failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; print_create_response(&resp, "channel_id", &channel_uuid.to_string()); Ok(()) @@ -1493,7 +1493,7 @@ pub async fn cmd_create_channel_from_template( // be selected. let owner = client .auth_tag_owner_hex() - .unwrap_or_else(|| client.keys().public_key().to_hex()); + .unwrap_or_else(|| client.public_key().to_hex()); let resolved = build_roster_resolution(client, &owner, &template.agents).await?; @@ -1519,7 +1519,7 @@ pub async fn cmd_create_channel_from_template( unlisted, ) .map_err(|e| CliError::Other(format!("build_create_channel failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; client.submit_event(event).await?; let mut canvas_applied = false; @@ -1532,7 +1532,7 @@ pub async fn cmd_create_channel_from_template( // `Some("none")` to match the create-assertion convention. let builder = buzz_sdk::build_set_canvas(channel_uuid, &content, Some("none")) .map_err(|e| CliError::Other(format!("build_set_canvas failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; client.submit_event(event).await?; Ok(()) } @@ -1554,7 +1554,7 @@ pub async fn cmd_create_channel_from_template( Some(buzz_sdk::MemberRole::Bot), ) .map_err(|e| CliError::Other(format!("build_add_member failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; client.submit_event(event).await?; Ok(()) } @@ -1640,6 +1640,7 @@ fn validate_update_channel_fields( ttl_change: Option>, join_role: Option, unlisted: Option, + auto_join: Option, ) -> Result<(), CliError> { if name.is_none() && description.is_none() @@ -1647,9 +1648,10 @@ fn validate_update_channel_fields( && ttl_change.is_none() && join_role.is_none() && unlisted.is_none() + && auto_join.is_none() { return Err(CliError::Usage( - "at least one field required (--name, --description, --visibility, --ttl, --no-ttl, --join-role, --unlisted)" + "at least one field required (--name, --description, --visibility, --ttl, --no-ttl, --join-role, --unlisted, --auto-join)" .into(), )); } @@ -1667,6 +1669,7 @@ pub async fn cmd_update_channel( no_ttl: bool, join_role: Option, unlisted: Option, + auto_join: Option, ) -> Result<(), CliError> { // Outer Option: None leaves TTL unchanged. Inner: Some(secs) sets it, // None (from --no-ttl) clears it, making the channel permanent. @@ -1683,6 +1686,7 @@ pub async fn cmd_update_channel( ttl_change, join_role, unlisted, + auto_join, )?; let channel_uuid = parse_uuid(channel_id)?; // `--unlisted false` needs no check: a relay without the extension lists @@ -1699,10 +1703,11 @@ pub async fn cmd_update_channel( ttl_change, join_role, unlisted, + auto_join, ) .map_err(|e| CliError::Other(format!("build_update_channel failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1718,7 +1723,7 @@ pub async fn cmd_set_channel_topic( let builder = buzz_sdk::build_set_topic(channel_uuid, topic) .map_err(|e| CliError::Other(format!("build_set_topic failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1734,7 +1739,7 @@ pub async fn cmd_set_channel_purpose( let builder = buzz_sdk::build_set_purpose(channel_uuid, purpose) .map_err(|e| CliError::Other(format!("build_set_purpose failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1746,7 +1751,7 @@ pub async fn cmd_join_channel(client: &BuzzClient, channel_id: &str) -> Result<( let builder = buzz_sdk::build_join(channel_uuid) .map_err(|e| CliError::Other(format!("build_join failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1758,7 +1763,7 @@ pub async fn cmd_leave_channel(client: &BuzzClient, channel_id: &str) -> Result< let builder = buzz_sdk::build_leave(channel_uuid) .map_err(|e| CliError::Other(format!("build_leave failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1770,7 +1775,7 @@ pub async fn cmd_archive_channel(client: &BuzzClient, channel_id: &str) -> Resul let builder = buzz_sdk::build_archive(channel_uuid) .map_err(|e| CliError::Other(format!("build_archive failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1782,7 +1787,7 @@ pub async fn cmd_unarchive_channel(client: &BuzzClient, channel_id: &str) -> Res let builder = buzz_sdk::build_unarchive(channel_uuid) .map_err(|e| CliError::Other(format!("build_unarchive failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1794,7 +1799,7 @@ pub async fn cmd_delete_channel(client: &BuzzClient, channel_id: &str) -> Result let builder = buzz_sdk::build_delete_channel(channel_uuid) .map_err(|e| CliError::Other(format!("build_delete_channel failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1825,7 +1830,7 @@ pub async fn cmd_add_channel_member( let builder = buzz_sdk::build_add_member(channel_uuid, pubkey, typed_role) .map_err(|e| CliError::Other(format!("build_add_member failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1842,7 +1847,7 @@ pub async fn cmd_remove_channel_member( let builder = buzz_sdk::build_remove_member(channel_uuid, pubkey) .map_err(|e| CliError::Other(format!("build_remove_member failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1886,7 +1891,7 @@ pub async fn cmd_set_add_policy(client: &BuzzClient, policy: &str) -> Result<(), &content, ) .tags([]); - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -1926,7 +1931,7 @@ pub async fn cmd_set_canvas( } .map_err(|e| CliError::Other(format!("build_set_canvas failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -1947,6 +1952,9 @@ pub async fn dispatch( let vis_str = visibility.as_ref().map(|v| v.to_string()); cmd_list_channels(client, vis_str.as_deref(), Some(member), limit, format).await } + ChannelsCmd::Unread { channel, limit } => { + crate::commands::channel_unread::cmd_unread(client, &channel, limit).await + } ChannelsCmd::Get { channel } => cmd_get_channel(client, &channel).await, ChannelsCmd::Search { query, @@ -2005,6 +2013,7 @@ pub async fn dispatch( no_ttl, join_role, unlisted, + auto_join, } => { let visibility = visibility.as_ref().map(|v| v.to_string()); cmd_update_channel( @@ -2017,6 +2026,7 @@ pub async fn dispatch( no_ttl, join_role.map(Into::into), unlisted, + auto_join, ) .await } @@ -2213,7 +2223,7 @@ mod tests { #[test] fn update_channel_fields_rejects_empty_update() { - let result = validate_update_channel_fields(None, None, None, None, None, None); + let result = validate_update_channel_fields(None, None, None, None, None, None, None); assert!(matches!(result, Err(CliError::Usage(_)))); let msg = result.unwrap_err().to_string(); assert!(msg.contains("at least one field required")); @@ -2222,7 +2232,8 @@ mod tests { #[test] fn update_channel_fields_accepts_visibility_only_update() { - let result = validate_update_channel_fields(None, None, Some("open"), None, None, None); + let result = + validate_update_channel_fields(None, None, Some("open"), None, None, None, None); assert!(result.is_ok(), "visibility-only update should be accepted"); } @@ -2289,8 +2300,11 @@ mod tests { let keys = nostr::Keys::parse("0000000000000000000000000000000000000000000000000000000000000001") .expect("valid test key"); - BuzzClient::new("ws://localhost:3000".to_string(), keys, None, None) - .expect("client construction should not fail") + BuzzClient::new( + "ws://localhost:3000".to_string(), + crate::credentials::Credentials::from_keys(keys), + ) + .expect("client construction should not fail") } #[tokio::test] @@ -3397,8 +3411,11 @@ mod tests { let keys = nostr::Keys::parse("0000000000000000000000000000000000000000000000000000000000000001") .expect("valid test key"); - let client = BuzzClient::new(format!("http://{addr}"), keys, None, None) - .expect("client construction should not fail"); + let client = BuzzClient::new( + format!("http://{addr}"), + crate::credentials::Credentials::from_keys(keys), + ) + .expect("client construction should not fail"); let map = fetch_candidate_hints( &client, @@ -3515,7 +3532,11 @@ mod set_canvas_tests { } fn client(base_url: &str) -> BuzzClient { - BuzzClient::new(base_url.to_string(), Keys::generate(), None, None).unwrap() + BuzzClient::new( + base_url.to_string(), + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap() } fn tag_value(event: &Value, key: &str) -> Option { @@ -3884,7 +3905,11 @@ mod restore_canvas_tests { } fn client(base_url: &str) -> BuzzClient { - BuzzClient::new(base_url.to_string(), Keys::generate(), None, None).unwrap() + BuzzClient::new( + base_url.to_string(), + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap() } /// Return all filter objects from all /query calls flattened into one vec. @@ -4710,7 +4735,11 @@ mod restore_canvas_already_current_tests { } fn client(base_url: &str) -> BuzzClient { - BuzzClient::new(base_url.to_string(), Keys::generate(), None, None).unwrap() + BuzzClient::new( + base_url.to_string(), + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap() } /// The already-current short-circuit must return Ok (exit 0) AND emit @@ -4798,7 +4827,11 @@ mod unlisted_support_tests { } fn client(base_url: &str) -> BuzzClient { - BuzzClient::new(base_url.to_string(), Keys::generate(), None, None).unwrap() + BuzzClient::new( + base_url.to_string(), + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap() } fn has_unlisted_true(event: &Value) -> bool { @@ -4829,6 +4862,7 @@ mod unlisted_support_tests { false, None, Some(true), + None, ) .await .unwrap_err(); @@ -4855,6 +4889,7 @@ mod unlisted_support_tests { false, None, Some(true), + None, ) .await .unwrap(); @@ -4883,6 +4918,7 @@ mod unlisted_support_tests { false, None, Some(false), + None, ) .await .unwrap(); diff --git a/crates/buzz-cli/src/commands/dms.rs b/crates/buzz-cli/src/commands/dms.rs index 589e4118270..092e4a3cb3f 100644 --- a/crates/buzz-cli/src/commands/dms.rs +++ b/crates/buzz-cli/src/commands/dms.rs @@ -4,47 +4,71 @@ use crate::client::{extract_d_tag, normalize_write_response, BuzzClient}; use crate::error::CliError; use crate::validate::{parse_uuid, sdk_err, validate_hex64}; -/// List DM conversations by querying kind:41001 (relay-confirmed DMs) filtered by our pubkey. +/// Tag values named `name` on a relay event. +fn tag_values<'a>(event: &'a serde_json::Value, name: &'a str) -> impl Iterator { + event + .get("tags") + .and_then(|t| t.as_array()) + .into_iter() + .flatten() + .filter_map(move |tag| { + let arr = tag.as_array()?; + (arr.first()?.as_str()? == name) + .then(|| arr.get(1)?.as_str()) + .flatten() + }) +} + +/// List visible DM conversations: the viewer's DM group metadata (kind:39000 +/// `t=dm`, one `p` per participant), minus the DMs in the viewer's newest +/// relay-signed visibility snapshot (kind:30622, one `h` per hidden DM). pub async fn cmd_list_dms(client: &BuzzClient, limit: Option) -> Result<(), CliError> { - let my_pk = client.keys().public_key().to_hex(); - let limit = limit.unwrap_or(50).min(200); - let filter = serde_json::json!({ - "kinds": [41001], - "#p": [my_pk], - "limit": limit - }); - let resp = client.query(&filter).await?; - let events: Vec = serde_json::from_str(&resp).unwrap_or_default(); - let dms: Vec = events + let dms = list_dms(client, limit.unwrap_or(50).min(200)).await?; + println!("{}", serde_json::Value::Array(dms)); + Ok(()) +} + +async fn list_dms(client: &BuzzClient, limit: u32) -> Result, CliError> { + let my_pk = client.public_key().to_hex(); + let snapshots = client + .query_paginated( + serde_json::json!({ + "kinds": [buzz_sdk::kind::KIND_DM_VISIBILITY], + "#p": [my_pk], + }), + 10, + ) + .await?; + let hidden: std::collections::HashSet = snapshots + .iter() + .max_by_key(|e| e.get("created_at").and_then(|v| v.as_u64()).unwrap_or(0)) + .map(|e| tag_values(e, "h").map(str::to_owned).collect()) + .unwrap_or_default(); + let events = client + .query_paginated_keeping( + serde_json::json!({ + "kinds": [39000], + "#t": ["dm"], + "#p": [my_pk], + }), + limit, + |e| { + let dm_id = extract_d_tag(e); + !dm_id.is_empty() && !hidden.contains(&dm_id) + }, + ) + .await?; + Ok(events .iter() .map(|e| { - let dm_id = extract_d_tag(e); - let participants: Vec = e - .get("tags") - .and_then(|t| t.as_array()) - .map(|tags| { - tags.iter() - .filter_map(|tag| { - let arr = tag.as_array()?; - if arr.first()?.as_str()? == "p" { - arr.get(1)?.as_str().map(|s| s.to_string()) - } else { - None - } - }) - .collect() - }) - .unwrap_or_default(); + let participants: Vec<&str> = tag_values(e, "p").collect(); serde_json::json!({ - "dm_id": dm_id, + "dm_id": extract_d_tag(e), "participants": participants, "created_at": e.get("created_at").and_then(|v| v.as_u64()).unwrap_or(0), }) }) - .collect(); - let output = serde_json::to_string(&dms).unwrap_or_default(); - println!("{output}"); - Ok(()) + .collect()) } /// Open a DM with one or more users — sign and submit a kind:41010 event with a d-tag. @@ -67,7 +91,7 @@ pub async fn cmd_open_dm(client: &BuzzClient, pubkeys: &[String]) -> Result<(), .collect::, _>>()?; tags.push(Tag::parse(["d", &dm_id]).map_err(|e| CliError::Other(format!("tag error: {e}")))?); let builder = EventBuilder::new(Kind::Custom(41010), "").tags(tags); - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; // Try to extract relay-assigned channel_id from response message. @@ -101,7 +125,7 @@ pub async fn cmd_hide_dm(client: &BuzzClient, channel_id: &str) -> Result<(), Cl .map_err(|e| CliError::Other(format!("tag error: {e}")))?]; let builder = EventBuilder::new(Kind::Custom(buzz_sdk::kind::KIND_DM_HIDE as u16), "").tags(tags); - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -118,7 +142,7 @@ pub async fn cmd_add_dm_member( validate_hex64(pubkey)?; let builder = buzz_sdk::build_dm_add_member(channel_uuid, pubkey).map_err(sdk_err)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -134,3 +158,212 @@ pub async fn dispatch(cmd: crate::DmsCmd, client: &BuzzClient) -> Result<(), Cli DmsCmd::Hide { channel } => cmd_hide_dm(client, &channel).await, } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + /// A relay holding `events` (newest first) that pages `/query` by its + /// composite cursor, logging each filter it answers. + async fn relay(events: Vec) -> (String, Arc>>) { + use axum::{routing::post, Json, Router}; + let log = Arc::new(Mutex::new(Vec::new())); + let seen = log.clone(); + let app = Router::new().route( + "/query", + post(move |Json(filters): Json>| { + let events = events.clone(); + let seen = seen.clone(); + async move { + let f = filters[0].clone(); + seen.lock().unwrap().push(f.clone()); + let kind = f["kinds"][0].as_u64(); + let limit = f["limit"].as_u64().unwrap_or(500) as usize; + let after_cursor = |e: &&serde_json::Value| match f["before_id"].as_str() { + None => true, + Some(id) => { + let at = f["until"].as_u64().unwrap(); + let t = e["created_at"].as_u64().unwrap(); + t < at || (t == at && e["id"].as_str().unwrap() > id) + } + }; + let page: Vec<_> = events + .iter() + .filter(|e| e["kind"].as_u64() == kind) + .filter(after_cursor) + .take(limit) + .cloned() + .collect(); + Json(page) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (base, log) + } + + fn dm(n: u64) -> serde_json::Value { + serde_json::json!({ + "id": format!("{n:064x}"), + "kind": 39000, + "created_at": 1_000 + n, + "tags": [["d", format!("dm-{n}")], ["t", "dm"]], + }) + } + + #[tokio::test] + async fn hidden_dms_do_not_crowd_out_older_visible_ones() { + // 200 newer hidden DMs, then one older visible DM. + let mut events: Vec<_> = (1..=200).rev().map(dm).collect(); + events.push(dm(0)); + let hidden: Vec<_> = (1..=200) + .map(|n| serde_json::json!(["h", format!("dm-{n}")])) + .collect(); + events.push(serde_json::json!({ + "id": "f".repeat(64), "kind": 30622, "created_at": 5_000, "tags": hidden, + })); + let (base, _) = relay(events).await; + let client = BuzzClient::new( + base, + crate::credentials::Credentials::from_keys(nostr::Keys::generate()), + ) + .unwrap(); + + let dms = list_dms(&client, 200).await.unwrap(); + + assert_eq!(dms.len(), 1, "{dms:?}"); + assert_eq!(dms[0]["dm_id"], "dm-0"); + } + + #[tokio::test] + async fn a_small_limit_still_reads_full_pages_past_hidden_dms() { + // 150 newer hidden DMs, then one older visible DM, with limit 1. + let mut events: Vec<_> = (1..=150).rev().map(dm).collect(); + events.push(dm(0)); + let hidden: Vec<_> = (1..=150) + .map(|n| serde_json::json!(["h", format!("dm-{n}")])) + .collect(); + events.push(serde_json::json!({ + "id": "f".repeat(64), "kind": 30622, "created_at": 5_000, "tags": hidden, + })); + let (base, log) = relay(events).await; + + let dms = list_dms(&client(base), 1).await.unwrap(); + + assert_eq!(dms.len(), 1, "{dms:?}"); + assert_eq!(dms[0]["dm_id"], "dm-0"); + let log = log.lock().unwrap(); + let dm_pages: Vec<_> = log.iter().filter(|f| f["kinds"][0] == 39000).collect(); + assert_eq!(dm_pages.len(), 1, "{dm_pages:?}"); + assert_eq!(dm_pages[0]["limit"], crate::client::QUERY_PAGE_SIZE); + } + + #[tokio::test] + async fn pages_past_a_hidden_dm_with_the_same_timestamp() { + // Equal timestamps come back in ascending id order. + let same = |n: u64| { + let mut e = dm(n); + e["created_at"] = serde_json::json!(1_000); + e + }; + // A full page of hidden DMs, then a visible one with the same + // timestamp and a larger id, so the cursor must stay on that second. + let page = crate::client::QUERY_PAGE_SIZE as u64; + let mut events: Vec<_> = (1..=page + 1).map(same).collect(); + let hidden: Vec<_> = (1..=page) + .map(|n| serde_json::json!(["h", format!("dm-{n}")])) + .collect(); + events.push(serde_json::json!({ + "id": "f".repeat(64), "kind": 30622, "created_at": 5_000, "tags": hidden, + })); + let (base, log) = relay(events).await; + + let dms = list_dms(&client(base), 1).await.unwrap(); + + assert_eq!(dms.len(), 1, "{dms:?}"); + assert_eq!(dms[0]["dm_id"], format!("dm-{}", page + 1)); + assert!(log + .lock() + .unwrap() + .iter() + .any(|f| f["before_id"].is_string())); + } + + /// A relay that answers every DM-metadata query with `page(filter)`. + async fn fixed_relay( + page: fn(&serde_json::Value) -> Vec, + ) -> (String, Arc>) { + use axum::{routing::post, Json, Router}; + let count = Arc::new(Mutex::new(0)); + let seen = count.clone(); + let app = Router::new().route( + "/query", + post(move |Json(filters): Json>| { + let seen = seen.clone(); + async move { + let f = &filters[0]; + if f["kinds"][0].as_u64() != Some(39000) { + return Json(Vec::new()); + } + *seen.lock().unwrap() += 1; + Json(page(f)) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (base, count) + } + + /// A full page of DMs with no `d` tag, which `list_dms` drops, older + /// than the filter's cursor. + fn dropped_page(f: &serde_json::Value) -> Vec { + let top = f["until"].as_u64().unwrap_or(1_000_000); + (1..=f["limit"].as_u64().unwrap()) + .map(|n| { + serde_json::json!({ + "id": "a".repeat(64), "kind": 39000, "created_at": top - n, "tags": [], + }) + }) + .collect() + } + + fn client(base: String) -> BuzzClient { + BuzzClient::new( + base, + crate::credentials::Credentials::from_keys(nostr::Keys::generate()), + ) + .unwrap() + } + + #[tokio::test] + async fn a_relay_repeating_the_same_page_fails() { + let (base, count) = fixed_relay(|f| { + let mut f = f.clone(); + f["until"] = serde_json::Value::Null; + dropped_page(&f) + }) + .await; + + let err = list_dms(&client(base), 10).await.unwrap_err(); + + assert_eq!(crate::error::exit_code(&err), 2, "{err}"); + assert!(err.to_string().contains("cursor"), "{err}"); + assert_eq!(*count.lock().unwrap(), 2); + } + + #[tokio::test] + async fn a_relay_that_never_runs_out_fails_at_the_page_cap() { + let (base, count) = fixed_relay(dropped_page).await; + + let err = list_dms(&client(base), 10).await.unwrap_err(); + + assert_eq!(crate::error::exit_code(&err), 2, "{err}"); + assert!(err.to_string().contains("pages"), "{err}"); + assert_eq!(*count.lock().unwrap(), crate::client::MAX_QUERY_PAGES); + } +} diff --git a/crates/buzz-cli/src/commands/emoji.rs b/crates/buzz-cli/src/commands/emoji.rs index 32aef2f9273..0dc4388c0c6 100644 --- a/crates/buzz-cli/src/commands/emoji.rs +++ b/crates/buzz-cli/src/commands/emoji.rs @@ -120,7 +120,7 @@ async fn cmd_list(client: &BuzzClient) -> Result<(), CliError> { /// Fetch the caller's own current custom emoji set (latest kind:30030 under /// the d-tag, authored by the caller). Empty when none published yet. async fn fetch_own_emoji(client: &BuzzClient) -> Result, CliError> { - let me = client.keys().public_key().to_hex(); + let me = client.public_key().to_hex(); let filter = serde_json::json!({ "kinds": [buzz_sdk::kind::KIND_EMOJI_SET], "#d": [CUSTOM_EMOJI_SET_D_TAG], @@ -147,7 +147,7 @@ async fn fetch_own_emoji(client: &BuzzClient) -> Result, CliErr async fn publish_own_set(client: &BuzzClient, emojis: &[CustomEmoji]) -> Result<(), CliError> { let builder = buzz_sdk::build_custom_emoji_set(emojis) .map_err(|e| CliError::Other(format!("build_custom_emoji_set failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -636,7 +636,11 @@ mod tests { use tokio::net::TcpListener; fn test_client(base_url: &str) -> BuzzClient { - BuzzClient::new(base_url.to_string(), Keys::generate(), None, None).unwrap() + BuzzClient::new( + base_url.to_string(), + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap() } /// Fake relay: serves a `/query` endpoint returning the given JSON body, diff --git a/crates/buzz-cli/src/commands/feed.rs b/crates/buzz-cli/src/commands/feed.rs index 64d82d5714e..c5f655ced75 100644 --- a/crates/buzz-cli/src/commands/feed.rs +++ b/crates/buzz-cli/src/commands/feed.rs @@ -14,7 +14,7 @@ pub async fn cmd_get_feed( types: Option<&str>, format: &crate::OutputFormat, ) -> Result<(), CliError> { - let my_pk = client.keys().public_key().to_hex(); + let my_pk = client.public_key().to_hex(); let limit = limit.unwrap_or(20).min(50); let mut filter = serde_json::json!({ diff --git a/crates/buzz-cli/src/commands/gifs.rs b/crates/buzz-cli/src/commands/gifs.rs index 0352d2cdb37..b09a9da216e 100644 --- a/crates/buzz-cli/src/commands/gifs.rs +++ b/crates/buzz-cli/src/commands/gifs.rs @@ -40,37 +40,6 @@ pub(crate) fn safe_relay_path(path: &str) -> bool { && !path.split('/').any(|seg| seg == "." || seg == "..") } -// --------------------------------------------------------------------------- -// Customer ID derivation -// --------------------------------------------------------------------------- - -/// Derive a stable, relay-scoped anonymous `customer_id` from secret key material. -/// -/// KLIPY requires a per-installation identifier that is stable and anonymous. -/// Using SHA-256 of the *public* key would be stable but NOT anonymous — the -/// input is public, so the ID is computable by any observer, and the same value -/// would appear across all relays (cross-relay linkability). -/// -/// Instead, we domain-separate with the relay URL and sign with the *secret* key: -/// `SHA-256(secret_key_bytes || '\0' || relay_url_bytes)` -/// This is: -/// - **stable**: deterministic given the same keypair + relay. -/// - **relay-scoped**: different relay → different ID, no cross-relay correlation. -/// - **not computable from public data**: requires secret key material. -/// - **stateless**: no file I/O, no storage. -/// -/// The first 16 bytes (32 hex chars) give 128 bits of uniqueness, ample for -/// KLIPY's per-installation needs. -fn customer_id(secret_key_bytes: &[u8], relay_url: &str) -> String { - use sha2::{Digest, Sha256}; - let mut hasher = Sha256::new(); - hasher.update(secret_key_bytes); - hasher.update(b"\0"); // domain separator - hasher.update(relay_url.as_bytes()); - let hash = hasher.finalize(); - hex::encode(&hash[..16]) // 16 bytes → 32 hex chars -} - // --------------------------------------------------------------------------- // Locale // --------------------------------------------------------------------------- @@ -336,10 +305,9 @@ pub(crate) async fn search_entries( locale: Option<&str>, ) -> Result, CliError> { let (search_path, _) = resolve_gif_descriptor(client).await?; - let cid = customer_id( - client.keys().secret_key().as_secret_bytes(), - client.relay_url(), - ); + let cid = client + .credentials() + .relay_scoped_customer_id(client.relay_url()); let locale = locale.map(|l| l.to_string()).unwrap_or_else(default_locale); let body = serde_json::json!({ @@ -358,10 +326,9 @@ pub(crate) async fn search_entries( /// `{"accepted": true}` on success. pub async fn cmd_share(client: &BuzzClient, slug: &str) -> Result<(), CliError> { let (_, share_path) = resolve_gif_descriptor(client).await?; - let cid = customer_id( - client.keys().secret_key().as_secret_bytes(), - client.relay_url(), - ); + let cid = client + .credentials() + .relay_scoped_customer_id(client.relay_url()); let body = serde_json::json!({ "slug": slug, @@ -429,51 +396,6 @@ mod tests { assert!(!safe_relay_path("//")); } - // ----------------------------------------------------------------------- - // customer_id - // ----------------------------------------------------------------------- - - #[test] - fn customer_id_is_32_hex_chars_and_stable() { - let sk = [0xab_u8; 32]; - let id = customer_id(&sk, "https://relay.example"); - assert_eq!(id.len(), 32); - assert!(id.chars().all(|c| c.is_ascii_hexdigit())); - assert_eq!(id, customer_id(&sk, "https://relay.example")); - } - - #[test] - fn customer_id_is_relay_scoped() { - let sk = [0xcd_u8; 32]; - let id_a = customer_id(&sk, "https://relay-a.example"); - let id_b = customer_id(&sk, "https://relay-b.example"); - assert_ne!( - id_a, id_b, - "same key, different relay → different customer_id" - ); - } - - #[test] - fn customer_id_differs_for_different_keys() { - let id_a = customer_id(&[0xaa_u8; 32], "https://relay.example"); - let id_b = customer_id(&[0xbb_u8; 32], "https://relay.example"); - assert_ne!(id_a, id_b); - } - - #[test] - fn customer_id_not_equal_to_pubkey_hash() { - // The customer_id must NOT be derivable from the public key alone. - use sha2::{Digest, Sha256}; - let sk = [0xde_u8; 32]; - // What the old pubkey-hash approach would have produced (approximately): - let naive_hash = hex::encode(&Sha256::digest(hex::encode(sk).as_bytes())[..16]); - let actual = customer_id(&sk, "https://relay.example"); - assert_ne!( - actual, naive_hash, - "customer_id must not equal SHA-256(pubkey_hex)[..16]" - ); - } - // ----------------------------------------------------------------------- // default_locale // ----------------------------------------------------------------------- @@ -783,7 +705,11 @@ mod tests { /// Client without an auth tag — used for basic NIP-98 / body / path tests. fn test_client(base_url: &str) -> BuzzClient { let keys = Keys::generate(); - BuzzClient::new(base_url.to_string(), keys, None, None).unwrap() + BuzzClient::new( + base_url.to_string(), + crate::credentials::Credentials::from_keys(keys), + ) + .unwrap() } /// Client with a synthetic `x-auth-tag` — used to assert that the header @@ -803,9 +729,7 @@ mod tests { let tag = Tag::parse(tag_vec).unwrap(); let client = BuzzClient::new( base_url.to_string(), - keys, - Some(tag), - Some(tag_json.clone()), + crate::credentials::Credentials::from_keys(keys).with_auth_tag(tag, tag_json.clone()), ) .unwrap(); (client, tag_json) diff --git a/crates/buzz-cli/src/commands/huddle_tracker.rs b/crates/buzz-cli/src/commands/huddle_tracker.rs new file mode 100644 index 00000000000..48d77c0650f --- /dev/null +++ b/crates/buzz-cli/src/commands/huddle_tracker.rs @@ -0,0 +1,455 @@ +//! Huddle lifecycle reconstruction. +//! +//! A port of desktop's `HuddlePresenceTracker` +//! (`desktop/src/features/huddle/lib/huddlePresence.ts`) so the CLI and the app +//! agree on who is in a huddle and whether it ended. Keep the two in step; the +//! unit tests replay recorded sequences that desktop's own tracker also accepts. +//! +//! The CLI reads over HTTP, where the relay's synthetic liveness snapshots +//! (kind 48104) are not served, so generations are never authoritative here. + +use std::collections::{HashMap, VecDeque}; + +use buzz_core::kind::{ + KIND_HUDDLE_ENDED, KIND_HUDDLE_PARTICIPANT_JOINED, KIND_HUDDLE_PARTICIPANT_LEFT, + KIND_HUDDLE_STARTED, +}; +use serde_json::Value; + +use crate::error::CliError; + +/// Departed admissions remembered per session before older ones are compacted. +const MAX_DEPARTED_ADMISSIONS: usize = 1_000; + +/// Largest integer JavaScript represents exactly (`Number.MAX_SAFE_INTEGER`). +const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1; + +/// One huddle lifecycle event, reduced to the fields the tracker reads. +#[derive(Debug, Clone)] +pub(crate) struct LifecycleEvent { + pub id: String, + pub kind: u32, + pub pubkey: String, + pub created_at: u64, + participant: Option, + session: Option, + roster_revision: Option, + admission_id: Option, + generation: Option, +} + +impl LifecycleEvent { + /// Reduce a relay event JSON object. Content that is not the expected + /// JSON yields an event with no session, which the tracker ignores. + pub(crate) fn parse(event: &Value) -> Result { + let field = |name: &str| { + event + .get(name) + .ok_or_else(|| CliError::Other(format!("relay event missing {name}"))) + }; + let id = field("id")? + .as_str() + .ok_or_else(|| CliError::Other("relay event id is not a string".into()))? + .to_string(); + let kind = field("kind")? + .as_u64() + .and_then(|kind| u32::try_from(kind).ok()) + .ok_or_else(|| CliError::Other(format!("relay event {id} has an invalid kind")))?; + let pubkey = normalize_pubkey( + field("pubkey")? + .as_str() + .ok_or_else(|| CliError::Other(format!("relay event {id} has no pubkey")))?, + ); + let created_at = field("created_at")?.as_u64().ok_or_else(|| { + CliError::Other(format!("relay event {id} has an invalid created_at")) + })?; + let tags = field("tags")? + .as_array() + .ok_or_else(|| CliError::Other(format!("relay event {id} tags are not an array")))?; + let participant = tags + .iter() + .find(|tag| tag.get(0).and_then(Value::as_str) == Some("p")) + .and_then(|tag| tag.get(1).and_then(Value::as_str)) + .map(normalize_pubkey) + .or_else(|| (!pubkey.is_empty()).then(|| pubkey.clone())) + .filter(|participant| !participant.is_empty()); + + let content = event + .get("content") + .and_then(Value::as_str) + .and_then(|content| serde_json::from_str::(content).ok()) + .unwrap_or(Value::Null); + let text = |name: &str| { + content + .get(name) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .map(str::to_string) + }; + Ok(Self { + id, + kind, + pubkey, + created_at, + participant, + session: text("ephemeral_channel_id"), + roster_revision: content.get("roster_revision").and_then(safe_integer), + admission_id: text("admission_id"), + generation: text("generation"), + }) + } +} + +fn normalize_pubkey(value: &str) -> String { + value.trim().to_lowercase() +} + +fn safe_integer(value: &Value) -> Option { + if let Some(n) = value.as_u64() { + return (n <= MAX_SAFE_INTEGER).then_some(n); + } + let f = value.as_f64()?; + (f >= 0.0 && f.fract() == 0.0 && f <= MAX_SAFE_INTEGER as f64).then_some(f as u64) +} + +fn lifecycle_phase(kind: u32) -> u8 { + match kind { + KIND_HUDDLE_STARTED => 0, + KIND_HUDDLE_ENDED => 2, + _ => 1, + } +} + +/// Order lifecycle events as desktop does: time, then start < join/leave < +/// end, then the relay's roster revision, then event id. +pub(crate) fn compare_lifecycle_events( + left: &LifecycleEvent, + right: &LifecycleEvent, +) -> std::cmp::Ordering { + left.created_at + .cmp(&right.created_at) + .then_with(|| lifecycle_phase(left.kind).cmp(&lifecycle_phase(right.kind))) + .then_with(|| match (left.roster_revision, right.roster_revision) { + (Some(l), Some(r)) => l.cmp(&r), + _ => std::cmp::Ordering::Equal, + }) + .then_with(|| left.id.cmp(&right.id)) +} + +#[derive(Debug, Clone)] +struct Admission { + present: bool, + roster_revision: Option, + created_at: u64, + event_id: String, +} + +fn is_newer(candidate: &Admission, existing: Option<&Admission>) -> bool { + let Some(existing) = existing else { + return true; + }; + if let (Some(c), Some(e)) = (candidate.roster_revision, existing.roster_revision) { + if c != e { + return c > e; + } + } + if candidate.created_at != existing.created_at { + return candidate.created_at > existing.created_at; + } + candidate.event_id > existing.event_id +} + +/// The reconstructed state of one huddle. +#[derive(Debug, Clone)] +pub(crate) struct HuddleSession { + pub start_creator: String, + pub start_created_at: u64, + pub start_event_id: String, + pub ended_at: Option, + end: Option, + admissions: HashMap>, + legacy: HashMap, + latest_roster_revision: Option, + latest_roster_created_at: u64, + latest_roster_event_id: String, + generation: Option, + departed: VecDeque<(String, Admission)>, + compacted_revision_floor: Option, +} + +impl HuddleSession { + fn clear_roster(&mut self) { + self.admissions.clear(); + self.legacy.clear(); + self.departed.clear(); + self.compacted_revision_floor = None; + } + + fn departed_position(&self, admission_id: &str) -> Option { + self.departed.iter().position(|(id, _)| id == admission_id) + } + + /// Present participants with the time they were first admitted, oldest + /// admission first, ties broken by pubkey. + pub(crate) fn participants(&self) -> Vec<(String, u64)> { + let mut roster: HashMap<&str, u64> = HashMap::new(); + for (participant, admissions) in &self.admissions { + for admission in admissions.values().filter(|a| a.present) { + roster + .entry(participant) + .and_modify(|at| *at = (*at).min(admission.created_at)) + .or_insert(admission.created_at); + } + } + for (participant, admission) in &self.legacy { + let has_admissions = self + .admissions + .get(participant) + .is_some_and(|admissions| !admissions.is_empty()); + if !has_admissions && admission.present { + roster.insert(participant, admission.created_at); + } + } + let mut roster: Vec<(String, u64)> = roster + .into_iter() + .map(|(participant, at)| (participant.to_string(), at)) + .collect(); + roster.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + roster + } +} + +/// Reconstructs huddles from relay-authenticated lifecycle events. +pub(crate) struct HuddleTracker { + relay_self: String, + sessions: HashMap, +} + +impl HuddleTracker { + pub(crate) fn new(relay_self_pubkey: &str) -> Self { + Self { + relay_self: normalize_pubkey(relay_self_pubkey), + sessions: HashMap::new(), + } + } + + /// Replay events in desktop's lifecycle order. + pub(crate) fn apply_history(&mut self, events: &[LifecycleEvent]) { + let mut sorted: Vec<&LifecycleEvent> = events.iter().collect(); + sorted.sort_by(|a, b| compare_lifecycle_events(a, b)); + for event in sorted { + self.apply(event); + } + } + + pub(crate) fn sessions(&self) -> &HashMap { + &self.sessions + } + + fn apply(&mut self, event: &LifecycleEvent) { + if self.relay_self.is_empty() { + return; + } + let Some(session_id) = event.session.as_deref() else { + return; + }; + + if event.kind == KIND_HUDDLE_STARTED { + if event.pubkey.is_empty() { + return; + } + if let Some(existing) = self.sessions.get(session_id) { + if existing.start_event_id == event.id + || event.created_at < existing.start_created_at + || (event.created_at == existing.start_created_at + && event.id > existing.start_event_id) + { + return; + } + } + self.sessions.insert( + session_id.to_string(), + HuddleSession { + start_creator: event.pubkey.clone(), + start_created_at: event.created_at, + start_event_id: event.id.clone(), + ended_at: None, + end: None, + admissions: HashMap::new(), + legacy: HashMap::new(), + latest_roster_revision: None, + latest_roster_created_at: 0, + latest_roster_event_id: String::new(), + generation: None, + departed: VecDeque::new(), + compacted_revision_floor: None, + }, + ); + return; + } + + let Some(session) = self.sessions.get_mut(session_id) else { + return; + }; + let generation = event.generation.as_deref(); + + if event.kind == KIND_HUDDLE_ENDED { + if event.pubkey != self.relay_self && event.pubkey != session.start_creator { + return; + } + if let (Some(generation), Some(current)) = (generation, session.generation.as_deref()) { + if generation != current { + return; + } + } + if let Some(generation) = generation { + session.generation = Some(generation.to_string()); + } + let next_end = Admission { + present: false, + roster_revision: None, + created_at: event.created_at, + event_id: event.id.clone(), + }; + if !is_newer(&next_end, session.end.as_ref()) { + return; + } + session.ended_at = Some(event.created_at); + session.end = Some(next_end); + session.clear_roster(); + return; + } + + if session.end.is_some() { + return; + } + if event.kind != KIND_HUDDLE_PARTICIPANT_JOINED + && event.kind != KIND_HUDDLE_PARTICIPANT_LEFT + { + return; + } + if event.pubkey != self.relay_self { + return; + } + let Some(participant) = event.participant.as_deref() else { + return; + }; + + if let (Some(generation), Some(current)) = (generation, session.generation.as_deref()) { + if generation != current { + if event.kind == KIND_HUDDLE_PARTICIPANT_LEFT { + return; + } + session.clear_roster(); + } + } + + let present = event.kind == KIND_HUDDLE_PARTICIPANT_JOINED; + let next = Admission { + present, + roster_revision: event.roster_revision, + created_at: event.created_at, + event_id: event.id.clone(), + }; + + let is_after_latest_roster_event = event.created_at > session.latest_roster_created_at + || (event.created_at == session.latest_roster_created_at + && event.id > session.latest_roster_event_id); + if let (Some(revision), Some(latest)) = + (event.roster_revision, session.latest_roster_revision) + { + let different_generation = match (generation, session.generation.as_deref()) { + (Some(g), Some(current)) => g != current, + _ => true, + }; + if revision < latest + && is_after_latest_roster_event + && different_generation + && session + .compacted_revision_floor + .is_none_or(|floor| revision > floor) + { + session.clear_roster(); + } + } + if let Some(generation) = generation { + session.generation = Some(generation.to_string()); + } + + if !present { + if let (Some(revision), Some(floor)) = + (next.roster_revision, session.compacted_revision_floor) + { + if revision <= floor { + return; + } + } + } + + if let Some(admission_id) = event.admission_id.as_deref() { + let departed_at = session.departed_position(admission_id); + let existing = session + .admissions + .get(participant) + .and_then(|admissions| admissions.get(admission_id)) + .or_else(|| departed_at.map(|index| &session.departed[index].1)); + if !is_newer(&next, existing) { + return; + } + if existing.is_none() { + if let (Some(revision), Some(floor)) = + (next.roster_revision, session.compacted_revision_floor) + { + if revision <= floor { + return; + } + } + } + if let Some(index) = departed_at { + if present { + session.departed.remove(index); + } + } + if present { + session + .admissions + .entry(participant.to_string()) + .or_default() + .insert(admission_id.to_string(), next); + } else { + if let Some(admissions) = session.admissions.get_mut(participant) { + admissions.remove(admission_id); + if admissions.is_empty() { + session.admissions.remove(participant); + } + } + if let Some(index) = session.departed_position(admission_id) { + session.departed.remove(index); + } + session.departed.push_back((admission_id.to_string(), next)); + while session.departed.len() > MAX_DEPARTED_ADMISSIONS { + let Some((_, oldest)) = session.departed.pop_front() else { + break; + }; + if let Some(revision) = oldest.roster_revision { + session.compacted_revision_floor = Some( + session + .compacted_revision_floor + .map_or(revision, |f| f.max(revision)), + ); + } + } + } + } else { + if !is_newer(&next, session.legacy.get(participant)) { + return; + } + session.legacy.insert(participant.to_string(), next); + } + if event.roster_revision.is_some() && is_after_latest_roster_event { + session.latest_roster_revision = event.roster_revision; + session.latest_roster_created_at = event.created_at; + session.latest_roster_event_id = event.id.clone(); + } + } +} diff --git a/crates/buzz-cli/src/commands/huddles.rs b/crates/buzz-cli/src/commands/huddles.rs new file mode 100644 index 00000000000..e0aec693dd6 --- /dev/null +++ b/crates/buzz-cli/src/commands/huddles.rs @@ -0,0 +1,930 @@ +//! Read-only huddle inspection: `buzz huddles list` and `buzz huddles participants`. +//! +//! State is derived exactly as desktop derives it (see [`super::huddle_tracker`]). +//! A huddle with no valid end event is `active` until its start is older than +//! desktop's one-hour joinable window, after which it is `stale`: desktop shows +//! it as ended, but no end event proves it. + +use std::collections::HashSet; + +use buzz_core::kind::{ + KIND_HUDDLE_ENDED, KIND_HUDDLE_PARTICIPANT_JOINED, KIND_HUDDLE_PARTICIPANT_LEFT, + KIND_HUDDLE_STARTED, +}; +use serde_json::{json, Value}; + +use super::huddle_tracker::{HuddleSession, HuddleTracker, LifecycleEvent}; +use crate::client::BuzzClient; +use crate::error::CliError; +use crate::validate::parse_uuid; + +/// Lifecycle events scanned per command. Reaching it is reported in the output. +const MAX_LIFECYCLE_EVENTS: u32 = 5_000; + +/// Matches desktop's `HUDDLE_JOINABLE_WINDOW_SECONDS`. +const JOINABLE_WINDOW_SECONDS: u64 = 60 * 60; + +/// The newest lifecycle events of one channel, and whether older ones exist. +struct Window { + events: Vec, + truncated: bool, + oldest_created_at: Option, +} + +impl Window { + fn from_events(raw: Vec, bound: u32) -> Result { + let bound = bound as usize; + let truncated = raw.len() > bound; + let mut seen = HashSet::new(); + let mut events = Vec::new(); + for value in raw.iter().take(bound) { + let event = LifecycleEvent::parse(value)?; + if seen.insert(event.id.clone()) { + events.push(event); + } + } + let oldest_created_at = events.iter().map(|event| event.created_at).min(); + Ok(Self { + events, + truncated, + oldest_created_at, + }) + } + + /// Whether every event at or after `created_at` was scanned. Events in the + /// oldest scanned second may have been cut off, so `created_at` must be + /// strictly newer than it. + fn covers(&self, created_at: u64) -> bool { + !self.truncated + || self + .oldest_created_at + .is_some_and(|oldest| created_at > oldest) + } + + fn scan_json(&self, bound: u32) -> Value { + json!({ + "truncated": self.truncated, + "events_scanned": self.events.len(), + "event_bound": bound, + "liveness_checked": false, + }) + } +} + +async fn fetch_relay_self(client: &BuzzClient) -> Result { + let raw = client.get_public("/").await?; + let info: Value = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("relay info document is not valid JSON: {e}")))?; + let self_hex = info.get("self").and_then(Value::as_str).ok_or_else(|| { + CliError::Other( + "relay info document has no 'self' pubkey; huddle events cannot be authenticated" + .into(), + ) + })?; + super::agents::normalize_relay_self_hex(self_hex) +} + +async fn fetch_window(client: &BuzzClient, channel: &str, bound: u32) -> Result { + let filter = json!({ + "kinds": [ + KIND_HUDDLE_STARTED, + KIND_HUDDLE_PARTICIPANT_JOINED, + KIND_HUDDLE_PARTICIPANT_LEFT, + KIND_HUDDLE_ENDED, + ], + "#h": [channel], + }); + let probe = bound + .checked_add(1) + .ok_or_else(|| CliError::Other("query bound is too large".into()))?; + let raw = client.query_paginated(filter, probe).await?; + Window::from_events(raw, bound) +} + +fn session_state(session: &HuddleSession, now: u64) -> &'static str { + if session.ended_at.is_some() { + "ended" + } else if now.saturating_sub(session.start_created_at) > JOINABLE_WINDOW_SECONDS { + "stale" + } else { + "active" + } +} + +fn track(window: &Window, relay_self: &str) -> HuddleTracker { + let mut tracker = HuddleTracker::new(relay_self); + tracker.apply_history(&window.events); + tracker +} + +fn build_list( + window: &Window, + relay_self: &str, + channel: &str, + now: u64, + active_only: bool, + limit: u32, + bound: u32, +) -> Value { + let tracker = track(window, relay_self); + let mut sessions: Vec<(&String, &HuddleSession)> = tracker.sessions().iter().collect(); + sessions.sort_by(|a, b| { + b.1.start_created_at + .cmp(&a.1.start_created_at) + .then_with(|| a.1.start_event_id.cmp(&b.1.start_event_id)) + }); + let selected: Vec<(&String, &HuddleSession)> = sessions + .into_iter() + .filter(|(_, session)| !active_only || session_state(session, now) == "active") + .take(limit as usize) + .collect(); + + // Truncation hides only older huddles; the newest `limit` are exact when + // all of them lie wholly inside the scanned window. + let complete = !window.truncated + || (selected.len() == limit as usize + && selected + .iter() + .all(|(_, session)| window.covers(session.start_created_at))); + + let huddles: Vec = selected + .iter() + .map(|(id, session)| { + json!({ + "huddle": id, + "channel": channel, + "state": session_state(session, now), + "started_at": session.start_created_at, + "ended_at": session.ended_at, + "started_by": session.start_creator, + "start_event": session.start_event_id, + "participant_count": session.participants().len(), + }) + }) + .collect(); + + let mut out = window.scan_json(bound); + out["complete"] = json!(complete); + out["huddles"] = json!(huddles); + out +} + +fn build_participants( + window: &Window, + relay_self: &str, + channel: &str, + huddle: &str, + now: u64, + bound: u32, +) -> Result { + let tracker = track(window, relay_self); + let mut out = window.scan_json(bound); + out["channel"] = json!(channel); + out["huddle"] = json!(huddle); + + let Some(session) = tracker.sessions().get(huddle) else { + if window.truncated { + out["state"] = json!("unknown"); + out["complete"] = json!(false); + out["participants"] = json!([]); + out["note"] = json!( + "the huddle's start is older than the scanned events; its roster is not known" + ); + return Ok(out); + } + return Err(CliError::NotFound(format!( + "no huddle {huddle} found in channel {channel}" + ))); + }; + + let participants: Vec = session + .participants() + .into_iter() + .map(|(pubkey, joined_at)| json!({ "pubkey": pubkey, "joined_at": joined_at })) + .collect(); + out["state"] = json!(session_state(session, now)); + out["started_at"] = json!(session.start_created_at); + out["ended_at"] = json!(session.ended_at); + out["complete"] = json!(window.covers(session.start_created_at)); + out["participants"] = json!(participants); + Ok(out) +} + +fn now_seconds() -> Result { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs()) + .map_err(|e| CliError::Other(format!("system clock is before the Unix epoch: {e}"))) +} + +async fn run_list( + client: &BuzzClient, + channel: &str, + active_only: bool, + limit: u32, + bound: u32, + now: u64, +) -> Result { + let channel = parse_uuid(channel)?.to_string(); + let relay_self = fetch_relay_self(client).await?; + let window = fetch_window(client, &channel, bound).await?; + Ok(build_list( + &window, + &relay_self, + &channel, + now, + active_only, + limit, + bound, + )) +} + +async fn run_participants( + client: &BuzzClient, + channel: &str, + huddle: &str, + bound: u32, + now: u64, +) -> Result { + let channel = parse_uuid(channel)?.to_string(); + let huddle = parse_uuid(huddle)?.to_string(); + let relay_self = fetch_relay_self(client).await?; + let window = fetch_window(client, &channel, bound).await?; + build_participants(&window, &relay_self, &channel, &huddle, now, bound) +} + +pub async fn cmd_list( + client: &BuzzClient, + channel: &str, + active_only: bool, + limit: u32, +) -> Result<(), CliError> { + let out = run_list( + client, + channel, + active_only, + limit, + MAX_LIFECYCLE_EVENTS, + now_seconds()?, + ) + .await?; + println!("{out}"); + Ok(()) +} + +pub async fn cmd_participants( + client: &BuzzClient, + channel: &str, + huddle: &str, +) -> Result<(), CliError> { + let out = run_participants( + client, + channel, + huddle, + MAX_LIFECYCLE_EVENTS, + now_seconds()?, + ) + .await?; + println!("{out}"); + Ok(()) +} + +pub async fn dispatch(cmd: crate::HuddlesCmd, client: &BuzzClient) -> Result<(), CliError> { + use crate::HuddlesCmd; + match cmd { + HuddlesCmd::List { + channel, + active, + limit, + } => cmd_list(client, &channel, active, limit).await, + HuddlesCmd::Participants { channel, huddle } => { + cmd_participants(client, &channel, &huddle).await + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + use axum::{body::Bytes, extract::State, routing::post, Router}; + use clap::Parser; + use nostr::Keys; + + const CHANNEL: &str = "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50"; + const HUDDLE: &str = "11111111-1111-4111-8111-111111111111"; + const OTHER_HUDDLE: &str = "22222222-2222-4222-8222-222222222222"; + const RELAY: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + const ALICE: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const BOB: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + const CAROL: &str = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"; + const EVE: &str = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; + + /// Recorded sequences shared with `tests/huddle_interop.mjs`, which replays + /// the same events through desktop's own tracker. + const SEQUENCES: &str = include_str!("../../tests/fixtures/huddle_sequences.json"); + + fn event( + id: u32, + kind: u32, + pubkey: &str, + created_at: u64, + tags: &[&[&str]], + content: Value, + ) -> Value { + json!({ + "id": format!("{id:064x}"), + "kind": kind, + "pubkey": pubkey, + "created_at": created_at, + "tags": tags, + "content": content.to_string(), + "sig": "", + }) + } + + fn lifecycle(raw: &[Value]) -> Window { + Window::from_events(raw.to_vec(), MAX_LIFECYCLE_EVENTS).unwrap() + } + + fn started(id: u32, at: u64, creator: &str, huddle: &str) -> Value { + event( + id, + KIND_HUDDLE_STARTED, + creator, + at, + &[&["h", CHANNEL]], + json!({ "ephemeral_channel_id": huddle }), + ) + } + + fn joined(id: u32, at: u64, who: &str, revision: u64, admission: &str) -> Value { + event( + id, + KIND_HUDDLE_PARTICIPANT_JOINED, + RELAY, + at, + &[&["h", CHANNEL], &["p", who]], + json!({ + "ephemeral_channel_id": HUDDLE, + "roster_revision": revision, + "admission_id": admission, + "generation": "1", + }), + ) + } + + fn left(id: u32, at: u64, who: &str, revision: u64, admission: &str) -> Value { + event( + id, + KIND_HUDDLE_PARTICIPANT_LEFT, + RELAY, + at, + &[&["h", CHANNEL], &["p", who]], + json!({ + "ephemeral_channel_id": HUDDLE, + "roster_revision": revision, + "admission_id": admission, + "generation": "1", + }), + ) + } + + fn ended(id: u32, at: u64, signer: &str) -> Value { + event( + id, + KIND_HUDDLE_ENDED, + signer, + at, + &[&["h", CHANNEL]], + json!({ "ephemeral_channel_id": HUDDLE }), + ) + } + + fn roster(out: &Value) -> Vec { + out["participants"] + .as_array() + .unwrap() + .iter() + .map(|p| p["pubkey"].as_str().unwrap().to_string()) + .collect() + } + + fn participants_of(raw: &[Value], now: u64) -> Value { + build_participants( + &lifecycle(raw), + RELAY, + CHANNEL, + HUDDLE, + now, + MAX_LIFECYCLE_EVENTS, + ) + .unwrap() + } + + #[test] + fn rejoin_keeps_one_entry_and_a_stale_leave_does_not_remove_it() { + let raw = [ + started(1, 100, ALICE, HUDDLE), + joined(2, 101, BOB, 1, "adm-1"), + left(3, 102, BOB, 2, "adm-1"), + joined(4, 103, BOB, 3, "adm-2"), + // A leave for the first admission delivered after the rejoin. + left(5, 104, BOB, 2, "adm-1"), + ]; + let out = participants_of(&raw, 200); + assert_eq!(roster(&out), vec![BOB]); + assert_eq!(out["participants"][0]["joined_at"], 103); + assert_eq!(out["state"], "active"); + assert_eq!(out["complete"], true); + } + + #[test] + fn leave_without_join_adds_nobody_and_a_later_join_still_counts() { + let raw = [ + started(1, 100, ALICE, HUDDLE), + left(2, 101, BOB, 1, "adm-1"), + joined(3, 102, CAROL, 2, "adm-2"), + ]; + assert_eq!(roster(&participants_of(&raw, 200)), vec![CAROL]); + + let raw = [ + started(1, 100, ALICE, HUDDLE), + left(2, 101, BOB, 2, "adm-1"), + joined(3, 102, BOB, 1, "adm-1"), + ]; + assert_eq!( + roster(&participants_of(&raw, 200)), + Vec::::new(), + "a join older than its recorded leave must not resurrect the participant" + ); + } + + #[test] + fn ended_huddle_has_an_empty_roster_and_ignores_later_joins() { + let raw = [ + started(1, 100, ALICE, HUDDLE), + joined(2, 101, BOB, 1, "adm-1"), + ended(3, 110, RELAY), + joined(4, 120, CAROL, 2, "adm-2"), + ]; + let out = participants_of(&raw, 200); + assert_eq!(out["state"], "ended"); + assert_eq!(out["ended_at"], 110); + assert!(roster(&out).is_empty()); + } + + #[test] + fn end_from_a_stranger_is_ignored() { + let raw = [ + started(1, 100, ALICE, HUDDLE), + joined(2, 101, BOB, 1, "adm-1"), + ended(3, 110, EVE), + ]; + let out = participants_of(&raw, 200); + assert_eq!(out["state"], "active"); + assert_eq!(roster(&out), vec![BOB]); + let by_creator = [raw[0].clone(), raw[1].clone(), ended(5, 110, ALICE)]; + assert_eq!(participants_of(&by_creator, 200)["state"], "ended"); + } + + #[test] + fn missing_end_event_turns_stale_after_the_joinable_window() { + let raw = [ + started(1, 1_000, ALICE, HUDDLE), + joined(2, 1_001, BOB, 1, "adm-1"), + ]; + let fresh = participants_of(&raw, 1_000 + JOINABLE_WINDOW_SECONDS); + assert_eq!(fresh["state"], "active"); + let stale = participants_of(&raw, 1_000 + JOINABLE_WINDOW_SECONDS + 1); + assert_eq!(stale["state"], "stale"); + assert_eq!(stale["ended_at"], Value::Null); + assert_eq!(roster(&stale), vec![BOB], "stale is not an end event"); + assert_eq!(stale["liveness_checked"], false); + } + + #[test] + fn untrusted_lifecycle_events_never_reach_the_roster() { + let forged_join = event( + 9, + KIND_HUDDLE_PARTICIPANT_JOINED, + EVE, + 102, + &[&["h", CHANNEL], &["p", EVE]], + json!({ "ephemeral_channel_id": HUDDLE, "admission_id": "x" }), + ); + let raw = [started(1, 100, ALICE, HUDDLE), forged_join]; + assert!(roster(&participants_of(&raw, 200)).is_empty()); + } + + #[test] + fn same_second_join_and_leave_follow_the_relay_roster_revision() { + // Delivered newest-first with an identical timestamp; revision decides. + let raw = [ + left(4, 101, BOB, 2, "adm-1"), + joined(3, 101, BOB, 1, "adm-1"), + started(1, 100, ALICE, HUDDLE), + ]; + assert!(roster(&participants_of(&raw, 200)).is_empty()); + } + + #[test] + fn recorded_sequences_match_the_expected_rosters() { + let sequences: Vec = serde_json::from_str(SEQUENCES).unwrap(); + assert!(sequences.len() >= 4); + for sequence in sequences { + let name = sequence["name"].as_str().unwrap(); + let relay_self = sequence["relay_self"].as_str().unwrap(); + let huddle = sequence["huddle"].as_str().unwrap(); + let events = sequence["events"].as_array().unwrap().clone(); + let window = Window::from_events(events, MAX_LIFECYCLE_EVENTS).unwrap(); + let out = build_participants(&window, relay_self, CHANNEL, huddle, 0, 0).unwrap(); + let mut got = roster(&out); + got.sort(); + let want: Vec = + serde_json::from_value(sequence["expected_participants"].clone()).unwrap(); + assert_eq!(got, want, "{name}: roster"); + assert_eq!( + out["state"] == "ended", + sequence["expected_ended"].as_bool().unwrap(), + "{name}: ended" + ); + } + } + + #[test] + fn list_orders_newest_first_and_filters_active() { + let other = |id: u32, at: u64, kind: u32, signer: &str| { + event( + id, + kind, + signer, + at, + &[&["h", CHANNEL]], + json!({ "ephemeral_channel_id": OTHER_HUDDLE }), + ) + }; + let raw = [ + other(10, 50, KIND_HUDDLE_STARTED, CAROL), + other(11, 60, KIND_HUDDLE_ENDED, RELAY), + started(1, 100, ALICE, HUDDLE), + joined(2, 101, BOB, 1, "adm-1"), + ]; + let window = lifecycle(&raw); + let all = build_list( + &window, + RELAY, + CHANNEL, + 200, + false, + 20, + MAX_LIFECYCLE_EVENTS, + ); + let huddles = all["huddles"].as_array().unwrap(); + assert_eq!(huddles.len(), 2); + assert_eq!(huddles[0]["huddle"], HUDDLE); + assert_eq!(huddles[0]["state"], "active"); + assert_eq!(huddles[0]["participant_count"], 1); + assert_eq!(huddles[1]["huddle"], OTHER_HUDDLE); + assert_eq!(huddles[1]["state"], "ended"); + assert_eq!(huddles[1]["ended_at"], 60); + assert_eq!(all["complete"], true); + + let active = build_list(&window, RELAY, CHANNEL, 200, true, 20, MAX_LIFECYCLE_EVENTS); + assert_eq!(active["huddles"].as_array().unwrap().len(), 1); + + let stale = build_list( + &window, + RELAY, + CHANNEL, + 100 + JOINABLE_WINDOW_SECONDS + 1, + true, + 20, + MAX_LIFECYCLE_EVENTS, + ); + assert!( + stale["huddles"].as_array().unwrap().is_empty(), + "stale huddles are not active" + ); + + let one = build_list(&window, RELAY, CHANNEL, 200, false, 1, MAX_LIFECYCLE_EVENTS); + assert_eq!(one["huddles"].as_array().unwrap().len(), 1); + } + + #[test] + fn truncated_scan_is_reported_not_returned_as_a_full_roster() { + let raw = vec![ + joined(5, 104, CAROL, 3, "adm-3"), + joined(4, 103, BOB, 2, "adm-2"), + joined(3, 102, ALICE, 1, "adm-1"), + started(1, 100, ALICE, HUDDLE), + ]; + + let window = Window::from_events(raw.clone(), 2).unwrap(); + assert!(window.truncated); + let out = build_participants(&window, RELAY, CHANNEL, HUDDLE, 200, 2).unwrap(); + assert_eq!(out["state"], "unknown"); + assert_eq!(out["complete"], false); + assert_eq!(out["truncated"], true); + assert_eq!(out["event_bound"], 2); + assert!(roster(&out).is_empty()); + + let list = build_list(&window, RELAY, CHANNEL, 200, false, 20, 2); + assert_eq!(list["complete"], false); + + // The start is inside the window, so the roster is exact even though + // older history exists. + let mut tail = raw.clone(); + tail.push(started(6, 20, CAROL, OTHER_HUDDLE)); + tail.push(started( + 7, + 10, + CAROL, + "33333333-3333-4333-8333-333333333333", + )); + let window = Window::from_events(tail, 5).unwrap(); + assert!(window.truncated); + let out = build_participants(&window, RELAY, CHANNEL, HUDDLE, 200, 5).unwrap(); + assert_eq!(out["complete"], true); + assert_eq!(roster(&out), vec![ALICE, BOB, CAROL]); + let list = build_list(&window, RELAY, CHANNEL, 200, false, 1, 5); + assert_eq!(list["complete"], true); + assert_eq!(list["huddles"][0]["huddle"], HUDDLE); + + // An event sharing the oldest scanned second may have been cut off. + let tie = vec![ + joined(3, 100, BOB, 1, "adm-1"), + started(1, 100, ALICE, HUDDLE), + joined(2, 100, CAROL, 2, "adm-2"), + ]; + let window = Window::from_events(tie, 2).unwrap(); + let out = build_participants(&window, RELAY, CHANNEL, HUDDLE, 200, 2).unwrap(); + assert_eq!(out["complete"], false); + } + + #[test] + fn unknown_huddle_is_not_found_when_nothing_was_cut_off() { + let window = lifecycle(&[started(1, 100, ALICE, HUDDLE)]); + let err = build_participants(&window, RELAY, CHANNEL, OTHER_HUDDLE, 200, 10).unwrap_err(); + assert!(matches!(err, CliError::NotFound(_))); + } + + #[test] + fn malformed_relay_events_fail_instead_of_being_skipped() { + assert!(Window::from_events(vec![json!({"id": "x"})], 10).is_err()); + let no_session = event( + 1, + KIND_HUDDLE_STARTED, + ALICE, + 1, + &[], + json!("not an object"), + ); + let window = Window::from_events(vec![no_session], 10).unwrap(); + assert!( + build_list(&window, RELAY, CHANNEL, 2, false, 20, 10)["huddles"] + .as_array() + .unwrap() + .is_empty() + ); + } + + #[derive(Clone)] + struct FakeRelay { + events: Arc>, + filters: Arc>>, + self_pubkey: Option<&'static str>, + } + + async fn fake_relay( + events: Vec, + self_pubkey: Option<&'static str>, + ) -> (String, FakeRelay) { + let relay = FakeRelay { + events: Arc::new(events), + filters: Arc::new(Mutex::new(Vec::new())), + self_pubkey, + }; + let app = Router::new() + .route( + "/", + axum::routing::get(|State(relay): State| async move { + let body = match relay.self_pubkey { + Some(pk) => json!({ "self": pk }), + None => json!({}), + }; + ( + [("content-type", "application/nostr+json")], + body.to_string(), + ) + }), + ) + .route( + "/query", + post(|State(relay): State, body: Bytes| async move { + let filters: Vec = serde_json::from_slice(&body).unwrap(); + let filter = filters[0].clone(); + relay.filters.lock().unwrap().push(filter.clone()); + let mut matching: Vec = relay + .events + .iter() + .filter(|e| { + filter["kinds"].as_array().unwrap().contains(&e["kind"]) + && e["tags"].as_array().unwrap().iter().any(|t| { + t[0] == "h" && filter["#h"].as_array().unwrap().contains(&t[1]) + }) + }) + .cloned() + .collect(); + matching.sort_by(|a, b| { + b["created_at"] + .as_u64() + .cmp(&a["created_at"].as_u64()) + .then_with(|| a["id"].as_str().cmp(&b["id"].as_str())) + }); + if let (Some(until), Some(before)) = + (filter["until"].as_u64(), filter["before_id"].as_str()) + { + matching.retain(|e| { + let at = e["created_at"].as_u64().unwrap(); + at < until || (at == until && e["id"].as_str().unwrap() > before) + }); + } + matching.truncate(filter["limit"].as_u64().unwrap() as usize); + axum::Json(matching) + }), + ) + .with_state(relay.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (format!("http://{addr}"), relay) + } + + fn client(base: &str) -> BuzzClient { + BuzzClient::new( + base.to_string(), + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap() + } + + #[tokio::test] + async fn commands_query_named_kinds_with_a_bound_and_report_truncation() { + let mut events = vec![started(1, 100, ALICE, HUDDLE)]; + for i in 0..6u32 { + let who = [ALICE, BOB, CAROL][i as usize % 3]; + events.push(joined( + 10 + i, + 101 + i as u64, + who, + i as u64, + &format!("adm-{i}"), + )); + } + let (base, relay) = fake_relay(events, Some(RELAY)).await; + let client = client(&base); + + let full = run_participants(&client, CHANNEL, HUDDLE, 100, 200) + .await + .unwrap(); + assert_eq!(full["complete"], true); + assert_eq!(roster(&full), vec![ALICE, BOB, CAROL]); + + let cut = run_participants(&client, CHANNEL, HUDDLE, 3, 200) + .await + .unwrap(); + assert_eq!(cut["complete"], false); + assert_eq!(cut["truncated"], true); + assert_eq!(cut["state"], "unknown"); + + let list = run_list(&client, CHANNEL, false, 20, 100, 200) + .await + .unwrap(); + assert_eq!(list["huddles"][0]["participant_count"], 3); + + let filters = relay.filters.lock().unwrap(); + assert!(!filters.is_empty()); + for filter in filters.iter() { + assert_eq!( + filter["kinds"], + json!([ + KIND_HUDDLE_STARTED, + KIND_HUDDLE_PARTICIPANT_JOINED, + KIND_HUDDLE_PARTICIPANT_LEFT, + KIND_HUDDLE_ENDED + ]) + ); + assert_eq!(filter["#h"], json!([CHANNEL])); + assert!(filter["limit"].as_u64().unwrap() <= 500); + } + } + + #[tokio::test] + async fn relay_without_a_self_key_is_an_error_not_an_empty_roster() { + let (base, _relay) = fake_relay(vec![started(1, 100, ALICE, HUDDLE)], None).await; + let err = run_list(&client(&base), CHANNEL, false, 20, 10, 200) + .await + .unwrap_err(); + assert!(err.to_string().contains("self")); + } + + #[tokio::test] + async fn relay_info_failures_keep_their_exit_codes() { + use crate::error::exit_code; + + let failing = |status: axum::http::StatusCode| async move { + let app = Router::new().route("/", axum::routing::get(move || async move { status })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + }; + let err = run_list( + &client(&failing(axum::http::StatusCode::INTERNAL_SERVER_ERROR).await), + CHANNEL, + false, + 20, + 10, + 200, + ) + .await + .unwrap_err(); + assert_eq!(exit_code(&err), 2, "{err}"); + let err = run_participants( + &client(&failing(axum::http::StatusCode::FORBIDDEN).await), + CHANNEL, + HUDDLE, + 10, + 200, + ) + .await + .unwrap_err(); + assert_eq!(exit_code(&err), 3, "{err}"); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let dead = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let err = run_list(&client(&dead), CHANNEL, false, 20, 10, 200) + .await + .unwrap_err(); + assert_eq!(exit_code(&err), 2, "{err}"); + } + + #[tokio::test] + async fn bad_ids_are_usage_errors() { + let (base, relay) = fake_relay(vec![], Some(RELAY)).await; + let client = client(&base); + assert!(matches!( + run_list(&client, "not-a-uuid", false, 20, 10, 0).await, + Err(CliError::Usage(_)) + )); + assert!(matches!( + run_participants(&client, CHANNEL, "nope", 10, 0).await, + Err(CliError::Usage(_)) + )); + assert!(relay.filters.lock().unwrap().is_empty()); + } + + #[test] + fn arguments_parse_to_the_documented_commands() { + let cli = crate::Cli::try_parse_from([ + "buzz", + "huddles", + "list", + "--channel", + CHANNEL, + "--active", + "--limit", + "5", + ]) + .unwrap(); + assert!(matches!( + cli.command, + crate::Cmd::Huddles(crate::HuddlesCmd::List { + active: true, + limit: 5, + .. + }) + )); + assert!(crate::Cli::try_parse_from([ + "buzz", + "huddles", + "list", + "--channel", + CHANNEL, + "--limit", + "0" + ]) + .is_err()); + assert!(crate::Cli::try_parse_from([ + "buzz", + "huddles", + "participants", + "--channel", + CHANNEL + ]) + .is_err()); + } +} diff --git a/crates/buzz-cli/src/commands/issues.rs b/crates/buzz-cli/src/commands/issues.rs index 8ae756617d5..5bb7c16e4c1 100644 --- a/crates/buzz-cli/src/commands/issues.rs +++ b/crates/buzz-cli/src/commands/issues.rs @@ -256,7 +256,7 @@ pub async fn cmd_create_issue( let builder = with_git_provenance( buzz_sdk::build_git_issue(&repo, subject, content, &meta).map_err(sdk_err)?, )?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let event_id = event.id.to_hex(); let resp = client.submit_event(event).await?; // `link` renders as a rich preview card in Buzz Desktop when included in @@ -367,7 +367,7 @@ async fn publish_issue_assignment_operation( owner: repo_owner.to_string(), id: repo_id.to_string(), }; - let signer = client.keys().public_key().to_hex(); + let signer = client.public_key().to_hex(); let is_self_service = assignees.len() == 1 && assignees[0].eq_ignore_ascii_case(&signer) && !signer.eq_ignore_ascii_case(repo_owner); @@ -399,7 +399,7 @@ async fn publish_issue_assignment_operation( } } .map(|builder| builder.custom_created_at(Timestamp::from_secs(context.created_at))); - let event = client.sign_event(builder.map_err(sdk_err)?)?; + let event = client.sign_event(builder.map_err(sdk_err)?).await?; let resp = client.submit_event(event).await?; println!("{resp}"); Ok(()) @@ -584,7 +584,7 @@ pub async fn cmd_issue_status( let builder = with_git_provenance(buzz_sdk::build_git_status(status, &body, &meta).map_err(sdk_err)?)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{resp}"); Ok(()) diff --git a/crates/buzz-cli/src/commands/mem.rs b/crates/buzz-cli/src/commands/mem.rs index eb15921bd4c..00485d6c140 100644 --- a/crates/buzz-cli/src/commands/mem.rs +++ b/crates/buzz-cli/src/commands/mem.rs @@ -19,9 +19,7 @@ use std::time::SystemTime; use sha2::{Digest, Sha256}; -use buzz_core::engram::{ - self, conversation_key, d_tag, normalize_slug, select_head, validate_and_decrypt, Body, Listing, -}; +use buzz_core::engram::{self, normalize_slug, select_head, Body, Listing}; use buzz_core::kind::KIND_AGENT_ENGRAM; use nostr::PublicKey; @@ -64,16 +62,16 @@ fn resolve_reader( } let agent = PublicKey::from_hex(agent) .map_err(|e| CliError::Usage(format!("--agent must be a 64-hex pubkey: {e}")))?; - if agent == client.keys().public_key() { + if agent == client.public_key() { return Err(CliError::Usage( "--agent must differ from the CLI identity; omit --agent for agent-side reads" .into(), )); } - return Ok((agent, client.keys().public_key(), agent)); + return Ok((agent, client.public_key(), agent)); } - let agent = client.keys().public_key(); + let agent = client.public_key(); let owner = resolve_owner(client, owner_flag)?; Ok((agent, owner, owner)) } @@ -132,6 +130,48 @@ fn parse_events(json: &str) -> Result, CliError> { Ok(out) } +/// NIP-AE read validation through the client's credentials: the envelope, +/// then NIP-44 decryption, then the slug re-deriving to the `d` tag. +/// `Ok(None)` means the event is not a valid engram and is skipped; `Err` is +/// a credential failure, which aborts rather than reading as "no entries". +async fn open_engram( + client: &BuzzClient, + ev: &nostr::Event, + agent: &PublicKey, + owner: &PublicKey, + their_pubkey: &PublicKey, +) -> Result, CliError> { + let Ok(d_value) = engram::validate_envelope(ev, agent, owner) else { + return Ok(None); + }; + let credentials = client.credentials(); + let Some(plaintext) = credentials.nip44_decrypt(their_pubkey, &ev.content).await? else { + return Ok(None); + }; + let Ok(body) = Body::from_json_bytes(plaintext.as_bytes()) else { + return Ok(None); + }; + let derived = credentials.engram_d_tag(their_pubkey, body.slug()).await?; + Ok(engram::check_d_tag(&d_value, &derived).ok().map(|()| body)) +} + +/// Encrypt `body` to `owner` and sign the `kind:30174` event with the +/// client's credentials (NIP-AE write path). +async fn seal_engram( + client: &BuzzClient, + owner: &PublicKey, + body: &Body, + created_at: u64, +) -> Result { + let build_failed = |e: engram::EngramError| CliError::Other(format!("build event failed: {e}")); + let credentials = client.credentials(); + let plaintext = engram::encode_body(body).map_err(build_failed)?; + let ciphertext = credentials.nip44_encrypt(owner, &plaintext).await?; + let d = credentials.engram_d_tag(owner, body.slug()).await?; + let builder = engram::event_builder(owner, &d, ciphertext, created_at).map_err(build_failed)?; + credentials.sign(builder).await +} + /// Fetch the head event for `slug`, returning `(Option, Option)`. async fn fetch_head( client: &BuzzClient, @@ -139,13 +179,15 @@ async fn fetch_head( owner: &PublicKey, slug: &str, ) -> Result<(Option, Option), CliError> { - let their_pubkey = if client.keys().public_key() == *agent { + let their_pubkey = if client.public_key() == *agent { owner } else { agent }; - let k_c = conversation_key(client.keys().secret_key(), their_pubkey); - let d = d_tag(&k_c, slug); + let d = client + .credentials() + .engram_d_tag(their_pubkey, slug) + .await?; let filter = serde_json::json!({ "kinds": [KIND_AGENT_ENGRAM], @@ -164,9 +206,8 @@ async fn fetch_head( if ev.verify().is_err() { continue; } - match validate_and_decrypt(&ev, agent, owner, client.keys().secret_key(), their_pubkey) { - Ok(body) => valid_with_body.push((ev, body)), - Err(_) => continue, + if let Some(body) = open_engram(client, &ev, agent, owner, their_pubkey).await? { + valid_with_body.push((ev, body)); } } if valid_with_body.is_empty() { @@ -219,15 +260,8 @@ pub async fn cmd_ls( else { continue; }; - let body = match validate_and_decrypt( - &ev, - &agent, - &owner, - client.keys().secret_key(), - &their_pubkey, - ) { - Ok(b) => b, - Err(_) => continue, + let Some(body) = open_engram(client, &ev, &agent, &owner, &their_pubkey).await? else { + continue; }; groups.entry(d_value).or_default().push((ev, body)); } @@ -357,14 +391,12 @@ pub async fn cmd_set( value: Some(value), } }; - let agent_pubkey = client.keys().public_key(); + let agent_pubkey = client.public_key(); let (head, _) = fetch_head(client, &agent_pubkey, &owner, &slug).await?; let prior_created_at = head.map(|e| e.created_at.as_secs()); let created_at = engram::monotonic_created_at(now_secs(), prior_created_at); - let agent = client.keys(); - let event = engram::build_event(agent, &owner, &body, created_at) - .map_err(|e| CliError::Other(format!("build event failed: {e}")))?; + let event = seal_engram(client, &owner, &body, created_at).await?; let id = event.id.to_hex(); submit_engram(client, event).await?; eprintln!("wrote {slug} (event {id}, created_at {created_at})"); @@ -598,7 +630,7 @@ pub async fn cmd_patch( }; let owner = resolve_owner(client, owner_flag)?; - let agent_pubkey = client.keys().public_key(); + let agent_pubkey = client.public_key(); let (head, current) = fetch_value(client, &agent_pubkey, &owner, &slug).await?; // Base-hash gate: concurrent-edit safety. @@ -688,9 +720,7 @@ pub async fn cmd_patch( let prior_created_at = Some(head.created_at.as_secs()); let created_at = engram::monotonic_created_at(now_secs(), prior_created_at); - let agent = client.keys(); - let event = engram::build_event(agent, &owner, &body, created_at) - .map_err(|e| CliError::Other(format!("build event failed: {e}")))?; + let event = seal_engram(client, &owner, &body, created_at).await?; let id = event.id.to_hex(); submit_engram(client, event).await?; eprintln!("wrote {slug} (event {id}, created_at {created_at}, sha256 {new_hash})"); @@ -720,14 +750,12 @@ pub async fn cmd_rm( slug: slug.clone(), value: None, }; - let agent_pubkey = client.keys().public_key(); + let agent_pubkey = client.public_key(); let (head, _) = fetch_head(client, &agent_pubkey, &owner, &slug).await?; let prior_created_at = head.map(|e| e.created_at.as_secs()); let created_at = engram::monotonic_created_at(now_secs(), prior_created_at); - let agent = client.keys(); - let event = engram::build_event(agent, &owner, &body, created_at) - .map_err(|e| CliError::Other(format!("build event failed: {e}")))?; + let event = seal_engram(client, &owner, &body, created_at).await?; let id = event.id.to_hex(); submit_engram(client, event).await?; eprintln!("tombstoned {slug} (event {id}, created_at {created_at})"); @@ -785,8 +813,134 @@ mod tests { // verify base-hash from the shell. Hard-coded vectors from the NIST and // common quick-check inputs. + /// Through the desktop, an engram with bad ciphertext is skipped while + /// a valid one opens; a credential failure aborts instead of reading as + /// "no entries". + #[cfg(unix)] + #[tokio::test] + async fn the_desktop_skips_bad_ciphertext_but_aborts_on_credential_failure() { + use crate::desktop_provider::{tests as dp, Provider}; + const RELAY: &str = "wss://community.example"; + let owner = nostr::Keys::generate(); + let agent = nostr::Keys::generate(); + let body = Body::Memory { + slug: "mem/a".into(), + value: Some("v".into()), + }; + let valid = engram::build_event(&agent, &owner.public_key(), &body, 1).unwrap(); + let k_c = engram::conversation_key(agent.secret_key(), &owner.public_key()); + let corrupt = engram::event_builder( + &owner.public_key(), + &engram::d_tag(&k_c, "mem/a"), + "AAAA".into(), + 2, + ) + .unwrap() + .sign_with_keys(&agent) + .unwrap(); + let open = |endpoint| async move { + let p = Provider::open(endpoint, "t".into(), false, RELAY) + .await + .unwrap() + .ok() + .unwrap(); + let credentials = crate::credentials::Credentials::from_desktop(p) + .await + .unwrap(); + BuzzClient::new("http://127.0.0.1:9".into(), credentials).unwrap() + }; + let (endpoint, _) = dp::desktop(owner.clone(), vec![RELAY.into()]).await; + let client = open(endpoint).await; + let (a, o) = (agent.public_key(), owner.public_key()); + let opened = open_engram(&client, &valid, &a, &o, &a).await.unwrap(); + assert!(matches!(opened, Some(Body::Memory { .. }))); + assert!(open_engram(&client, &corrupt, &a, &o, &a) + .await + .unwrap() + .is_none()); + + let (endpoint, _) = dp::provider(move |_, r| match r["method"].as_str() { + Some("describe") => serde_json::json!({"result": serde_json::json!({ + "pubkey": owner.public_key().to_hex(), "relays": [RELAY], "methods": [], + }).to_string()}), + _ => serde_json::json!({"result": "", "error": "unavailable"}), + }) + .await; + let client = open(endpoint).await; + assert!(open_engram(&client, &valid, &a, &o, &a).await.is_err()); + } + + /// A desktop that throttles partway through `buzz mem ls` is waited out, + /// and the list completes. + #[cfg(unix)] + #[tokio::test] + async fn a_list_completes_when_the_desktop_throttles_partway() { + use crate::desktop_provider::{tests as dp, Provider}; + use std::sync::atomic::{AtomicUsize, Ordering}; + let agent = nostr::Keys::generate(); + let owner = nostr::Keys::generate().public_key(); + let events: Vec = (0..3) + .map(|i| { + let body = Body::Memory { + slug: format!("mem/{i}"), + value: Some("v".into()), + }; + let ev = engram::build_event(&agent, &owner, &body, 1).unwrap(); + serde_json::to_value(&ev).unwrap() + }) + .collect(); + let app = axum::Router::new().route( + "/query", + axum::routing::post(move || async move { axum::Json(events) }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + // The second decrypt is refused once with `rate_limited`. + let decrypts = std::sync::Arc::new(AtomicUsize::new(0)); + let counted = decrypts.clone(); + let answer = dp::desktop_answers(agent.clone(), vec![relay.clone()]); + let (endpoint, seen) = dp::provider(move |version, request| { + if request["method"] == "nip44_decrypt" && counted.fetch_add(1, Ordering::SeqCst) == 1 { + return serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 1}); + } + answer(version, request) + }) + .await; + let provider = Provider::open(endpoint, "t".into(), false, &relay) + .await + .unwrap() + .ok() + .unwrap(); + let credentials = crate::credentials::Credentials::from_desktop(provider) + .await + .unwrap(); + let client = BuzzClient::new(relay, credentials).unwrap(); + + cmd_ls(&client, Some(&owner.to_hex()), None, true) + .await + .unwrap(); + assert_eq!( + decrypts.load(Ordering::SeqCst), + 4, + "three entries, one retry" + ); + let d_tags = seen + .lock() + .unwrap() + .iter() + .filter(|(_, _, r)| r["method"] == "engram_d_tag") + .count(); + assert_eq!(d_tags, 3); + } + fn test_client(keys: nostr::Keys) -> BuzzClient { - BuzzClient::new("http://127.0.0.1:9".into(), keys, None, None).unwrap() + BuzzClient::new( + "http://127.0.0.1:9".into(), + crate::credentials::Credentials::from_keys(keys), + ) + .unwrap() } #[test] diff --git a/crates/buzz-cli/src/commands/message_report.rs b/crates/buzz-cli/src/commands/message_report.rs new file mode 100644 index 00000000000..26db0f265af --- /dev/null +++ b/crates/buzz-cli/src/commands/message_report.rs @@ -0,0 +1,484 @@ +//! `buzz messages report` — NIP-56 report (kind 1984) to community moderators. +//! +//! The relay queues a report for moderators only: it is never stored as an +//! ordinary event or fanned out, so the command prints the write envelope and +//! nothing else. A message report carries the author's `p` tag and an `e` tag +//! whose third element is the report type, exactly as desktop sends it. + +use buzz_sdk::ReportTarget; + +use super::messages::{channel_id_from_event, fetch_event}; +use crate::client::{normalize_write_response, BuzzClient}; +use crate::error::CliError; +use crate::validate::validate_hex64; + +/// Parsed `buzz messages report` arguments. +pub struct ReportParams<'a> { + /// Channel UUID the message must belong to, when given. + pub channel: Option<&'a str>, + /// Hex id of the message to report. + pub event: Option<&'a str>, + /// Hex pubkey of a user to report without a message. + pub pubkey: Option<&'a str>, + /// NIP-56 report type. + pub reason: &'a str, + /// Optional free-text note for moderators. + pub note: Option<&'a str>, +} + +/// The relay rejects a report whose target it cannot read exactly like a +/// missing one, so both surface as not-found rather than a relay failure. +fn interpret_submit_error(e: CliError) -> CliError { + match e { + CliError::Relay { status: 400, body } + if body.starts_with("invalid: report target ") && body.ends_with(" not found") => + { + CliError::NotFound(body) + } + other => other, + } +} + +/// Build, sign, and submit a report; print the write envelope. +pub async fn cmd_report_message( + client: &BuzzClient, + params: ReportParams<'_>, +) -> Result<(), CliError> { + let event = params.event.map(str::to_ascii_lowercase); + let pubkey = params.pubkey.map(str::to_ascii_lowercase); + let builder = match (event.as_deref(), pubkey.as_deref()) { + (Some(event_id), None) => { + validate_hex64(event_id)?; + let event = fetch_event(client, event_id).await?; + if let Some(channel) = params.channel { + let actual = channel_id_from_event(event_id, &event)?; + if !actual.to_string().eq_ignore_ascii_case(channel.trim()) { + return Err(CliError::Usage(format!( + "event {event_id} is not in channel {channel}" + ))); + } + } + let author = event + .get("pubkey") + .and_then(|v| v.as_str()) + .ok_or_else(|| CliError::Other(format!("event {event_id} has no pubkey")))?; + buzz_sdk::build_report( + ReportTarget::Event { + author_pubkey: author, + event_id, + }, + params.reason, + params.note, + ) + } + (None, Some(pubkey)) => { + buzz_sdk::build_report(ReportTarget::Pubkey(pubkey), params.reason, params.note) + } + _ => { + return Err(CliError::Usage( + "report needs exactly one of --event or --pubkey".into(), + )) + } + } + .map_err(|e| CliError::Usage(format!("invalid report: {e}")))?; + + let event = client.sign_event(builder).await?; + let resp = client + .submit_event(event) + .await + .map_err(interpret_submit_error)?; + println!("{}", normalize_write_response(&resp)); + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use axum::{extract::State, http::StatusCode, routing::post, Router}; + use nostr::Keys; + use tokio::net::TcpListener; + + use super::*; + use crate::error::exit_code; + use crate::{Cli, Cmd, MessagesCmd}; + use clap::Parser; + + const CHANNEL: &str = "123e4567-e89b-12d3-a456-426614174000"; + const EVENT: &str = "cd00000000000000000000000000000000000000000000000000000000000000"; + const AUTHOR: &str = "ab00000000000000000000000000000000000000000000000000000000000000"; + + #[derive(Clone)] + struct Relay { + query: String, + events_status: StatusCode, + events_body: String, + captured: Arc>>, + } + + async fn fake_relay( + query: serde_json::Value, + events_status: StatusCode, + events_body: &str, + ) -> (String, Arc>>) { + let captured = Arc::new(Mutex::new(Vec::new())); + let state = Relay { + query: query.to_string(), + events_status, + events_body: events_body.to_string(), + captured: captured.clone(), + }; + let app = Router::new() + .route( + "/query", + post(|State(s): State, body: String| async move { + let matches = serde_json::from_str::(&s.query) + .ok() + .and_then(|events| events[0]["id"].as_str().map(|id| body.contains(id))) + .unwrap_or(true); + let reply = if matches { s.query } else { "[]".to_string() }; + ( + StatusCode::OK, + [("content-type", "application/json")], + reply, + ) + }), + ) + .route( + "/events", + post(|State(s): State, body: String| async move { + s.captured + .lock() + .unwrap() + .push(serde_json::from_str(&body).unwrap()); + ( + s.events_status, + [("content-type", "application/json")], + s.events_body, + ) + }), + ) + .with_state(state); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (format!("http://{addr}"), captured) + } + + fn message_in_channel() -> serde_json::Value { + message_by(AUTHOR) + } + + fn message_by(author: &str) -> serde_json::Value { + serde_json::json!([{ + "id": EVENT, "pubkey": author, "kind": 9, "content": "hi", + "created_at": 1, "tags": [["h", CHANNEL]], "sig": "00" + }]) + } + + fn client(url: String) -> BuzzClient { + BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap() + } + + fn parse(args: &[&str]) -> Result { + let mut argv = vec!["buzz", "messages", "report"]; + argv.extend_from_slice(args); + Cli::try_parse_from(argv).map(|cli| cli.command) + } + + fn tags(event: &serde_json::Value) -> Vec> { + serde_json::from_value(event["tags"].clone()).unwrap() + } + + #[test] + fn parse_requires_known_reason_and_one_target() { + assert!(parse(&["--event", EVENT]).is_err(), "reason is required"); + assert!( + parse(&["--event", EVENT, "--reason", "harassment"]).is_err(), + "unknown reason" + ); + assert!(parse(&["--reason", "spam"]).is_err(), "target is required"); + assert!( + parse(&["--event", EVENT, "--pubkey", AUTHOR, "--reason", "spam"]).is_err(), + "event and pubkey conflict" + ); + assert!( + parse(&["--channel", CHANNEL, "--pubkey", AUTHOR, "--reason", "spam"]).is_err(), + "channel needs an event" + ); + for reason in buzz_sdk::REPORT_TYPES { + assert!( + parse(&["--event", EVENT, "--reason", reason]).is_ok(), + "{reason}" + ); + } + let Cmd::Messages(MessagesCmd::Report { reason, note, .. }) = + parse(&["--pubkey", AUTHOR, "--reason", "spam", "--note", "x"]).unwrap() + else { + panic!("expected messages report"); + }; + assert_eq!((reason.as_str(), note.as_deref()), ("spam", Some("x"))); + } + + #[tokio::test] + async fn reports_a_message_with_desktop_tag_shape() { + let (url, captured) = fake_relay( + message_in_channel(), + StatusCode::OK, + r#"{"event_id":"e1","accepted":true,"message":""}"#, + ) + .await; + cmd_report_message( + &client(url), + ReportParams { + channel: Some(CHANNEL), + event: Some(EVENT), + pubkey: None, + reason: "spam", + note: Some(" buy now "), + }, + ) + .await + .unwrap(); + let sent = captured.lock().unwrap(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0]["kind"], 1984); + assert_eq!(sent[0]["content"], "buy now"); + assert_eq!( + tags(&sent[0]), + vec![ + vec!["p".to_string(), AUTHOR.to_string()], + vec!["e".to_string(), EVENT.to_string(), "spam".to_string()], + ] + ); + } + + #[tokio::test] + async fn self_reports_keep_the_p_tag() { + let keys = Keys::generate(); + let me = keys.public_key().to_hex(); + let ok = r#"{"event_id":"e1","accepted":true,"message":""}"#; + + let (url, captured) = fake_relay(message_by(&me), StatusCode::OK, ok).await; + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(keys.clone()), + ) + .unwrap(); + cmd_report_message( + &client, + ReportParams { + channel: None, + event: Some(EVENT), + pubkey: None, + reason: "spam", + note: None, + }, + ) + .await + .unwrap(); + assert_eq!( + tags(&captured.lock().unwrap()[0]), + vec![ + vec!["p".to_string(), me.clone()], + vec!["e".to_string(), EVENT.to_string(), "spam".to_string()], + ] + ); + + let (url, captured) = fake_relay(serde_json::json!([]), StatusCode::OK, ok).await; + let client = + BuzzClient::new(url, crate::credentials::Credentials::from_keys(keys)).unwrap(); + cmd_report_message( + &client, + ReportParams { + channel: None, + event: None, + pubkey: Some(&me), + reason: "spam", + note: None, + }, + ) + .await + .unwrap(); + assert_eq!( + tags(&captured.lock().unwrap()[0]), + vec![vec!["p".to_string(), me, "spam".to_string()]] + ); + } + + #[tokio::test] + async fn uppercase_ids_are_normalized_before_lookup_and_signing() { + let (url, captured) = fake_relay( + message_in_channel(), + StatusCode::OK, + r#"{"event_id":"e1","accepted":true,"message":""}"#, + ) + .await; + let upper = EVENT.to_uppercase(); + cmd_report_message( + &client(url), + ReportParams { + channel: None, + event: Some(&upper), + pubkey: None, + reason: "spam", + note: None, + }, + ) + .await + .unwrap(); + assert_eq!(tags(&captured.lock().unwrap()[0])[1][1], EVENT); + } + + #[tokio::test] + async fn reports_a_user_without_a_message() { + let (url, captured) = fake_relay( + serde_json::json!([]), + StatusCode::OK, + r#"{"event_id":"e1","accepted":true,"message":""}"#, + ) + .await; + cmd_report_message( + &client(url), + ReportParams { + channel: None, + event: None, + pubkey: Some(AUTHOR), + reason: "impersonation", + note: None, + }, + ) + .await + .unwrap(); + let sent = captured.lock().unwrap(); + assert_eq!( + tags(&sent[0]), + vec![vec![ + "p".to_string(), + AUTHOR.to_string(), + "impersonation".to_string() + ]] + ); + } + + #[tokio::test] + async fn channel_mismatch_is_a_usage_error_and_sends_nothing() { + let (url, captured) = fake_relay(message_in_channel(), StatusCode::OK, "{}").await; + let err = cmd_report_message( + &client(url), + ReportParams { + channel: Some("00000000-0000-0000-0000-000000000000"), + event: Some(EVENT), + pubkey: None, + reason: "spam", + note: None, + }, + ) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err}"); + assert_eq!(exit_code(&err), 1); + assert!(captured.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn malformed_ids_are_usage_errors_before_any_network_call() { + let dead = client("http://127.0.0.1:1".into()); + for (event, pubkey) in [(Some("abc"), None), (None, Some("abc"))] { + let err = cmd_report_message( + &dead, + ReportParams { + channel: None, + event, + pubkey, + reason: "spam", + note: None, + }, + ) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err}"); + } + } + + #[tokio::test] + async fn missing_event_is_not_found_and_sends_nothing() { + let (url, captured) = fake_relay(serde_json::json!([]), StatusCode::OK, "{}").await; + let err = cmd_report_message( + &client(url), + ReportParams { + channel: None, + event: Some(EVENT), + pubkey: None, + reason: "spam", + note: None, + }, + ) + .await + .unwrap_err(); + assert_eq!(exit_code(&err), 1); + assert!(captured.lock().unwrap().is_empty()); + } + + async fn rejected_exit_code(status: StatusCode, body: &str) -> (CliError, i32) { + let (url, _) = fake_relay(message_in_channel(), status, body).await; + let err = cmd_report_message( + &client(url), + ReportParams { + channel: None, + event: Some(EVENT), + pubkey: None, + reason: "spam", + note: None, + }, + ) + .await + .unwrap_err(); + let code = exit_code(&err); + (err, code) + } + + #[tokio::test] + async fn relay_rejections_map_to_exit_codes() { + let (err, code) = rejected_exit_code( + StatusCode::BAD_REQUEST, + r#"{"error":"invalid: report target event not found"}"#, + ) + .await; + assert!(matches!(err, CliError::NotFound(_)), "{err}"); + assert_eq!(code, 1); + + let (err, code) = rejected_exit_code( + StatusCode::BAD_REQUEST, + r#"{"error":"invalid: report target blob not found"}"#, + ) + .await; + assert!(matches!(err, CliError::NotFound(_)), "{err}"); + assert_eq!(code, 1); + + let (_, code) = rejected_exit_code( + StatusCode::BAD_REQUEST, + r#"{"error":"invalid: report must include a p tag"}"#, + ) + .await; + assert_eq!(code, 2); + + let (_, code) = rejected_exit_code( + StatusCode::BAD_REQUEST, + r#"{"error":"invalid: unsupported report type: x"}"#, + ) + .await; + assert_eq!(code, 2); + + let (_, code) = rejected_exit_code( + StatusCode::FORBIDDEN, + r#"{"error":"restricted: community writes are fenced"}"#, + ) + .await; + assert_eq!(code, 3); + } +} diff --git a/crates/buzz-cli/src/commands/messages.rs b/crates/buzz-cli/src/commands/messages.rs index 644b661b51b..1bbb2f85f83 100644 --- a/crates/buzz-cli/src/commands/messages.rs +++ b/crates/buzz-cli/src/commands/messages.rs @@ -1,9 +1,12 @@ +mod edit; + use buzz_sdk::{DeleteMessageOptions, DiffMeta, ThreadRef, VoteDirection}; use nostr::PublicKey; use uuid::Uuid; use crate::client::{normalize_events, normalize_write_response, BuzzClient}; use crate::commands::event_output::{format_events, thread_markers}; +use crate::commands::sent_from_thread; use crate::error::CliError; use crate::validate::{ infer_language, parse_event_id, parse_uuid, read_content_or_file, read_or_stdin, truncate_diff, @@ -51,7 +54,10 @@ fn thread_ref_from_parent_tags( /// - Nested reply: `root` is the parent's own root marker; `parent` is unchanged. /// /// Ensures CLI-sent replies thread correctly using the same NIP-10 logic. -async fn fetch_event(client: &BuzzClient, event_id: &str) -> Result { +pub(super) async fn fetch_event( + client: &BuzzClient, + event_id: &str, +) -> Result { let filter = serde_json::json!({ "ids": [event_id], "limit": 1 }); let raw = client.query(&filter).await?; let events: serde_json::Value = serde_json::from_str(&raw) @@ -82,7 +88,10 @@ fn thread_ref_from_event(event_id: &str, event: &serde_json::Value) -> Result
Result { +pub(super) fn channel_id_from_event( + event_id: &str, + event: &serde_json::Value, +) -> Result { let tags = event .get("tags") .and_then(|tags| tags.as_array()) @@ -340,10 +349,7 @@ pub async fn cmd_get_messages( // If specific kinds requested, override if let Some(k) = kinds { - let kind_list: Vec = k.split(',').filter_map(|s| s.trim().parse().ok()).collect(); - if !kind_list.is_empty() { - filter["kinds"] = serde_json::json!(kind_list); - } + filter["kinds"] = serde_json::json!(parse_kinds(k)?); } if let Some(b) = before { @@ -431,11 +437,14 @@ pub async fn cmd_get_thread( Ok(()) } +#[allow(clippy::too_many_arguments)] pub async fn cmd_search( client: &BuzzClient, query: Option<&str>, author: Option<&str>, since: Option, + before: Option, + before_id: Option<&str>, limit: Option, format: &crate::OutputFormat, ) -> Result<(), CliError> { @@ -444,26 +453,23 @@ pub async fn cmd_search( "at least one of --query or --author is required".into(), )); } - let limit = limit.unwrap_or(20).min(100); + // Validate the cursor before resolving the author, so a bad flag fails + // without a relay round trip. + search_filter(query, None, since, before, before_id, None)?; let author_hex = match author { Some(a) => Some(resolve_author(client, a).await?), None => None, }; - let mut filter = serde_json::json!({ - "kinds": [9, 40002, 45001, 45003], - "limit": limit - }); - if let Some(q) = query { - filter["search"] = serde_json::json!(q); - } - if let Some(ref pk) = author_hex { - filter["authors"] = serde_json::json!([pk]); - } - if let Some(s) = since { - filter["since"] = serde_json::json!(s); - } + let filter = search_filter( + query, + author_hex.as_deref(), + since, + before, + before_id, + limit, + )?; let resp = client.query(&filter).await?; let mut events: Vec = serde_json::from_str(&resp).unwrap_or_default(); // The full-text path returns relevance order; a pure author/time query has @@ -478,6 +484,53 @@ pub async fn cmd_search( Ok(()) } +/// The relay filter for `messages search`. +/// +/// `before` maps to `until`; `before_id` adds the relay's composite +/// `(until, before_id)` cursor, so an author-only search pages back with the +/// last result's `created_at` and `id`. Full-text results are ranked by +/// relevance, not time, so `before_id` is rejected with `query`. +fn search_filter( + query: Option<&str>, + author_hex: Option<&str>, + since: Option, + before: Option, + before_id: Option<&str>, + limit: Option, +) -> Result { + if let Some(bid) = before_id { + if query.is_some() { + return Err(CliError::Usage( + "--before-id cannot be combined with --query: full-text results are ranked by relevance, not time".into(), + )); + } + if before.is_none() { + return Err(CliError::Usage("--before-id requires --before".into())); + } + validate_hex64(bid)?; + } + let mut filter = serde_json::json!({ + "kinds": [9, 40002, 45001, 45003], + "limit": limit.unwrap_or(20).min(100) + }); + if let Some(q) = query { + filter["search"] = serde_json::json!(q); + } + if let Some(pk) = author_hex { + filter["authors"] = serde_json::json!([pk]); + } + if let Some(s) = since { + filter["since"] = serde_json::json!(s); + } + if let Some(b) = before { + filter["until"] = serde_json::json!(b); + } + if let Some(bid) = before_id { + filter["before_id"] = serde_json::json!(bid.to_ascii_lowercase()); + } + Ok(filter) +} + /// Resolve an `--author` value to a 64-char hex pubkey. /// /// Accepts, in order of precedence: 64-char hex (validated), an `npub1…` @@ -485,7 +538,7 @@ pub async fn cmd_search( /// must match exactly one user (case-insensitive, on `display_name` or /// `name`) — ambiguity is an error listing the candidates rather than a /// silent mix of authors. -async fn resolve_author(client: &BuzzClient, author: &str) -> Result { +pub(crate) async fn resolve_author(client: &BuzzClient, author: &str) -> Result { let author = author.trim(); if author.len() == 64 && author.chars().all(|c| c.is_ascii_hexdigit()) { return Ok(author.to_ascii_lowercase()); @@ -573,6 +626,46 @@ pub struct SendMessageParams { pub broadcast: bool, pub files: Vec, pub mentions: Vec, + pub from_thread: Option, +} + +/// Verify the thread root exists in `channel` and build the provenance tag +/// desktop's "Send to channel" attaches. +async fn resolve_sent_from_thread_tag( + client: &BuzzClient, + channel: Uuid, + root_event_id: &str, +) -> Result { + let root_hex = parse_event_id(root_event_id)?.to_hex(); + let root = fetch_event(client, &root_hex).await?; + sent_from_thread_tag_for_root(channel, &root_hex, &root) +} + +fn sent_from_thread_tag_for_root( + channel: Uuid, + root_hex: &str, + root: &serde_json::Value, +) -> Result { + if channel_id_from_event(root_hex, root)? != channel { + return Err(CliError::Usage(format!( + "--from-thread event {root_hex} is not in channel {channel}" + ))); + } + if root.get("kind").and_then(|k| k.as_u64()) != Some(9) { + return Err(CliError::Usage(format!( + "--from-thread event {root_hex} is not an ordinary channel message (kind 9)" + ))); + } + if let Some(real_root) = root.get("tags").and_then(find_root_from_tags) { + return Err(CliError::Usage(format!( + "--from-thread takes a thread root, but {root_hex} is a reply; use {real_root}" + ))); + } + let content = root.get("content").and_then(|c| c.as_str()).unwrap_or(""); + Ok(sent_from_thread::build_tag( + root_hex, + sent_from_thread::summarize_thread_root(content).as_deref(), + )) } pub async fn cmd_send_message(client: &BuzzClient, p: SendMessageParams) -> Result<(), CliError> { @@ -581,6 +674,15 @@ pub async fn cmd_send_message(client: &BuzzClient, p: SendMessageParams) -> Resu validate_hex64(r)?; } let channel_uuid = parse_uuid(&p.channel_id)?; + if p.from_thread.is_some() && !matches!(p.kind, None | Some(9)) { + return Err(CliError::Usage( + "--from-thread only applies to kind 9 messages".into(), + )); + } + let sent_from_thread_tag = match p.from_thread.as_deref() { + Some(root) => Some(resolve_sent_from_thread_tag(client, channel_uuid, root).await?), + None => None, + }; let explicit_mentions = normalize_explicit_mentions(&p.mentions)?; let stripped = strip_code_regions(&p.content); @@ -610,18 +712,13 @@ pub async fn cmd_send_message(client: &BuzzClient, p: SendMessageParams) -> Resu let mut media_tags: Vec> = Vec::new(); let mut media_content = String::new(); for file_path in &p.files { - let desc = client - .upload_file(file_path) - .await - .map_err(|e| CliError::Other(format!("upload failed for {file_path}: {e}")))?; - media_tags.push(crate::client::build_imeta_tag(&desc)); - if desc.mime_type.starts_with("video/") { - media_content.push_str("\n![video]("); - } else { - media_content.push_str("\n![image]("); - } - media_content.push_str(&desc.url); - media_content.push(')'); + let desc = client.upload_file(file_path).await?; + let name = attachment_name(file_path); + let mut tag = crate::client::build_imeta_tag(&desc); + tag.push(format!("filename {name}")); + media_tags.push(tag); + media_content.push('\n'); + media_content.push_str(&attachment_markdown(&name, &desc)); } let final_content = if media_content.is_empty() { p.content.clone() @@ -683,7 +780,7 @@ pub async fn cmd_send_message(client: &BuzzClient, p: SendMessageParams) -> Resu } else { Vec::new() }; - buzz_sdk::build_message( + let builder = buzz_sdk::build_message( channel_uuid, &final_content, thread_ref.as_ref(), @@ -692,7 +789,11 @@ pub async fn cmd_send_message(client: &BuzzClient, p: SendMessageParams) -> Resu &media_tags, &emoji_tags, ) - .map_err(|e| CliError::Other(format!("build_message failed: {e}")))? + .map_err(|e| CliError::Other(format!("build_message failed: {e}")))?; + match sent_from_thread_tag { + Some(tag) => builder.tag(tag), + None => builder, + } } Some(k) => { return Err(CliError::Usage(format!( @@ -701,7 +802,7 @@ pub async fn cmd_send_message(client: &BuzzClient, p: SendMessageParams) -> Resu } }; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let emitted_mentions = event_mention_pubkeys(&event); let resp = client.submit_event(event).await?; let mut output: serde_json::Value = serde_json::from_str(&normalize_write_response(&resp)) @@ -797,7 +898,7 @@ pub async fn cmd_send_diff_message(client: &BuzzClient, p: SendDiffParams) -> Re buzz_sdk::build_diff_message(channel_uuid, &diff, &diff_meta, thread_ref.as_ref()) .map_err(|e| CliError::Other(format!("build_diff_message failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -828,30 +929,7 @@ pub async fn cmd_delete_message( ) .map_err(|e| CliError::Other(format!("build_delete_message failed: {e}")))?; - let event = client.sign_event(builder)?; - - let resp = client.submit_event(event).await?; - println!("{}", normalize_write_response(&resp)); - Ok(()) -} - -/// Edit a message you previously sent. -pub async fn cmd_edit_message( - client: &BuzzClient, - event_id: &str, - content: &str, -) -> Result<(), CliError> { - validate_hex64(event_id)?; - validate_content_size(content)?; - - // Resolve channel_id from the event's h-tag - let channel_uuid = resolve_channel_id(client, event_id).await?; - let target_eid = parse_event_id(event_id)?; - - let builder = buzz_sdk::build_edit(channel_uuid, target_eid, content) - .map_err(|e| CliError::Other(format!("build_edit failed: {e}")))?; - - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -882,7 +960,7 @@ pub async fn cmd_vote_on_post( let builder = buzz_sdk::build_vote(channel_uuid, target_eid, vote_dir) .map_err(|e| CliError::Other(format!("build_vote failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -905,6 +983,7 @@ pub async fn dispatch( broadcast, files, mentions, + from_thread, } => { cmd_send_message( client, @@ -921,6 +1000,7 @@ pub async fn dispatch( broadcast, files, mentions, + from_thread, }, ) .await @@ -958,7 +1038,11 @@ pub async fn dispatch( ) .await } - MessagesCmd::Edit { event, content } => cmd_edit_message(client, &event, &content).await, + MessagesCmd::Edit { + event, + content, + clear_attachments, + } => edit::edit_message(client, &event, &content, clear_attachments).await, MessagesCmd::Delete { event, action_id, @@ -974,6 +1058,25 @@ pub async fn dispatch( ) .await } + MessagesCmd::Report { + channel, + event, + pubkey, + reason, + note, + } => { + super::message_report::cmd_report_message( + client, + super::message_report::ReportParams { + channel: channel.as_deref(), + event: event.as_deref(), + pubkey: pubkey.as_deref(), + reason: &reason, + note: note.as_deref(), + }, + ) + .await + } MessagesCmd::Get { channel, limit, @@ -1028,6 +1131,8 @@ pub async fn dispatch( query, author, since, + before, + before_id, limit, } => { cmd_search( @@ -1035,6 +1140,8 @@ pub async fn dispatch( query.as_deref(), author.as_deref(), since, + before, + before_id.as_deref(), limit, format, ) @@ -1046,14 +1153,156 @@ pub async fn dispatch( } } +/// A file's name as relay filename metadata takes it: its basename with +/// control characters and path separators as spaces, capped at 255 UTF-8 bytes. +fn attachment_name(file_path: &str) -> String { + let base = std::path::Path::new(file_path) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let mut name = String::new(); + for c in base.chars() { + let c = if c.is_control() || c == '/' || c == '\\' { + ' ' + } else { + c + }; + if name.len() + c.len_utf8() > 255 { + break; + } + name.push(c); + } + match name.trim() { + "" => "File".to_string(), + trimmed => trimmed.to_string(), + } +} + +/// An uploaded file's Markdown link: inline media embeds, other files link. +fn attachment_markdown(name: &str, desc: &crate::client::BlobDescriptor) -> String { + let mut label = String::new(); + for c in name.chars() { + if "\\`*_{}[]()!<>&".contains(c) { + label.push('\\'); + } + label.push(c); + } + let embed = matches!( + desc.mime_type.as_str(), + "image/jpeg" | "image/png" | "image/gif" | "image/webp" | "video/mp4" + ); + format!("{}[{label}](<{}>)", if embed { "!" } else { "" }, desc.url) +} + +/// A `--kinds` list: comma-separated event kinds, each 0–65535. +fn parse_kinds(list: &str) -> Result, CliError> { + list.split(',') + .map(|s| { + s.trim() + .parse() + .map_err(|_| CliError::Usage(format!("--kinds: invalid kind {s:?}"))) + }) + .collect() +} + #[cfg(test)] mod tests { + #[test] + fn search_filter_pages_by_composite_cursor() { + use super::{search_filter, CliError}; + let pk = "a".repeat(64); + let id = "B".repeat(64); + + // No cursor flags: the filter is unchanged from before. + assert_eq!( + search_filter(None, Some(&pk), Some(100), None, None, None).unwrap(), + serde_json::json!({ + "kinds": [9, 40002, 45001, 45003], + "limit": 20, + "authors": [pk], + "since": 100 + }) + ); + + // --before maps to `until`; --before-id rides along, lowercased. + assert_eq!( + search_filter(None, Some(&pk), Some(100), Some(200), Some(&id), Some(500)).unwrap(), + serde_json::json!({ + "kinds": [9, 40002, 45001, 45003], + "limit": 100, + "authors": [pk], + "since": 100, + "until": 200, + "before_id": "b".repeat(64) + }) + ); + + // --before alone is a plain time bound, allowed with --query. + let f = search_filter(Some("q"), None, None, Some(200), None, None).unwrap(); + assert_eq!(f["until"], 200); + assert_eq!(f["search"], "q"); + assert!(f.get("before_id").is_none()); + + for (query, before, before_id) in [ + (Some("q"), Some(200), Some(id.as_str())), // relevance order has no cursor + (None, None, Some(id.as_str())), // before_id needs until + (None, Some(200), Some("short")), // malformed id + ] { + assert!( + matches!( + search_filter(query, Some(&pk), None, before, before_id, None), + Err(CliError::Usage(_)) + ), + "{query:?} {before:?} {before_id:?}" + ); + } + } + + #[test] + fn parse_kinds_rejects_any_invalid_kind() { + use super::{parse_kinds, CliError}; + assert_eq!(parse_kinds("9, 40002").unwrap(), vec![9, 40002]); + for bad in ["bad", "65536", "9,typo", "", "-1"] { + assert!(matches!(parse_kinds(bad), Err(CliError::Usage(_))), "{bad}"); + } + } + + #[test] + fn attachments_embed_media_and_link_other_files() { + use super::{attachment_markdown, attachment_name}; + let blob = |mime: &str| crate::client::BlobDescriptor { + url: "https://r.example/media/x.bin".into(), + sha256: "x".into(), + size: 1, + mime_type: mime.into(), + uploaded: 0, + dim: None, + blurhash: None, + thumb: None, + duration: None, + }; + assert_eq!( + attachment_markdown("notes [v1].txt", &blob("application/octet-stream")), + "[notes \\[v1\\].txt]()" + ); + assert_eq!( + attachment_markdown("a.png", &blob("image/png")), + "![a.png]()" + ); + assert_eq!(attachment_name("/tmp/dir/report.pdf"), "report.pdf"); + assert_eq!(attachment_name("/tmp/a\nb.txt"), "a b.txt"); + assert_eq!(attachment_name("/"), "File"); + // On Windows a backslash is a path separator, not part of the name. + #[cfg(unix)] + assert_eq!(attachment_name("/tmp/a\\b.txt"), "a b.txt"); + } + use super::{ channel_id_from_event, cmd_get_thread, cmd_send_message, event_mention_pubkeys, find_root_from_tags, match_profiles_by_name, merge_message_mentions, missing_members, normalize_explicit_mentions, parse_member_pubkeys, resolve_names_to_pubkeys, - resolve_thread_target, thread_ref_from_event, thread_ref_from_parent_tags, BuzzClient, - CliError, Uuid, + resolve_thread_target, sent_from_thread_tag_for_root, thread_ref_from_event, + thread_ref_from_parent_tags, BuzzClient, CliError, Uuid, }; use buzz_sdk::mentions::{ extract_at_mentions_with_known, extract_at_names, match_names_to_profiles, MentionProfile, @@ -1073,8 +1322,11 @@ mod tests { #[tokio::test] async fn malformed_channel_is_rejected_before_thread_fetch() { - let client = - BuzzClient::new("http://127.0.0.1:1".into(), Keys::generate(), None, None).unwrap(); + let client = BuzzClient::new( + "http://127.0.0.1:1".into(), + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); let error = cmd_get_thread( &client, "not-a-uuid", @@ -1115,6 +1367,32 @@ mod tests { ); } + #[test] + fn from_thread_accepts_only_top_level_kind_9_roots_in_the_channel() { + let channel = "123e4567-e89b-12d3-a456-426614174000"; + let other = "123e4567-e89b-12d3-a456-426614174001"; + let channel_uuid = Uuid::parse_str(channel).unwrap(); + let root = |kind: u64, h: &str| json!({"kind": kind, "content": "hi", "tags": [["h", h]]}); + + let tag = sent_from_thread_tag_for_root(channel_uuid, ID_A, &root(9, channel)).unwrap(); + assert_eq!(tag.as_slice()[1], ID_A); + + for kind in [40002, 40008, 45001, 45003] { + let err = sent_from_thread_tag_for_root(channel_uuid, ID_A, &root(kind, channel)) + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "kind {kind}"); + assert!(err.to_string().contains("kind 9"), "kind {kind}"); + } + let no_kind = json!({"content": "hi", "tags": [["h", channel]]}); + assert!(sent_from_thread_tag_for_root(channel_uuid, ID_A, &no_kind).is_err()); + assert!(sent_from_thread_tag_for_root(channel_uuid, ID_A, &root(9, other)).is_err()); + let reply = json!({"kind": 9, "tags": [["h", channel], ["e", ID_B, "", "reply"]]}); + assert!(sent_from_thread_tag_for_root(channel_uuid, ID_A, &reply) + .unwrap_err() + .to_string() + .contains(ID_B)); + } + #[test] fn selected_event_requires_a_valid_channel_tag() { let missing = json!({"tags": []}); @@ -1655,6 +1933,7 @@ mod tests { broadcast: false, files: vec![], mentions: vec![], + from_thread: None, } } @@ -1663,7 +1942,11 @@ mod tests { // Content contains `:wave:` which resolves in the palette. // The submitted event must carry an `emoji` tag for `wave`. let (url, query_count, captured_event) = fake_send_relay(send_palette_response()).await; - let client = BuzzClient::new(url, Keys::generate(), None, None).unwrap(); + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); cmd_send_message(&client, send_params("hello :wave: everyone")) .await @@ -1715,7 +1998,11 @@ mod tests { // Content has no `:` at all — the palette query must be skipped // entirely (zero RTTs), and the submitted event must have no emoji tags. let (url, query_count, captured_event) = fake_send_relay(send_palette_response()).await; - let client = BuzzClient::new(url, Keys::generate(), None, None).unwrap(); + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); cmd_send_message(&client, send_params("plain message no colons")) .await @@ -1776,7 +2063,11 @@ mod tests { }; let (url, _, captured_event) = fake_send_relay(send_palette_response()).await; - let client = BuzzClient::new(url, Keys::generate(), None, None).unwrap(); + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); super::dispatch(cmd, &client, &crate::OutputFormat::Json) .await .unwrap(); @@ -1828,7 +2119,11 @@ mod tests { let addr: StdSocketAddr = listener.local_addr().unwrap(); tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); let url = format!("http://{addr}"); - let client = BuzzClient::new(url, Keys::generate(), None, None).unwrap(); + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); // Must not return Err — a palette failure is a soft warning. cmd_send_message(&client, send_params(":wave: message with emoji candidate")) @@ -1860,4 +2155,151 @@ mod tests { "palette-error fallback must produce no emoji tags, got: {emoji_tags:?}" ); } + + /// Fake relay that answers `/query` by `ids` filter from `stored` and + /// records every `/events` body. + async fn fake_thread_relay( + stored: Vec, + ) -> (String, StdArc>>) { + type S = ( + Vec, + StdArc>>, + ); + let published = StdArc::new(std::sync::Mutex::new(Vec::new())); + let app = AxumRouter::new() + .route( + "/query", + axum_post( + |AxumState((stored, _)): AxumState, body: AxumBytes| async move { + let filter: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let filter = filter.get(0).unwrap_or(&filter); + let found: Vec<_> = stored + .iter() + .filter(|e| { + filter["ids"] + .as_array() + .is_some_and(|ids| ids.contains(&e["id"])) + }) + .collect(); + ( + AxumStatusCode::OK, + [("content-type", "application/json")], + serde_json::to_string(&found).unwrap(), + ) + }, + ), + ) + .route( + "/events", + axum_post( + |AxumState((_, published)): AxumState, body: AxumBytes| async move { + published + .lock() + .unwrap() + .push(String::from_utf8_lossy(&body).to_string()); + ( + AxumStatusCode::OK, + [("content-type", "application/json")], + r#"{"event_id":"fake0000","accepted":true}"#, + ) + }, + ), + ) + .with_state((stored, published.clone())); + let listener = TokioTcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr: StdSocketAddr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (format!("http://{addr}"), published) + } + + fn stored_message( + id: &str, + channel: &str, + content: &str, + extra: &[serde_json::Value], + ) -> serde_json::Value { + let mut tags = vec![serde_json::json!(["h", channel])]; + tags.extend(extra.iter().cloned()); + serde_json::json!({ "id": id, "kind": 9, "content": content, "tags": tags }) + } + + #[tokio::test] + async fn send_from_thread_publishes_a_top_level_tagged_message() { + let root = "a".repeat(64); + let reply = "b".repeat(64); + let other_channel = "223e4567-e89b-12d3-a456-426614174000"; + let (url, published) = fake_thread_relay(vec![ + stored_message( + &root, + SEND_TEST_CHANNEL, + "**Plan**: see [doc](https://x.io) 😀", + &[], + ), + stored_message( + &reply, + SEND_TEST_CHANNEL, + "reply", + &[serde_json::json!(["e", root, "", "reply"])], + ), + stored_message(&"c".repeat(64), other_channel, "elsewhere", &[]), + ]) + .await; + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); + + let send = |from_thread: &str, kind: Option| { + let mut params = send_params("decision: ship it"); + params.from_thread = Some(from_thread.to_string()); + params.kind = kind; + cmd_send_message(&client, params) + }; + + for (target, kind) in [ + (reply.as_str(), None), + ("c".repeat(64).as_str(), None), + ("d".repeat(64).as_str(), None), + ("not-hex", None), + (root.as_str(), Some(45001)), + ] { + let err = send(target, kind).await.unwrap_err(); + let expected = match target { + t if t == "d".repeat(64) => matches!(err, CliError::NotFound(_)), + _ => matches!(err, CliError::Usage(_)), + }; + assert!(expected, "{target} {kind:?}: {err}"); + if target == reply { + assert!(err.to_string().contains(&root), "{err}"); + } + } + assert!( + published.lock().unwrap().is_empty(), + "failed checks must not publish" + ); + + send(&root.to_uppercase(), None).await.unwrap(); + let bodies = published.lock().unwrap(); + assert_eq!(bodies.len(), 1, "one send is one publish"); + let event: serde_json::Value = serde_json::from_str(&bodies[0]).unwrap(); + assert_eq!(event["kind"], 9); + assert_eq!(event["content"], "decision: ship it"); + let tags = event["tags"].as_array().unwrap(); + assert!(tags.contains(&serde_json::json!(["h", SEND_TEST_CHANNEL]))); + assert!( + tags.contains(&serde_json::json!([ + "buzz:sent-from-thread", + root, + "Plan : see doc 😀" + ])), + "{tags:?}" + ); + assert!( + !tags + .iter() + .any(|t| matches!(t[0].as_str(), Some("e" | "broadcast"))), + "must be top-level: {tags:?}" + ); + } } diff --git a/crates/buzz-cli/src/commands/messages/edit.rs b/crates/buzz-cli/src/commands/messages/edit.rs new file mode 100644 index 00000000000..1f02ff44689 --- /dev/null +++ b/crates/buzz-cli/src/commands/messages/edit.rs @@ -0,0 +1,132 @@ +//! Resolve replacement attachment state before publishing an edit. +use super::{channel_id_from_event, fetch_event}; +use crate::{ + client::BuzzClient, + error::CliError, + validate::{parse_event_id, validate_content_size, validate_hex64}, +}; +use nostr::{Event, Timestamp}; + +pub(super) async fn edit_message( + client: &BuzzClient, + event_id: &str, + content: &str, + clear_attachments: bool, +) -> Result<(), CliError> { + validate_hex64(event_id)?; + validate_content_size(content)?; + let target = parse_event_id(event_id)?; + let raw = fetch_event(client, &target.to_hex()).await?; + let channel = channel_id_from_event(event_id, &raw)?; + let original: Event = serde_json::from_value(raw) + .map_err(|e| CliError::Other(format!("invalid edit target: {e}")))?; + if original.id != target { + return Err(CliError::Other( + "relay returned the wrong edit target".into(), + )); + } + // Keep this boundary aligned with media_reference_query and the relay lookup. + // Other channel-tagged events retain the historical plain-edit behavior. + if !buzz_core::media::EDIT_GOVERNED_KINDS.contains(&original.kind.as_u16()) { + if clear_attachments { + return Err(CliError::Usage(format!( + "attachments on kind {} are not edit-governed", + original.kind.as_u16() + ))); + } + let builder = buzz_sdk::build_edit(channel, target, content) + .map_err(|e| CliError::Other(format!("build_edit failed: {e}")))?; + let event = client.sign_event(builder).await?; + let resp = client.submit_event(event).await?; + println!("{}", crate::client::normalize_write_response(&resp)); + return Ok(()); + } + let raw = client + .query(&serde_json::json!({ + "kinds": buzz_core::media::EDIT_GOVERNED_KINDS, "ids": [target.to_hex()], "#h": [channel.to_string()], + "effective_edit": 1, "consistency": "strong", + })) + .await?; + let snapshot: serde_json::Value = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("invalid effective edit response: {e}")))?; + if snapshot.get("effective_edit") != Some(&serde_json::json!(1)) + || snapshot.get("edit").is_none() + { + return Err(CliError::Other( + "relay does not support effective_edit v1; upgrade the relay before editing".into(), + )); + } + let original: Event = serde_json::from_value(snapshot["original"].clone()) + .map_err(|e| CliError::Other(format!("invalid effective original: {e}")))?; + if original.id != target + || !buzz_core::media::EDIT_GOVERNED_KINDS.contains(&original.kind.as_u16()) + || channel_id_from_event(event_id, &snapshot["original"])? != channel + { + return Err(CliError::Other( + "effective edit response has the wrong original".into(), + )); + } + let edits: Vec = if snapshot["edit"].is_null() { + vec![] + } else { + vec![serde_json::from_value(snapshot["edit"].clone()) + .map_err(|e| CliError::Other(format!("invalid effective edit: {e}")))?] + }; + let effective = latest_edit(&original, &edits); + if !edits.is_empty() && effective.id == original.id { + return Err(CliError::Other( + "effective edit response has the wrong replacement".into(), + )); + } + let media = if clear_attachments { + Vec::new() + } else { + effective + .tags + .iter() + .filter(|t| t.as_slice().first().map(String::as_str) == Some("imeta")) + .map(|t| t.as_slice().to_vec()) + .collect() + }; + let now = Timestamp::now().as_secs(); + // Make successive edits effective even when issued in the same second. + // Refuse an unexpectedly future timeline instead of extending it forever. + let head = effective.created_at.as_secs(); + if head > now.saturating_add(60) { + return Err(CliError::Other( + "latest edit is too far in the future; retry when the clock catches up".into(), + )); + } + let created_at = now.max(head + 1); + let builder = buzz_sdk::build_edit_with_media(channel, target, content, &media) + .map_err(|e| CliError::Other(format!("build_edit failed: {e}")))? + .custom_created_at(Timestamp::from(created_at)); + let event = client.sign_event(builder).await?; + let resp = client.submit_event(event).await?; + println!("{}", crate::client::normalize_write_response(&resp)); + Ok(()) +} + +fn latest_edit<'a>(original: &'a Event, edits: &'a [Event]) -> &'a Event { + let channel = |event: &Event| { + event + .tags + .iter() + .find(|t| t.as_slice().first().map(String::as_str) == Some("h")) + .and_then(|t| t.content()) + .and_then(|id| uuid::Uuid::parse_str(id).ok()) + }; + edits + .iter() + .filter(|edit| { + edit.kind.as_u16() == 40003 + && channel(edit) == channel(original) + && buzz_core::media::first_edit_target(edit).as_deref() + == Some(original.id.as_bytes().as_slice()) + }) + .max_by_key(|edit| (edit.created_at, edit.id)) + .unwrap_or(original) +} + +#[cfg(test)] +mod tests; diff --git a/crates/buzz-cli/src/commands/messages/edit/tests.rs b/crates/buzz-cli/src/commands/messages/edit/tests.rs new file mode 100644 index 00000000000..b6033b84d80 --- /dev/null +++ b/crates/buzz-cli/src/commands/messages/edit/tests.rs @@ -0,0 +1,309 @@ +use super::*; +use axum::{extract::State, routing::post, Json, Router}; +use nostr::{EventBuilder, Keys, Kind, Tag}; +use std::sync::{Arc, Mutex}; +use uuid::Uuid; + +fn message(keys: &Keys, channel: Uuid, media: &[Vec]) -> Event { + EventBuilder::new(Kind::Custom(9), "original") + .tags( + std::iter::once(Tag::parse(["h", &channel.to_string()]).unwrap()) + .chain(media.iter().map(|t| Tag::parse(t.clone()).unwrap())), + ) + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() - 20)) + .sign_with_keys(keys) + .unwrap() +} +fn edit(keys: &Keys, original: &Event, at: u64, extra: &[Vec]) -> Event { + let channel = original + .tags + .iter() + .find(|t| t.as_slice()[0] == "h") + .unwrap() + .content() + .unwrap(); + EventBuilder::new(Kind::Custom(40003), "edit") + .tags( + std::iter::once(Tag::parse(["h", channel]).unwrap()) + .chain(extra.iter().map(|t| Tag::parse(t.clone()).unwrap())), + ) + .custom_created_at(Timestamp::from(at)) + .sign_with_keys(keys) + .unwrap() +} +fn imeta(name: &str) -> Vec { + vec![ + "imeta".into(), + format!("url https://example.com/{name}"), + "m image/png".into(), + "alt original label".into(), + "blurhash complete metadata".into(), + ] +} + +#[test] +fn latest_uses_server_order_target_and_channel() { + let keys = Keys::generate(); + let original = message(&keys, Uuid::new_v4(), &[imeta("original")]); + let target = vec!["e".into(), original.id.to_hex()]; + let now = Timestamp::now().as_secs(); + let older = edit(&keys, &original, now - 1, &[target.clone(), imeta("older")]); + let cleared = edit(&keys, &original, now, std::slice::from_ref(&target)); + let tied = edit(&keys, &original, now, &[target.clone(), imeta("tie")]); + let winner = if cleared.id > tied.id { + &cleared + } else { + &tied + }; + assert_eq!( + latest_edit(&original, &[older.clone(), cleared.clone(), tied.clone()]).id, + winner.id + ); + // First valid e wins; a later matching tag must not select this edit. + let decoy = edit( + &keys, + &original, + now + 1, + &[ + vec!["e".into(), "f".repeat(64)], + target.clone(), + imeta("decoy"), + ], + ); + let wrong_channel_original = message(&keys, Uuid::new_v4(), &[]); + let wrong_channel = edit( + &keys, + &wrong_channel_original, + now + 2, + std::slice::from_ref(&target), + ); + assert_eq!( + latest_edit(&original, &[older, cleared.clone(), decoy, wrong_channel]).id, + cleared.id + ); + let mixed = original + .id + .to_hex() + .chars() + .enumerate() + .map(|(i, c)| { + if i % 2 == 0 { + c.to_ascii_uppercase() + } else { + c + } + }) + .collect::(); + let valid_after_invalid = edit( + &keys, + &original, + now + 3, + &[vec!["e".into(), "invalid".into()], vec!["e".into(), mixed]], + ); + assert_eq!( + latest_edit(&original, std::slice::from_ref(&valid_after_invalid)).id, + valid_after_invalid.id + ); + assert_eq!(latest_edit(&original, &[]).id, original.id); +} + +#[derive(Clone)] +struct Relay { + events: Arc>>, + submitted: Arc>>, + fail_history: bool, + effective_queries: Arc, + ignore_extension: Arc, +} +async fn relay(events: Vec, fail_history: bool) -> (String, Relay) { + let state = Relay { + events: Arc::new(Mutex::new(events)), + submitted: Default::default(), + fail_history, + effective_queries: Default::default(), + ignore_extension: Default::default(), + }; + let app = Router::new() + .route("/query", post(|State(state): State, Json(filters): Json>| async move { + let filter = &filters[0]; + if filter.get("effective_edit").is_some() { + state.effective_queries.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + if state.fail_history && filter.get("kinds").is_some() { + return (axum::http::StatusCode::FORBIDDEN, Json(serde_json::json!({"error":"denied"}))); + } + if filter.get("effective_edit").is_some() && !state.ignore_extension.load(std::sync::atomic::Ordering::SeqCst) { + assert_eq!(filter["consistency"], "strong"); + assert_eq!(filter, &serde_json::json!({ + "kinds":[9,40002,40008,45001,45003], "ids":filter["ids"], + "#h":filter["#h"], "effective_edit":1, "consistency":"strong" + })); + let events = state.events.lock().unwrap(); + let original = events.iter().find(|event| serde_json::json!(event.id.to_hex()) == filter["ids"][0]).unwrap(); + let latest = events.iter().filter(|event| event.kind.as_u16() == 40003 && buzz_core::media::first_edit_target(event).as_deref() == Some(original.id.as_bytes().as_slice())) + .max_by_key(|event| (event.created_at,event.id)); + return (axum::http::StatusCode::OK, Json(serde_json::json!({"effective_edit":1,"original":original,"edit":latest}))); + } + let events: Vec = state.events.lock().unwrap().iter().filter(|event| { + filter["ids"].as_array().is_none_or(|ids| ids.contains(&serde_json::json!(event.id.to_hex()))) + && filter["kinds"].as_array().is_none_or(|kinds| kinds.contains(&serde_json::json!(event.kind.as_u16()))) + }).cloned().collect(); + (axum::http::StatusCode::OK, Json(serde_json::json!(events))) + })) + .route("/events", post(|State(state): State, Json(event): Json| async move { + event.verify().unwrap(); + state.events.lock().unwrap().push(event.clone()); + state.submitted.lock().unwrap().push(event.clone()); + Json(serde_json::json!({"event_id":event.id.to_hex(), "accepted":true})) + })).with_state(state.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + (url, state) +} +fn client(url: String, keys: Keys) -> BuzzClient { + BuzzClient::new(url, crate::credentials::Credentials::from_keys(keys)).unwrap() +} + +#[tokio::test] +async fn command_retains_latest_full_set_then_keeps_clear_across_same_second_edits() { + let keys = Keys::generate(); + let channel = Uuid::new_v4(); + let original = message(&keys, channel, &[imeta("removed"), imeta("kept")]); + let replacement = edit( + &keys, + &original, + Timestamp::now().as_secs(), + &[vec!["e".into(), original.id.to_hex()], imeta("kept")], + ); + let (url, state) = relay(vec![original.clone(), replacement.clone()], false).await; + let client = client(url, keys); + for index in 0..4 { + edit_message( + &client, + &original.id.to_hex(), + &format!("edit {index}"), + index == 2, + ) + .await + .unwrap(); + } + let submitted = state.submitted.lock().unwrap(); + let mut previous = replacement.created_at; + for (index, event) in submitted.iter().enumerate() { + let tags: Vec<_> = event + .tags + .iter() + .filter(|t| t.as_slice()[0] == "imeta") + .map(|t| t.as_slice().to_vec()) + .collect(); + assert_eq!( + tags, + if index < 2 { + vec![imeta("kept")] + } else { + vec![] + } + ); + assert!(event.created_at > previous); + previous = event.created_at; + } +} + +#[tokio::test] +async fn command_aborts_on_unreadable_history_or_future_head() { + for fail_history in [true, false] { + let keys = Keys::generate(); + let original = message(&keys, Uuid::new_v4(), &[imeta("kept")]); + let poisoned = edit( + &keys, + &original, + Timestamp::now().as_secs() + 1000, + &[vec!["e".into(), original.id.to_hex()]], + ); + let (url, state) = relay(vec![original.clone(), poisoned], fail_history).await; + let client = client(url, keys); + assert!(edit_message(&client, &original.id.to_hex(), "new", false) + .await + .is_err()); + assert!(state.submitted.lock().unwrap().is_empty()); + } +} + +#[tokio::test] +async fn command_refuses_an_older_relay_that_ignores_the_extension() { + for kind in [9, 40002, 40008, 45001, 45003] { + let keys = Keys::generate(); + let channel = Uuid::new_v4(); + let original = EventBuilder::new(Kind::Custom(kind), "original") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(imeta("kept")).unwrap(), + ]) + .sign_with_keys(&keys) + .unwrap(); + let (url, state) = relay(vec![original.clone()], false).await; + state + .ignore_extension + .store(true, std::sync::atomic::Ordering::SeqCst); + let client = client(url, keys); + let error = edit_message(&client, &original.id.to_hex(), "new", false) + .await + .unwrap_err(); + assert!( + error.to_string().contains("upgrade the relay"), + "kind {kind}" + ); + assert!(state.submitted.lock().unwrap().is_empty()); + } +} + +#[tokio::test] +async fn other_channel_kinds_keep_plain_edits_on_older_relays() { + for kind in [40003, 7, 45002, 12345] { + let keys = Keys::generate(); + let channel = Uuid::new_v4(); + let original = EventBuilder::new(Kind::Custom(kind), "original") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(imeta("original")).unwrap(), + ]) + .sign_with_keys(&keys) + .unwrap(); + let (url, state) = relay(vec![original.clone()], false).await; + state + .ignore_extension + .store(true, std::sync::atomic::Ordering::SeqCst); + let client = client(url, keys); + for content in ["first edit", "second edit"] { + edit_message(&client, &original.id.to_hex(), content, false) + .await + .unwrap(); + } + let error = edit_message(&client, &original.id.to_hex(), "clear", true) + .await + .unwrap_err(); + assert!(error + .to_string() + .contains(&format!("attachments on kind {kind} are not edit-governed"))); + assert_eq!( + state + .effective_queries + .load(std::sync::atomic::Ordering::SeqCst), + 0 + ); + let submitted = state.submitted.lock().unwrap(); + assert_eq!(submitted.len(), 2, "clear must not publish"); + for (event, content) in submitted.iter().zip(["first edit", "second edit"]) { + assert_eq!(event.kind.as_u16(), 40003); + assert_eq!(event.content, content); + assert_eq!( + buzz_core::media::first_edit_target(event).as_deref(), + Some(original.id.as_bytes().as_slice()) + ); + assert!(!event.tags.iter().any(|tag| tag.as_slice()[0] == "imeta")); + } + } +} diff --git a/crates/buzz-cli/src/commands/mod.rs b/crates/buzz-cli/src/commands/mod.rs index f7a3ebe9e0d..8578eeaaf3b 100644 --- a/crates/buzz-cli/src/commands/mod.rs +++ b/crates/buzz-cli/src/commands/mod.rs @@ -1,13 +1,17 @@ pub mod agents; pub mod channel_templates; +pub mod channel_unread; pub mod channels; pub mod dms; pub mod emoji; pub(crate) mod event_output; pub mod feed; pub mod gifs; +mod huddle_tracker; +pub mod huddles; pub mod issues; pub mod mem; +pub mod message_report; pub mod messages; pub mod moderation; pub mod notes; @@ -17,8 +21,15 @@ pub mod pr; pub mod project_channel; pub mod projects; pub mod reactions; +pub(crate) mod read_state; mod repo_default_branch; pub mod repos; +pub(crate) mod sent_from_thread; +pub mod sidebar; +mod sidebar_doc; +mod sidebar_flags; +mod sidebar_sort; +mod sidebar_sync; pub mod social; pub mod upload; pub mod users; diff --git a/crates/buzz-cli/src/commands/moderation.rs b/crates/buzz-cli/src/commands/moderation.rs index c53aecaf852..34393caebc3 100644 --- a/crates/buzz-cli/src/commands/moderation.rs +++ b/crates/buzz-cli/src/commands/moderation.rs @@ -42,7 +42,7 @@ async fn cmd_ban( let expiry = resolve_expiry(expires_in, expires_at); let builder = buzz_sdk::build_moderation_ban(pubkey, expiry, reason) .map_err(|e| CliError::Usage(format!("invalid ban: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -52,7 +52,7 @@ async fn cmd_unban(client: &BuzzClient, pubkey: &str) -> Result<(), CliError> { validate_hex64(pubkey)?; let builder = buzz_sdk::build_moderation_unban(pubkey) .map_err(|e| CliError::Usage(format!("invalid unban: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -70,7 +70,7 @@ async fn cmd_timeout( .ok_or_else(|| CliError::Usage("timeout requires --expires-in or --expires-at".into()))?; let builder = buzz_sdk::build_moderation_timeout(pubkey, expiry, reason) .map_err(|e| CliError::Usage(format!("invalid timeout: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -80,7 +80,7 @@ async fn cmd_untimeout(client: &BuzzClient, pubkey: &str) -> Result<(), CliError validate_hex64(pubkey)?; let builder = buzz_sdk::build_moderation_untimeout(pubkey) .map_err(|e| CliError::Usage(format!("invalid untimeout: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) @@ -96,7 +96,7 @@ async fn cmd_resolve( validate_hex64(report)?; let builder = buzz_sdk::build_moderation_resolve_report(report, status, action, reason) .map_err(|e| CliError::Usage(format!("invalid resolution: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) diff --git a/crates/buzz-cli/src/commands/notes.rs b/crates/buzz-cli/src/commands/notes.rs index 08ef345be11..9c58dd21965 100644 --- a/crates/buzz-cli/src/commands/notes.rs +++ b/crates/buzz-cli/src/commands/notes.rs @@ -166,7 +166,7 @@ fn parse_events(json: &str) -> Result, CliError> { /// needs its presence to decide first-publish vs. update / deletable-or-not. /// (Quinn's option (b) — single tag-parser, isolated.) pub async fn fetch_own_note(client: &BuzzClient, slug: &str) -> Result, CliError> { - let me = client.keys().public_key(); + let me = client.public_key(); let filter = serde_json::json!({ "kinds": [KIND_LONG_FORM], "authors": [me.to_hex()], @@ -203,7 +203,7 @@ pub async fn fetch_by_slug(client: &BuzzClient, slug: &str) -> Result /// kind:0 profiles. Exact-one match required; ambiguity is a hard error. pub async fn resolve_author(client: &BuzzClient, author_flag: &str) -> Result { if author_flag == "me" { - return Ok(client.keys().public_key()); + return Ok(client.public_key()); } if validate_hex64(author_flag).is_ok() { return PublicKey::from_hex(author_flag) @@ -539,7 +539,7 @@ pub async fn cmd_set( now_secs(), )?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let event_id = event.id; let me = event.pubkey; let raw = client.submit_event(event).await?; @@ -718,7 +718,7 @@ pub async fn cmd_rm(client: &BuzzClient, slug: &str) -> Result<(), CliError> { // Read-before-write: only the author can delete their own note, and we // want a clear "nothing to delete" signal rather than emitting a kind:5 // for a coordinate that was never published. - let me = client.keys().public_key(); + let me = client.public_key(); if fetch_own_note(client, slug).await?.is_none() { return Err(CliError::NotFound(format!( "no note {slug:?} found for you ({}); nothing to delete", @@ -728,7 +728,7 @@ pub async fn cmd_rm(client: &BuzzClient, slug: &str) -> Result<(), CliError> { let coord = coord_for(&me, slug); let builder = build_rm_event(&coord)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let event_id = event.id; let raw = client.submit_event(event).await?; let parsed: serde_json::Value = serde_json::from_str(&raw) diff --git a/crates/buzz-cli/src/commands/patches.rs b/crates/buzz-cli/src/commands/patches.rs index 413934a3c11..283cfa43e3b 100644 --- a/crates/buzz-cli/src/commands/patches.rs +++ b/crates/buzz-cli/src/commands/patches.rs @@ -50,7 +50,7 @@ pub async fn cmd_send_patch( let builder = with_git_provenance(buzz_sdk::build_git_patch(&repo, &content, &meta).map_err(sdk_err)?)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{resp}"); Ok(()) @@ -184,7 +184,7 @@ pub async fn cmd_patch_status( let builder = with_git_provenance(buzz_sdk::build_git_status(status, &body, &meta).map_err(sdk_err)?)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{resp}"); Ok(()) diff --git a/crates/buzz-cli/src/commands/pr.rs b/crates/buzz-cli/src/commands/pr.rs index 74c580a6d6a..47a76357e84 100644 --- a/crates/buzz-cli/src/commands/pr.rs +++ b/crates/buzz-cli/src/commands/pr.rs @@ -59,7 +59,7 @@ pub async fn cmd_open_pr( let builder = with_git_provenance( buzz_sdk::build_git_pull_request(&repo, &content, &meta).map_err(sdk_err)?, )?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let event_id = event.id.to_hex(); let resp = client.submit_event(event).await?; // `link` renders as a rich preview card in Buzz Desktop when included in @@ -107,7 +107,7 @@ pub async fn cmd_update_pr( let builder = with_git_provenance( buzz_sdk::build_git_pr_update(&repo, &content, &meta).map_err(sdk_err)?, )?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{resp}"); Ok(()) @@ -217,7 +217,7 @@ pub async fn cmd_pr_status( let builder = with_git_provenance(buzz_sdk::build_git_status(status, &content, &meta).map_err(sdk_err)?)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{resp}"); Ok(()) diff --git a/crates/buzz-cli/src/commands/project_channel.rs b/crates/buzz-cli/src/commands/project_channel.rs index 887239f704f..4a04bcf9777 100644 --- a/crates/buzz-cli/src/commands/project_channel.rs +++ b/crates/buzz-cli/src/commands/project_channel.rs @@ -34,7 +34,7 @@ pub async fn resolve_or_ensure_repo_for_channel( return Ok(repo); } - let caller = client.keys().public_key().to_hex(); + let caller = client.public_key().to_hex(); if let Some(repo) = repos.iter().find_map(|event| { event .pubkey @@ -201,7 +201,7 @@ async fn ensure_default_repo( let repo_id = repo_id_from_project_slug(&slug)?; let name = project_name(project).unwrap_or_else(|| slug.clone()); let name = truncate_repo_name(&name); - let caller = client.keys().public_key().to_hex(); + let caller = client.public_key().to_hex(); if let Some(existing) = crate::commands::repos::fetch_own_repo_announcement(client, &repo_id).await? @@ -223,7 +223,7 @@ async fn ensure_default_repo( &[], Some(channel), )?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let raw = client.submit_event(event).await?; let winner = crate::commands::repos::fetch_own_repo_announcement(client, &repo_id).await?; verify_default_repo_write(&raw, winner.as_ref(), channel)?; @@ -474,7 +474,11 @@ mod tests { socket.write_all(response.as_bytes()).await.unwrap(); } }); - let client = crate::client::BuzzClient::new(base_url, keys, None, None).unwrap(); + let client = crate::client::BuzzClient::new( + base_url, + crate::credentials::Credentials::from_keys(keys), + ) + .unwrap(); let result = ensure_default_repo(&client, requested, &project).await; diff --git a/crates/buzz-cli/src/commands/projects.rs b/crates/buzz-cli/src/commands/projects.rs index 3edad04b412..949ffa661c6 100644 --- a/crates/buzz-cli/src/commands/projects.rs +++ b/crates/buzz-cli/src/commands/projects.rs @@ -47,7 +47,7 @@ async fn cmd_add_channel_draft( let owner = PublicKey::parse(&owner_hex) .map_err(|error| CliError::Auth(format!("invalid owner attestation: {error}")))?; let built = build_project_channel( - client.keys(), + client.credentials(), &owner, CreateProjectChannelDraft { home_channel_id: home_channel, @@ -57,7 +57,8 @@ async fn cmd_add_channel_draft( ttl_seconds, template_name, }, - )?; + ) + .await?; let response = client.publish_ephemeral_event(built.event).await?; let mut output: serde_json::Value = serde_json::from_str(&response) .map_err(|error| CliError::Other(format!("invalid relay response: {error}")))?; @@ -173,7 +174,7 @@ pub async fn add_repos_to_own_project( repos: &[String], ) -> Result { validate_project_slug(slug)?; - let caller_pubkey = client.keys().public_key().to_hex(); + let caller_pubkey = client.public_key().to_hex(); let new_members: Vec = repos .iter() @@ -222,7 +223,7 @@ pub async fn add_repos_to_own_project( } let builder = rebuild_project(&head.content, tags, next_ts)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; client.submit_event(event).await } @@ -233,7 +234,7 @@ pub async fn try_add_own_repo_to_channel_project( repo_id: &str, ) -> Result<(), CliError> { let projects = fetch_projects_for_channel(client, channel).await?; - let caller = client.keys().public_key().to_hex(); + let caller = client.public_key().to_hex(); let Some(event) = projects.iter().find(|candidate| { candidate.pubkey.to_hex().eq_ignore_ascii_case(&caller) && !project_is_unlisted(candidate) }) else { @@ -259,7 +260,7 @@ async fn fetch_project( crate::validate::validate_hex64(pk)?; pk.to_string() } - None => client.keys().public_key().to_hex(), + None => client.public_key().to_hex(), }; let filter = serde_json::json!({ "kinds": [KIND_PROJECT], @@ -306,7 +307,7 @@ async fn submit_project( builder: EventBuilder, link_slug: Option<&str>, ) -> Result<(), CliError> { - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let owner = event.pubkey.to_hex(); let raw = client.submit_event(event).await?; let response = parse_write_response(&raw, "project changed concurrently; retry")?; @@ -369,7 +370,7 @@ pub async fn cmd_create( // ── Local validation (all checks before any .await) ─────────────────── validate_project_slug(slug)?; - let caller_pubkey = client.keys().public_key().to_hex(); + let caller_pubkey = client.public_key().to_hex(); // Expand and validate repo coordinates. let mut members: Vec = repos @@ -492,7 +493,7 @@ pub async fn cmd_list( crate::validate::validate_hex64(pk)?; pk.to_string() } - None => client.keys().public_key().to_hex(), + None => client.public_key().to_hex(), }; let mut filter = serde_json::json!({ "kinds": [KIND_PROJECT], @@ -525,7 +526,7 @@ pub async fn cmd_remove_repo( repos: &[String], ) -> Result<(), CliError> { validate_project_slug(slug)?; - let caller_pubkey = client.keys().public_key().to_hex(); + let caller_pubkey = client.public_key().to_hex(); // ── Local validation before any .await ──────────────────────────────── let to_remove: Vec = repos @@ -697,12 +698,12 @@ pub async fn cmd_delete(client: &BuzzClient, slug: &str) -> Result<(), CliError> .ok_or_else(|| CliError::NotFound(format!("project {slug:?} not found")))?; let next_ts = next_timestamp(&head, Timestamp::now())?; - let pubkey_hex = client.keys().public_key().to_hex(); + let pubkey_hex = client.public_key().to_hex(); let tombstone = build_delete_addressable(KIND_PROJECT, &pubkey_hex, slug) .map_err(|e| CliError::Other(format!("failed to build delete event: {e}")))? .custom_created_at(next_ts); - let event = client.sign_event(tombstone)?; + let event = client.sign_event(tombstone).await?; let raw = client.submit_event(event).await?; parse_write_response(&raw, "delete event was dominated; a newer head exists")?; @@ -742,7 +743,7 @@ async fn ensure_default_create_repo( &[], Some(channel), )?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let raw = client.submit_event(event).await?; let winner = fetch_own_repo_announcement(client, &repo_id).await?; verify_default_repo_write(&raw, winner.as_ref(), channel)?; @@ -956,7 +957,11 @@ mod tests { socket.write_all(response.as_bytes()).await.unwrap(); } }); - let client = crate::client::BuzzClient::new(base_url, keys, None, None).unwrap(); + let client = crate::client::BuzzClient::new( + base_url, + crate::credentials::Credentials::from_keys(keys), + ) + .unwrap(); let result = cmd_create( &client, "app", @@ -1029,8 +1034,11 @@ mod tests { .await .unwrap(); }); - let client = - crate::client::BuzzClient::new(base_url, nostr::Keys::generate(), None, None).unwrap(); + let client = crate::client::BuzzClient::new( + base_url, + crate::credentials::Credentials::from_keys(nostr::Keys::generate()), + ) + .unwrap(); let projects = fetch_projects_for_channel(&client, channel).await.unwrap(); assert!(projects.is_empty()); @@ -1077,8 +1085,11 @@ mod tests { ); socket.write_all(response.as_bytes()).await.unwrap(); }); - let client = - crate::client::BuzzClient::new(base_url, nostr::Keys::generate(), None, None).unwrap(); + let client = crate::client::BuzzClient::new( + base_url, + crate::credentials::Credentials::from_keys(nostr::Keys::generate()), + ) + .unwrap(); let projects = fetch_projects_for_channel_bounded(&client, channel, 1) .await @@ -1518,8 +1529,11 @@ mod tests { // Port 9 is the discard protocol — any real connect will be refused // immediately, but the guard fires before the first await so this // never reaches the network. - let client = crate::client::BuzzClient::new("http://127.0.0.1:9".into(), keys, None, None) - .expect("client construction"); + let client = crate::client::BuzzClient::new( + "http://127.0.0.1:9".into(), + crate::credentials::Credentials::from_keys(keys), + ) + .expect("client construction"); let err = cmd_update( &client, "my-slug", None, false, // name / clear_name @@ -1544,8 +1558,11 @@ mod tests { fn discard_client() -> crate::client::BuzzClient { let keys = nostr::Keys::generate(); - crate::client::BuzzClient::new("http://127.0.0.1:9".into(), keys, None, None) - .expect("client construction") + crate::client::BuzzClient::new( + "http://127.0.0.1:9".into(), + crate::credentials::Credentials::from_keys(keys), + ) + .expect("client construction") } /// Creating without --repo or --channel must fail locally; the default diff --git a/crates/buzz-cli/src/commands/reactions.rs b/crates/buzz-cli/src/commands/reactions.rs index 9e23d301312..f684a8beca8 100644 --- a/crates/buzz-cli/src/commands/reactions.rs +++ b/crates/buzz-cli/src/commands/reactions.rs @@ -24,7 +24,7 @@ pub async fn cmd_add_reaction( .map_err(|e| CliError::Other(format!("build_reaction failed: {e}")))? }; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -37,10 +37,8 @@ pub async fn cmd_remove_reaction( emoji: &str, ) -> Result<(), CliError> { validate_hex64(event_id)?; - let keys = client.keys(); - // Find our reaction event by querying kind:7 reactions on this event from us - let my_pk = keys.public_key().to_hex(); + let my_pk = client.public_key().to_hex(); let filter = serde_json::json!({ "kinds": [7], "#e": [event_id], @@ -70,7 +68,7 @@ pub async fn cmd_remove_reaction( let builder = buzz_sdk::build_remove_reaction(reaction_eid) .map_err(|e| CliError::Other(format!("build_remove_reaction failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); diff --git a/crates/buzz-cli/src/commands/read_state.rs b/crates/buzz-cli/src/commands/read_state.rs new file mode 100644 index 00000000000..c7aad6260eb --- /dev/null +++ b/crates/buzz-cli/src/commands/read_state.rs @@ -0,0 +1,540 @@ +//! Read-only view of the user's own NIP-RS read state (kind:30078, +//! `d=read-state:`, NIP-44 encrypted to self). +//! +//! Frontiers are decoded and max-merged the way desktop's +//! `readStateFormat.ts` / `readStateSnapshot.ts` do. Unlike desktop, which +//! drops a slot it cannot decode and carries on, a slot this CLI cannot read +//! is an error: an unread count built on a partial merge would overstate +//! unread, never understate it, and the user could not tell. + +use std::collections::HashMap; + +use buzz_core::kind::KIND_READ_STATE; +use nostr::Event; +use serde_json::{json, Value}; + +use crate::client::BuzzClient; +use crate::error::CliError; + +const D_TAG_PREFIX: &str = "read-state:"; +const T_TAG: &str = "read-state"; +const MAX_CONTEXTS: usize = 10_000; +const MAX_CONTEXT_KEY_BYTES: usize = 256; +const MAX_SLOT_ID_LEN: usize = 64; +const MAX_CLIENT_ID_UTF16_UNITS: usize = 64; +const SNAPSHOT_VERSION: u64 = 1; + +/// A slot that was valid but written by a newer schema, so left out of the merge. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct SkippedSlot { + pub d_tag: String, + pub version: i64, +} + +/// Max-merged frontiers of every readable slot. +#[derive(Debug, Default)] +pub(crate) struct ReadState { + frontiers: HashMap, + pub skipped: Vec, +} + +impl ReadState { + /// The merged read marker of a context, in unix seconds. + pub(crate) fn frontier(&self, context: &str) -> Option { + self.frontiers.get(context).copied() + } +} + +/// Load and merge every read-state slot of the signed-in identity. +/// +/// Uses the relay's atomic snapshot (NIP-RS, Buzz Atomic Snapshot Extension): +/// paginating by cursor cannot see a slot another client replaces mid-load, so +/// a relay without the extension is an error rather than a partial read. +pub(crate) async fn fetch(client: &BuzzClient) -> Result { + let community_id = discover_snapshot(client).await?; + let me = client.public_key().to_hex(); + let filter = json!({ + "kinds": [KIND_READ_STATE], + "authors": [me], + "read_state_snapshot": SNAPSHOT_VERSION, + }); + let raw = client.query(&filter).await?; + let events = snapshot_events(&raw, &community_id, &me)?; + merge(client.credentials(), events).await +} + +fn cannot_prove_complete(detail: impl std::fmt::Display) -> CliError { + CliError::Other(format!( + "cannot prove your read state is complete: {detail}; refusing to report unread counts" + )) +} + +/// The community id a relay advertises for its atomic read-state snapshot. +async fn discover_snapshot(client: &BuzzClient) -> Result { + let raw = client.get_public("/info").await?; + let info: Value = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("invalid NIP-11 response: {e}")))?; + let descriptor = info + .get("read_state_snapshot") + .filter(|d| d.is_object()) + .ok_or_else(|| { + cannot_prove_complete("this relay does not offer the atomic read_state_snapshot") + })?; + if descriptor.get("version").and_then(Value::as_u64) != Some(SNAPSHOT_VERSION) { + return Err(cannot_prove_complete( + "this relay offers an unsupported read_state_snapshot version", + )); + } + descriptor + .get("community_id") + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| cannot_prove_complete("the relay advertised no community_id")) +} + +/// Validate the snapshot envelope and return its events. Anything but a +/// complete, version-1 envelope for this identity and community is rejected, +/// including the plain event array an older relay returns when it ignores the +/// extension. +fn snapshot_events(raw: &str, community_id: &str, me: &str) -> Result, CliError> { + let mut envelope: Value = serde_json::from_str(raw) + .map_err(|e| CliError::Other(format!("failed to parse query response: {e}")))?; + let field = |name: &str| envelope.get(name); + if field("read_state_snapshot").and_then(Value::as_u64) != Some(SNAPSHOT_VERSION) + || field("complete") != Some(&Value::Bool(true)) + { + return Err(cannot_prove_complete( + "the relay did not return a complete read_state_snapshot", + )); + } + if field("community_id").and_then(Value::as_str) != Some(community_id) + || field("pubkey").and_then(Value::as_str) != Some(me) + { + return Err(cannot_prove_complete( + "the snapshot belongs to a different community or identity", + )); + } + match envelope.get_mut("events").map(Value::take) { + Some(Value::Array(events)) => Ok(events), + _ => Err(cannot_prove_complete("the snapshot has no events array")), + } +} + +fn unreadable(event: &Event, detail: impl std::fmt::Display) -> CliError { + CliError::Other(format!( + "your read-state slot {} is unreadable ({detail}); refusing to report unread counts from a partial read state", + event.id.to_hex() + )) +} + +fn single_d_tag(event: &Event) -> Option<&str> { + let mut d = event + .tags + .iter() + .filter(|t| t.as_slice().first().map(String::as_str) == Some("d")); + let tag = d.next()?; + if d.next().is_some() { + return None; + } + tag.as_slice().get(1).map(String::as_str) +} + +fn is_slot_coordinate(event: &Event) -> Option<&str> { + let d = single_d_tag(event)?; + let slot = d.strip_prefix(D_TAG_PREFIX)?; + if slot.is_empty() || slot.len() > MAX_SLOT_ID_LEN || !slot.is_ascii() { + return None; + } + let t_count = event + .tags + .iter() + .filter(|t| matches!(t.as_slice(), [k, v, ..] if k == "t" && v == T_TAG)) + .count(); + (t_count == 1).then_some(d) +} + +/// JS `Number.isInteger` within the uint32 range. +fn uint32(value: &Value) -> Option { + let n = value.as_u64().or_else(|| { + let f = value.as_f64()?; + (f >= 0.0 && f.fract() == 0.0 && f <= u32::MAX as f64).then_some(f as u64) + })?; + (n <= u64::from(u32::MAX)).then_some(n) +} + +/// Decode one blob. `Ok(Err(version))` is a valid blob of an unknown schema. +fn decode(event: &Event, plaintext: &str) -> Result, i64>, CliError> { + let blob: Value = serde_json::from_str(plaintext).map_err(|e| unreadable(event, e))?; + let Some(blob) = blob.as_object() else { + return Err(unreadable(event, "not a JSON object")); + }; + let version = blob + .get("v") + .and_then(Value::as_f64) + .filter(|v| v.fract() == 0.0); + match version { + Some(1.0) => {} + Some(other) => return Ok(Err(other as i64)), + None => return Err(unreadable(event, "missing or non-integer schema version")), + } + let client_id_ok = blob + .get("client_id") + .and_then(Value::as_str) + .is_some_and(|id| (1..=MAX_CLIENT_ID_UTF16_UNITS).contains(&id.encode_utf16().count())); + if !client_id_ok { + return Err(unreadable(event, "invalid client_id")); + } + let Some(contexts) = blob.get("contexts").and_then(Value::as_object) else { + return Err(unreadable(event, "contexts is not an object")); + }; + if contexts.len() > MAX_CONTEXTS { + return Err(unreadable(event, "too many contexts")); + } + Ok(Ok(contexts + .iter() + .filter(|(key, _)| key.len() <= MAX_CONTEXT_KEY_BYTES) + .filter_map(|(key, value)| Some((key.clone(), uint32(value)?))) + .collect())) +} + +/// Verify, decrypt and max-merge raw relay events. Events that are not read-state +/// coordinates are ignored; a coordinate that cannot be read is an error. +pub(crate) async fn merge( + credentials: &crate::credentials::Credentials, + raw: Vec, +) -> Result { + let me = credentials.public_key(); + let mut heads: HashMap = HashMap::new(); + for value in raw { + let event: Event = serde_json::from_value(value) + .map_err(|e| CliError::Other(format!("relay returned a malformed event: {e}")))?; + if event.pubkey != me || event.kind.as_u16() as u32 != KIND_READ_STATE { + return Err(CliError::Other(format!( + "relay returned event {} that is not your read state", + event.id.to_hex() + ))); + } + event.verify().map_err(|_| { + CliError::Other(format!( + "relay returned event {} with an invalid signature", + event.id.to_hex() + )) + })?; + let Some(d) = is_slot_coordinate(&event) else { + continue; + }; + let d = d.to_string(); + let newer = heads + .get(&d) + .is_none_or(|head| (event.created_at, head.id) > (head.created_at, event.id)); + if newer { + heads.insert(d, event); + } + } + + let mut state = ReadState::default(); + let mut ordered: Vec<_> = heads.into_iter().collect(); + ordered.sort_by(|a, b| a.0.cmp(&b.0)); + for (d_tag, event) in ordered { + let plaintext = credentials + .nip44_decrypt(&me, &event.content) + .await? + .ok_or_else(|| unreadable(&event, "not valid NIP-44 ciphertext for your key"))?; + match decode(&event, &plaintext)? { + Ok(contexts) => { + for (key, ts) in contexts { + let slot = state.frontiers.entry(key).or_insert(0); + *slot = (*slot).max(ts); + } + } + Err(version) => state.skipped.push(SkippedSlot { d_tag, version }), + } + } + Ok(state) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use axum::{body::Bytes, extract::State, routing::get, routing::post, Json, Router}; + use nostr::nips::nip44; + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + use std::sync::{Arc, Mutex}; + use tokio::net::TcpListener; + + /// Merge with local `keys`; the local-key signer never suspends. + fn merge(keys: &Keys, raw: Vec) -> Result { + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(super::merge( + &crate::credentials::Credentials::from_keys(keys.clone()), + raw, + )) + } + + pub(crate) const COMMUNITY: &str = "5f0c1b9e-2d0b-4f4e-9a7c-0d6f3f3f3f3f"; + + pub(crate) fn snapshot_envelope(pubkey: &str, events: Vec) -> Value { + json!({ + "read_state_snapshot": 1, + "complete": true, + "community_id": COMMUNITY, + "pubkey": pubkey, + "snapshot_id": "0".repeat(64), + "events": events, + }) + } + + pub(crate) fn snapshot_descriptor() -> Value { + json!({"version": 1, "community_id": COMMUNITY, "max_events": 4096}) + } + + pub(crate) fn slot_event(keys: &Keys, slot: &str, plaintext: &str, at: u64) -> Value { + let content = nip44::encrypt( + keys.secret_key(), + &keys.public_key(), + plaintext, + nip44::Version::V2, + ) + .unwrap(); + let event = EventBuilder::new(Kind::Custom(KIND_READ_STATE as u16), content) + .tags([ + Tag::identifier(format!("{D_TAG_PREFIX}{slot}")), + Tag::hashtag(T_TAG), + ]) + .custom_created_at(Timestamp::from(at)) + .sign_with_keys(keys) + .unwrap(); + serde_json::to_value(event).unwrap() + } + + fn blob(contexts: Value) -> String { + json!({"v": 1, "client_id": "dev", "contexts": contexts}).to_string() + } + + #[test] + fn max_merges_every_slot_and_ignores_override_and_foreign_entries() { + let keys = Keys::generate(); + let state = merge( + &keys, + vec![ + slot_event(&keys, "a", &blob(json!({"c1": 10, "c2": 50, "ov_s:c1": 3, "esc:ov_c:x": 9})), 1), + slot_event(&keys, "b", &blob(json!({"c1": 20, "c2": 5, "c3": 1.0e3, "neg": -1, "k".repeat(257): 9, "big": 4294967296u64, "frac": 1.5, "str": "7"})), 2), + ], + ) + .unwrap(); + assert_eq!(state.frontier("c1"), Some(20)); + assert_eq!(state.frontier("c2"), Some(50)); + assert_eq!(state.frontier("c3"), Some(1000)); + assert_eq!(state.frontier(&"k".repeat(257)), None); + for dropped in ["neg", "big", "frac", "str", "missing"] { + assert_eq!(state.frontier(dropped), None, "{dropped}"); + } + assert!(state.skipped.is_empty()); + } + + #[test] + fn newest_version_of_a_coordinate_wins() { + let keys = Keys::generate(); + let old = slot_event(&keys, "a", &blob(json!({"c1": 99})), 1); + let new = slot_event(&keys, "a", &blob(json!({"c1": 5})), 2); + let state = merge(&keys, vec![new, old]).unwrap(); + assert_eq!(state.frontier("c1"), Some(5)); + } + + #[test] + fn an_unreadable_slot_is_an_error_not_an_empty_state() { + let keys = Keys::generate(); + let good = slot_event(&keys, "a", &blob(json!({"c1": 1})), 1); + for bad in [ + "not json", + "[]", + r#"{"client_id":"d","contexts":{}}"#, + r#"{"v":1,"client_id":"","contexts":{}}"#, + r#"{"v":1,"client_id":"d","contexts":[]}"#, + r#"{"v":"1","client_id":"d","contexts":{}}"#, + ] { + let err = + merge(&keys, vec![good.clone(), slot_event(&keys, "b", bad, 2)]).expect_err(bad); + assert!(err.to_string().contains("unreadable"), "{bad}: {err}"); + } + + let other = Keys::generate(); + let foreign = slot_event(&other, "b", &blob(json!({})), 2); + let err = merge(&keys, vec![foreign]).unwrap_err(); + assert!(err.to_string().contains("not your read state"), "{err}"); + + let mut tampered = slot_event(&keys, "b", &blob(json!({"c1": 1})), 2); + tampered["created_at"] = json!(3); + assert!(merge(&keys, vec![tampered]).is_err()); + + let mut undecryptable = slot_event(&keys, "b", &blob(json!({})), 2); + let wrong = slot_event(&other, "b", &blob(json!({})), 2); + undecryptable["content"] = wrong["content"].clone(); + assert!(merge(&keys, vec![undecryptable]).is_err()); + } + + #[test] + fn a_newer_schema_is_reported_not_merged() { + let keys = Keys::generate(); + let future = json!({"v": 2, "client_id": "d", "contexts": {"c1": 99}}).to_string(); + let state = merge(&keys, vec![slot_event(&keys, "a", &future, 1)]).unwrap(); + assert_eq!(state.frontier("c1"), None); + assert_eq!( + state.skipped, + vec![SkippedSlot { + d_tag: "read-state:a".into(), + version: 2 + }] + ); + } + + #[test] + fn non_coordinates_are_ignored() { + let keys = Keys::generate(); + let unrelated = EventBuilder::new(Kind::Custom(KIND_READ_STATE as u16), "x") + .tags([Tag::identifier("channel-sections"), Tag::hashtag(T_TAG)]) + .sign_with_keys(&keys) + .unwrap(); + let no_t_event = EventBuilder::new(Kind::Custom(KIND_READ_STATE as u16), "x") + .tags([Tag::identifier("read-state:a")]) + .sign_with_keys(&keys) + .unwrap(); + let state = merge( + &keys, + vec![ + serde_json::to_value(unrelated).unwrap(), + serde_json::to_value(no_t_event).unwrap(), + ], + ) + .unwrap(); + assert!(state.frontiers.is_empty()); + } + + type Bodies = Arc>>; + + #[derive(Clone)] + struct Canned { + info: Value, + query: String, + bodies: Bodies, + } + + async fn relay(keys: &Keys, info: Value, query: Value) -> (BuzzClient, Bodies) { + let canned = Canned { + info, + query: query.to_string(), + bodies: Bodies::default(), + }; + let bodies = canned.bodies.clone(); + let app = Router::new() + .route( + "/info", + get(|State(c): State| async move { Json(c.info) }), + ) + .route( + "/query", + post(|State(c): State, body: Bytes| async move { + c.bodies + .lock() + .unwrap() + .push(serde_json::from_slice(&body).unwrap()); + c.query + }), + ) + .with_state(canned); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + ( + BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(keys.clone()), + ) + .unwrap(), + bodies, + ) + } + + fn advertised() -> Value { + json!({"read_state_snapshot": snapshot_descriptor()}) + } + + #[tokio::test] + async fn fetch_loads_one_atomic_snapshot() { + let keys = Keys::generate(); + let slots = vec![ + slot_event(&keys, "a", &blob(json!({"c1": 10})), 1), + slot_event(&keys, "b", &blob(json!({"c1": 20})), 2), + ]; + let (client, bodies) = relay( + &keys, + advertised(), + snapshot_envelope(&keys.public_key().to_hex(), slots), + ) + .await; + + let state = fetch(&client).await.unwrap(); + + assert_eq!(state.frontier("c1"), Some(20)); + assert_eq!( + *bodies.lock().unwrap(), + vec![json!([{ + "kinds": [KIND_READ_STATE], + "authors": [keys.public_key().to_hex()], + "read_state_snapshot": 1, + }])], + "one exact snapshot request: no tag, limit or cursor that could page" + ); + } + + #[tokio::test] + async fn fetch_refuses_a_load_it_cannot_prove_complete() { + let keys = Keys::generate(); + let slot = slot_event(&keys, "a", &blob(json!({"c1": 10})), 1); + let good = snapshot_envelope(&keys.public_key().to_hex(), vec![slot.clone()]); + let with = |field: &str, value: Value| { + let mut envelope = good.clone(); + envelope[field] = value; + envelope + }; + let cases: Vec<(&str, Value, Value)> = vec![ + ("no descriptor", json!({}), good.clone()), + ( + "descriptor version", + json!({"read_state_snapshot": {"version": 2, "community_id": COMMUNITY}}), + good.clone(), + ), + ( + "descriptor community", + json!({"read_state_snapshot": {"version": 1}}), + good.clone(), + ), + ("relay ignored the extension", advertised(), json!([slot])), + ("incomplete", advertised(), with("complete", json!(false))), + ("unmarked", advertised(), with("complete", Value::Null)), + ( + "version", + advertised(), + with("read_state_snapshot", json!(2)), + ), + ( + "community", + advertised(), + with("community_id", json!("other")), + ), + ( + "identity", + advertised(), + with("pubkey", json!("f".repeat(64))), + ), + ("events", advertised(), with("events", Value::Null)), + ]; + for (name, info, response) in cases { + let (client, _) = relay(&keys, info, response).await; + let err = fetch(&client).await.expect_err(name); + assert!(err.to_string().contains("cannot prove"), "{name}: {err}"); + } + } +} diff --git a/crates/buzz-cli/src/commands/repo_default_branch.rs b/crates/buzz-cli/src/commands/repo_default_branch.rs index 23aba9f5426..24659df4ed0 100644 --- a/crates/buzz-cli/src/commands/repo_default_branch.rs +++ b/crates/buzz-cli/src/commands/repo_default_branch.rs @@ -52,7 +52,7 @@ pub(super) async fn dispatch( } => (id, owner, Some((branch, expected_manifest))), }; crate::validate::validate_repo_id(&id)?; - let owner = owner.unwrap_or_else(|| client.keys().public_key().to_hex()); + let owner = owner.unwrap_or_else(|| client.public_key().to_hex()); crate::validate::validate_hex64(&owner)?; let path = format!("/git/{owner}/{id}/default-branch"); let result = match update { @@ -168,7 +168,8 @@ mod tests { }); let app = Router::new().route(&path, route); let server = tokio::spawn(async { axum::serve(listener, app).await.unwrap() }); - let client = BuzzClient::new(url, keys, None, None).unwrap(); + let client = + BuzzClient::new(url, crate::credentials::Credentials::from_keys(keys)).unwrap(); let result = dispatch( ReposDefaultBranchCmd::Get { id: "demo".into(), @@ -276,7 +277,8 @@ mod tests { }), ); let server = tokio::spawn(async { axum::serve(listener, app).await.unwrap() }); - let client = BuzzClient::new(url, keys, None, None).unwrap(); + let client = + BuzzClient::new(url, crate::credentials::Credentials::from_keys(keys)).unwrap(); let result = crate::commands::repos::dispatch( crate::ReposCmd::DefaultBranch(ReposDefaultBranchCmd::Set { id: "demo".into(), diff --git a/crates/buzz-cli/src/commands/repos.rs b/crates/buzz-cli/src/commands/repos.rs index 3e6b0ac15cf..e408f7be852 100644 --- a/crates/buzz-cli/src/commands/repos.rs +++ b/crates/buzz-cli/src/commands/repos.rs @@ -20,7 +20,7 @@ pub(crate) async fn fetch_own_repo_announcement( ) -> Result, CliError> { let filter = serde_json::json!({ "kinds": [KIND_GIT_REPO_ANNOUNCEMENT], - "authors": [client.keys().public_key().to_hex()], + "authors": [client.public_key().to_hex()], "#d": [repo_id], "limit": 1, }); @@ -194,7 +194,7 @@ fn validate_write_response(raw: &str) -> Result { } async fn submit_repo_update(client: &BuzzClient, builder: EventBuilder) -> Result<(), CliError> { - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let raw = client.submit_event(event).await?; println!("{}", validate_write_response(&raw)?); Ok(()) @@ -260,7 +260,7 @@ pub async fn cmd_create_repo( relays, channel, )?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let owner = event.pubkey.to_hex(); let resp = client.submit_event(event).await?; // `link` renders as a rich preview card in Buzz Desktop when included in @@ -313,7 +313,7 @@ pub async fn cmd_list_repos( crate::validate::validate_hex64(pk)?; pk.to_string() } - None => client.keys().public_key().to_hex(), + None => client.public_key().to_hex(), }; let mut filter = serde_json::json!({ diff --git a/crates/buzz-cli/src/commands/sent_from_thread.rs b/crates/buzz-cli/src/commands/sent_from_thread.rs new file mode 100644 index 00000000000..e30928be883 --- /dev/null +++ b/crates/buzz-cli/src/commands/sent_from_thread.rs @@ -0,0 +1,255 @@ +//! `buzz:sent-from-thread` provenance tag, mirroring desktop's +//! `features/messages/lib/sentFromThread.ts` and the validation in +//! `desktop/src-tauri/src/events/message_tags.rs`. + +use nostr::{Tag, TagKind}; + +const TAG_NAME: &str = "buzz:sent-from-thread"; +const EXCERPT_MAX_CHARS: usize = 64; +const MIN_WORD_BREAK_UTF16: usize = 32; + +/// JavaScript `\s` / `String.prototype.trim` whitespace. +fn is_js_space(c: char) -> bool { + c.is_whitespace() || c == '\u{feff}' +} + +fn starts_with_at(chars: &[char], at: usize, pat: &str) -> bool { + pat.chars() + .enumerate() + .all(|(i, p)| chars.get(at + i) == Some(&p)) +} + +fn find_from(chars: &[char], from: usize, pat: &str) -> Option { + (from..chars.len()).find(|&i| starts_with_at(chars, i, pat)) +} + +/// Match `||…||` (no `||` inside) at `at`; returns the end index. +fn spoiler_end(chars: &[char], at: usize) -> Option { + if !starts_with_at(chars, at, "||") { + return None; + } + find_from(chars, at + 2, "||").map(|close| close + 2) +} + +/// Match `[label](target)` at `at`; returns `(end, label_end)` where the label +/// is `at + 1..label_end`. `min_label` is the minimum label length. +fn link_end(chars: &[char], at: usize, min_label: usize) -> Option<(usize, usize)> { + if chars.get(at) != Some(&'[') { + return None; + } + let close = (at + 1..chars.len()).find(|&i| chars[i] == ']')?; + if close - (at + 1) < min_label || chars.get(close + 1) != Some(&'(') { + return None; + } + let paren = (close + 2..chars.len()).find(|&i| chars[i] == ')')?; + Some((paren + 1, close)) +} + +/// Match `?` at `at`; returns the end index. +fn url_end(chars: &[char], at: usize) -> Option { + let start = if chars.get(at) == Some(&'<') { + at + 1 + } else { + at + }; + let after_scheme = if starts_with_at(chars, start, "https://") { + start + 8 + } else if starts_with_at(chars, start, "http://") { + start + 7 + } else { + return None; + }; + let end = (after_scheme..chars.len()) + .find(|&i| is_js_space(chars[i])) + .unwrap_or(chars.len()); + (end > after_scheme).then_some(end) +} + +/// Left-to-right `String.prototype.replace` with a global pattern: `matcher` +/// returns the match end and replacement for a match starting at the index. +fn replace_all( + chars: &[char], + matcher: impl Fn(&[char], usize) -> Option<(usize, Vec)>, +) -> Vec { + let mut out = Vec::with_capacity(chars.len()); + let mut i = 0; + while i < chars.len() { + match matcher(chars, i) { + Some((end, replacement)) => { + out.extend(replacement); + i = end; + } + None => { + out.push(chars[i]); + i += 1; + } + } + } + out +} + +fn strip_markdown(content: &str) -> String { + let controls_removed: Vec = content + .chars() + .map(|c| { + let cp = c as u32; + if cp <= 0x1f || (0x7f..=0x9f).contains(&cp) { + ' ' + } else { + c + } + }) + .collect(); + let spoilers = replace_all(&controls_removed, |chars, at| { + spoiler_end(chars, at).map(|end| (end, vec![' '])) + }); + let images = replace_all(&spoilers, |chars, at| { + if chars[at] != '!' { + return None; + } + link_end(chars, at + 1, 0).map(|(end, _)| (end, vec![' '])) + }); + let links = replace_all(&images, |chars, at| { + link_end(chars, at, 1).map(|(end, label_end)| (end, chars[at + 1..label_end].to_vec())) + }); + let urls = replace_all(&links, |chars, at| { + url_end(chars, at).map(|end| (end, vec![' '])) + }); + urls.into_iter() + .map(|c| if "`*_~>#|".contains(c) { ' ' } else { c }) + .collect() +} + +fn collapse_whitespace(text: &str) -> String { + text.split(is_js_space) + .filter(|part| !part.is_empty()) + .collect::>() + .join(" ") +} + +/// Summarize a thread root for the tag excerpt exactly as desktop's +/// `summarizeThreadRoot` does. Returns `None` when nothing readable remains. +pub(crate) fn summarize_thread_root(content: &str) -> Option { + let normalized = collapse_whitespace(&strip_markdown(content)); + if normalized.is_empty() { + return None; + } + let chars: Vec = normalized.chars().collect(); + if chars.len() <= EXCERPT_MAX_CHARS { + return Some(normalized); + } + let clipped: String = chars[..EXCERPT_MAX_CHARS - 1].iter().collect(); + let units: Vec = clipped.encode_utf16().collect(); + let excerpt = match units.iter().rposition(|&u| u == u16::from(b' ')) { + Some(space) if space > MIN_WORD_BREAK_UTF16 => String::from_utf16_lossy(&units[..space]), + _ => clipped, + }; + Some(format!("{}…", excerpt.trim_end_matches(is_js_space))) +} + +/// Build the `["buzz:sent-from-thread", , ]` tag. +pub(crate) fn build_tag(root_event_id: &str, excerpt: Option<&str>) -> Tag { + let mut parts = vec![root_event_id.to_string()]; + parts.extend(excerpt.map(str::to_string)); + Tag::custom(TagKind::custom(TAG_NAME), parts) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(content: &str) -> Option { + summarize_thread_root(content) + } + + #[test] + fn strips_markdown_like_desktop() { + assert_eq!(s(" hello\n\tworld ").as_deref(), Some("hello world")); + assert_eq!( + s("**bold** _it_ `code` ~~x~~ > q # h").as_deref(), + Some("bold it code x q h") + ); + assert_eq!( + s("see [the doc](https://x.io/a) now").as_deref(), + Some("see the doc now") + ); + assert_eq!(s("a ![alt](https://x.io/i.png) b").as_deref(), Some("a b")); + assert_eq!(s("a ||secret | x|| b").as_deref(), Some("a b")); + assert_eq!(s("a ||unclosed b").as_deref(), Some("a unclosed b")); + assert_eq!( + s("go and http://y.io z").as_deref(), + Some("go and z") + ); + assert_eq!(s("[](x) [a]b").as_deref(), Some("[](x) [a]b")); + assert_eq!(s("a\u{0}b\u{7f}c\u{85}d").as_deref(), Some("a b c d")); + assert_eq!(s("a\u{feff}b\u{a0}c").as_deref(), Some("a b c")); + assert_eq!(s("*** ||x|| ![i](u)"), None); + assert_eq!(s(""), None); + } + + #[test] + fn clips_at_the_desktop_boundaries() { + let exact = "a".repeat(64); + assert_eq!(s(&exact).as_deref(), Some(exact.as_str())); + + let unbroken = "a".repeat(65); + assert_eq!(s(&unbroken), Some(format!("{}…", "a".repeat(63)))); + + let words = format!("{} {}", "a".repeat(40), "b".repeat(40)); + assert_eq!(s(&words), Some(format!("{}…", "a".repeat(40)))); + + let early_space = format!("{} {}", "a".repeat(32), "b".repeat(40)); + assert_eq!( + s(&early_space), + Some(format!("{} {}…", "a".repeat(32), "b".repeat(30))) + ); + + let late_space = format!("{} {}", "a".repeat(33), "b".repeat(40)); + assert_eq!(s(&late_space), Some(format!("{}…", "a".repeat(33)))); + } + + #[test] + fn clips_by_code_point_and_breaks_by_utf16_unit() { + let wide = "é".repeat(65); + assert_eq!(s(&wide), Some(format!("{}…", "é".repeat(63)))); + let emoji = "😀".repeat(65); + assert_eq!(s(&emoji), Some(format!("{}…", "😀".repeat(63)))); + let kept = "😀".repeat(64); + assert_eq!(s(&kept).as_deref(), Some(kept.as_str())); + + // 16 emoji take 32 UTF-16 units, so the space sits at unit 32: kept whole. + let at_32 = format!("{} {}", "😀".repeat(16), "b".repeat(60)); + assert_eq!( + s(&at_32), + Some(format!("{} {}…", "😀".repeat(16), "b".repeat(46))) + ); + // 17 emoji put the space at unit 34 (> 32), though only 17 code points in: break there. + let at_34 = format!("{} {}", "😀".repeat(17), "b".repeat(60)); + assert_eq!(s(&at_34), Some(format!("{}…", "😀".repeat(17)))); + } + + #[test] + fn matches_desktop_summarize_thread_root_on_generated_vectors() { + let vectors: Vec = + serde_json::from_str(include_str!("sent_from_thread_vectors.json")).unwrap(); + assert!(vectors.len() > 600); + for vector in vectors { + let input = vector["input"].as_str().unwrap(); + assert_eq!( + s(input).as_deref(), + vector["expected"].as_str(), + "input: {input:?}" + ); + } + } + + #[test] + fn tag_has_desktop_shape() { + let id = "a".repeat(64); + assert_eq!(build_tag(&id, None).as_slice(), [TAG_NAME, id.as_str()]); + assert_eq!( + build_tag(&id, Some("hi")).as_slice(), + [TAG_NAME, id.as_str(), "hi"] + ); + } +} diff --git a/crates/buzz-cli/src/commands/sent_from_thread_vectors.json b/crates/buzz-cli/src/commands/sent_from_thread_vectors.json new file mode 100644 index 00000000000..b72c329fef6 --- /dev/null +++ b/crates/buzz-cli/src/commands/sent_from_thread_vectors.json @@ -0,0 +1,2558 @@ +[ + { + "input": "", + "expected": null + }, + { + "input": " ", + "expected": null + }, + { + "input": "hello", + "expected": "hello" + }, + { + "input": " hello\n\tworld ", + "expected": "hello world" + }, + { + "input": "**bold** _it_ `code` ~~x~~ > q # h", + "expected": "bold it code x q h" + }, + { + "input": "see [the doc](https://x.io/a) now", + "expected": "see the doc now" + }, + { + "input": "a ![alt](https://x.io/i.png) b", + "expected": "a b" + }, + { + "input": "a ||secret | x|| b", + "expected": "a b" + }, + { + "input": "a ||unclosed b", + "expected": "a unclosed b" + }, + { + "input": "||a|||b||", + "expected": "b" + }, + { + "input": "||||", + "expected": null + }, + { + "input": "|||", + "expected": null + }, + { + "input": "go and http://y.io z", + "expected": "go and z" + }, + { + "input": "http:// x", + "expected": "http:// x" + }, + { + "input": "https://", + "expected": "https://" + }, + { + "input": "[](x) [a]b", + "expected": "[](x) [a]b" + }, + { + "input": "[a[b](c)", + "expected": "a[b" + }, + { + "input": "![a](b", + "expected": "![a](b" + }, + { + "input": "![](x)", + "expected": null + }, + { + "input": "[a](b(c)d)", + "expected": "ad)" + }, + { + "input": "a\u0000bc…d", + "expected": "a b c d" + }, + { + "input": "ab c d", + "expected": "a b c d" + }, + { + "input": "*** ||x|| ![i](u)", + "expected": null + }, + { + "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "expected": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + { + "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "expected": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa…" + }, + { + "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expected": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa…" + }, + { + "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expected": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb…" + }, + { + "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expected": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa…" + }, + { + "input": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expected": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa…" + }, + { + "input": "ééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé", + "expected": "ééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé…" + }, + { + "input": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀", + "expected": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀" + }, + { + "input": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀", + "expected": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀…" + }, + { + "input": "漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢", + "expected": "漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢漢…" + }, + { + "input": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expected": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb…" + }, + { + "input": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expected": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀…" + }, + { + "input": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expected": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb…" + }, + { + "input": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀a bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expected": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀a bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb…" + }, + { + "input": "x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x ", + "expected": "x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x…" + }, + { + "input": "ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab  z", + "expected": "ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab ab…" + }, + { + "input": "](漢!__\n`#~)>\né||**>  http://x.io`)![[\u0000]]#", + "expected": "](漢! ) é ]]" + }, + { + "input": " ]([https://y.io/p!http://x.io~**", + "expected": "]([" + }, + { + "input": "#](😀 ` éword_[_||[]]…]a||", + "expected": "](😀 éword [" + }, + { + "input": "_a![![]**", + "expected": "a![![]" + }, + { + "input": "http://x.io😀 漢_a😀!http://x.io\né_ é_word…word||", + "expected": "漢 a😀 漢a" + }, + { + "input": "#]( ||#]]a](`#>!é ](a||https://y.io/p|_", + "expected": "](" + }, + { + "input": "http://x.io|\u0000_ é**_<](_)[||]( 😀!`https://y.io/p##](http://x.iohttp://x.io )a漢[", + "expected": "é <]( ) a漢[" + }, + { + "input": " >`", + "expected": null + }, + { + "input": ")**http://x.io\u0000](word)!**||é!||`](#![https://y.io/p`https://y.io/p__![ >a http://x.io<)_", + "expected": ") ](word )! ]( ![ a" + }, + { + "input": "é)<<é](\u0000\u0000漢]![b][…!a][\n![…`!>http://x.io_", + "expected": "é)<<é]( 漢] ![b][ !a][ ![ !" + }, + { + "input": "](>é漢😀word\u0000~a|![#`…https://y.io/p** **\u0000>![]( >_`\n##~** word||)http://x.iohttp://x.iob](漢", + "expected": "]( é漢😀word a" + }, + { + "input": "\nb||>http://x.io|é #<|漢]( é😀>]b!>>||\n_\u0000]http://x.io!_http://x.io_https://y.io/phttps://y.io/p``![||b  ", + "expected": "b ]" + }, + { + "input": "](a !#é!>`#!|_ >)_http://x.io\u0000>[**`ba ] ||| wordéé|word![||word\n ![  http://x.io\u0000b`_]a \n_#|**http://x.io**>a![](", + "expected": "[ ba ] word ![ b ]a" + }, + { + "input": "]]wordbwordhttps://y.io/p…#\nb**\u0000>)…](word", + "expected": "]]wordb word b ) ](word" + }, + { + "input": "|http://x.io#<~éb… a[[ [http://x.ioé>😀a aé", + "expected": "]( wordé <<](>\u0000](漢\n漢http://x.io😀a](]( **\né# 漢  # |> é]漢** ![\u0000", + "expected": "] word <<]( ](漢 漢 é 漢 é] 漢 ![" + }, + { + "input": " ~a!~![ \n))`**![漢é]<]![||…`]( _#http://x.io", + "expected": "a ! ![ ) ) ![漢é]<]![ ](" + }, + { + "input": "a](http://x.io!#\n_http://x.iohttp://x.io!…\u0000a… |>|)![…|``**)`…漢[]", + "expected": "a]( a )![ ) 漢[]" + }, + { + "input": "~https://y.io/p !|~b![é漢]wordhttps://y.io/p<)**https://y.io/p\u0000b_  |…~>]()[)] ", + "expected": "! b![é漢]word b ]()[)]" + }, + { + "input": "\u0000||~😀>", + "expected": "😀" + }, + { + "input": "…[||wordword >![`[|![~é…**|http://x.io**a!`>]", + "expected": "[ wordword ![ [ ![ é" + }, + { + "input": " `https://y.io/p_~aahttp://x.iohttp://x.iob😀** >![  https://y.io/p[ [`a**http://x.io||https://y.io/p_😀\n||ééhttp://x.io](![![é", + "expected": "aa ![ [ a éé" + }, + { + "input": "é…😀😀 https://y.io/pb\u0000", + "expected": "é 😀😀" + }, + { + "input": "![ba", + "expected": "![b a" + }, + { + "input": "_bé>\n_ http://x.ioéaéhttps://y.io/p `", + "expected": "bé" + }, + { + "input": "b) \né`_", + "expected": "b) é" + }, + { + "input": "~https://y.io/pa😀 a http://x.io**`aabwordé]~ http://x.io_||word~\n]( >\u0000![", + "expected": "a ]( ![" + }, + { + "input": "a![http://x.io", + "expected": "a![" + }, + { + "input": "]| ]…[😀![ ", + "expected": "] ] [😀![" + }, + { + "input": "http://x.iob_||😀![![~**é[|\n| **\nb", + "expected": "😀![![ é[ b" + }, + { + "input": "](…>\u0000](\n >… |**|<~_aé#é]", + "expected": "]( ]( < aé é]" + }, + { + "input": "![]( b> ~|\u0000漢[a \n\n https://y.io/p])~![|é\nword![https://y.io/pword** ab|]||!>!…é", + "expected": "![ é word![ ab ] ! ! é" + }, + { + "input": "~>>bhttps://y.io/p![漢wordé![… é漢`…](<[漢é…#]\n[|b~**!…漢word#…word😀|é", + "expected": "b é漢 ](<[漢é ] [ b ! 漢word word😀 é" + }, + { + "input": "😀é](https://y.io/p#漢><é>||![ [", + "expected": ") é [ 😀é]( [" + }, + { + "input": "https://y.io/p**a\u0000](a |#\u0000< 😀\u0000é`]\n <漢_|| word|| [ b\u0000<[ahttps://y.io/pword[word é…", + "expected": "](a < 😀 é ] <漢 [ b <[a é" + }, + { + "input": "![_word😀 ![>_wordhttp://x.io**||**)漢…![!…]![~<😀https://y.io/p>)\n <`", + "expected": "![ word😀 ![ word ![! ]![ <😀 <" + }, + { + "input": "`b漢<#😀word]\n<|…", + "expected": "b漢< 😀word] <" + }, + { + "input": "[](http://x.io[…>]<\n<  \u0000word😀\u0000![\u0000#_](word![…**word", + "expected": "[]( ]< < word😀 ![ ](word![ word" + }, + { + "input": " ](\u0000https://y.io/p#)ahttps://y.io/p||……~😀wordbbword ]> _a漢", + "expected": "]( 😀wordbbword ] a漢" + }, + { + "input": "#漢a||]…_~![](b😀é![\u0000\n||http://x.io<_ éhttps://y.io/p|word\u0000#](漢ahttps://y.io/p||a漢!||]漢b\u0000", + "expected": "漢a é ](漢a ]漢b" + }, + { + "input": "`|#…\n]https://y.io/p`](>漢~", + "expected": "]" + }, + { + "input": "**#[>\nbbb> ", + "expected": "b> a|a|)b…bhttp://x.io\na…_", + "expected": "ab b a a )b b a" + }, + { + "input": "]<]éa\nhttp://x.io) **[http://x.io\nhttp://x.io漢  b !||#![>", + "expected": "]<]éa [ b ! ![" + }, + { + "input": "a~\u0000😀 ]", + "expected": "a 😀 ]" + }, + { + "input": " … `word![![!", + "expected": "word![![!" + }, + { + "input": "~!~`](](… 😀 <_ )http://x.ioa`||>b`| [http://x.ioé#`~[http://x.io", + "expected": "[] ! ) [ [" + }, + { + "input": "a _~漢_|https://y.io/p<)\u0000>>>![>~#<||**\u0000\n!é~a|#[ word", + "expected": "a 漢 ![ < !é a [ word" + }, + { + "input": "…`)~http://x.io||a](word<||||`#", + "expected": ")" + }, + { + "input": "> https://y.io/p!](>`)aa", + "expected": "! 😀]😀<漢 😀 é]![ [ )aa" + }, + { + "input": "![![_]( ~漢http://x.io||", + "expected": "![![ ]( 漢" + }, + { + "input": "\u0000![漢😀](>[!a~)|word漢[||**", + "expected": "word漢[" + }, + { + "input": "~![😀…)…)[", + "expected": "![😀 ) )[" + }, + { + "input": "**#< [ **<]( a\u0000](!](# ~<[](~ ||b ", + "expected": "< [ < ]( a ](! ]( <[]( b" + }, + { + "input": "~]) [ _ ](||~)b~bé||😀[\u0000<éa<…word\n ![!_b", + "expected": "]) [ ]( 😀[ <éa< word ![! b" + }, + { + "input": "_|~a#!]", + "expected": "a !]" + }, + { + "input": "`…| ![![<\n!漢<](<#||__ || #!~…)<](a…>b_\n", + "expected": "<](a b" + }, + { + "input": "…\u0000http://x.io # |b )<…> `😀 ](`b<  漢a`…😀_[b…http://x.io) ||_😀😀 b!~", + "expected": "漢 😀😀 b!" + }, + { + "input": "[b", + "expected": "[b" + }, + { + "input": "`漢 https://y.io/p)word http://x.io|||![` <😀😀](\nwordhttps://y.io/p**", + "expected": "漢 ![ <😀😀]( word" + }, + { + "input": "wordhttp://x.ioaéé]a![http://x.io![](>\u0000…\n](", + "expected": "word ](" + }, + { + "input": "**[…é`!>漢||\u0000 aword😀 é< ![] ![", + "expected": "]( < ![] ![" + }, + { + "input": "\u0000#ahttps://y.io/p](word>)https://y.io/p!~>#https://y.io/pba](http://x.io😀a`[http://x.io**_https://y.io/p[https://y.io/p ~http://x.iohttps://y.io/p]https://y.io/p]( `", + "expected": "a word ) ](" + }, + { + "input": "|]|| ", + "expected": "]" + }, + { + "input": " #!![!**é\n#…a ]`漢|]_😀http://x.io>)`é`", + "expected": "<)漢 a ] 漢 ] 😀" + }, + { + "input": "#\n😀😀|[漢 é", + "expected": "😀😀 [漢 é" + }, + { + "input": "漢", + "expected": "漢" + }, + { + "input": "]~)![word😀\nhttps://y.io/p**||word\u0000 \n ||漢 😀#https://y.io/p ||||word><~b 漢[http://x.io", + "expected": "] )![word😀 漢 😀 word < b 漢[" + }, + { + "input": ">! http://x.io)~word <#word )](…word", + "expected": "! < word )]( word" + }, + { + "input": "é>a!>~  `~ 😀!|`<😀![|| |[>\nword[~bhttps://y.io/p||[https://y.io/p!https://y.io/pab)漢\n", + "expected": "é a! 😀! <😀![ [" + }, + { + "input": "…[_a<]|>\u0000é漢word", + "expected": "[ a<] é漢word" + }, + { + "input": "[  😀~!~~`~](_b😀…**http://x.io||…_>!>ba**😀https://y.io/p", + "expected": "[ 😀 ! ]( b😀 ! ba 😀" + }, + { + "input": "é| ****![~\u0000éaword](<…<[word… ]#\nab`!word_😀**](||#  \u0000) || 漢#  `", + "expected": "é ![ éaword](< <[word ] ab !word 😀 ]( 漢" + }, + { + "input": "_!word**<…\u0000…http://x.io漢](漢 `…#😀", + "expected": "!word < 😀" + }, + { + "input": "word|b~) a`>\u0000a>~", + "expected": "word b ) a a" + }, + { + "input": "<…](**… |**😀\n\u0000😀![漢[]\u0000](**", + "expected": "< ]( 😀 😀 [] ](" + }, + { + "input": "![https://y.io/p)a[b <#wordhttp://x.io|[>>>~#b! >", + "expected": "![ < word" + }, + { + "input": "a` ", + "expected": "a" + }, + { + "input": "word![_>bé …<#word", + "expected": "word![ bé < word" + }, + { + "input": "…_|<[ ) !wordb漢`#~ ])__漢…~[!` https://y.io/phttp://x.io||)漢b\u0000é😀https://y.io/pword>]>![", + "expected": "<[ ) !wordb漢 ]) 漢 [! é😀" + }, + { + "input": "…é)>!", + "expected": "é) !" + }, + { + "input": "](", + "expected": "](" + }, + { + "input": " b… word …!a", + "expected": "b word !a" + }, + { + "input": " ](||#||…`]( ]…https://y.io/p` !https://y.io/p>😀wordword😀http://x.io||#>`>~)😀", + "expected": "]( ]( ] !" + }, + { + "input": "**`[…\n )![ !http://x.io[ [https://y.io/p! https://y.io/p漢_word`😀# … `_!https://y.io/p>](https://y.io/p )漢", + "expected": "word[é ! 漢" + }, + { + "input": "a ]é_…![![# word~~ [漢< \u0000 ", + "expected": "a ]é ![![ word [漢<" + }, + { + "input": "\n😀![!😀[>>é b](]( word|||)**](||word_…\n漢word`漢  #\u0000|<😀😀< ", + "expected": "😀![!😀[ é b](]( word word 漢word 漢 <😀😀<" + }, + { + "input": "|a#http://x.io[https://y.io/p[ <|word# |漢https://y.io/p||\u0000b[)) 漢[ #|!", + "expected": "a < word 漢 ]😀 !" + }, + { + "input": "b\u0000#http://x.io[\n||> \u0000 https://y.io/pword`…!  é http://x.io](é||~…\u0000 漢||😀word ", + "expected": "b 漢 😀word" + }, + { + "input": "_)![`ahttp://x.io\u0000word>!b](…`b_ )~é\n[)]é\n~]([", + "expected": "é < a word é [)]é ]([" + }, + { + "input": "`http://x.iohttp://x.io\néa![![😀\n… \u0000)b~漢![ \u0000 ", + "expected": "éa![![ 😀 )b 漢![" + }, + { + "input": " \u0000\u0000!a**|éa漢…", + "expected": "!a é a漢" + }, + { + "input": "… b||😀 _ ]…>~……|) https://y.io/phttps://y.io/p||a! … 😀||**https://y.io/p", + "expected": "b a < _!😀|**|漢__\u0000éhttp://x.io漢_é|| ~])😀漢漢", + "expected": "b < !😀 漢 é ] )😀漢漢" + }, + { + "input": "http://x.io\n<\né>>é|aword!\n]http://x.io![worda]", + "expected": "< é é aword! ]" + }, + { + "input": "[…aé]…![\u0000a<||<漢", + "expected": "[ aé] ![ a< <漢" + }, + { + "input": "b~a", + "expected": "b a" + }, + { + "input": "`[é https://y.io/p](http://x.ioword~b`||]éahttps://y.io/p😀http://x.io ahttps://y.io/p[ !||é!\n[", + "expected": "[é é! [" + }, + { + "input": "]_#wordé", + "expected": "] wordé" + }, + { + "input": "|http://x.io|!||[…`\u0000)[https://y.io/phttp://x.io![ [http://x.io\n!https://y.io/p_https://y.io/p~word_\n|_https://y.io/p>漢)word]>", + "expected": ")[ [ !" + }, + { + "input": "word  ) ~https://y.io/pb** _b!<\u0000[\n _![[>https://y.io/phttps://y.io/p](\n", + "expected": "word ) b!< [ ![[" + }, + { + "input": "~éa#word![>https://y.io/p\u0000😀…😀ahttp://x.io]|", + "expected": "éa word![ 😀 😀a" + }, + { + "input": "<`é!~]!)#https://y.io/p<~](~…http://x.io>", + "expected": "< é! ]!)" + }, + { + "input": "~\u0000https://y.io/pa<](![****\nhttp://x.io||![_\u0000", + "expected": null + }, + { + "input": "漢éhttp://x.ioword _😀`[|_ a\u0000 >|| … |http://x.io||~\u0000**||~b word…b><…a|a b", + "expected": "漢é 😀 [ a b word b < a a b" + }, + { + "input": "😀[\u0000http://x.io![\u0000", + "expected": "😀[" + }, + { + "input": "![\n", + "expected": "![" + }, + { + "input": " ](<|\nb\u0000b ](ba>  !\n||`![]**||##[ ![!é\n_😀!\nhttps://y.io/p", + "expected": "](< b b ](ba ! [ ![!é 😀!" + }, + { + "input": ">\n…>https://y.io/pword)word é ![](https://y.io/p#\u0000**#|\u0000~||``** ![…", + "expected": "é ![]( ![" + }, + { + "input": "b 😀é !]( \nhttps://y.io/phttps://y.io/p\n# …[]( `)b漢", + "expected": "b 😀é !]( b漢" + }, + { + "input": "# ||![漢 )||> é …http://x.io[😀 http://x.io#\n …😀 ![**[", + "expected": "é 😀 ![ [" + }, + { + "input": "[b…漢a**\n", + "expected": "[b 漢a" + }, + { + "input": "http://x.ioé)http://x.iohttp://x.iob)#[b_…]", + "expected": ") ]" + }, + { + "input": " [https://y.io/p`\n…||[~[", + "expected": "[ [ [" + }, + { + "input": "> |||]<<||b漢](||~#…[word )é漢é漢\n…_**word!\n", + "expected": "b漢]( [word )é漢é漢 word !" + }, + { + "input": ")漢<](\u0000 …https://y.io/p)) ", + "expected": "] word)a <](" + }, + { + "input": "]](b]]wordé\u0000\u0000", + "expected": "]](b]]wordé" + }, + { + "input": "!_http://x.io…#http://x.io![a__ b](https://y.io/p_>http://x.io😀é ![\u0000漢", + "expected": "! b]( ![ 漢" + }, + { + "input": "wordhttps://y.io/p](word#![) ) ~漢…](\u0000 || ~||\n`_bhttp://x.io![~)_![😀", + "expected": "word ![😀" + }, + { + "input": ">_", + "expected": null + }, + { + "input": "\u0000 bwordhttp://x.io\u0000…![#漢`word<", + "expected": "bword ![ 漢 word<" + }, + { + "input": " http://x.io…<é ", + "expected": "<é" + }, + { + "input": "![\n>**![]\né!…|😀|~# ||漢", + "expected": "![ ![] é! 😀 漢" + }, + { + "input": "\n](>http://x.io… <", + "expected": "]( <" + }, + { + "input": "``é\né!…_é ", + "expected": "é é! é" + }, + { + "input": "!word!éé😀b )!#](word#!http://x.io😀![ < `a![ ||**`a![", + "expected": "!word!éé😀b )! ](word ! < a![ a![" + }, + { + "input": "![]!b!é##漢…https://y.io/p`!## é漢漢 ]( # \u0000[**https://y.io/p#漢a\u0000!#`http://x.io_](😀[**_https://y.io/p||…#", + "expected": "b ![]( bbb😀] 漢 ]( [ !" + }, + { + "input": "~\nword](", + "expected": "word](" + }, + { + "input": "#word](\u0000#!**||😀https://y.io/pbhttps://y.io/phttp://x.io!https://y.io/p<\n\u0000>😀a![![!![_[é", + "expected": "word]( ! 😀 😀a![![!![ [é" + }, + { + "input": "![[~éhttp://x.io`_😀`漢|http://x.io` **\n|a](漢]https://y.io/p<**  ]", + "expected": "![[ é a](漢] ]" + }, + { + "input": "]!b|\u0000漢http://x.io||https://y.io/p! …) \u0000  é**|~http://x.io#[😀](~…b", + "expected": "]!b 漢 ) é b" + }, + { + "input": "||漢]<  ~\n…] \u0000bword](#aé\nb]<\u0000bhttps://y.io/p", + "expected": "漢]< ] bword]( aé b]< b" + }, + { + "input": ")\u0000[…**\n**#word", + "expected": ") [ word" + }, + { + "input": "]()😀漢_||](_b]https://y.io/p< …\u0000bword \nhttps://y.io/p\u0000~]\né !…![__**😀b )[ [](||[漢", + "expected": "]()😀漢 [漢" + }, + { + "input": "|[~_ ![ 漢a…[word漢 https://y.io/p![ ]()|b ~é|\n~_#éé #😀 https://y.io/p[#>_[", + "expected": "[ b é éé 😀" + }, + { + "input": "**]**]a)|| bhttp://x.io__**~****… #[|| \n", + "expected": "] ]a)" + }, + { + "input": "]word]b><]", + "expected": "]word]b <]" + }, + { + "input": "word)\né😀http://x.io https://y.io/p ! [#é|é\u0000 ****http://x.io\u0000`https://y.io/p|| **b é**word`|![\n||\nhttp://x.io", + "expected": "word) é😀 ! [ é é" + }, + { + "input": "a||! a\n)_[a**#<", + "expected": "a ! a ) [a <" + }, + { + "input": "\u0000![漢!\u0000#!\n_** ](漢)!https://y.io/p~>](~ab]b…|| a漢…##", + "expected": "! a漢" + }, + { + "input": "http://x.io", + "expected": null + }, + { + "input": "ba !](_>]**a]_>漢漢éword|😀é", + "expected": "ba !]( ] ![ b é ) é a] 漢漢éword 😀é" + }, + { + "input": "](#漢|>![漢**)| **https://y.io/p_>|\u0000>\u0000ba|||![](`)`>…漢\u0000…", + "expected": "]( 漢 漢" + }, + { + "input": " ]é😀漢](a😀\n_||)a|word~]]!](\n_", + "expected": "]é😀漢](a😀 )a word ]]!](" + }, + { + "input": "word\n>![b`", + "expected": "word ![b" + }, + { + "input": "…](****<a![](**…https://y.io/phttp://x.io ](**b||a||] \u0000b](_", + "expected": "a ] b](" + }, + { + "input": "<_", + "expected": "<" + }, + { + "input": "…)`!word|| ![😀](|_)||] _**http://x.ioword **\n… ", + "expected": ") !word ]" + }, + { + "input": "\n>http://x.iohttps://y.io/p!)… ~ 😀`😀\n_)`a**", + "expected": "😀 😀 ) a" + }, + { + "input": "`b< ]…http://x.io~ ~😀", + "expected": "b< ] 😀" + }, + { + "input": "||é)** 😀`!…# 漢<\n[||漢\na|)~#`> #\n", + "expected": "漢 a )" + }, + { + "input": "漢\n https://y.io/p||<…b word\u0000`a_[b", + "expected": "b[[ a ! word漢 b" + }, + { + "input": "https://y.io/p", + "expected": null + }, + { + "input": "https://y.io/phttps://y.io/p![https://y.io/p)) ]", + "expected": "a![)a ]" + }, + { + "input": "a `http://x.iob<# https://y.io/pwordé]…~||", + "expected": "a" + }, + { + "input": "#é](![``http://x.io`]` #**aahttp://x.io] ", + "expected": "é](![ aa" + }, + { + "input": "![](…\n\u0000![ >漢b~>~**||\n\n<漢a word漢_)word#漢!😀wordhttp://x.iobé**http://x.io<word~\n)[<😀|![~", + "expected": "word[ << [<😀 ![" + }, + { + "input": "#|…||https://y.io/p_https://y.io/p!éb[)\u0000](é>#]~…", + "expected": "](é ]" + }, + { + "input": "](aword |a] 漢_]  #_|](漢 **漢éword", + "expected": "](aword a ] 漢 ] ](漢 漢éword" + }, + { + "input": "!http://x.io]漢", + "expected": "!" + }, + { + "input": "a b![é\u0000https://y.io/p|| b<_…**", + "expected": "a é b![é b<" + }, + { + "input": "\u0000 `> >é\u0000[_]<>||_)b``_](#_ https://y.io/pb![`\nb", + "expected": "é [ ]< )b ]( b" + }, + { + "input": "](word~word\u0000word](]漢\u0000\na \n\u0000漢 ]||` http://x.ioaa…https://y.io/p b>](![>b]…\u0000b#[word", + "expected": "](word word word](]漢 a 漢 ] b ](![ b] b [word" + }, + { + "input": "…``ba<\u0000<é)[_` `<\u0000]( 漢>😀! !b) <", + "expected": "a< <é) < <" + }, + { + "input": "漢|a||word… > )", + "expected": "漢 a word )" + }, + { + "input": "|| ``é_ #](a", + "expected": "é ](a" + }, + { + "input": " <…#_漢http://x.io!![#…a![ \n**)", + "expected": "< 漢 ![ a![ )" + }, + { + "input": "!é>![", + "expected": "!é ![" + }, + { + "input": "\nhttps://y.io/phttps://y.io/p](", + "expected": null + }, + { + "input": "a!…`[https://y.io/p ](https://y.io/p`…![||)…  [** \n\n#http://x.io]😀\u0000`bhttps://y.io/p[~😀", + "expected": ")< !< word ![ ) [ b" + }, + { + "input": "…\u0000é😀<漢…b~😀~#](漢]…[word\nhttps://y.io/p\u0000\u0000>", + "expected": "é😀<漢 b 😀 ](漢] [word" + }, + { + "input": "a`]漢[\u0000ba…😀](b!||漢[ …~b>…#|https://y.io/p ~bhttps://y.io/phttps://y.io/p 😀b😀_](~", + "expected": "a ]漢[ ba 😀]( b! 漢[ b b 😀b😀 ](" + }, + { + "input": "**😀 )]![é…", + "expected": "😀 )]![é" + }, + { + "input": ">漢[wordé…[`| ~http://x.io a[](] ~` ||a![[**b)_<…a**", + "expected": "漢wordé [ a[ < a" + }, + { + "input": "ééé#||!![ ` ](é`]**_https://y.io/p]||[!漢\né http://x.io", + "expected": "ééé [!漢 é" + }, + { + "input": "漢https://y.io/p**~> b😀…**… https://y.io/p`)https://y.io/p|", + "expected": "漢 b😀" + }, + { + "input": "https://y.io/p`<>漢 )|>**bhttp://x.io", + "expected": "< 漢 ) b" + }, + { + "input": "](bhttps://y.io/p!https://y.io/p b_\u0000](漢a!word|b", + "expected": "](b b ]( 漢a!word b" + }, + { + "input": "`[\u0000  ||a word ||~~](>\n<~`>]![http://x.io\u0000aé![é![]( http://x.io\u0000||~|]([>word]bhttps://y.io/p", + "expected": "[ ]( < ]![ aé![é![]( ]([ word]b" + }, + { + "input": "![||bhttp://x.io!_||_]||", + "expected": "![ ]" + }, + { + "input": "https://y.io/p](", + "expected": null + }, + { + "input": ">😀` é>漢` <_ http://x.io_", + "expected": "😀 é 漢 <" + }, + { + "input": "~)~#_\n\n漢!a) \u0000[|_~…]( https://y.io/p", + "expected": "b) [https://y.io/p**||>ahttps://y.io/pa…😀word |**||<", + "expected": "b) [ <" + }, + { + "input": "#a\u0000b\n|[<<__\u0000漢\u0000](||é`漢word~ \n 漢**é[|wordé 漢**https://y.io/p**", + "expected": "a b [<< 漢 ]( é 漢word 漢 é[ wordé 漢" + }, + { + "input": "~|…漢b \u0000", + "expected": "漢b" + }, + { + "input": "\u0000漢bé||…<~", + "expected": "漢bé <" + }, + { + "input": "[_é|](wordhttp://x.io\u0000 …|", + "expected": "[ é ](word" + }, + { + "input": ">_ https://y.io/p])#>|** 漢 >)`", + "expected": "漢 )" + }, + { + "input": "漢", + "expected": "漢" + }, + { + "input": "#!#b||_\u0000…漢**|\n\u0000b`awordword`>)||wordhttps://y.io/p< \n\na[)](漢\u0000![😀!b![😀", + "expected": "! b word a[)](漢 ![😀!b![😀" + }, + { + "input": "|| ! …[😀  _![ <", + "expected": "! [😀 ![ <" + }, + { + "input": "_]|  ba漢\n[ b||`", + "expected": "] ba漢 [ b" + }, + { + "input": " ![_!)!", + "expected": "![ !)!" + }, + { + "input": " \u0000|| |!b_|![![😀<…b<||", + "expected": " ](worda\u0000| ||| )~…](~~)]", + "expected": "!é ]" + }, + { + "input": "漢||)\n)_", + "expected": "漢 ) )" + }, + { + "input": "#**>漢b<\u0000)![`[http://x.iohttp://x.iohttps://y.io/p]()!", + "expected": "](" + }, + { + "input": "b _ \n||wordhttps://y.io/p)]~…é…||\n[_a…https://y.io/p||![b😀http://x.ioa](! !`|https://y.io/pword😀\n> ", + "expected": "b [ a !" + }, + { + "input": " \nb漢a |b) \nword…]>😀http://x.iob) )…b>)[", + "expected": "b漢a b) word ] 😀 ) b )[" + }, + { + "input": "` _<\u0000http://x.io\u0000||)éword #!漢`😀||~>#||](](!http://x.io\n)", + "expected": "< ](](! )" + }, + { + "input": "http://x.iohttp://x.iohttp://x.ioé<é~](é…[\u0000**b_漢`é`a||\n漢é`é! **[a](**https://y.io/p😀~http://x.io😀…", + "expected": "[ b 漢 é a 漢é é! [a ](" + }, + { + "input": "a](](😀`word![😀|](\na]\n)a<)word", + "expected": "a](](😀 word a<)word" + }, + { + "input": "~])#b漢 #b", + "expected": "]) b漢 b" + }, + { + "input": "é**\u0000_](#](<|||< ", + "expected": "é ]( ](< <" + }, + { + "input": "#é~https://y.io/phttps://y.io/p)http://x.io !\u0000word[  …\u0000 [é>http://x.io", + "expected": "😀] 😀! ] [ a <" + }, + { + "input": "\u0000|**>😀https://y.io/p |…**![\n\u0000_\u0000[漢😀`**]~`http://x.io)", + "expected": "😀 ![ [漢😀 ]" + }, + { + "input": "…**[](a~|~<é![!!\u0000#…#](http://x.io [**word~[**http://x.io\n", + "expected": "[](a <é![!! ]( [ word [" + }, + { + "input": ">http://x.io~https://y.io/p\u0000|]word**![)>**https://y.io/p))!", + "expected": "]word ![)" + }, + { + "input": " \u0000)||``![", + "expected": ") ![" + }, + { + "input": " word…![ _…漢b|~", + "expected": "word ![ 漢b" + }, + { + "input": ">!bbhttps://y.io/p> …wordhttp://x.ioé~😀a\u0000#<\u0000\u0000b… !https://y.io/p…||)[http://x.io||> 漢**)", + "expected": "漢 b ! 漢 )" + }, + { + "input": "\n![ …<] #`https://y.io/pword#]ahttps://y.io/p](", + "expected": "![ <]" + }, + { + "input": ">~ **||éb\u0000https://y.io/pé a~_ **https://y.io/p~_)a\u0000||)**https://y.io/p~", + "expected": ")" + }, + { + "input": "|\n…a||é 😀`[ _", + "expected": "a é 😀 [" + }, + { + "input": "…<**a ](漢   ]…", + "expected": "< a ](漢 ]" + }, + { + "input": "](||)~||_[\u0000", + "expected": "]( [" + }, + { + "input": "<||!é\u0000 … word😀](<> !#  ** \u0000_[b]` !", + "expected": "< !é word😀](< ! [b] !" + }, + { + "input": "http://x.io||\u0000_\u0000_>a\u0000a#`< 😀…_", + "expected": "a a < 😀" + }, + { + "input": "é](`", + "expected": "é](" + }, + { + "input": " <é![](b] >_)!漢 word`http://x.io|)#é< …)#é\u0000http://x.io!>https://y.io/p", + "expected": "<é https://y.io/p](https://y.io/p>](", + "expected": "< b ! 😀b ! 😀" + }, + { + "input": "#)… **[||`word![\n word ](]||_)# ](éaaé||…[word<)||||`😀", + "expected": ") [ ) ](éaaé 😀" + }, + { + "input": "\u0000[>#word\n|https://y.io/p<)|😀https://y.io/p[||<]漢#!>", + "expected": "[ word <]漢 !" + }, + { + "input": "<**)…||\u0000![]<~![b\u0000**ahttps://y.io/p||", + "expected": "< )" + }, + { + "input": "ba`word~~](_漢#|)||…![** http://x.io#\nbword#word |…_|\u0000!https://y.io/p~é", + "expected": "b a word ]( 漢 ) ![ bword word !" + }, + { + "input": "[](😀`<[||https://y.io/p)http://x.io😀#![| ] <\n**é>word漢 ", + "expected": "[](😀 <[ ] < é word漢" + }, + { + "input": ")||#😀`#word#||é", + "expected": ") é" + }, + { + "input": "~http://x.io|| !~[~ ` _漢|b", + "expected": "! [ 漢 b" + }, + { + "input": " \n!`![` _a |||| éa]😀`)<\u0000![` ", + "expected": "! ![ a éa]😀 )< ![" + }, + { + "input": " _😀http://x.io~é\nhttp://x.io[)!!漢b😀a ~word>](](  `word!😀](~😀\u0000** ](||word](", + "expected": "😀 word ](]( word!😀]( 😀 ]( word](" + }, + { + "input": " 😀](<", + "expected": "😀](<" + }, + { + "input": "😀\n |_)\u0000|~)\n\u0000_https://y.io/péa \u0000é… |漢 <||<", + "expected": ") [] é 漢 < <" + }, + { + "input": "b\u0000…! word#a ", + "expected": "b ! word a" + }, + { + "input": "é)]`| #\u0000 … |`\n", + "expected": "é)]" + }, + { + "input": "_word_", + "expected": "word" + }, + { + "input": "ahttp://x.io~)\u0000\u0000word漢https://y.io/pa#)**https://y.io/p>_!_http://x.io>~||](_\nahttp://x.io word![", + "expected": "a word漢 a word![" + }, + { + "input": "bhttps://y.io/p**https://y.io/p||\nb[_` ![https://y.io/pb", + "expected": "b b[ ![" + }, + { + "input": "😀\u0000[]https://y.io/p>\u0000<é…b", + "expected": "😀 [] <é b" + }, + { + "input": "word **`[\n)éhttp://x.io **](http://x.io| **`http://x.io\n [||]!b_ ]()![éword](#é`**||||https://y.io/p#)", + "expected": "word )é" + }, + { + "input": "](worda\n😀]> [) aa>|> 😀word\n!http://x.io![| ![| 漢[#…[||https://y.io/p", + "expected": "](worda 😀] [) aa 😀word ! ![ 漢[ [" + }, + { + "input": "word", + "expected": "word" + }, + { + "input": "http://x.io ])`_ _![](`||![~  ||", + "expected": "]) ![](" + }, + { + "input": "😀[** [ ****é|>>)bb漢[](**)![![`[\u0000word](![]é||http://x.io[ ", + "expected": "😀 [ é )bb漢[![![ [ word](![]é" + }, + { + "input": "](#…]|漢`](#é~漢 ~https://y.io/pb😀|]", + "expected": "]( ] 漢 ]( é 漢 ]" + }, + { + "input": "b#!! |>< https://y.io/phttps://y.io/p<](http://x.io  \u0000… 漢b…漢 ]éword 😀**……**>~", + "expected": "b !! < 漢b 漢 ]éword 😀" + }, + { + "input": "_]<]![[]**<||](漢b|]b<> 😀\n**_||a#)![\u0000![b漢", + "expected": "]<]![[] < a )![ ![b漢" + }, + { + "input": "b~…a<<_http://x.ioa<😀>#a😀https://y.io/p<>![", + "expected": "b a<<" + }, + { + "input": ") **https://y.io/pword<😀_\u0000` 😀 b 😀#)](……a!<) \u0000漢![word", + "expected": ") 😀 b 😀 )]( a!<) 漢![word" + }, + { + "input": "!>]||](>![ <#é ||😀a** 漢>< )http://x.io!", + "expected": "! ] ]![b!< 😀a 漢 < )" + }, + { + "input": " ||[**||https://y.io/pword]word…", + "expected": null + }, + { + "input": ")http://x.iohttps://y.io/p  …😀 https://y.io/p](https://y.io/p😀]](http://x.io>https://y.io/p\n](**😀**\u0000]( ||a_aawordhttp://x.io![😀)][\n>漢", + "expected": ") 😀 ]( 😀 ]( a aaword ][ 漢" + }, + { + "input": "]![`https://y.io/pword`)\n!\né||~éword| )http://x.io漢 #~…é\n_\n <**]\u0000\néé||<)b wordb", + "expected": "]![ ! é <)b wordb" + }, + { + "input": "_#éé)_…_ |||ahttp://x.io", + "expected": "éé) a" + }, + { + "input": " ", + "expected": null + }, + { + "input": "https://y.io/phttps://y.io/p**_\u0000#](é\n<>![ ]漢]https://y.io/pb#b[![", + "expected": "](é < ![ ]漢]" + }, + { + "input": "b>#**~_é![!é😀>\n<éa)~…![![![ é !||](#|>word", + "expected": "b é![! é😀 <éa) ![![![ é ! ]( word" + }, + { + "input": "]](] é**é\u0000_******#!**#]#**]](\n", + "expected": "]](] é é ! ] ]](" + }, + { + "input": "\u0000\n  _|http://x.io>_)]…))>])a~_é|**< 漢]#< >b~ <`\u0000#b**<", + "expected": ")) ])a é < 漢] < b < b <" + }, + { + "input": "||`))…**a…|https://y.io/p>[>[_", + "expected": ")) a" + }, + { + "input": " é [ ](https://y.io/pé|`<漢<…]https://y.io/p", + "expected": "é [ ]( <漢< ]" + }, + { + "input": "a漢]|<>😀 \nhttp://x.io~**||~|http://x.io**#<<", + "expected": "a漢] < 😀" + }, + { + "input": "![https://y.io/p[#|>b||>_|😀漢||…é\na…`https://y.io/p😀!😀 ](", + "expected": "word](é 漢 ]( []é 漢 😀!😀 ](" + }, + { + "input": "`! 漢<** ` !https://y.io/pa\u0000… `)bab é<~…**https://y.io/p](!<\n ", + "expected": "! 漢< ! )bab é<" + }, + { + "input": "#…😀é![]>漢_b]é\n\u0000**![é ~**https://y.io/p\u0000é||word__||||![_", + "expected": "😀é![] 漢 b]é ![é é ![" + }, + { + "input": "<", + "expected": "<" + }, + { + "input": ">**~|](![] http://x.io~|😀!a#~https://y.io/pa[b >](word~[😀>>|`]a~ \n_http://x.io>éhttp://x.io\n!", + "expected": "](![] ](word [😀 ]a !" + }, + { + "input": "!](!http://x.io<\n_~]#…||…`https://y.io/p`](<](**https://y.io/p|é\n~ #>![<)~![#![#!", + "expected": "!](! ] ![<) ![ ![ !" + }, + { + "input": "\n\n#>||||b)http://x.iobwordé<", + "expected": "b)" + }, + { + "input": ">||…a![|!http://x.io word) )……)https://y.io/p_ http://x.io****` \u0000![]|a|](漢#**#** [](**](", + "expected": "a![ ! word) ) ) ![] a ](漢 []( ](" + }, + { + "input": ">😀`!![>é漢b漢](http://x.io~||😀\u0000https://y.io/p\u0000b é[![\n #![!>[b](\n😀[b_\u0000_>`http://x.io\u0000**](😀\n`](|", + "expected": "漢 b é[![ ![! [b]( 😀[b ](😀 ](" + }, + { + "input": ">`**||****😀\u0000é](漢http://x.iob", + "expected": "! b![ a[😀 word 漢" + }, + { + "input": "~word![é\nhttp://x.io**https://y.io/p!http://x.io[](\n](!éaa!`é][**http://x.io](word~bé) ", + "expected": "word" + }, + { + "input": "b~a![~😀é😀||", + "expected": "![] ![a漢 b é b[ !word![ é😀" + }, + { + "input": "|a😀]http://x.io\u0000 !!漢 漢https://y.io/p\nhttp://x.io \n 漢", + "expected": "a😀] ! !漢 漢 漢" + }, + { + "input": "!é", + "expected": "!é" + }, + { + "input": "|a]|bhttps://y.io/p", + "expected": "a] b" + }, + { + "input": "~~|…é# é`#<[\n<#]b]https://y.io/p \n!ahttps://y.io/p😀~) bb", + "expected": "é é < [ < ] b] !a bb" + }, + { + "input": "![!**_<|]) ||[>)[ 漢#_b ", + "expected": "![! < ]) [ )[ 漢 b" + }, + { + "input": "https://y.io/p](éhttp://x.io\u0000||\u0000http://x.io~**😀", + "expected": "](" + }, + { + "input": "`b é |\na é!", + "expected": "b é a é!" + }, + { + "input": "漢`](https://y.io/p>]()\n! ||~ ", + "expected": "漢 ]( !" + }, + { + "input": "](~ >~#\nword", + "expected": "]( b ~a<||>a~|[~😀é||…aa` …", + "expected": ")漢 [ b a< aa" + }, + { + "input": "a)[", + "expected": "a )[" + }, + { + "input": "#https://y.io/p 😀 word#||!#<[[ _…`!!é`** http://x.iohttp://x.io<\u0000!_[漢a )`**`!", + "expected": "😀 word ! <[[ !!é ! [漢a ) !" + }, + { + "input": "!!http://x.io", + "expected": "!!" + }, + { + "input": "\u0000|||😀a\nhttp://x.io`… 😀_b!** é漢aé\u0000]a aa![", + "expected": "😀 a 😀 b! é漢aé ]a aa![" + }, + { + "input": "|| aword`! ](~#`b…||](****  #http://x.io](a`_]([ 😀word \u0000", + "expected": "]( 😀word" + }, + { + "input": "\nword  [http://x.io)])][http://x.iohttp://x.io](#]( <||aé\u0000||!>]||b \u0000\u0000😀é]", + "expected": "word [ < ! ] b 😀é]" + }, + { + "input": "http://x.io]([_]#漢https://y.io/p😀|\u0000#!b] ||||>)  !", + "expected": "漢 !b] ) !" + }, + { + "input": "http://x.io**wordhttps://y.io/pa![ ] a!**[** …](<_\néa😀b](>https://y.io/p…>…", + "expected": "] a! [ ](< éa😀b](" + }, + { + "input": " a _))**word||\n>\nbb`\n|| \u0000|| \u0000>]", + "expected": "b b ]" + }, + { + "input": " ![", + "expected": "![" + }, + { + "input": "`\n](|| 漢![#]](](~_漢![ 😀** [b\u0000b", + "expected": "]( 漢![ ]](]( 漢![ 😀 [b b" + }, + { + "input": "a<#a#http://x.io|| 😀a![]", + "expected": "a< a a漢! ! ] ] 😀a![]" + }, + { + "input": " 漢a`[|é ` ||http://x.io😀", + "expected": "漢a [ é" + }, + { + "input": "||)\n", + "expected": ")" + }, + { + "input": "<|", + "expected": "<" + }, + { + "input": "<[!_\u0000漢|]\u0000 \u0000!]() **漢[https://y.io/p)…#>)||", + "expected": "](![)!é!" + }, + { + "input": "![`…https://y.io/p`]( \n😀~||)!**`]**>~**wordhttp://x.io` [\nword)]!](|< **\n<\n<漢", + "expected": "! ] word [ word)]!]( < < < 漢" + }, + { + "input": "![https://y.io/p|||>](|\n\u0000", + "expected": "![" + }, + { + "input": " <~**https://y.io/p )|**`😀|**a😀# ![)~# ]([) <]]](http://x.io _\u0000#<\u0000**b", + "expected": "<] < b" + }, + { + "input": "aéhttps://y.io/p#~[||é#[`ahttps://y.io/p \n<>aword😀<>https://y.io/p](|a~!漢](…!b]\n…|| !", + "expected": "aé !" + }, + { + "input": "||", + "expected": null + }, + { + "input": "! \u0000||http://x.io<`b_ \u0000\n 漢http://x.io|| a!😀]https://y.io/p![||~>>aé||a~>", + "expected": "! a!😀] a" + }, + { + "input": "a||`http://x.io`\u0000", + "expected": "a" + }, + { + "input": "\u0000\n漢![![😀]\n😀\u0000](wordéé~||http://x.io!![", + "expected": "漢![![😀 ] 😀 ](wordéé" + }, + { + "input": "b**😀![!#]![)>! [\n\n>\n|a#… ](wordéhttp://x.io[**b](_`é\n\n", + "expected": "b 😀![! ] ![) ! [ a ](wordé" + }, + { + "input": " ||_][\n](漢_||…!>…é )é >word~https://y.io/p!a![ é漢\u0000b |#é!](", + "expected": "! é )é word é漢 b é!](" + }, + { + "input": "](~a_\u0000word`)\n😀<)😀`#", + "expected": "]( a word ) 😀<)😀" + }, + { + "input": "…**>![`https://y.io/p #!http://x.iohttps://y.io/p_ word`>_wordhttp://x.io😀**_#éa#a_", + "expected": "![ ! word word" + }, + { + "input": "b|[word_ […a](**é#)http://x.io#😀!|word![…\u0000b\n>https://y.io/pa漢**]( ![](]||wordhttps://y.io/p!|é", + "expected": "b word [ a b 漢 ]( ![](] word" + }, + { + "input": "![漢\nb\u0000|_]a[**http://x.io)b]||>~漢)漢😀 **…|\u0000`|| http://x.io](é\u0000http://x.io ~é", + "expected": "![漢 b ]a[ é" + }, + { + "input": "😀~https://y.io/p[ http://x.io!_><漢>a`[ #wordword  a\nword\n<a)", + "expected": "![![漢 wordword a word < a)" + }, + { + "input": "![) >)_ http://x.io😀|\naa`>##a", + "expected": "![) ) aa a" + }, + { + "input": "`~_]http://x.io]([||)漢wordééa _a http://x.io#!#|word**…a>#~", + "expected": "] wordééa a a" + }, + { + "input": "**\nhttps://y.io/p", + "expected": null + }, + { + "input": "…a`…b**", + "expected": "! ! )![😀!a b" + }, + { + "input": "_https://y.io/pa\u0000😀 …~  >[\u0000|| |>漢|é~é<#`漢 ||http://x.io >漢![漢\n)", + "expected": "😀 [ 漢![漢 )" + }, + { + "input": " >_]<**\u0000\u0000`😀b![)**https://y.io/p**漢b", + "expected": "]< 😀b![) 漢b" + }, + { + "input": "[é~](_)]([[\nhttps://y.io/p\u0000 `\n|!_\u0000|https://y.io/p #", + "expected": "é ]([[ !" + }, + { + "input": "word😀 a\u0000 https://y.io/pb\u0000漢漢#`](é [http://x.io\u0000_~!漢~]]word\u0000", + "expected": "word😀 a 漢漢 ](é [ !漢 ]]word" + }, + { + "input": "\u0000[http://x.io~**😀>![\n||)](https://y.io/p**https://y.io/p漢)word", + "expected": "[ word" + }, + { + "input": "漢 wordé||](] |😀 http://x.ioa[\nword[b]!😀||\u0000\u0000 a\u0000!\na\u0000\n]", + "expected": "漢 wordé a ! a ]" + }, + { + "input": "…😀#漢|é)a) word)https://y.io/p# < a_ \u0000|漢éhttps://y.io/phttps://y.io/pé_a|||]|| a](]word", + "expected": "😀 漢 é)a) word) < a 漢é a](]word" + }, + { + "input": "\u0000😀http://x.io!![a**~http://x.io|<**[bb)…a…#😀[](~\n![![<éa\u0000<[ [**# <>…é", + "expected": "😀 ![a a 😀[]( ![![< éa <[ [ < é" + }, + { + "input": "~漢\u0000![![||éhttp://x.io<](http://x.io!é ! **)é![", + "expected": "漢 é![" + }, + { + "input": "\n_>", + "expected": null + }, + { + "input": "_>]b…[\u0000<**]([<`", + "expected": "]b [ < ]([<" + }, + { + "input": " |\u0000", + "expected": "😀![ )b 漢漢 漢 ]( ![  http://x.io😀#漢\n_> 漢\u0000 **> )](a|**#><)|**<", + "expected": "é](wordé 漢 )](a <) <" + }, + { + "input": "`http://x.io😀   #b…**", + "expected": "b" + }, + { + "input": " https://y.io/phttp://x.io>]é😀\u0000<ééé~#~_#[] ! ||é\nwordword`#", + "expected": "![  ]", + "expected": "😀 漢]( !] é ![ ]" + }, + { + "input": "**||\u0000#>é[!](_漢\n)[**\n_#>\n…]||é)…  ![]a>http://x.iohttp://x.io|", + "expected": "é) ![]a" + }, + { + "input": "_b](… <<\n…😀`]😀~éhttp://x.iob漢#[\néword[**a…**![\u0000~", + "expected": "b]( << 😀 ]😀 é éword[ a ![" + }, + { + "input": "![ b|[_", + "expected": "![ b [" + }, + { + "input": "\n https://y.io/p ~**_||])[word", + "expected": "])[word" + }, + { + "input": "[http://x.io )<`](😀 ~](`漢)!", + "expected": ")< !" + }, + { + "input": " http://x.ioword! `~](\u0000 ]( http://x.io]", + "expected": "]( ](" + }, + { + "input": "#]", + "expected": "]" + }, + { + "input": "[http://x.iohttps://y.io/p \u0000|~[|http://x.io![http://x.io é\n![ < )\néb\n![| <**\u0000😀http://x.io ~_😀||![>", + "expected": "b ) 😀 ![" + }, + { + "input": "**!漢)漢 ~…https://y.io/p|# ||!_éhttp://x.iohttp://x.io", + "expected": "!漢)漢 ! é" + }, + { + "input": "|||])", + "expected": "])" + }, + { + "input": "bword!![漢[ <|||", + "expected": "bword!![漢[ <" + }, + { + "input": "https://y.io/p>_漢\n~~…[|_![https://y.io/p<…![漢)a**b**)…[[wordb\u0000b](#a😀", + "expected": "[ ![ ![漢 )a b ) [[wordb b]( a😀" + }, + { + "input": " ||<#\u0000b>#\n", + "expected": "< b" + }, + { + "input": "aawordhttp://x.ioé\u0000|", + "expected": "aaword é" + }, + { + "input": "<_![|**\u0000漢😀 [ba😀`https://y.io/p<](wordhttp://x.io![ ](] #é_", + "expected": "< ![ 漢😀 [ba😀 ](] é" + }, + { + "input": "😀]()\u0000\u0000word#~http://x.io ~#😀**[a)a>é )http://x.io)…)]https://y.io/p!~)**` #||……](]", + "expected": "é< ] ](]" + }, + { + "input": "http://x.ioaword😀](\u0000…\n)\n]\u0000\u0000[\n漢é…é)\n\u0000a)", + "expected": "]( ) ] [ 漢é é) a)" + }, + { + "input": "**![!\nhttps://y.io/pb…![~a\n漢…` ](漢", + "expected": "![! b ![ a 漢 ](漢" + }, + { + "input": "_|a!a# ](|< é! [ |…>\u0000…](a~_https://y.io/p", + "expected": "a!a ]( < é! [ ](a" + }, + { + "input": "http://x.io…#!漢http://x.io", + "expected": "!漢" + }, + { + "input": "_😀éhttp://x.io ![[!_ http://x.iob_!😀](b漢a)a# ~b", + "expected": "😀é a b" + }, + { + "input": "||b]**!https://y.io/p#>", + "expected": "😀 ]) ]( ]( a !" + }, + { + "input": "#||~**é!\n~![](]( éhttp://x.io ](http://x.io<é![|bhttps://y.io/p~\u0000 )|![**", + "expected": "é! ![" + }, + { + "input": " [😀 ||é#漢ééb\n[漢~>~](b… #||`", + "expected": "[😀" + }, + { + "input": "!>漢<…word|||~#\n<](\n…漢> `a…>é||]![\u0000 😀漢\u0000_<_ https://y.io/p", + "expected": "! 漢< word ]![ 😀漢 <" + }, + { + "input": "<||a_b😀[**_**b|![ a", + "expected": "<) ]( ![![]( a" + }, + { + "input": "~![# >_ [é_<)😀b)![]|#**||…](…http://x.io**\nword", + "expected": "![ [é <)😀b)![] ]( word" + }, + { + "input": "漢)\n![http://x.io \n", + "expected": "漢) ![" + }, + { + "input": "…a漢…!a)**word![ #  ", + "expected": "a漢 !a) word![" + }, + { + "input": "**", + "expected": null + }, + { + "input": "漢|_éhttps://y.io/phttps://y.io/phttps://y.io/paé)\u0000https://y.io/p# >http://x.ioé##![漢)](…>||…>](]\u0000]é😀 ahttps://y.io/p||) ", + "expected": "漢 é" + }, + { + "input": "!b| ||éword…](~`** ](\u0000~**[a)éword", + "expected": "!b éword ]( ]( [a)éword" + }, + { + "input": "https://y.io/pa**…[`!…  >||[` ] <]#!!#a](![😀a)_>", + "expected": "[ ! [ ] <] !! a](![😀a)" + }, + { + "input": "[~||~ ", + "expected": "[" + }, + { + "input": "é||\n 😀http://x.io#漢 **||!<", + "expected": "é !<" + }, + { + "input": "\u0000 !)])\u0000\n…é~http://x.iowordhttp://x.io ~word !||a_  |é![", + "expected": "!)]) é word ! a é![" + }, + { + "input": "http://x.io[! ||)😀………http://x.iohttp://x.io😀\n\n**)](a) ]…b…**漢wordéword!][ wordhttp://x.iob ", + "expected": ")😀 ) ] b 漢wordéword!][ word" + }, + { + "input": "||! ![http://x.io)! ||éhttps://y.io/p", + "expected": "é" + }, + { + "input": "_~https://y.io/p <漢\n>http://x.io_b漢**![|https://y.io/p**é`http://x.iohttp://x.io!< `…![https://y.io/p~ **||\u0000\n ]!![\u0000a", + "expected": "<漢 ![ ]!![ a" + }, + { + "input": "#😀#|****é`**\u0000!**a]http://x.io[](\u0000_<)]https://y.io/p… ![https://y.io/pb http://x.io", + "expected": "😀 é ! a] <)] ![" + }, + { + "input": "https://y.io/pbb`> a#ab__#|\n#😀](~] [漢\n", + "expected": "a ab 😀]( ] [漢" + }, + { + "input": " é)_**word[>😀!>#a", + "expected": "é) word[ 😀! a" + }, + { + "input": " \nhttp://x.io😀http://x.io", + "expected": null + }, + { + "input": "…#]漢", + "expected": "]漢" + }, + { + "input": "b!…![~…", + "expected": "b! ![" + }, + { + "input": "# _ ", + "expected": null + }, + { + "input": "](😀https://y.io/p é![>#é**< 漢 ", + "expected": "](😀 é![ é < 漢" + }, + { + "input": "word😀\n\u0000word[||~[ \u0000![ ||<", + "expected": "word😀 word[ <" + }, + { + "input": "[](!)<|漢😀 _]é[… |**]http://x.iob😀", + "expected": "[](!)< 漢😀 ]é[ ]" + }, + { + "input": "**…`_b\nhttp://x.io !é\n[<_ |#<_ |]b", + "expected": "b !é [< < ]b" + }, + { + "input": "**<))||http://x.io#**`|\n )…~>** >a😀 \u0000_))漢", + "expected": "<)) ) >>>b~é ![`# http://x.iohttp://x.io漢http://x.io ~**…> a漢![||https://y.io/p_a", + "expected": "a]()漢" + }, + { + "input": " a`ab>`https://y.io/p>é", + "expected": "a ab" + }, + { + "input": "**…http://x.io\n\n…\n< \u0000)é]**a](! )](é)[é](**!wordword", + "expected": "< )é] a](! )]( é)[é]( ! wordword" + }, + { + "input": "~]ba…[]#\n![`\n", + "expected": "]ba [] ![" + }, + { + "input": "😀`||…é_a~[\n**>", + "expected": "😀 é a [" + }, + { + "input": "a||[漢\n\n漢 ~ éword]![]![a\u0000", + "expected": "a [漢 漢 éword]![]![a" + }, + { + "input": "`http://x.io ![](_[…>b||https://y.io/p[ `é||](https://y.io/pa![` ](b |)_word ~_\u0000] ]\n#`", + "expected": "word ] ]" + }, + { + "input": "_\n** ](a`😀)`~\n http://x.io~ ##)>漢 ||![~]]", + "expected": "](a 😀) ) 漢 ![ ] ]" + }, + { + "input": "|||http://x.io||é_", + "expected": "é" + }, + { + "input": "|| aéhttps://y.io/phttps://y.io/p](awordhttp://x.ioa😀éword https://y.io/p_!http://x.io", + "expected": "aé" + }, + { + "input": ">|| 漢\u0000…b~bb _word__\n… _ [![]é", + "expected": "漢 b bb word [![]é" + }, + { + "input": "`漢http://x.io\n]([`![]~\u0000_b", + "expected": "漢 ]([ ![] b" + }, + { + "input": "_b_#](😀wordhttps://y.io/p||word]😀 a>)# ~`>http://x.io!b", + "expected": null + }, + { + "input": " _é`!`😀!_](_ [http://x.io", + "expected": "é ! 😀! ]( [" + }, + { + "input": "b\n|漢…b  漢 ~|word_>https://y.io/p 漢b](~< [ https://y.io/p#[…`< \n\u0000é!)http://x.io| ", + "expected": "b 漢 b 漢 word 漢b]( < [ < é!)" + }, + { + "input": ">#http://x.ioword**](😀b`\nhttps://y.io/p[\n~|]()[|** 漢~|`bé`)| a[>b[|![http://x.io", + "expected": "漢漢[ ]( b[ ![" + }, + { + "input": " éhttps://y.io/p> a ![<漢<##😀>漢 _ 😀\n**http://x.io](\u0000)[>!<…\u0000#_ ](||)", + "expected": "é a !<" + }, + { + "input": " 😀https://y.io/p<**漢||éhttp://x.io\u0000😀😀!`b`…!<漢**\nhttp://x.ioa !](…http://x.io\n\n__)http://x.io](http://x.io", + "expected": "😀 😀😀! b !<漢 !]( )" + }, + { + "input": " é]😀!\u0000[\u0000)](`https://y.io/p~http://x.io>\u0000 ](![)](<é…https://y.io/p\u0000` ", + "expected": "é]😀! )](<é" + }, + { + "input": " )b …", + "expected": ")b" + }, + { + "input": "![http://x.io > ~**漢https://y.io/p<😀é [bb😀 |", + "expected": "![ 漢 [b b😀" + }, + { + "input": "||😀<****https://y.io/p_||](wordhttp://x.io]word!<**>http://x.iohttps://y.io/p!<|| ![a漢**|![](![[b**!![[!word", + "expected": "](word ![a漢 ![](![[b !![[!word" + }, + { + "input": "|", + "expected": null + }, + { + "input": "😀|bé漢https://y.io/p…||**<\nb<…http://x.io_|~~ ||https://y.io/p|> [`漢 漢||漢>]漢word)[ ", + "expected": "😀 bé漢 [ 漢 漢 漢 ]漢word)[" + }, + { + "input": "`~|||éba <_……![漢", + "expected": "a! ![ < ]😀 word漢 ![ 漢 ](![] < ![漢" + }, + { + "input": "\u0000]http://x.io](\u0000](![~é]>](](😀…<[)]http://x.ioé[https://y.io/p)éhttps://y.io/phttp://x.io\u0000word ~)http://x.io![ 😀_>", + "expected": "] ](![ é] ](](😀 <[)] word ) 😀" + }, + { + "input": "a漢\n漢](http://x.io|>\u0000[😀~!a_|` <**|**é😀\u0000 ![  ||😀http://x.io\u0000#http://x.ioab]]([word…\n ", + "expected": "b b ] a 😀 [ word) 😀" + }, + { + "input": "http://x.io😀 a漢|https://y.io/pwordhttps://y.io/p~<` \u0000", + "expected": "a漢" + }, + { + "input": "word !)\u0000||a~\u0000a )é[!]\n[[<😀https://y.io/pé![_\u0000#> >漢!** …https://y.io/pb!!)", + "expected": "!) a a )é[!] [[<😀 漢! !)" + }, + { + "input": "word😀😀\u0000[漢", + "expected": "word😀😀 [漢" + }, + { + "input": "[漢酅a wordb]", + "expected": "[漢 é a wordb]" + }, + { + "input": ">_![|word]||![b~]`word]https://y.io/p|!…_https://y.io/p|a![http://x.io<é`![ 漢https://y.io/p a ** ](!ahttp://x.io…|", + "expected": "![ word] ![b ] word] 漢 a ](!a" + }, + { + "input": "<[!…~![ 😀\u0000**a![** ! b**…https://y.io/p_\u0000`~http://x.io漢漢#漢**_😀|| !~[!😀http://x.ioword", + "expected": "<[! ![ 😀 a![ ! b ! [!😀" + }, + { + "input": "||word…https://y.io/phttps://y.io/p![ word~#)https://y.io/péb #>]!\nhttp://x.ioé[](#_http://x.io_]**[**", + "expected": "word word ) ]!" + }, + { + "input": "漢😀é> _[b]( http://x.io**<](|[`worda>| ||~!word ](![![[![\u0000b漢`", + "expected": "漢😀é [b]( !word ](![ ![[![ b漢" + }, + { + "input": "word!_\u0000_~#><<||😀 !\n**a](\nhttp://x.io** _)!_😀[", + "expected": "😀 ](< ! 😀[" + }, + { + "input": "![](_||\n||\n_word[😀)", + "expected": null + }, + { + "input": "#|](😀é<\n![](||![漢\n||_# )https://y.io/p!\u0000`\n||>b…[…]… word!>😀", + "expected": "](😀é< b [ ] word! 😀" + }, + { + "input": "#~a] **` **`|!]http://x.io**[[] ]http://x.io#_\u0000~!https://y.io/p … _||…", + "expected": "a] !] ] ~](http://x.ioé`bab|b#https://y.io/p", + "expected": "b ](" + }, + { + "input": ")](aa漢漢**a#… ab ![\u0000\u0000|😀![ <éé`_ >`~", + "expected": ")](aa 漢漢 a ab ![ 😀![ <éé" + }, + { + "input": "](https://y.io/p~ ![]([<|](b…#|", + "expected": "]( ![]([< ](é😀…\u0000漢>é]é`_b`\u0000\n <<]![]…>< é[<  _||||<", + "expected": "é😀 漢 é]é b <<]![] < é[< <" + }, + { + "input": "<>`\u0000<…> http://x.ioa😀#**\u0000](é`https://y.io/p)😀_!😀>😀漢", + "expected": "< < ](é" + }, + { + "input": "||||`a [**!b éhttp://x.iohttps://y.io/pé😀é `ahttp://x.io", + "expected": "a [ !b é a" + }, + { + "input": "\u0000#http://x.io", + "expected": null + }, + { + "input": "](word<|`||wordé`b éa**", + "expected": "](word< wordé b éa" + }, + { + "input": "https://y.io/p漢漢worda ![ `http://x.io![**b wordb_baé", + "expected": "![ )](\u0000![)`>word", + "expected": ") < word" + }, + { + "input": "` !](<|b ~\u0000漢😀https://y.io/p~a>é> http://x.io ]( ~|||\n[漢 [||https://y.io/p`_<_|_]~https://y.io/p)||", + "expected": "!](< b 漢😀 ](" + }, + { + "input": "…a漢ab#`worda||https://y.io/p]( ]![_!**`<#[ 😀a#|](aba漢 > ># word…é é[", + "expected": "a漢ab worda ]![ ! < [ 😀a ](aba漢 word é é[" + }, + { + "input": "\u0000 **<\u0000word#https://y.io/p#>…!#", + "expected": "< word !" + }, + { + "input": "…a[…](`word[😀[|<\u0000`http://x.io!http://x.iohttp://x.ioa]\u0000![**||||http://x.io)|\u0000![ ~\n#https://y.io/p](https://y.io/p", + "expected": "a ![" + }, + { + "input": "])aéaba", + "expected": "])aéaba" + }, + { + "input": "😀**", + "expected": "😀" + }, + { + "input": "😀\u0000>word|| word\nhttp://x.io]**`_é#~漢#😀**_!\n_**\u0000**…#b)b!http://x.io # \u0000b ", + "expected": "😀 word word b)b! b" + }, + { + "input": "|é# )\u0000", + "expected": "é )" + }, + { + "input": " !![![word|<😀#[word#a**\n``<é)word\u0000 [\u0000\u0000http://x.io…<é>[)\u0000\u0000![#é word\nhttps://y.io/p ", + "expected": "!![![word <😀 [word a <é)word [ <é [) ![ é word" + }, + { + "input": "] …~||<[漢>` < ]b", + "expected": "] <[漢 < ]b" + }, + { + "input": "aaéé>||_[\n~#<😀a!\n é…](\u0000||<é漢[`http://x.io_<\u0000](…![a~<漢", + "expected": "aaéé <é漢[ ]( ![ http://x.io", + "expected": "😀" + }, + { + "input": "😀\u0000b**](é![ba**éword \n![ \u0000", + "expected": "😀 b ](é![ba éword ![" + }, + { + "input": "[漢 **|<é![ [>", + "expected": "[漢 <é![ [" + }, + { + "input": "http://x.io](é漢)\u0000…b\u0000>😀a## [||é![|https://y.io/p)!bhttps://y.io/p\n#`]", + "expected": "b 😀a [ é![ ]" + }, + { + "input": "b漢<](># ……_http://x.io||~|漢word||#a!b漢…!|ahttp://x.ioword)b||](](\n**", + "expected": "漢word ](](" + }, + { + "input": "`](`|| < _\n😀<\u0000… **` _😀https://y.io/p#é| #|`http://x.io # word>", + "expected": "]( < 😀< 😀 word" + }, + { + "input": "![ http://x.io#", + "expected": "![" + }, + { + "input": "!]()~a||[||** 😀_a)![_<]( ]( ", + "expected": "!]() a 😀 a)![ _  >b `https://y.io/p 漢#`\u0000a>", + "expected": "![) ]aa é b 漢 a" + }, + { + "input": "!\n`](~éé]([wordb\u0000`)é#|ahttp://x.iohttps://y.io/p_|#\u0000**", + "expected": "! ]( éé]([wordb )é a" + }, + { + "input": " é | https://y.io/p||😀  ! #||]…#word`!||https://y.io/p~😀http://x.iohttps://y.io/p\n_**>[**\n…<", + "expected": "![](]😀 worda漢 [ <" + }, + { + "input": "_ ![||~||word] ]<`]** !| \n|~\n> | [||>)!\u0000a~😀||é|", + "expected": "![ word] ]< ] ! [ é" + }, + { + "input": " 😀https://y.io/p![_**漢> bé", + "expected": "😀 bé" + }, + { + "input": "|aword~](!a!", + "expected": "aword ](! a!" + }, + { + "input": "**]()_~~http://x.iob[a![漢 _https://y.io/pa[~|word**![", + "expected": "]()" + }, + { + "input": ">a>|https://y.io/pa😀|😀http://x.io> ****word\n)éhttp://x.io word😀b é", + "expected": "aé[a word )é word😀b é" + }, + { + "input": "![** http://x.iohttp://x.io**`](b…\u0000 ![]]( _ !\nword[\u0000…]| b😀 _b", + "expected": "![ ![ ] ]( ! word[ ] b😀 b" + }, + { + "input": "a][word\u0000b", + "expected": "a][word b" + }, + { + "input": " ](`[<[word]` ![|word ~漢<[http://x.iohttp://x.io![](**[…`[_😀[~** >漢#é>##http://x.io ||", + "expected": "]( [<[word] ![ word 漢<[ [ 😀[ 漢 é" + }, + { + "input": "****#**[_b[](😀 word#!… é word)word😀http://x.io||`😀](**", + "expected": "b[word😀" + }, + { + "input": "||\n#\u0000>![https://y.io/p || \u0000 http://x.io\u0000>](word<[a)a~_ ~ >)béb!http://x.iohttps://y.io/p >\u0000! ", + "expected": "]( word<[a)a ) béb! !" + }, + { + "input": "_\n**a)word)~![ )éa ](https://y.io/p…word~`\u0000]( …!![#漢~!](\u0000!~ )", + "expected": "a)word)" + }, + { + "input": "é[)\u0000 b]< **a)\n`![]…# ]]!word[😀", + "expected": "![ b < a) ~#![<…a#< https://y.io/p _é**>é](\n**漢https://y.io/phttps://y.io/p[_< **\n", + "expected": "< ![< a < é é]( 漢" + }, + { + "input": "https://y.io/p <…![` ~<<_>aéhttps://y.io/p!word **漢|]( \n ~word漢😀>![]( _https://y.io/p ])](漢||😀http://x.io", + "expected": "< ](漢 😀" + } +] diff --git a/crates/buzz-cli/src/commands/sidebar.rs b/crates/buzz-cli/src/commands/sidebar.rs new file mode 100644 index 00000000000..708bf8a7588 --- /dev/null +++ b/crates/buzz-cli/src/commands/sidebar.rs @@ -0,0 +1,496 @@ +//! `buzz sidebar sections` — your own channel sections, the same synced +//! preference the desktop sidebar edits (kind:30078, d=`channel-sections`, +//! NIP-44 encrypted to yourself). +//! +//! Every write is one read of the current head followed by one publish, so a +//! multi-channel `move` lands atomically. A head this CLI cannot read is never +//! overwritten. + +use serde_json::{json, Value}; + +use super::sidebar_doc::{self, Edit, Projection, Section, Tree}; +use super::sidebar_sync::{self, channel_ids, Lane}; +use super::{sidebar_flags, sidebar_sort}; +use crate::client::BuzzClient; +use crate::error::CliError; +use crate::{SidebarCmd, SidebarSectionsCmd}; + +const LANE: Lane = Lane { + d_tag: "channel-sections", + label: "sidebar sections", +}; + +async fn fetch_head(client: &BuzzClient) -> Result { + Ok( + sidebar_sync::fetch_tree(client, LANE, &sidebar_doc::SECTIONS) + .await? + .1, + ) +} + +/// The live sections and assignments in your current sections document. +pub(super) async fn fetch_view(client: &BuzzClient) -> Result { + Ok(sidebar_doc::project(&fetch_head(client).await?)) +} + +/// A live section by exact id, or by exact name when that name is unique. +pub(super) fn resolve<'a>(view: &'a Projection, key: &str) -> Result<&'a Section, CliError> { + if let Some(section) = view.sections.iter().find(|s| s.id == key) { + return Ok(section); + } + let key = key.trim(); + let mut named = view.sections.iter().filter(|s| s.name == key); + match (named.next(), named.next()) { + (Some(section), None) => Ok(section), + (Some(_), Some(_)) => Err(CliError::Usage(format!( + "more than one section is named \"{key}\"; pass the section id from `buzz sidebar sections list`" + ))), + (None, _) => Err(CliError::NotFound(format!( + "no section has the id or name \"{key}\"" + ))), + } +} + +fn section_name(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err(CliError::Usage("section name must not be empty".into())); + } + Ok(name.to_string()) +} + +fn section_icon(icon: Option<&str>) -> Result, CliError> { + match icon.map(str::trim) { + Some("") => Err(CliError::Usage( + "--icon must not be empty; use --clear-icon to remove an icon".into(), + )), + icon => Ok(icon.map(str::to_string)), + } +} + +/// Reads the head, applies `apply`, and publishes the result once. Returns +/// the write response, or an `unchanged` response without publishing. +async fn edit( + client: &BuzzClient, + apply: impl FnOnce(&mut Edit, &Projection) -> Result<(), CliError>, +) -> Result { + sidebar_sync::edit_tree( + client, + LANE, + &sidebar_doc::SECTIONS, + |tree| { + if sidebar_doc::project(tree).within_limits() { + return Ok(()); + } + Err(CliError::Usage(format!( + "the sidebar supports at most {} sections and {} channel assignments", + sidebar_doc::MAX_SECTIONS, + sidebar_doc::MAX_ASSIGNMENTS + ))) + }, + |edit, head| apply(edit, &sidebar_doc::project(head)), + ) + .await +} + +async fn run(cmd: SidebarSectionsCmd, client: &BuzzClient) -> Result { + match cmd { + SidebarSectionsCmd::List => { + let tree = fetch_head(client).await?; + serde_json::to_value(sidebar_doc::project(&tree)) + .map_err(|e| CliError::Other(format!("failed to encode sections: {e}"))) + } + SidebarSectionsCmd::Create { name, icon } => { + let name = section_name(&name)?; + let icon = section_icon(icon.as_deref())?; + let id = uuid::Uuid::new_v4().to_string(); + let mut response = edit(client, |edit, _| { + edit.create_section(&id, &name, icon.as_deref()); + Ok(()) + }) + .await?; + response["section_id"] = json!(id); + Ok(response) + } + SidebarSectionsCmd::Update { + section, + name, + icon, + clear_icon, + } => { + if name.is_none() && icon.is_none() && !clear_icon { + return Err(CliError::Usage( + "pass --name, --icon, or --clear-icon".into(), + )); + } + let name = name.as_deref().map(section_name).transpose()?; + let icon = section_icon(icon.as_deref())?; + edit(client, |edit, view| { + let id = resolve(view, §ion)?.id.clone(); + if let Some(name) = name { + edit.set(&["s", &id, "name"], json!(name)); + } + if clear_icon || icon.is_some() { + edit.set(&["s", &id, "icon"], json!(icon)); + } + Ok(()) + }) + .await + } + SidebarSectionsCmd::Delete { section } => { + edit(client, |edit, view| { + let id = resolve(view, §ion)?.id.clone(); + edit.set(&["s", &id, "live"], json!(false)); + Ok(()) + }) + .await + } + SidebarSectionsCmd::Reorder { sections } => { + edit(client, |edit, view| { + let ids = sections + .iter() + .map(|key| Ok(resolve(view, key)?.id.clone())) + .collect::, CliError>>()?; + edit.reorder(&ids); + Ok(()) + }) + .await + } + SidebarSectionsCmd::Move { channels, section } => { + let channels = channel_ids(&channels)?; + edit(client, |edit, view| { + let id = resolve(view, §ion)?.id.clone(); + for channel in &channels { + edit.set(&["a", channel], json!(id)); + } + Ok(()) + }) + .await + } + SidebarSectionsCmd::Unassign { channels } => { + let channels = channel_ids(&channels)?; + edit(client, |edit, _| { + for channel in &channels { + edit.clear(&["a", channel]); + } + Ok(()) + }) + .await + } + } +} + +pub async fn dispatch(cmd: SidebarCmd, client: &BuzzClient) -> Result<(), CliError> { + let output = match cmd { + SidebarCmd::Sections(cmd) => run(cmd, client).await?, + SidebarCmd::Sort(cmd) => sidebar_sort::run(cmd, client).await?, + SidebarCmd::Stars(cmd) => { + sidebar_flags::run(&sidebar_flags::STARS, cmd.into(), client).await? + } + SidebarCmd::Mutes(cmd) => { + sidebar_flags::run(&sidebar_flags::MUTES, cmd.into(), client).await? + } + SidebarCmd::Projects(cmd) => { + sidebar_flags::run(&sidebar_flags::PROJECTS, cmd.into(), client).await? + } + }; + println!("{output}"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::super::sidebar_doc::Stamp; + use super::super::sidebar_sync::now; + use super::super::sidebar_sync::test_support::{self, Shared}; + use super::*; + use crate::credentials::Credentials; + use nostr::Keys; + + async fn setup() -> (BuzzClient, Shared) { + test_support::setup().await + } + + fn seed_at(client: &BuzzClient, relay: &Shared, plaintext: &str, created_at: u64) -> Value { + test_support::seed_at(client, relay, LANE, plaintext, created_at) + } + + fn seed(client: &BuzzClient, relay: &Shared, plaintext: &str) { + seed_at(client, relay, plaintext, now().as_secs()); + } + + fn doc_with_sections(names: &[&str]) -> String { + let mut tree = Tree::new(); + let stamp = Stamp { + now_ms: 1, + dev: "0123456789abcdef".into(), + }; + let mut edit = Edit::new(&mut tree, &stamp); + for name in names { + edit.create_section(&format!("id-{name}"), name, None); + } + sidebar_doc::encode(&sidebar_doc::SECTIONS, &tree).to_string() + } + + use test_support::{published, published_count}; + + const C1: &str = "11111111-1111-4111-8111-111111111111"; + const C2: &str = "22222222-2222-4222-8222-222222222222"; + const C3: &str = "abcdef01-2345-4678-89ab-cdef01234567"; + + fn mv(channels: &[&str], section: &str) -> SidebarSectionsCmd { + SidebarSectionsCmd::Move { + channels: channels.iter().map(|c| c.to_string()).collect(), + section: section.into(), + } + } + + #[tokio::test] + async fn sets_up_a_sidebar_in_one_pass_and_syncs_desktop_format() { + let (client, relay) = setup().await; + let list = run(SidebarSectionsCmd::List, &client).await.unwrap(); + assert_eq!(list, json!({"sections": [], "assignments": {}})); + + let eng = run( + SidebarSectionsCmd::Create { + name: " Engineering ".into(), + icon: Some("🛠".into()), + }, + &client, + ) + .await + .unwrap(); + let eng_id = eng["section_id"].as_str().unwrap().to_string(); + run( + SidebarSectionsCmd::Create { + name: "Design".into(), + icon: None, + }, + &client, + ) + .await + .unwrap(); + + // Both channels land in one publish, addressed by section name. + let before = published_count(&relay); + run(mv(&[C1, C2], "Engineering"), &client).await.unwrap(); + assert_eq!(published_count(&relay), before + 1); + + let (event, doc) = published(&client, &relay); + assert_eq!(event.kind.as_u16(), 30078); + assert!(event.tags.iter().any(|t| t.as_slice() == ["d", LANE.d_tag])); + assert!(event.tags.iter().any(|t| t.as_slice() == ["t", LANE.d_tag])); + assert_eq!(doc["meta"]["v"], json!(1)); + assert_eq!(doc["assignments"][C1], json!(eng_id)); + assert_eq!(doc["sections"][0]["icon"], json!("🛠")); + + // A repeated command publishes nothing. + let again = run(mv(&[C1, C2], &eng_id), &client).await.unwrap(); + assert_eq!(again["message"], json!("unchanged")); + assert_eq!(published_count(&relay), before + 1); + + // Invalid input fails before any publish. + let err = run(mv(&[C1, "not-a-uuid"], "Design"), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + let err = run(mv(&[C1], "Nope"), &client).await.unwrap_err(); + assert!(matches!(err, CliError::NotFound(_)), "{err:?}"); + assert_eq!(published_count(&relay), before + 1); + + run( + SidebarSectionsCmd::Reorder { + sections: vec!["Design".into()], + }, + &client, + ) + .await + .unwrap(); + run( + SidebarSectionsCmd::Update { + section: eng_id.clone(), + name: Some("Eng".into()), + icon: None, + clear_icon: true, + }, + &client, + ) + .await + .unwrap(); + run( + SidebarSectionsCmd::Unassign { + channels: vec![C2.into()], + }, + &client, + ) + .await + .unwrap(); + run( + SidebarSectionsCmd::Delete { + section: "Design".into(), + }, + &client, + ) + .await + .unwrap(); + + let list = run(SidebarSectionsCmd::List, &client).await.unwrap(); + assert_eq!( + list, + json!({ + "sections": [{"id": eng_id, "name": "Eng", "order": 0}], + "assignments": {C1: eng_id}, + }) + ); + let (_, doc) = published(&client, &relay); + assert_eq!(doc["sections"], list["sections"]); + } + + #[tokio::test] + async fn keeps_a_mobile_head_and_never_overwrites_an_unreadable_one() { + let (client, relay) = setup().await; + seed( + &client, + &relay, + r#"{"version":1,"sections":[{"id":"m1","name":"Mobile","order":0}],"assignments":{}}"#, + ); + run(mv(&[C1], "Mobile"), &client).await.unwrap(); + let list = run(SidebarSectionsCmd::List, &client).await.unwrap(); + assert_eq!(list["sections"][0]["name"], json!("Mobile")); + assert_eq!(list["assignments"][C1], json!("m1")); + + seed_at( + &client, + &relay, + r#"{"version":1,"meta":{"v":2}}"#, + now().as_secs() + 100, + ); + let count = published_count(&relay); + assert!(run(SidebarSectionsCmd::List, &client).await.is_err()); + assert!(run(mv(&[C2], "Mobile"), &client).await.is_err()); + assert_eq!(published_count(&relay), count); + } + + #[tokio::test] + async fn picks_the_newest_head_and_publishes_after_it() { + let (client, relay) = setup().await; + let future = now().as_secs() + 1_000; + seed_at(&client, &relay, &doc_with_sections(&["Old"]), future - 1); + let a = seed_at(&client, &relay, &doc_with_sections(&["A"]), future); + let b = seed_at(&client, &relay, &doc_with_sections(&["B"]), future); + // Equal `created_at`: the lower id wins, as on the relay. + let winner = if a["id"].as_str() < b["id"].as_str() { + "A" + } else { + "B" + }; + let list = run(SidebarSectionsCmd::List, &client).await.unwrap(); + assert_eq!(list["sections"][0]["name"], json!(winner)); + + // Another author's head is never read as ours. + let other = + BuzzClient::new(String::new(), Credentials::from_keys(Keys::generate())).unwrap(); + seed_at(&other, &relay, &doc_with_sections(&["Theirs"]), future + 5); + + // An uppercase channel id is stored in desktop's canonical form. + run(mv(&[&C3.to_uppercase()], winner), &client) + .await + .unwrap(); + let (event, doc) = published(&client, &relay); + assert_eq!(event.created_at.as_secs(), future + 1); + assert_eq!(doc["assignments"][C3], json!(format!("id-{winner}"))); + } + + #[tokio::test] + async fn refuses_a_tampered_head_and_oversized_documents() { + let (client, relay) = setup().await; + let mut head = seed_at(&client, &relay, &doc_with_sections(&["A"]), 10); + head["content"] = json!("tampered"); + relay.lock().unwrap().events = vec![head]; + let err = run(mv(&[C1], "A"), &client).await.unwrap_err(); + assert!(matches!(err, CliError::Other(_)), "{err:?}"); + assert_eq!(published_count(&relay), 1); + + let names: Vec = (0..sidebar_doc::MAX_SECTIONS) + .map(|i| i.to_string()) + .collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + relay.lock().unwrap().events.clear(); + seed(&client, &relay, &doc_with_sections(&names)); + let over_count = SidebarSectionsCmd::Create { + name: "one too many".into(), + icon: None, + }; + let rename = |len: usize| SidebarSectionsCmd::Update { + section: "0".into(), + name: Some("x".repeat(len)), + icon: None, + clear_icon: false, + }; + let err = run(over_count, &client).await.unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + + // Ciphertext over the relay cap, then plaintext over the NIP-44 cap. + relay.lock().unwrap().events.clear(); + seed(&client, &relay, &doc_with_sections(&["0"])); + for cmd in [rename(25_000), rename(70_000)] { + let err = run(cmd, &client).await.unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + } + assert_eq!(published_count(&relay), 1); + + let err = run( + SidebarSectionsCmd::Update { + section: "0".into(), + name: None, + icon: Some(" ".into()), + clear_icon: false, + }, + &client, + ) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + } + + #[tokio::test] + async fn a_dominated_write_is_a_conflict() { + let (client, relay) = setup().await; + seed_at( + &client, + &relay, + &doc_with_sections(&["Theirs"]), + now().as_secs() + 3_600, + ); + relay.lock().unwrap().duplicate = true; + let err = run( + SidebarSectionsCmd::Create { + name: "Late".into(), + icon: None, + }, + &client, + ) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Conflict(_)), "{err:?}"); + } + + #[tokio::test] + async fn a_retry_of_a_stored_write_is_success() { + let (client, relay) = setup().await; + relay.lock().unwrap().stored_duplicate = true; + let out = run( + SidebarSectionsCmd::Create { + name: "Once".into(), + icon: None, + }, + &client, + ) + .await + .unwrap(); + let (event, _) = published(&client, &relay); + assert_eq!(out["event_id"], json!(event.id.to_hex())); + assert_eq!(out["message"], json!("")); + assert_eq!(published_count(&relay), 1); + } +} diff --git a/crates/buzz-cli/src/commands/sidebar_doc.rs b/crates/buzz-cli/src/commands/sidebar_doc.rs new file mode 100644 index 00000000000..75bf3d8977e --- /dev/null +++ b/crates/buzz-cli/src/commands/sidebar_doc.rs @@ -0,0 +1,672 @@ +//! The synced register-tree documents: channel sections (kind:30078, +//! d=`channel-sections`) and sort modes (d=`channel-sort`). +//! +//! Wire-compatible with desktop `channelSectionsSync.ts`, `channelSortSync.ts`, +//! `sidebarLaneStore.ts` and `sidebarLwwMap.ts`: a tree of per-field +//! last-writer-wins registers `[v, dev, value]` under `meta`, plus the +//! projected legacy fields that meta-less clients (mobile) read and write. +//! A [`Codec`] describes one document's shape, legacy import and projection. +//! +//! Like desktop, decoding drops any key or register its shape does not know, +//! and the republished snapshot omits it. Buzz Desktop (`block/buzz-app`, +//! `validate_sidebar_payload`) refuses to sign a document with unknown keys, +//! so a new field needs a new `meta.v`; [`decode`] refuses an unknown +//! `meta.v`, and the commands then neither read nor overwrite the head. + +use std::collections::BTreeMap; + +use serde_json::{json, Map, Value}; + +/// Register tree: `{"s": {section_id: {name, icon, order, live}}, "a": {channel_id: section_id|null}}`. +pub(crate) type Tree = Map; + +/// Live-section cap shared with desktop; larger documents are never published. +pub(crate) const MAX_SECTIONS: usize = 100; +/// Live-assignment cap shared with desktop. +pub(crate) const MAX_ASSIGNMENTS: usize = 1_000; +/// Cap on non-null sort registers shared with desktop. +pub(crate) const MAX_SORT_GROUPS: usize = 104; + +/// Device id desktop stamps on registers imported from meta-less payloads. +const LEGACY_DEV: &str = "0000000000000000"; +const MAX_SAFE_INTEGER: i64 = (1 << 53) - 1; + +/// One live section, densely renumbered by `(order, id)`. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub(crate) struct Section { + pub id: String, + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, + pub order: usize, +} + +/// The view every client renders: live sections and assignments to them. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub(crate) struct Projection { + pub sections: Vec
, + pub assignments: BTreeMap, +} + +impl Projection { + pub(crate) fn within_limits(&self) -> bool { + self.sections.len() <= MAX_SECTIONS && self.assignments.len() <= MAX_ASSIGNMENTS + } +} + +/// `Number.isSafeInteger`, accepting integral floats such as `1.0`. +fn safe_int(value: &Value) -> Option { + let n = match value.as_i64() { + Some(n) => n, + None => { + let f = value.as_f64()?; + if f.fract() != 0.0 || f.abs() > MAX_SAFE_INTEGER as f64 { + return None; + } + f as i64 + } + }; + (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER) + .contains(&n) + .then_some(n) +} + +fn is_dev(value: &Value) -> bool { + value + .as_str() + .is_some_and(|s| s.len() == 16 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))) +} + +fn valid_reg(node: &Value, leaf: Leaf) -> Option { + let reg = node.as_array().filter(|reg| reg.len() == 3)?; + let v = safe_int(®[0]).filter(|v| *v >= 0)?; + (is_dev(®[1]) && leaf(®[2])).then(|| json!([v, reg[1], reg[2]])) +} + +fn is_string(value: &Value) -> bool { + value.is_string() +} +fn is_string_or_null(value: &Value) -> bool { + value.is_string() || value.is_null() +} +fn is_order(value: &Value) -> bool { + safe_int(value).is_some() +} +fn is_bool(value: &Value) -> bool { + value.is_boolean() +} +fn is_sort_mode(value: &Value) -> bool { + value.is_null() || matches!(value.as_str(), Some("alpha" | "recent")) +} + +type Leaf = fn(&Value) -> bool; + +/// Shape of a register-tree node, as desktop `Shape`: a leaf register, fixed +/// fields, or a map whose every entry has one shape. +pub(crate) enum Shape { + Leaf(Leaf), + Fields(&'static [(&'static str, Shape)]), + Map(&'static Shape), +} + +/// One synced document: its tree shape, how a meta-less payload becomes +/// registers, and the legacy fields projected from them. +pub(crate) struct Codec { + shape: Shape, + from_legacy: fn(&Value, i64) -> Value, + project: fn(&Tree) -> Value, +} + +pub(crate) const SECTIONS: Codec = Codec { + shape: Shape::Fields(&[ + ( + "s", + Shape::Map(&Shape::Fields(&[ + ("name", Shape::Leaf(is_string)), + ("icon", Shape::Leaf(is_string_or_null)), + ("order", Shape::Leaf(is_order)), + ("live", Shape::Leaf(is_bool)), + ])), + ), + ("a", Shape::Map(&Shape::Leaf(is_string_or_null))), + ]), + from_legacy: sections_from_legacy, + project: sections_view, +}; + +pub(crate) const SORT: Codec = Codec { + shape: Shape::Fields(&[("g", Shape::Map(&Shape::Leaf(is_sort_mode)))]), + from_legacy: sort_from_legacy, + project: |tree| json!({ "groups": sort_groups(tree) }), +}; + +/// Own entries of a JSON object, skipping the `__proto__` key desktop drops. +fn entries(node: &Value) -> impl Iterator { + node.as_object() + .into_iter() + .flatten() + .filter(|(key, _)| key.as_str() != "__proto__") +} + +/// Keeps only well-formed nodes of `shape`; an invalid register or record is +/// dropped while its valid siblings survive (desktop `validTree`). +fn valid_node(node: &Value, shape: &Shape) -> Option { + if let Shape::Leaf(leaf) = shape { + return valid_reg(node, *leaf); + } + node.as_object()?; + let mut out = Map::new(); + for (key, child) in entries(node) { + let sub = match shape { + Shape::Map(sub) => Some(*sub), + Shape::Fields(fields) => fields + .iter() + .find_map(|(name, sub)| (*name == key).then_some(sub)), + Shape::Leaf(_) => None, + }; + if let Some(valid) = sub.and_then(|sub| valid_node(child, sub)) { + out.insert(key.clone(), valid); + } + } + Some(Value::Object(out)) +} + +fn valid_tree(fields: &Value, shape: &Shape) -> Option { + match valid_node(fields, shape)? { + Value::Object(tree) => Some(tree), + _ => None, + } +} + +/// JS `Math.round`, as an integer when it is a safe one. +fn js_round(f: f64) -> Value { + let rounded = (f + 0.5).floor(); + if rounded.abs() <= MAX_SAFE_INTEGER as f64 { + json!(rounded as i64) + } else { + json!(rounded) + } +} + +/// Registers for a meta-less (legacy/mobile) sections payload, every value +/// stamped at `legacy_v`. +fn sections_from_legacy(json: &Value, legacy_v: i64) -> Value { + let stamp = |value: Value| json!([legacy_v, LEGACY_DEV, value]); + let mut s = Map::new(); + for entry in json + .get("sections") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let (Some(id), Some(name), Some(order)) = ( + entry.get("id").and_then(Value::as_str), + entry.get("name").and_then(Value::as_str), + entry.get("order").and_then(Value::as_f64), + ) else { + continue; + }; + let icon = entry + .get("icon") + .and_then(Value::as_str) + .map(str::trim) + .filter(|icon| !icon.is_empty()); + s.insert( + id.to_string(), + json!({ + "name": stamp(json!(name)), + "icon": stamp(json!(icon)), + "order": stamp(js_round(order)), + "live": stamp(json!(true)), + }), + ); + } + let a: Map = entries(json.get("assignments").unwrap_or(&Value::Null)) + .filter(|(_, target)| target.as_str().is_some_and(|t| s.contains_key(t))) + .map(|(id, target)| (id.clone(), stamp(target.clone()))) + .collect(); + json!({ "s": s, "a": a }) +} + +/// Registers for a meta-less sort payload; unknown group keys are kept and +/// unknown modes dropped, as desktop `parseChannelSortPayload`. +fn sort_from_legacy(json: &Value, legacy_v: i64) -> Value { + let g: Map = entries(json.get("groups").unwrap_or(&Value::Null)) + .filter(|(_, mode)| matches!(mode.as_str(), Some("alpha" | "recent"))) + .map(|(key, mode)| (key.clone(), json!([legacy_v, LEGACY_DEV, mode]))) + .collect(); + json!({ "g": g }) +} + +/// Decodes a `version: 1` payload, importing a meta-less one at `legacy_v`. +/// Returns `None` when unreadable, including an unknown `meta.v`. +pub(crate) fn decode(codec: &Codec, json: &Value, legacy_v: i64) -> Option { + let is_one = |value: Option<&Value>| value.and_then(safe_int) == Some(1); + if !is_one(json.get("version")) { + return None; + } + match json.get("meta") { + None => valid_tree(&(codec.from_legacy)(json, legacy_v), &codec.shape), + Some(meta) if is_one(meta.get("v")) => { + let mut fields = meta.as_object()?.clone(); + fields.remove("v"); + valid_tree(&Value::Object(fields), &codec.shape) + } + Some(_) => None, + } +} + +fn val<'a>(node: &'a Value, field: &str) -> Option<&'a Value> { + node.get(field)?.as_array()?.get(2) +} + +/// Live sections by `(order, id)` with their stored `order`. +fn ranked(tree: &Tree) -> Vec<(String, String, Option, i64)> { + let mut out: Vec<_> = tree + .get("s") + .map(entries) + .into_iter() + .flatten() + .filter(|(_, node)| val(node, "live") == Some(&json!(true))) + .filter_map(|(id, node)| { + let name = val(node, "name")?.as_str()?.to_string(); + let icon = val(node, "icon") + .and_then(Value::as_str) + .filter(|icon| !icon.is_empty()) + .map(str::to_string); + let order = val(node, "order").and_then(safe_int).unwrap_or(0); + Some((id.clone(), name, icon, order)) + }) + .collect(); + // JS compares strings by UTF-16 code unit. + out.sort_by(|a, b| { + a.3.cmp(&b.3) + .then_with(|| a.0.encode_utf16().cmp(b.0.encode_utf16())) + }); + out +} + +/// Highest stored `order` among live sections, or -1 when there are none. +fn max_live_order(tree: &Tree) -> i64 { + ranked(tree).iter().map(|s| s.3).max().unwrap_or(-1) +} + +pub(crate) fn project(tree: &Tree) -> Projection { + let sections: Vec
= ranked(tree) + .into_iter() + .enumerate() + .map(|(order, (id, name, icon, _))| Section { + id, + name, + icon, + order, + }) + .collect(); + let assignments = tree + .get("a") + .map(entries) + .into_iter() + .flatten() + .filter_map(|(channel, reg)| { + let target = reg.as_array()?.get(2)?.as_str()?; + sections + .iter() + .any(|s| s.id == target) + .then(|| (channel.clone(), target.to_string())) + }) + .collect(); + Projection { + sections, + assignments, + } +} + +fn sections_view(tree: &Tree) -> Value { + let Projection { + sections, + assignments, + } = project(tree); + json!({ "sections": sections, "assignments": assignments }) +} + +/// Non-null sort modes by group key; `null` registers are explicit resets. +pub(crate) fn sort_groups(tree: &Tree) -> BTreeMap { + tree.get("g") + .map(entries) + .into_iter() + .flatten() + .filter_map(|(key, reg)| Some((key.clone(), reg.get(2)?.as_str()?.to_string()))) + .collect() +} + +/// The plaintext document: projected legacy fields plus the register tree. +pub(crate) fn encode(codec: &Codec, tree: &Tree) -> Value { + let mut doc = match (codec.project)(tree) { + Value::Object(fields) => fields, + _ => Map::new(), + }; + let mut meta = tree.clone(); + meta.insert("v".into(), json!(1)); + doc.insert("version".into(), json!(1)); + doc.insert("meta".into(), Value::Object(meta)); + Value::Object(doc) +} + +fn max_version(node: &Value) -> i64 { + match node { + Value::Array(reg) => reg.first().and_then(safe_int).unwrap_or(0), + Value::Object(map) => map.values().map(max_version).max().unwrap_or(0), + _ => 0, + } +} + +/// The version and device every register written by one edit shares. +#[derive(Debug, Clone)] +pub(crate) struct Stamp { + pub now_ms: i64, + pub dev: String, +} + +/// One edit against a tree. Each call to [`Edit::set`] that changes a leaf +/// writes a register stamped `max(now, newest + 1)`, like desktop `setRegs`. +pub(crate) struct Edit<'a> { + tree: &'a mut Tree, + reg: (i64, String), +} + +impl<'a> Edit<'a> { + pub(crate) fn new(tree: &'a mut Tree, stamp: &Stamp) -> Self { + let newest = tree.values().map(max_version).max().unwrap_or(0); + let v = stamp.now_ms.max(newest + 1); + Self { + tree, + reg: (v, stamp.dev.clone()), + } + } + + fn current(&self, path: &[&str]) -> Option<&Value> { + let (first, rest) = path.split_first()?; + let mut node = self.tree.get(*first)?; + for key in rest { + node = node.get(key)?; + } + node.as_array()?.get(2) + } + + fn write(&mut self, parents: &[&str], leaf: &str, value: Value) { + let reg = json!([self.reg.0, self.reg.1, value]); + let mut node = &mut *self.tree; + for key in parents { + let child = node.entry(key.to_string()).or_insert_with(|| json!({})); + if !child.is_object() { + *child = json!({}); + } + let Value::Object(map) = child else { + return; + }; + node = map; + } + node.insert(leaf.to_string(), reg); + } + + /// Writes `value` at `path` unless it already holds that value. + pub(crate) fn set(&mut self, path: &[&str], value: Value) { + let Some((leaf, parents)) = path.split_last() else { + return; + }; + if self.current(path) != Some(&value) { + self.write(parents, leaf, value); + } + } + + pub(crate) fn create_section(&mut self, id: &str, name: &str, icon: Option<&str>) { + let order = max_live_order(self.tree) + 1; + self.set(&["s", id, "name"], json!(name)); + self.set(&["s", id, "icon"], json!(icon)); + self.set(&["s", id, "order"], json!(order)); + self.set(&["s", id, "live"], json!(true)); + } + + /// Orders live sections `requested` first, then the rest in their current + /// relative order. Any change rewrites every live `order` register. + pub(crate) fn reorder(&mut self, requested: &[String]) { + let live: Vec = project(self.tree) + .sections + .into_iter() + .map(|s| s.id) + .collect(); + let mut ids: Vec = Vec::with_capacity(live.len()); + for id in requested.iter().chain(&live) { + if live.contains(id) && !ids.contains(id) { + ids.push(id.clone()); + } + } + let unchanged = ids + .iter() + .enumerate() + .all(|(index, id)| self.current(&["s", id, "order"]) == Some(&json!(index))); + if unchanged { + return; + } + for (index, id) in ids.iter().enumerate() { + self.write(&["s", id], "order", json!(index)); + } + } + + /// Tombstones the register at `path` when one exists (as a value or tombstone). + pub(crate) fn clear(&mut self, path: &[&str]) { + let Some((first, rest)) = path.split_first() else { + return; + }; + let exists = rest + .iter() + .fold(self.tree.get(*first), |node, key| node?.get(key)) + .is_some(); + if exists { + self.set(path, Value::Null); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const DEV: &str = "0123456789abcdef"; + + fn stamp(now_ms: i64) -> Stamp { + Stamp { + now_ms, + dev: DEV.into(), + } + } + + fn reg(v: i64, value: Value) -> Value { + json!([v, DEV, value]) + } + + /// A document in the shape desktop `encodeDoc` publishes. + fn desktop_doc() -> Value { + json!({ + "version": 1, + "sections": [], + "assignments": {}, + "meta": { + "v": 1, + "s": { + "b": {"name": reg(5, json!("Beta")), "icon": reg(5, Value::Null), + "order": reg(5, json!(1)), "live": reg(5, json!(true))}, + "a": {"name": reg(4, json!("Alpha")), "icon": reg(4, json!("🚀")), + "order": reg(4, json!(0)), "live": reg(4, json!(true))}, + "dead": {"name": reg(3, json!("Gone")), "icon": reg(3, Value::Null), + "order": reg(3, json!(2)), "live": reg(6, json!(false))}, + "bad": {"name": [7, "not-a-dev", "Bad"], "order": reg(7, json!(3)), + "live": reg(7, json!(true))}, + }, + "a": { + "c1": reg(8, json!("a")), + "c2": reg(8, json!("dead")), + "c3": reg(9, Value::Null), + }, + "future": reg(1, json!("ignored")), + }, + }) + } + + #[test] + fn decodes_desktop_document_and_projects_live_state() { + let tree = decode(&SECTIONS, &desktop_doc(), 0).expect("readable"); + let view = project(&tree); + let names: Vec<_> = view + .sections + .iter() + .map(|s| (s.name.as_str(), s.order)) + .collect(); + // `bad` keeps its valid registers but has no name, so it is not live. + assert_eq!(names, [("Alpha", 0), ("Beta", 1)]); + assert_eq!(view.sections[0].icon.as_deref(), Some("🚀")); + assert_eq!( + view.assignments, + BTreeMap::from([("c1".to_string(), "a".to_string())]) + ); + assert!(!tree.contains_key("future")); + } + + #[test] + fn unreadable_payloads_are_rejected() { + for payload in [ + json!({"version": 2, "meta": {"v": 1}}), + json!({"version": 1, "meta": {"v": 2}}), + json!({"meta": {"v": 1}}), + json!("text"), + ] { + assert!(decode(&SECTIONS, &payload, 0).is_none(), "{payload}"); + } + let bad_version = json!({"version": 1.0, "meta": {"v": 1, "s": {"x": { + "order": [i64::MIN, DEV, 0], "live": [-1, DEV, true], "name": [1, DEV, "X"]}}}}); + let tree = decode(&SECTIONS, &bad_version, 0).expect("readable"); + assert_eq!(tree["s"]["x"], json!({"name": [1, DEV, "X"]})); + } + + #[test] + fn imports_mobile_flat_payload_at_the_event_version() { + let mobile = json!({ + "version": 1, + "sections": [ + {"id": "x", "name": "Team", "icon": " ", "order": 1.6}, + {"id": "y", "name": "Ops", "order": 0}, + {"name": "no id", "order": 0}, + ], + "assignments": {"c1": "x", "c2": "missing"}, + }); + let tree = decode(&SECTIONS, &mobile, 42_000).expect("readable"); + assert_eq!(tree["s"]["x"]["order"], json!([42_000, LEGACY_DEV, 2])); + assert_eq!(tree["s"]["x"]["icon"], json!([42_000, LEGACY_DEV, null])); + let view = project(&tree); + let names: Vec<_> = view.sections.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Ops", "Team"]); + assert_eq!(view.assignments.len(), 1); + } + + #[test] + fn encode_round_trips_and_carries_the_projection() { + let tree = decode(&SECTIONS, &desktop_doc(), 0).expect("readable"); + let doc = encode(&SECTIONS, &tree); + assert_eq!(doc["meta"]["v"], json!(1)); + assert_eq!(doc["sections"][0]["name"], json!("Alpha")); + assert!(doc["sections"][1].get("icon").is_none()); + assert_eq!(doc["assignments"], json!({"c1": "a"})); + assert_eq!(decode(&SECTIONS, &doc, 0).expect("readable"), tree); + } + + #[test] + fn edits_share_one_stamp_newer_than_every_register() { + let mut tree = decode(&SECTIONS, &desktop_doc(), 0).expect("readable"); + let mut edit = Edit::new(&mut tree, &stamp(1)); + edit.create_section("n", "New", None); + edit.set(&["a", "c9"], json!("n")); + assert_eq!(tree["s"]["n"]["order"], reg(10, json!(2))); + assert_eq!(tree["a"]["c9"], reg(10, json!("n"))); + + let mut edit = Edit::new(&mut tree, &stamp(500)); + edit.set(&["s", "n", "name"], json!("New")); + assert_eq!( + tree["s"]["n"]["name"], + reg(10, json!("New")), + "unchanged leaf" + ); + } + + #[test] + fn reorder_puts_requested_first_and_keeps_the_rest() { + let mut tree = Tree::new(); + let mut edit = Edit::new(&mut tree, &stamp(1)); + for id in ["a", "b", "c"] { + edit.create_section(id, id, None); + } + let mut edit = Edit::new(&mut tree, &stamp(2)); + edit.reorder(&["c".into(), "dead".into(), "c".into()]); + let ids: Vec<_> = project(&tree).sections.into_iter().map(|s| s.id).collect(); + assert_eq!(ids, ["c", "a", "b"]); + assert_eq!(tree["s"]["a"]["order"], json!([2, DEV, 1])); + + let before = tree.clone(); + Edit::new(&mut tree, &stamp(3)).reorder(&["c".into(), "a".into()]); + assert_eq!( + tree, before, + "a reorder to the current order writes nothing" + ); + } + + #[test] + fn unassign_tombstones_only_existing_assignments() { + let mut tree = Tree::new(); + let mut edit = Edit::new(&mut tree, &stamp(1)); + edit.create_section("s1", "S", None); + edit.set(&["a", "c1"], json!("s1")); + let mut edit = Edit::new(&mut tree, &stamp(2)); + edit.clear(&["a", "c1"]); + edit.clear(&["a", "never"]); + assert_eq!(tree["a"]["c1"], json!([2, DEV, null])); + assert!(tree["a"].get("never").is_none()); + } + + #[test] + fn sort_documents_decode_project_and_round_trip() { + let desktop = json!({ + "version": 1, + "groups": {"dms": "recent"}, + "meta": {"v": 1, "g": { + "dms": reg(4, json!("recent")), + "forums": reg(5, Value::Null), + "starred": reg(6, json!("newest")), + "section:x": reg(7, json!("alpha")), + }, "future": reg(1, json!("ignored"))}, + }); + let tree = decode(&SORT, &desktop, 0).expect("readable"); + assert_eq!(tree["g"]["forums"], reg(5, Value::Null)); + assert!(tree["g"].get("starred").is_none()); + assert!(!tree.contains_key("future")); + assert_eq!( + sort_groups(&tree), + BTreeMap::from([ + ("dms".to_string(), "recent".to_string()), + ("section:x".to_string(), "alpha".to_string()), + ]) + ); + let doc = encode(&SORT, &tree); + assert_eq!( + doc["groups"], + json!({"dms": "recent", "section:x": "alpha"}) + ); + assert_eq!(decode(&SORT, &doc, 0).expect("readable"), tree); + + let mobile = json!({"version": 1, "groups": {"dms": "recent", "x": "bogus", "n": null}}); + let tree = decode(&SORT, &mobile, 42_000).expect("readable"); + assert_eq!(tree["g"]["dms"], json!([42_000, LEGACY_DEV, "recent"])); + assert!(tree["g"].get("x").is_none() && tree["g"].get("n").is_none()); + let bare = decode(&SORT, &json!({"version": 1, "groups": []}), 1).expect("readable"); + assert!(bare["g"].as_object().is_some_and(Map::is_empty)); + assert!(decode(&SORT, &json!({"version": 1, "meta": {"v": 2}}), 0).is_none()); + } +} diff --git a/crates/buzz-cli/src/commands/sidebar_flags.rs b/crates/buzz-cli/src/commands/sidebar_flags.rs new file mode 100644 index 00000000000..796ec94eb8c --- /dev/null +++ b/crates/buzz-cli/src/commands/sidebar_flags.rs @@ -0,0 +1,627 @@ +//! `buzz sidebar stars|mutes|projects` — your own synced per-id flags +//! (kind:30078, d=`channel-stars` / `channel-mutes` / +//! `project-sidebar-membership`, NIP-44 encrypted to yourself). +//! +//! All three documents are `{version: 1, : {: {, +//! updatedAt}}}` with a per-entry last-writer-wins merge, wire-compatible with +//! desktop `channelStarsStorage.ts`, `channelMutesStorage.ts` and +//! `projectSidebarMembership.ts`. Every write is one head read and one publish. + +use std::collections::BTreeMap; + +use buzz_core::kind::KIND_PROJECT; +use serde_json::{json, Map, Value}; + +use super::sidebar_sync::{self, channel_ids, now, Lane}; +use crate::client::BuzzClient; +use crate::error::CliError; +use crate::{SidebarChannelFlagCmd, SidebarProjectsCmd}; + +/// Entry cap shared with desktop's star and mute stores. +const MAX_ENTRIES: usize = 500; + +#[derive(Clone, Copy)] +enum Unit { + Seconds, + Millis, +} + +#[derive(Clone, Copy)] +enum Ids { + Channels, + Projects, +} + +/// How one document differs from the others. +pub(crate) struct Spec { + lane: Lane, + collection: &'static str, + flag: &'static str, + ids: Ids, + unit: Unit, + /// Oldest entries are evicted past this many (stars and mutes only). + max_entries: Option, + /// Projects reject a document without a collection and accept the legacy + /// array of addresses; stars and mutes read a missing collection as empty. + strict: bool, +} + +pub(crate) const STARS: Spec = Spec { + lane: Lane { + d_tag: "channel-stars", + label: "channel stars", + }, + collection: "channels", + flag: "starred", + ids: Ids::Channels, + unit: Unit::Seconds, + max_entries: Some(MAX_ENTRIES), + strict: false, +}; + +pub(crate) const MUTES: Spec = Spec { + lane: Lane { + d_tag: "channel-mutes", + label: "channel mutes", + }, + collection: "channels", + flag: "muted", + ids: Ids::Channels, + unit: Unit::Seconds, + max_entries: Some(MAX_ENTRIES), + strict: false, +}; + +pub(crate) const PROJECTS: Spec = Spec { + lane: Lane { + d_tag: "project-sidebar-membership", + label: "project sidebar membership", + }, + collection: "projects", + flag: "selected", + ids: Ids::Projects, + unit: Unit::Millis, + max_entries: None, + strict: true, +}; + +impl From for Action { + fn from(cmd: SidebarChannelFlagCmd) -> Self { + match cmd { + SidebarChannelFlagCmd::List => Action::List, + SidebarChannelFlagCmd::Add { channels } => Action::Set { + ids: channels, + on: true, + }, + SidebarChannelFlagCmd::Remove { channels } => Action::Set { + ids: channels, + on: false, + }, + } + } +} + +impl From for Action { + fn from(cmd: SidebarProjectsCmd) -> Self { + match cmd { + SidebarProjectsCmd::List => Action::List, + SidebarProjectsCmd::Add { projects } => Action::Set { + ids: projects, + on: true, + }, + SidebarProjectsCmd::Remove { projects } => Action::Set { + ids: projects, + on: false, + }, + } + } +} + +/// What a flag command asks for; ids are validated and canonicalised by `run`. +pub(crate) enum Action { + List, + Set { ids: Vec, on: bool }, +} + +#[derive(Debug, Clone, PartialEq)] +struct Entry { + on: bool, + updated_at: f64, +} + +type Store = BTreeMap; + +fn valid_entry(spec: &Spec, key: &str, value: &Value) -> Option { + if spec.strict && key.is_empty() { + return None; + } + let object = value.as_object()?; + let updated_at = object.get("updatedAt")?.as_f64().filter(|n| *n >= 0.0)?; + Some(Entry { + on: object.get(spec.flag)?.as_bool()?, + updated_at, + }) +} + +/// Desktop's `boundStarStore`: keeps the newest `max` entries, oldest first by +/// `(updatedAt, id)`. +fn bound(spec: &Spec, store: &mut Store) { + let Some(max) = spec.max_entries else { return }; + if store.len() <= max { + return; + } + let mut entries: Vec<_> = std::mem::take(store).into_iter().collect(); + entries.sort_by(|(left_id, left), (right_id, right)| { + left.updated_at + .total_cmp(&right.updated_at) + .then_with(|| left_id.cmp(right_id)) + }); + store.extend(entries.split_off(entries.len() - max)); +} + +/// Desktop's `parse*Payload`: entries that fail validation are dropped. +fn decode(spec: &Spec, json: &Value) -> Option { + if let (true, Some(addresses)) = (spec.strict, json.as_array()) { + return Some( + addresses + .iter() + .filter_map(Value::as_str) + .filter(|address| !address.is_empty()) + .map(|address| { + ( + address.to_string(), + Entry { + on: true, + updated_at: 0.0, + }, + ) + }) + .collect(), + ); + } + let object = json.as_object()?; + if object.get("version")?.as_f64()? != 1.0 { + return None; + } + let mut store = match object.get(spec.collection) { + Some(Value::Object(entries)) => entries + .iter() + .filter_map(|(key, value)| Some((key.clone(), valid_entry(spec, key, value)?))) + .collect(), + _ if spec.strict => return None, + _ => Store::new(), + }; + bound(spec, &mut store); + Some(store) +} + +fn number(n: f64) -> Value { + if n.fract() == 0.0 && n < 9_007_199_254_740_992.0 { + json!(n as u64) + } else { + json!(n) + } +} + +fn encode(spec: &Spec, store: &Store) -> Value { + let entries: Map = store + .iter() + .map(|(id, entry)| { + ( + id.clone(), + json!({spec.flag: entry.on, "updatedAt": number(entry.updated_at)}), + ) + }) + .collect(); + json!({"version": 1, spec.collection: entries}) +} + +/// `30621::` with a lowercase owner, as desktop builds project +/// addresses. +fn project_addresses(addresses: &[String]) -> Result, CliError> { + addresses + .iter() + .map(|address| { + let invalid = || CliError::Usage(format!("invalid project address: {address}")); + let mut parts = address.trim().splitn(3, ':'); + let (Some(kind), Some(owner), Some(d)) = (parts.next(), parts.next(), parts.next()) + else { + return Err(invalid()); + }; + let owner_ok = owner.len() == 64 && owner.bytes().all(|b| b.is_ascii_hexdigit()); + if kind != KIND_PROJECT.to_string() || !owner_ok || d.is_empty() { + return Err(invalid()); + } + Ok(format!("{kind}:{}:{d}", owner.to_ascii_lowercase())) + }) + .collect() +} + +fn canonical_ids(spec: &Spec, ids: &[String]) -> Result, CliError> { + match spec.ids { + Ids::Channels => channel_ids(ids), + Ids::Projects => project_addresses(ids), + } +} + +fn clock(spec: &Spec) -> f64 { + let now = now(); + match spec.unit { + Unit::Seconds => now.as_secs() as f64, + Unit::Millis => now.as_millis() as f64, + } +} + +/// Sets `ids` to `on`, stamping each changed entry strictly newer than the one +/// it replaces so the edit wins every client's merge. Returns the changed ids; +/// an id already in the requested state, or absent when switching off, is left +/// alone. +fn set_flags(spec: &Spec, store: &mut Store, ids: &[String], on: bool) -> Vec { + let clock = clock(spec); + let mut changed = Vec::new(); + for id in ids { + let current = store.get(id); + if current.map_or(!on, |entry| entry.on == on) { + continue; + } + let updated_at = current.map_or(clock, |entry| clock.max(entry.updated_at + 1.0)); + store.insert(id.clone(), Entry { on, updated_at }); + changed.push(id.clone()); + } + changed +} + +async fn fetch_store(spec: &Spec, client: &BuzzClient) -> Result<(u64, Store), CliError> { + let head = sidebar_sync::fetch_head(client, spec.lane, |json, _| decode(spec, json)).await?; + Ok((head.created_at, head.doc.unwrap_or_default())) +} + +pub(crate) async fn run( + spec: &Spec, + action: Action, + client: &BuzzClient, +) -> Result { + match action { + Action::List => { + let (_, store) = fetch_store(spec, client).await?; + let on: Vec<&String> = store + .iter() + .filter(|(_, entry)| entry.on) + .map(|(id, _)| id) + .collect(); + Ok(json!({spec.collection: on})) + } + Action::Set { ids, on } => { + let ids = canonical_ids(spec, &ids)?; + let (head_created_at, mut store) = fetch_store(spec, client).await?; + let changed = set_flags(spec, &mut store, &ids, on); + if changed.is_empty() { + return Ok(sidebar_sync::unchanged()); + } + bound(spec, &mut store); + if changed.iter().any(|id| !store.contains_key(id)) { + return Err(CliError::Usage(format!( + "{} keeps at most {MAX_ENTRIES} entries; pass fewer ids", + spec.lane.label + ))); + } + let plaintext = serde_json::to_string(&encode(spec, &store)).map_err(|e| { + CliError::Other(format!("failed to encode {}: {e}", spec.lane.label)) + })?; + sidebar_sync::publish(client, spec.lane, plaintext, head_created_at).await + } + } +} + +#[cfg(test)] +mod tests { + use super::super::sidebar_sync::test_support::{ + published, published_count, seed_at, setup, Shared, + }; + use super::*; + use crate::credentials::Credentials; + use nostr::Keys; + + const C1: &str = "11111111-1111-4111-8111-111111111111"; + const C2: &str = "22222222-2222-4222-8222-222222222222"; + const C3: &str = "abcdef01-2345-4678-89ab-cdef01234567"; + const OWNER: &str = "ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12"; + + fn set(ids: &[&str], on: bool) -> Action { + Action::Set { + ids: ids.iter().map(|id| id.to_string()).collect(), + on, + } + } + + fn seed( + client: &BuzzClient, + relay: &Shared, + spec: &Spec, + doc: Value, + created_at: u64, + ) -> Value { + seed_at(client, relay, spec.lane, &doc.to_string(), created_at) + } + + fn entries(count: usize, flag: &str, first_updated_at: u64) -> Value { + let map: Map = (0..count) + .map(|i| { + let id = format!("{i:036}"); + ( + id, + json!({flag: true, "updatedAt": first_updated_at + i as u64}), + ) + }) + .collect(); + Value::Object(map) + } + + #[tokio::test] + async fn stars_and_mutes_sync_desktop_format() { + for spec in [&STARS, &MUTES] { + let (client, relay) = setup().await; + let list = |client| run(spec, Action::List, client); + assert_eq!(list(&client).await.unwrap(), json!({"channels": []})); + + // Two channels land in one publish; an uppercase id is canonicalised. + let before = now().as_secs(); + run(spec, set(&[C1, &C3.to_uppercase()], true), &client) + .await + .unwrap(); + assert_eq!(published_count(&relay), 1); + let (event, doc) = published(&client, &relay); + assert_eq!(event.kind.as_u16(), 30078); + assert!(event + .tags + .iter() + .any(|t| t.as_slice() == ["d", spec.lane.d_tag])); + assert!(event + .tags + .iter() + .any(|t| t.as_slice() == ["t", spec.lane.d_tag])); + assert_eq!(doc["version"], json!(1)); + assert_eq!(doc["channels"][C3][spec.flag], json!(true)); + let stamp = doc["channels"][C1]["updatedAt"].as_u64().unwrap(); + assert!(stamp >= before && stamp < before + 60, "seconds: {stamp}"); + assert_eq!(list(&client).await.unwrap(), json!({"channels": [C1, C3]})); + + // Repeats and clearing an unknown channel publish nothing. + for action in [set(&[C1], true), set(&[C2], false)] { + let again = run(spec, action, &client).await.unwrap(); + assert_eq!(again["message"], json!("unchanged")); + } + assert_eq!(published_count(&relay), 1); + + // Clearing keeps a `false` entry, as desktop does, so the clear syncs. + run(spec, set(&[C1], false), &client).await.unwrap(); + let (_, doc) = published(&client, &relay); + assert_eq!(doc["channels"][C1][spec.flag], json!(false)); + assert_eq!(list(&client).await.unwrap(), json!({"channels": [C3]})); + + // Invalid input fails before any publish. + let err = run(spec, set(&[C2, "nope"], true), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + assert_eq!(published_count(&relay), 2); + } + } + + #[tokio::test] + async fn an_edit_beats_the_entry_it_replaces_and_follows_the_head() { + let (client, relay) = setup().await; + let future = now().as_secs() + 1_000; + // An entry from a clock ahead of ours, a mobile-shaped entry, and one + // desktop would drop. + seed( + &client, + &relay, + &STARS, + json!({"version": 1.0, "channels": { + C1: {"starred": false, "updatedAt": future}, + C2: {"starred": true, "updatedAt": 5}, + C3: {"starred": "yes", "updatedAt": 5}, + "no-time": {"starred": true}, + "negative": {"starred": true, "updatedAt": -1}, + }}), + future, + ); + run(&STARS, set(&[C1], true), &client).await.unwrap(); + let (event, doc) = published(&client, &relay); + assert_eq!(event.created_at.as_secs(), future + 1); + assert_eq!(doc["channels"][C1]["updatedAt"], json!(future + 1)); + assert_eq!(doc["channels"][C2]["updatedAt"], json!(5)); + assert_eq!(doc["channels"].as_object().unwrap().len(), 2); + } + + #[tokio::test] + async fn refuses_an_unreadable_head_and_a_dominated_write() { + for doc in [ + json!({"version": 2, "channels": {}}), + json!(["not", "a", "store"]), + json!("text"), + ] { + let (client, relay) = setup().await; + seed(&client, &relay, &STARS, doc, 10); + assert!(run(&STARS, Action::List, &client).await.is_err()); + assert!(run(&STARS, set(&[C1], true), &client).await.is_err()); + assert_eq!(published_count(&relay), 1); + } + + let (client, relay) = setup().await; + let mut head = seed(&client, &relay, &MUTES, json!({"version": 1}), 10); + head["content"] = json!("tampered"); + relay.lock().unwrap().events = vec![head]; + let err = run(&MUTES, set(&[C1], true), &client).await.unwrap_err(); + assert!(matches!(err, CliError::Other(_)), "{err:?}"); + + // A head with a forged signature, or from another author, is refused + // even when the relay returns it. + let (client, relay) = setup().await; + let mut forged = seed(&client, &relay, &MUTES, json!({"version": 1}), 10); + forged["sig"] = json!("0".repeat(128)); + relay.lock().unwrap().events = vec![forged]; + relay.lock().unwrap().leaky = true; + let refused = run(&MUTES, set(&[C1], true), &client).await.unwrap_err(); + assert!( + refused.to_string().contains("fails verification"), + "{refused}" + ); + let (client, relay) = setup().await; + let other = + BuzzClient::new(String::new(), Credentials::from_keys(Keys::generate())).unwrap(); + seed(&other, &relay, &MUTES, json!({"version": 1}), 10); + relay.lock().unwrap().leaky = true; + let refused = run(&MUTES, set(&[C1], true), &client).await.unwrap_err(); + assert!( + refused.to_string().contains("fails verification"), + "{refused}" + ); + assert_eq!(published_count(&relay), 1); + + // Another author's head is never read as ours. + let (client, relay) = setup().await; + let other = + BuzzClient::new(String::new(), Credentials::from_keys(Keys::generate())).unwrap(); + seed( + &other, + &relay, + &MUTES, + json!({"version": 1, "channels": entries(1, "muted", 1)}), + 10, + ); + let list = run(&MUTES, Action::List, &client).await.unwrap(); + assert_eq!(list, json!({"channels": []})); + + relay.lock().unwrap().duplicate = true; + let err = run(&MUTES, set(&[C1], true), &client).await.unwrap_err(); + assert!(matches!(err, CliError::Conflict(_)), "{err:?}"); + } + + #[tokio::test] + async fn keeps_the_newest_500_entries() { + let (client, relay) = setup().await; + seed( + &client, + &relay, + &STARS, + json!({"version": 1, "channels": entries(500, "starred", 100)}), + 10, + ); + run(&STARS, set(&[C1], true), &client).await.unwrap(); + let (_, doc) = published(&client, &relay); + let channels = doc["channels"].as_object().unwrap(); + assert_eq!(channels.len(), 500); + assert!(channels.contains_key(C1)); + assert!(!channels.contains_key(&format!("{:036}", 0))); + assert!(channels.contains_key(&format!("{:036}", 1))); + + // A head over the cap is trimmed the way desktop trims it on read. + let (client, relay) = setup().await; + seed( + &client, + &relay, + &STARS, + json!({"version": 1, "channels": entries(520, "starred", 100)}), + 10, + ); + let list = run(&STARS, Action::List, &client).await.unwrap(); + assert_eq!(list["channels"].as_array().unwrap().len(), 500); + + // An edit that would evict its own entries is refused. + let ids: Vec = (0..501) + .map(|i| format!("ffffffff-0000-4000-8000-{i:012}")) + .collect(); + let err = run(&STARS, Action::Set { ids, on: true }, &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + assert_eq!(published_count(&relay), 1); + } + + #[tokio::test] + async fn projects_use_milliseconds_and_keep_every_entry() { + let (client, relay) = setup().await; + let address = format!("30621:{}:my-project", OWNER.to_uppercase()); + let canonical = format!("30621:{OWNER}:my-project"); + let before = now().as_millis() as u64; + run(&PROJECTS, set(&[&address], true), &client) + .await + .unwrap(); + let (event, doc) = published(&client, &relay); + assert!(event + .tags + .iter() + .any(|t| t.as_slice() == ["d", "project-sidebar-membership"])); + assert!(event + .tags + .iter() + .any(|t| t.as_slice() == ["t", "project-sidebar-membership"])); + let entry = &doc["projects"][&canonical]; + assert_eq!(entry["selected"], json!(true)); + assert!(entry["updatedAt"].as_u64().unwrap() >= before); + assert_eq!( + run(&PROJECTS, Action::List, &client).await.unwrap(), + json!({"projects": [canonical]}) + ); + let again = run(&PROJECTS, set(&[&canonical], true), &client) + .await + .unwrap(); + assert_eq!(again["message"], json!("unchanged")); + run(&PROJECTS, set(&[&canonical], false), &client) + .await + .unwrap(); + let (_, doc) = published(&client, &relay); + assert_eq!(doc["projects"][&canonical]["selected"], json!(false)); + + for bad in [ + "my-project", + &format!("30617:{OWNER}:x"), + &format!("30621:{}:x", "zz".repeat(32)), + &format!("30621:{OWNER}:"), + ] { + let err = run(&PROJECTS, set(&[bad], true), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{bad}: {err:?}"); + } + + // The legacy address array reads as selected; a document without a + // collection is unreadable rather than empty. + let (client, relay) = setup().await; + seed(&client, &relay, &PROJECTS, json!(["a:b:c", ""]), 10); + let list = run(&PROJECTS, Action::List, &client).await.unwrap(); + assert_eq!(list, json!({"projects": ["a:b:c"]})); + seed(&client, &relay, &PROJECTS, json!({"version": 1}), 20); + assert!(run(&PROJECTS, Action::List, &client).await.is_err()); + + // No eviction: 520 entries survive a write, and the size cap is an error. + let (client, relay) = setup().await; + seed( + &client, + &relay, + &PROJECTS, + json!({"version": 1, "projects": entries(520, "selected", 1)}), + 10, + ); + run(&PROJECTS, set(&[&canonical], true), &client) + .await + .unwrap(); + let (_, doc) = published(&client, &relay); + assert_eq!(doc["projects"].as_object().unwrap().len(), 521); + let (client, relay) = setup().await; + seed( + &client, + &relay, + &PROJECTS, + json!({"version": 1, "projects": entries(800, "selected", 1)}), + 10, + ); + let err = run(&PROJECTS, set(&[&canonical], true), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + assert_eq!(published_count(&relay), 1); + } +} diff --git a/crates/buzz-cli/src/commands/sidebar_sort.rs b/crates/buzz-cli/src/commands/sidebar_sort.rs new file mode 100644 index 00000000000..13635987eb2 --- /dev/null +++ b/crates/buzz-cli/src/commands/sidebar_sort.rs @@ -0,0 +1,465 @@ +//! `buzz sidebar sort` — how each sidebar group orders its channels, the same +//! synced preference the desktop sidebar edits (kind:30078, d=`channel-sort`, +//! NIP-44 encrypted to yourself). +//! +//! One register per group key, merged per field like the sections document. +//! Every write is one sort-head read and one publish; naming a section also +//! reads the sections document. Desktop never prunes the `section:` key of +//! a deleted section, so neither does this command. + +use serde_json::{json, Value}; + +use super::sidebar::{fetch_view, resolve}; +use super::sidebar_doc::{self, Edit, MAX_SORT_GROUPS, SORT}; +use super::sidebar_sync::{self, Lane}; +use crate::client::BuzzClient; +use crate::error::CliError; +use crate::{SidebarSortCmd, SidebarSortMode}; + +const LANE: Lane = Lane { + d_tag: "channel-sort", + label: "sidebar sort modes", +}; + +const FIXED_GROUPS: [&str; 4] = ["starred", "channels", "forums", "dms"]; +const SECTION_PREFIX: &str = "section:"; + +fn wire(mode: SidebarSortMode) -> &'static str { + match mode { + SidebarSortMode::Alpha => "alpha", + SidebarSortMode::Recent => "recent", + } +} + +/// The group key desktop stores for `group`. A fixed group name wins over a +/// section of the same name. Setting a mode needs a live section; resetting +/// accepts any `section:` so a deleted section's key can be cleared. +async fn group_key( + client: &BuzzClient, + group: &str, + needs_live_section: bool, +) -> Result { + let group = group.trim(); + if FIXED_GROUPS.contains(&group) { + return Ok(group.to_string()); + } + if let Some(id) = group.strip_prefix(SECTION_PREFIX) { + if id.is_empty() { + return Err(CliError::Usage("section: needs a section id".into())); + } + if needs_live_section + && !fetch_view(client) + .await? + .sections + .iter() + .any(|s| s.id == id) + { + return Err(CliError::NotFound(format!( + "no live section has the id \"{id}\"" + ))); + } + return Ok(group.to_string()); + } + let id = resolve_section(client, group).await?; + Ok(format!("{SECTION_PREFIX}{id}")) +} + +async fn resolve_section(client: &BuzzClient, key: &str) -> Result { + let view = fetch_view(client).await?; + Ok(resolve(&view, key)?.id.clone()) +} + +async fn edit( + client: &BuzzClient, + apply: impl FnOnce(&mut Edit) -> Result<(), CliError>, +) -> Result { + sidebar_sync::edit_tree( + client, + LANE, + &SORT, + |tree| { + if sidebar_doc::sort_groups(tree).len() <= MAX_SORT_GROUPS { + return Ok(()); + } + Err(CliError::Usage(format!( + "the sidebar keeps at most {MAX_SORT_GROUPS} sort modes; reset unused groups with `buzz sidebar sort reset`" + ))) + }, + |edit, _| apply(edit), + ) + .await +} + +pub(super) async fn run(cmd: SidebarSortCmd, client: &BuzzClient) -> Result { + match cmd { + SidebarSortCmd::List => { + let (_, tree) = sidebar_sync::fetch_tree(client, LANE, &SORT).await?; + Ok(json!({"default": "alpha", "groups": sidebar_doc::sort_groups(&tree)})) + } + SidebarSortCmd::Set { group, mode } => { + let key = group_key(client, &group, true).await?; + let mut response = edit(client, |edit| { + edit.set(&["g", &key], json!(wire(mode))); + Ok(()) + }) + .await?; + response["group"] = json!(key); + Ok(response) + } + SidebarSortCmd::Reset { group } => { + let key = group_key(client, &group, false).await?; + let mut response = edit(client, |edit| { + edit.clear(&["g", &key]); + Ok(()) + }) + .await?; + response["group"] = json!(key); + Ok(response) + } + } +} + +#[cfg(test)] +mod tests { + use super::super::sidebar_doc::{Stamp, Tree, SECTIONS}; + use super::super::sidebar_sync::now; + use super::super::sidebar_sync::test_support::{self, published, published_count, Shared}; + use super::*; + + const DEV: &str = "0123456789abcdef"; + const SECTIONS_LANE: Lane = Lane { + d_tag: "channel-sections", + label: "sidebar sections", + }; + + fn seed_sort(client: &BuzzClient, relay: &Shared, plaintext: &str, created_at: u64) -> Value { + test_support::seed_at(client, relay, LANE, plaintext, created_at) + } + + /// Seeds a sections document; ids are `id-`, and names listed in + /// `dead` are deleted. + fn seed_sections(client: &BuzzClient, relay: &Shared, names: &[&str], dead: &[&str]) { + let mut tree = Tree::new(); + let stamp = Stamp { + now_ms: 1, + dev: DEV.into(), + }; + let mut edit = Edit::new(&mut tree, &stamp); + for name in names { + edit.create_section(&format!("id-{name}"), name, None); + } + let mut edit = Edit::new(&mut tree, &stamp); + for name in dead { + edit.set(&["s", &format!("id-{name}"), "live"], json!(false)); + } + let plaintext = sidebar_doc::encode(&SECTIONS, &tree).to_string(); + test_support::seed_at(client, relay, SECTIONS_LANE, &plaintext, 5); + } + + fn set(group: &str, mode: SidebarSortMode) -> SidebarSortCmd { + SidebarSortCmd::Set { + group: group.into(), + mode, + } + } + + fn reset(group: &str) -> SidebarSortCmd { + SidebarSortCmd::Reset { + group: group.into(), + } + } + + fn groups(list: &Value) -> Value { + list["groups"].clone() + } + + #[tokio::test] + async fn sets_and_resets_group_sort_modes_in_desktop_format() { + let (client, relay) = test_support::setup().await; + seed_sections(&client, &relay, &["Eng", "Ops"], &[]); + assert_eq!( + run(SidebarSortCmd::List, &client).await.unwrap(), + json!({"default": "alpha", "groups": {}}) + ); + + let before = published_count(&relay); + let response = run(set("dms", SidebarSortMode::Recent), &client) + .await + .unwrap(); + assert_eq!(response["group"], json!("dms")); + assert_eq!(published_count(&relay), before + 1); + let (event, doc) = published(&client, &relay); + assert_eq!(event.kind.as_u16(), 30078); + assert!(event + .tags + .iter() + .any(|t| t.as_slice() == ["d", "channel-sort"])); + assert!(event + .tags + .iter() + .any(|t| t.as_slice() == ["t", "channel-sort"])); + assert_eq!(doc["version"], json!(1)); + assert_eq!(doc["groups"], json!({"dms": "recent"})); + assert_eq!(doc["meta"]["v"], json!(1)); + assert_eq!(doc["meta"]["g"]["dms"][2], json!("recent")); + + // A section is addressed by name, by id, or by its stored key. + let by_name = run(set("Eng", SidebarSortMode::Recent), &client) + .await + .unwrap(); + assert_eq!(by_name["group"], json!("section:id-Eng")); + run(set("section:id-Ops", SidebarSortMode::Alpha), &client) + .await + .unwrap(); + run(set(" starred ", SidebarSortMode::Recent), &client) + .await + .unwrap(); + let list = run(SidebarSortCmd::List, &client).await.unwrap(); + assert_eq!( + groups(&list), + json!({ + "dms": "recent", "starred": "recent", + "section:id-Eng": "recent", "section:id-Ops": "alpha", + }) + ); + + // A repeat publishes nothing; an explicit alpha is a real register. + let count = published_count(&relay); + let again = run(set("dms", SidebarSortMode::Recent), &client) + .await + .unwrap(); + assert_eq!(again["message"], json!("unchanged")); + assert_eq!(published_count(&relay), count); + + // A reset is a null register that every projection drops. + run(reset("dms"), &client).await.unwrap(); + let (_, doc) = published(&client, &relay); + assert_eq!(doc["meta"]["g"]["dms"][2], Value::Null); + assert!(doc["groups"].get("dms").is_none()); + let count = published_count(&relay); + for group in ["dms", "forums"] { + let response = run(reset(group), &client).await.unwrap(); + assert_eq!(response["message"], json!("unchanged"), "{group}"); + } + assert_eq!(published_count(&relay), count); + run(set("dms", SidebarSortMode::Alpha), &client) + .await + .unwrap(); + + // Bad input fails before any publish. + let count = published_count(&relay); + for (group, not_found) in [ + ("Nope", true), + ("section:", false), + ("section:missing", true), + ("section:Eng", true), + ("section: id-Eng", true), + ] { + let err = run(set(group, SidebarSortMode::Recent), &client) + .await + .unwrap_err(); + let expected = if not_found { + matches!(err, CliError::NotFound(_)) + } else { + matches!(err, CliError::Usage(_)) + }; + assert!(expected, "{group}: {err:?}"); + } + assert_eq!(published_count(&relay), count); + } + + #[tokio::test] + async fn ambiguous_section_names_are_refused() { + let (client, relay) = test_support::setup().await; + let mut tree = Tree::new(); + let stamp = Stamp { + now_ms: 1, + dev: DEV.into(), + }; + let mut edit = Edit::new(&mut tree, &stamp); + edit.create_section("a", "Same", None); + edit.create_section("b", "Same", None); + let plaintext = sidebar_doc::encode(&SECTIONS, &tree).to_string(); + test_support::seed_at(&client, &relay, SECTIONS_LANE, &plaintext, 5); + let err = run(set("Same", SidebarSortMode::Recent), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + assert_eq!(published_count(&relay), 1); + } + + #[tokio::test] + async fn a_deleted_sections_key_stays_until_reset() { + let (client, relay) = test_support::setup().await; + seed_sections(&client, &relay, &["Old"], &[]); + run(set("Old", SidebarSortMode::Recent), &client) + .await + .unwrap(); + relay + .lock() + .unwrap() + .events + .retain(|e| e["tags"][0][1] != json!("channel-sections")); + seed_sections(&client, &relay, &["Old"], &["Old"]); + + // Desktop leaves the register behind and still projects it. + let list = run(SidebarSortCmd::List, &client).await.unwrap(); + assert_eq!(groups(&list), json!({"section:id-Old": "recent"})); + let err = run(set("section:id-Old", SidebarSortMode::Alpha), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::NotFound(_)), "{err:?}"); + let err = run(set("Old", SidebarSortMode::Alpha), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::NotFound(_)), "{err:?}"); + + run(reset("section:id-Old"), &client).await.unwrap(); + let list = run(SidebarSortCmd::List, &client).await.unwrap(); + assert_eq!(groups(&list), json!({})); + } + + #[tokio::test] + async fn keeps_a_mobile_head_and_never_overwrites_an_unreadable_one() { + let (client, relay) = test_support::setup().await; + seed_sort( + &client, + &relay, + r#"{"version":1,"groups":{"dms":"recent","stale":"alpha","bad":"newest"}}"#, + now().as_secs(), + ); + let list = run(SidebarSortCmd::List, &client).await.unwrap(); + assert_eq!(groups(&list), json!({"dms": "recent", "stale": "alpha"})); + run(set("forums", SidebarSortMode::Recent), &client) + .await + .unwrap(); + let (_, doc) = published(&client, &relay); + assert_eq!( + doc["groups"], + json!({"dms": "recent", "forums": "recent", "stale": "alpha"}) + ); + + seed_sort( + &client, + &relay, + r#"{"version":1,"meta":{"v":2}}"#, + now().as_secs() + 100, + ); + let count = published_count(&relay); + assert!(run(SidebarSortCmd::List, &client).await.is_err()); + assert!(run(set("dms", SidebarSortMode::Alpha), &client) + .await + .is_err()); + assert!(run(reset("dms"), &client).await.is_err()); + assert_eq!(published_count(&relay), count); + + // An unreadable sections document blocks only a section lookup. + relay.lock().unwrap().events.clear(); + test_support::seed_at( + &client, + &relay, + SECTIONS_LANE, + r#"{"version":1,"meta":{"v":2}}"#, + 5, + ); + assert!(run(set("Eng", SidebarSortMode::Recent), &client) + .await + .is_err()); + run(set("dms", SidebarSortMode::Recent), &client) + .await + .unwrap(); + } + + #[tokio::test] + async fn an_edit_is_newer_than_the_head_and_its_registers() { + let (client, relay) = test_support::setup().await; + let future = now().as_secs() + 1_000; + let far_v = (future as i64 + 5_000) * 1_000; + let doc = json!({ + "version": 1, "groups": {"dms": "recent"}, + "meta": {"v": 1, "g": {"dms": [far_v, DEV, "recent"]}}, + }); + seed_sort(&client, &relay, &doc.to_string(), future); + + run(set("dms", SidebarSortMode::Alpha), &client) + .await + .unwrap(); + let (event, doc) = published(&client, &relay); + assert_eq!(event.created_at.as_secs(), future + 1); + assert_eq!(doc["meta"]["g"]["dms"][0], json!(far_v + 1)); + + // Another author's head is never read as ours. + let other = BuzzClient::new( + String::new(), + crate::credentials::Credentials::from_keys(nostr::Keys::generate()), + ) + .unwrap(); + seed_sort( + &other, + &relay, + r#"{"version":1,"groups":{"dms":"recent"}}"#, + future + 9, + ); + let list = run(SidebarSortCmd::List, &client).await.unwrap(); + assert_eq!(groups(&list), json!({"dms": "alpha"})); + } + + #[tokio::test] + async fn enforces_the_group_cap_and_refuses_bad_heads() { + let (client, relay) = test_support::setup().await; + let full: Value = (0..MAX_SORT_GROUPS) + .map(|i| (format!("section:{i}"), json!("recent"))) + .collect::>() + .into(); + seed_sort( + &client, + &relay, + &json!({"version": 1, "groups": full}).to_string(), + now().as_secs(), + ); + let count = published_count(&relay); + let err = run(set("dms", SidebarSortMode::Recent), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + assert_eq!(published_count(&relay), count); + + // Resetting a stale key makes room; a change at the cap still works. + run(reset("section:0"), &client).await.unwrap(); + run(set("dms", SidebarSortMode::Recent), &client) + .await + .unwrap(); + assert_eq!(published_count(&relay), count + 2); + + let mut head = test_support::seed_at( + &client, + &relay, + LANE, + r#"{"version":1,"groups":{}}"#, + now().as_secs() + 50, + ); + head["content"] = json!("tampered"); + relay + .lock() + .unwrap() + .events + .retain(|e| e["tags"][0][1] != json!("channel-sort")); + relay.lock().unwrap().events.push(head); + let count = published_count(&relay); + let err = run(set("dms", SidebarSortMode::Recent), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Other(_)), "{err:?}"); + assert_eq!(published_count(&relay), count); + } + + #[tokio::test] + async fn a_dominated_write_is_a_conflict() { + let (client, relay) = test_support::setup().await; + relay.lock().unwrap().duplicate = true; + let err = run(set("dms", SidebarSortMode::Recent), &client) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Conflict(_)), "{err:?}"); + } +} diff --git a/crates/buzz-cli/src/commands/sidebar_sync.rs b/crates/buzz-cli/src/commands/sidebar_sync.rs new file mode 100644 index 00000000000..1a43885354f --- /dev/null +++ b/crates/buzz-cli/src/commands/sidebar_sync.rs @@ -0,0 +1,348 @@ +//! Read and write path shared by every synced sidebar document (kind:30078, +//! NIP-44 encrypted to yourself): one verified head read, one signed publish. + +use std::time::SystemTime; + +use buzz_core::kind::KIND_READ_STATE; +use nostr::{EventBuilder, Kind, Tag, Timestamp}; +use serde_json::{json, Value}; + +use super::parse_write_response; +use super::sidebar_doc::{self, Codec, Edit, Stamp, Tree}; +use crate::client::BuzzClient; +use crate::error::CliError; + +/// Relay event size ceiling shared with desktop's sidebar blobs. +const MAX_CIPHERTEXT_BYTES: usize = 65_535; + +/// One synced document: its `d` tag and the name used in messages. +#[derive(Clone, Copy)] +pub(crate) struct Lane { + pub d_tag: &'static str, + pub label: &'static str, +} + +/// The decoded head. `doc` is `None` when the relay holds no event yet. +pub(crate) struct Head { + pub created_at: u64, + pub doc: Option, +} + +pub(crate) fn now() -> std::time::Duration { + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap_or_default() +} + +/// Channel ids in the lowercase hyphenated form desktop keys entries by. +pub(crate) fn channel_ids(channels: &[String]) -> Result, CliError> { + channels + .iter() + .map(|channel| { + uuid::Uuid::parse_str(channel.trim()) + .map(|id| id.hyphenated().to_string()) + .map_err(|_| CliError::Usage(format!("invalid channel UUID: {channel}"))) + }) + .collect() +} + +/// The relay's current verified `lane` event for this identity, read from the +/// writer. `None` when the relay holds none; an error when it returns only +/// events that are not yours or fail verification. +async fn head_event(client: &BuzzClient, lane: Lane) -> Result, CliError> { + let me = client.public_key(); + let filter = json!({ + "kinds": [KIND_READ_STATE], + "authors": [me.to_hex()], + "#d": [lane.d_tag], + "limit": 1, + "consistency": "strong", + }); + let raw = client.query(&filter).await?; + let events: Vec = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("failed to parse {} query: {e}", lane.label)))?; + let returned = events.len(); + let head = events + .into_iter() + .filter_map(|event| serde_json::from_value::(event).ok()) + .filter(|event| { + event.pubkey == me + && event.tags.identifier() == Some(lane.d_tag) + && event.verify().is_ok() + }) + .min_by(|a, b| { + b.created_at + .cmp(&a.created_at) + .then_with(|| a.id.to_hex().cmp(&b.id.to_hex())) + }); + if head.is_none() && returned > 0 { + return Err(CliError::Other(format!( + "the relay returned a {} event that is not yours or fails verification; refusing to overwrite it", + lane.label + ))); + } + Ok(head) +} + +/// The relay's current event for `lane` and this identity, decrypted and +/// passed to `decode` with the event's `created_at`. An absent head is +/// `doc: None`; an unreadable one is an error, never an empty document. The +/// read is pinned to the writer (`consistency: strong`): a write derives a +/// full snapshot from it, and a lagging replica would drop the caller's own +/// just-accepted edits. +pub(crate) async fn fetch_head( + client: &BuzzClient, + lane: Lane, + decode: impl FnOnce(&Value, u64) -> Option, +) -> Result, CliError> { + let Some(event) = head_event(client, lane).await? else { + return Ok(Head { + created_at: 0, + doc: None, + }); + }; + let me = client.public_key(); + let unreadable = |detail: String| { + CliError::Other(format!( + "your {} event {} is unreadable ({detail}); refusing to read or overwrite it", + lane.label, + event.id.to_hex() + )) + }; + let plaintext = client + .credentials() + .nip44_decrypt(&me, &event.content) + .await? + .ok_or_else(|| unreadable("not valid ciphertext for this key".into()))?; + let json: Value = serde_json::from_str(&plaintext).map_err(|e| unreadable(e.to_string()))?; + let created_at = event.created_at.as_secs(); + let doc = decode(&json, created_at).ok_or_else(|| { + unreadable("unsupported format; a newer client may have written it".into()) + })?; + Ok(Head { + created_at, + doc: Some(doc), + }) +} + +/// Encrypts `plaintext` to yourself and publishes it as the new head, one +/// second after `head_created_at` at the earliest. A relay `duplicate:` reply +/// is a conflict unless the head is this event: `submit_event` retries an +/// ambiguous attempt with the same signed event, which the relay then reports +/// as a duplicate of the copy it already stored. +pub(crate) async fn publish( + client: &BuzzClient, + lane: Lane, + plaintext: String, + head_created_at: u64, +) -> Result { + let me = client.public_key(); + let too_large = || { + CliError::Usage(format!( + "{} would exceed the relay's event size limit", + lane.label + )) + }; + // NIP-44 rejects longer plaintexts outright. + if plaintext.len() > u16::MAX as usize { + return Err(too_large()); + } + let content = client + .credentials() + .nip44_encrypt(&me, &plaintext) + .await + .map_err(|e| CliError::Other(format!("failed to encrypt {}: {e}", lane.label)))?; + if content.len() > MAX_CIPHERTEXT_BYTES { + return Err(too_large()); + } + let created_at = now().as_secs().max(head_created_at + 1); + let builder = EventBuilder::new(Kind::Custom(KIND_READ_STATE as u16), content) + .tags([Tag::identifier(lane.d_tag), Tag::hashtag(lane.d_tag)]) + .custom_created_at(Timestamp::from(created_at)); + let event = client.sign_event(builder).await?; + let event_id = event.id; + let raw = client.submit_event(event).await?; + let normalized = match parse_write_response( + &raw, + &format!("a newer {} update won; run the command again", lane.label), + ) { + Err(CliError::Conflict(conflict)) => match head_event(client, lane).await? { + Some(head) if head.id == event_id => { + json!({"event_id": event_id.to_hex(), "accepted": true, "message": ""}).to_string() + } + _ => return Err(CliError::Conflict(conflict)), + }, + other => other?, + }; + serde_json::from_str(&normalized) + .map_err(|e| CliError::Other(format!("relay response is not JSON: {e}"))) +} + +/// The current register-tree document of `lane` and the `created_at` of its +/// head; an absent head is an empty tree at `created_at` 0. +pub(crate) async fn fetch_tree( + client: &BuzzClient, + lane: Lane, + codec: &Codec, +) -> Result<(u64, Tree), CliError> { + let head = fetch_head(client, lane, |json, created_at| { + let legacy_v = i64::try_from(created_at.saturating_mul(1_000)).unwrap_or(i64::MAX); + sidebar_doc::decode(codec, json, legacy_v) + }) + .await?; + Ok((head.created_at, head.doc.unwrap_or_default())) +} + +/// Reads the head tree, applies `apply` (which sees the unedited head), and +/// publishes the result once. `check` rejects an edited tree over the +/// document's limits. Returns the write response, or an `unchanged` response +/// without publishing. +pub(crate) async fn edit_tree( + client: &BuzzClient, + lane: Lane, + codec: &Codec, + check: impl FnOnce(&Tree) -> Result<(), CliError>, + apply: impl FnOnce(&mut Edit, &Tree) -> Result<(), CliError>, +) -> Result { + let (head_created_at, head) = fetch_tree(client, lane, codec).await?; + let mut tree = head.clone(); + let stamp = Stamp { + now_ms: i64::try_from(now().as_millis()).unwrap_or(i64::MAX), + dev: format!("{:016x}", rand::random::()), + }; + apply(&mut Edit::new(&mut tree, &stamp), &head)?; + if tree == head { + return Ok(unchanged()); + } + check(&tree)?; + let plaintext = serde_json::to_string(&sidebar_doc::encode(codec, &tree)) + .map_err(|e| CliError::Other(format!("failed to encode {}: {e}", lane.label)))?; + publish(client, lane, plaintext, head_created_at).await +} + +/// The response of a command that changed nothing and published nothing. +pub(crate) fn unchanged() -> Value { + json!({"event_id": null, "accepted": true, "message": "unchanged"}) +} + +/// Shared fake relay and signing helpers for the sidebar command tests. +#[cfg(test)] +pub(crate) mod test_support { + use super::*; + use crate::credentials::Credentials; + use axum::{body::Bytes, extract::State, routing::post, Json, Router}; + use nostr::nips::nip44; + use nostr::Keys; + use std::sync::{Arc, Mutex}; + use tokio::net::TcpListener; + + #[derive(Default)] + pub struct Relay { + pub events: Vec, + pub duplicate: bool, + /// Store the event but answer `duplicate:`, as the relay answers a + /// retry of an attempt it already stored. + pub stored_duplicate: bool, + /// Answer every query with all stored events, whoever authored them. + pub leaky: bool, + } + pub type Shared = Arc>; + + /// Fake relay: `/query` checks the head filter and returns every stored + /// event matching its author and requested d-tag (more than the relay's + /// `limit`, so head selection is exercised); `/events` stores one. + async fn fake_relay(relay: Shared) -> String { + let app = Router::new() + .route( + "/query", + post(|State(relay): State, body: Bytes| async move { + let filters: Vec = serde_json::from_slice(&body).unwrap(); + let [filter] = filters.as_slice() else { + panic!("one filter expected: {filters:?}") + }; + assert_eq!(filter["kinds"], json!([KIND_READ_STATE])); + assert_eq!(filter["limit"], json!(1)); + assert_eq!(filter["consistency"], json!("strong")); + let author = &filter["authors"][0]; + let d_tag = &filter["#d"][0]; + let relay = relay.lock().unwrap(); + let matching: Vec<_> = relay + .events + .iter() + .filter(|e| { + relay.leaky || (&e["pubkey"] == author && &e["tags"][0][1] == d_tag) + }) + .cloned() + .collect(); + Json(json!(matching)) + }), + ) + .route( + "/events", + post(|State(relay): State, body: Bytes| async move { + let event: Value = serde_json::from_slice(&body).unwrap(); + let mut relay = relay.lock().unwrap(); + let message = if relay.duplicate || relay.stored_duplicate { + "duplicate:" + } else { + "" + }; + if !relay.duplicate { + relay.events.push(event.clone()); + } + Json(json!({"event_id": event["id"], "accepted": true, "message": message})) + }), + ) + .with_state(relay); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + pub async fn setup() -> (BuzzClient, Shared) { + let relay = Shared::default(); + let url = fake_relay(relay.clone()).await; + let client = BuzzClient::new(url, Credentials::from_keys(Keys::generate())).unwrap(); + (client, relay) + } + + pub fn seed_at( + client: &BuzzClient, + relay: &Shared, + lane: Lane, + plaintext: &str, + created_at: u64, + ) -> Value { + let keys = client.credentials().test_keys(); + let content = nip44::encrypt( + keys.secret_key(), + &keys.public_key(), + plaintext, + nip44::Version::V2, + ) + .unwrap(); + let event = EventBuilder::new(Kind::Custom(KIND_READ_STATE as u16), content) + .tags([Tag::identifier(lane.d_tag)]) + .custom_created_at(Timestamp::from(created_at)) + .sign_with_keys(&keys) + .unwrap(); + let event = serde_json::to_value(event).unwrap(); + relay.lock().unwrap().events.push(event.clone()); + event + } + + /// The decrypted document of the newest published event. + pub fn published(client: &BuzzClient, relay: &Shared) -> (nostr::Event, Value) { + let raw = relay.lock().unwrap().events.last().cloned().unwrap(); + let event: nostr::Event = serde_json::from_value(raw).unwrap(); + let keys = client.credentials().test_keys(); + let plaintext = + nip44::decrypt(keys.secret_key(), &keys.public_key(), &event.content).unwrap(); + (event, serde_json::from_str(&plaintext).unwrap()) + } + + pub fn published_count(relay: &Shared) -> usize { + relay.lock().unwrap().events.len() + } +} diff --git a/crates/buzz-cli/src/commands/social.rs b/crates/buzz-cli/src/commands/social.rs index 89c028a8ae3..e6db415b13f 100644 --- a/crates/buzz-cli/src/commands/social.rs +++ b/crates/buzz-cli/src/commands/social.rs @@ -33,7 +33,7 @@ pub async fn cmd_publish_note( let builder = buzz_sdk::build_note(content, reply_id) .map_err(|e| CliError::Other(format!("build error: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -61,7 +61,7 @@ pub async fn cmd_set_contact_list( let builder = buzz_sdk::build_contact_list(&contacts) .map_err(|e| CliError::Other(format!("build error: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -175,7 +175,7 @@ pub async fn cmd_set_list( } let builder = EventBuilder::new(Kind::Custom(kind), content).tags(tags); - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{resp}"); Ok(()) diff --git a/crates/buzz-cli/src/commands/users.rs b/crates/buzz-cli/src/commands/users.rs index 165de6185ac..4b5a895a639 100644 --- a/crates/buzz-cli/src/commands/users.rs +++ b/crates/buzz-cli/src/commands/users.rs @@ -39,7 +39,7 @@ pub async fn cmd_get_users( return Err(CliError::Usage("--pubkey: maximum 200 pubkeys".into())); } - let my_pk = client.keys().public_key().to_hex(); + let my_pk = client.public_key().to_hex(); let authors: Vec<&str> = if pubkeys.is_empty() { vec![my_pk.as_str()] } else { @@ -89,7 +89,7 @@ pub async fn cmd_get_users( fn effective_owner(client: &BuzzClient) -> String { client .auth_tag_owner_hex() - .unwrap_or_else(|| client.keys().public_key().to_hex()) + .unwrap_or_else(|| client.public_key().to_hex()) } fn resolve_owner(client: &BuzzClient, owner: Option<&str>) -> Result, CliError> { @@ -419,7 +419,7 @@ pub async fn cmd_set_profile( ) .map_err(|e| CliError::Other(format!("build_profile failed: {e}")))?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -431,7 +431,7 @@ pub async fn cmd_set_profile( async fn fetch_current_profile( client: &BuzzClient, ) -> Result, CliError> { - let my_pk = client.keys().public_key().to_hex(); + let my_pk = client.public_key().to_hex(); let filter = serde_json::json!({ "kinds": [0], "authors": [my_pk], @@ -510,26 +510,217 @@ pub(crate) fn presence_subject(event: &serde_json::Value) -> &str { /// publishes the event directly — bypassing the HTTP bridge. pub async fn cmd_set_presence(client: &BuzzClient, status: &str) -> Result<(), CliError> { let builder = buzz_sdk::build_presence_update(status).map_err(crate::validate::sdk_err)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.publish_ephemeral_event(event).await?; println!("{}", normalize_write_response(&resp)); Ok(()) } -/// Set user status — sign and submit a NIP-38 kind:30315 user status event. +/// Seconds in each `--expires` duration unit. +fn expiry_unit_secs(unit: char) -> Option { + match unit { + 's' => Some(1), + 'm' => Some(60), + 'h' => Some(3_600), + 'd' => Some(86_400), + 'w' => Some(604_800), + _ => None, + } +} + +/// Resolve `--expires` to an absolute unix time that is after `now`. +/// +/// A bare integer is a unix timestamp; an integer with an `s`, `m`, `h`, `d`, +/// or `w` suffix is a duration from `now`. +fn parse_expiry(value: &str, now: u64) -> Result { + let value = value.trim(); + let bad = || { + CliError::Usage(format!( + "--expires must be a unix timestamp or a duration like 30m, 2h, 1d (got: {value})" + )) + }; + let split = value + .char_indices() + .find(|(_, c)| !c.is_ascii_digit()) + .map_or(value.len(), |(i, _)| i); + let (digits, unit) = value.split_at(split); + let number: u64 = digits.parse().map_err(|_| bad())?; + let expires_at = match unit { + "" => number, + _ => { + let mut chars = unit.chars(); + let secs = chars.next().and_then(expiry_unit_secs).ok_or_else(bad)?; + if chars.next().is_some() { + return Err(bad()); + } + number + .checked_mul(secs) + .and_then(|delta| now.checked_add(delta)) + .ok_or_else(bad)? + } + }; + if expires_at <= now { + return Err(CliError::Usage(format!( + "--expires must be in the future (got {expires_at}, now is {now}); a bare number is a unix timestamp, so add a unit such as 1h for a duration" + ))); + } + Ok(expires_at) +} + +fn now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +/// Sign and submit a NIP-38 kind:30315 user status event. /// /// Uses the `d:general` coordinate that the desktop client reads for the /// profile status line. A blank `text` with no `emoji` clears the status. +/// `expires` is validated before anything is signed. +async fn publish_status( + client: &BuzzClient, + text: &str, + emoji: Option<&str>, + expires: Option<&str>, + now: u64, +) -> Result { + let expires_at = expires.map(|value| parse_expiry(value, now)).transpose()?; + let builder = buzz_sdk::build_user_status_expiring(text, emoji, expires_at) + .map_err(crate::validate::sdk_err)?; + let event = client.sign_event(builder).await?; + let resp = client.submit_event(event).await?; + Ok(normalize_write_response(&resp)) +} + +/// Set user status and print the write response. pub async fn cmd_set_status( client: &BuzzClient, text: &str, emoji: Option<&str>, + expires: Option<&str>, ) -> Result<(), CliError> { - let builder = buzz_sdk::build_user_status(text, emoji).map_err(crate::validate::sdk_err)?; - let event = client.sign_event(builder)?; - let resp = client.submit_event(event).await?; - println!("{}", normalize_write_response(&resp)); + println!( + "{}", + publish_status(client, text, emoji, expires, now_secs()).await? + ); + Ok(()) +} + +/// Most pubkeys one `users status` call reads; each name costs a profile search. +const MAX_STATUS_PUBKEYS: usize = 100; + +/// Desktop's `parseUserStatusEvent` reads `expiration` with `parseInt`: an +/// optional sign and leading digits, ignoring any trailing text. +fn parse_expiration_tag(value: &str) -> Option { + let value = value.trim_start(); + let unsigned = value.strip_prefix(['+', '-']).unwrap_or(value); + let digits = unsigned + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(unsigned.len()); + let end = value.len() - unsigned.len() + digits; + value[..end].parse().ok() +} + +fn tag_value<'a>(event: &'a serde_json::Value, name: &str) -> Option<&'a str> { + event + .get("tags")? + .as_array()? + .iter() + .filter_map(|tag| tag.as_array()) + .find(|tag| tag.len() >= 2 && tag[0].as_str() == Some(name)) + .and_then(|tag| tag[1].as_str()) +} + +/// The visible status per requested author, in request order. The newest +/// event per author wins, as on desktop (higher `created_at`, then lower id); +/// a newest event that is empty or expired hides the author, and an older +/// status never resurfaces behind it. +fn visible_statuses( + events: &[serde_json::Value], + authors: &[String], + now: u64, +) -> Vec { + fn key(event: &serde_json::Value) -> (u64, &str) { + ( + event + .get("created_at") + .and_then(|v| v.as_u64()) + .unwrap_or(0), + event.get("id").and_then(|v| v.as_str()).unwrap_or(""), + ) + } + authors + .iter() + .filter_map(|author| { + let event = events + .iter() + .filter(|e| { + e.get("pubkey").and_then(|v| v.as_str()) == Some(author.as_str()) + && tag_value(e, "d") == Some("general") + }) + .min_by(|a, b| { + let (a_at, a_id) = key(a); + let (b_at, b_id) = key(b); + b_at.cmp(&a_at).then_with(|| a_id.cmp(b_id)) + })?; + let text = event.get("content").and_then(|v| v.as_str()).unwrap_or(""); + let emoji = tag_value(event, "emoji").unwrap_or(""); + let expires_at = tag_value(event, "expiration").and_then(parse_expiration_tag); + let expired = expires_at.is_some_and(|at| at <= now as i64); + if (text.is_empty() && emoji.is_empty()) || expired { + return None; + } + Some(serde_json::json!({ + "pubkey": author, + "text": text, + "emoji": emoji, + "expires_at": expires_at, + "updated_at": key(event).0, + })) + }) + .collect() +} + +/// Read the visible `d:general` statuses for `pubkeys` (default: you). +async fn read_statuses( + client: &BuzzClient, + pubkeys: &[String], + now: u64, +) -> Result, CliError> { + if pubkeys.len() > MAX_STATUS_PUBKEYS { + return Err(CliError::Usage(format!( + "--pubkey: maximum {MAX_STATUS_PUBKEYS} pubkeys" + ))); + } + let mut authors: Vec = Vec::new(); + for pubkey in pubkeys { + let resolved = crate::commands::messages::resolve_author(client, pubkey).await?; + if !authors.contains(&resolved) { + authors.push(resolved); + } + } + if authors.is_empty() { + authors.push(client.public_key().to_hex()); + } + let filter = serde_json::json!({ + "kinds": [buzz_core::kind::KIND_USER_STATUS], + "authors": authors, + "#d": ["general"], + "limit": authors.len(), + }); + let raw = client.query(&filter).await?; + let events: Vec = serde_json::from_str(&raw) + .map_err(|e| CliError::Other(format!("failed to parse status query: {e}")))?; + Ok(visible_statuses(&events, &authors, now)) +} + +/// Print the visible statuses for `pubkeys` as a JSON array. +pub async fn cmd_get_status(client: &BuzzClient, pubkeys: &[String]) -> Result<(), CliError> { + let statuses = read_statuses(client, pubkeys, now_secs()).await?; + println!("{}", serde_json::Value::Array(statuses)); Ok(()) } @@ -562,7 +753,12 @@ pub async fn dispatch( } UsersCmd::Presence { pubkeys } => cmd_get_presence(client, &pubkeys).await, UsersCmd::SetPresence { status } => cmd_set_presence(client, &status.to_string()).await, - UsersCmd::SetStatus { text, emoji, clear } => { + UsersCmd::SetStatus { + text, + emoji, + clear, + expires, + } => { // `--clear` is mutually exclusive with `--text`/`--emoji`: publish the // empty `d:general` event that clients read as "no status". let (text, emoji) = if clear { @@ -570,8 +766,9 @@ pub async fn dispatch( } else { (text.as_deref().unwrap_or_default(), emoji.as_deref()) }; - cmd_set_status(client, text, emoji).await + cmd_set_status(client, text, emoji, expires.as_deref()).await } + UsersCmd::Status { pubkeys } => cmd_get_status(client, &pubkeys).await, } } @@ -579,10 +776,389 @@ pub async fn dispatch( mod tests { use super::{ owned_agent_pubkeys_from_events, owner_scoped_profiles, owner_verification, - presence_subject, + parse_expiration_tag, parse_expiry, presence_subject, publish_status, read_statuses, }; - use nostr::Keys; - use serde_json::json; + use crate::client::BuzzClient; + use crate::error::CliError; + use axum::{body::Bytes, extract::State, routing::post, Json, Router}; + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + use serde_json::{json, Value}; + use std::sync::{Arc, Mutex}; + use tokio::net::TcpListener; + + const NOW: u64 = 1_800_000_000; + + #[derive(Default)] + struct Relay { + events: Vec, + queries: Vec, + raw_query_response: Option, + } + type Shared = Arc>; + + /// Fake relay: `/query` records the filter and returns stored events of the + /// requested kind and authors (kind 0 also honors `search`); `/events` + /// stores one. + async fn fake_relay(relay: Shared) -> String { + let app = Router::new() + .route( + "/query", + post(|State(relay): State, body: Bytes| async move { + let filters: Vec = serde_json::from_slice(&body).unwrap(); + let [filter] = filters.as_slice() else { + panic!("one filter expected: {filters:?}") + }; + let mut relay = relay.lock().unwrap(); + relay.queries.push(filter.clone()); + if let Some(raw) = relay.raw_query_response.clone() { + return raw; + } + let kind = &filter["kinds"][0]; + let matching: Vec = relay + .events + .iter() + .filter(|e| &e["kind"] == kind) + .filter(|e| match filter.get("authors") { + Some(authors) => authors.as_array().unwrap().contains(&e["pubkey"]), + None => true, + }) + .filter(|e| match filter.get("search").and_then(|s| s.as_str()) { + Some(q) => e["content"] + .as_str() + .unwrap() + .to_lowercase() + .contains(&q.to_lowercase()), + None => true, + }) + .cloned() + .collect(); + serde_json::to_string(&matching).unwrap() + }), + ) + .route( + "/events", + post(|State(relay): State, body: Bytes| async move { + let event: Value = serde_json::from_slice(&body).unwrap(); + relay.lock().unwrap().events.push(event.clone()); + Json(json!({"event_id": event["id"], "accepted": true, "message": ""})) + }), + ) + .with_state(relay); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") + } + + async fn setup() -> (BuzzClient, Shared) { + let relay = Shared::default(); + let url = fake_relay(relay.clone()).await; + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); + (client, relay) + } + + fn seed(relay: &Shared, keys: &Keys, kind: u16, content: &str, tags: Vec>, at: u64) { + let tags: Vec = tags.into_iter().map(|t| Tag::parse(t).unwrap()).collect(); + let event = EventBuilder::new(Kind::Custom(kind), content) + .tags(tags) + .custom_created_at(Timestamp::from(at)) + .sign_with_keys(keys) + .unwrap(); + relay + .lock() + .unwrap() + .events + .push(serde_json::to_value(event).unwrap()); + } + + fn seed_status(relay: &Shared, keys: &Keys, text: &str, extra: Vec>, at: u64) { + let mut tags = vec![vec!["d", "general"]]; + tags.extend(extra); + seed(relay, keys, 30315, text, tags, at); + } + + fn event_count(relay: &Shared) -> usize { + relay.lock().unwrap().events.len() + } + + fn last_tags(relay: &Shared) -> Vec> { + let event = relay.lock().unwrap().events.last().cloned().unwrap(); + serde_json::from_value(event["tags"].clone()).unwrap() + } + + #[tokio::test] + async fn set_status_publishes_one_expiring_event_and_rejects_bad_expiry_before_signing() { + let (client, relay) = setup().await; + let resp = publish_status(&client, "lunch", Some("🥪"), Some("30m"), NOW) + .await + .unwrap(); + assert_eq!( + serde_json::from_str::(&resp).unwrap()["accepted"], + true + ); + assert_eq!(event_count(&relay), 1); + assert_eq!( + last_tags(&relay), + vec![ + vec!["d", "general"], + vec!["emoji", "🥪"], + vec!["expiration", &(NOW + 1_800).to_string()], + ] + ); + + publish_status(&client, "later", None, Some(&(NOW + 5).to_string()), NOW) + .await + .unwrap(); + assert_eq!( + last_tags(&relay).last().unwrap(), + &vec!["expiration".to_string(), (NOW + 5).to_string()] + ); + + publish_status(&client, "no expiry", None, None, NOW) + .await + .unwrap(); + assert_eq!(last_tags(&relay), vec![vec!["d", "general"]]); + + let published = event_count(&relay); + for expires in [ + &NOW.to_string(), + "0", + "1700000000", + "0m", + "soon", + "", + "1x", + "1hh", + "-5m", + "99999999999999999999d", + "999999999999999d", + ] { + let err = publish_status(&client, "x", None, Some(expires), NOW) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{expires}: {err:?}"); + } + let err = publish_status(&client, "", None, Some("1h"), NOW) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + assert_eq!(event_count(&relay), published); + } + + #[test] + fn expiry_parses_timestamps_and_durations() { + for (input, expected) in [ + ("30s", NOW + 30), + ("30m", NOW + 1_800), + ("2h", NOW + 7_200), + ("1d", NOW + 86_400), + (" 1w ", NOW + 604_800), + ("1800000001", 1_800_000_001), + ] { + assert_eq!(parse_expiry(input, NOW).unwrap(), expected, "{input}"); + } + } + + #[test] + fn expiration_tag_reads_like_desktop_parse_int() { + for (input, expected) in [ + ("1800000060", Some(1_800_000_060)), + (" 42", Some(42)), + ("+42", Some(42)), + ("-5", Some(-5)), + ("90abc", Some(90)), + ("abc", None), + ("", None), + ("-", None), + ] { + assert_eq!(parse_expiration_tag(input), expected, "{input:?}"); + } + } + + #[tokio::test] + async fn status_read_hides_expired_and_cleared_and_reports_the_rest() { + let (client, relay) = setup().await; + let me = client.credentials().test_keys(); + let (expired, cleared, emoji_only, odd, timed) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + let silent = Keys::generate(); + seed_status(&relay, &me, "writing docs", vec![vec!["emoji", "📝"]], 100); + seed_status( + &relay, + &expired, + "gone", + vec![vec!["expiration", &NOW.to_string()]], + 100, + ); + seed_status(&relay, &cleared, "old text", vec![], 100); + seed_status(&relay, &cleared, "", vec![], 200); + seed_status(&relay, &emoji_only, "", vec![vec!["emoji", "🎧"]], 100); + seed_status(&relay, &odd, "odd", vec![vec!["expiration", "soon"]], 100); + seed_status( + &relay, + &timed, + "back soon", + vec![vec!["expiration", &format!("{}xyz", NOW + 60)]], + 100, + ); + // Wrong coordinate and wrong kind are not statuses. + seed( + &relay, + &silent, + 30315, + "music", + vec![vec!["d", "music"]], + 100, + ); + seed(&relay, &silent, 1, "note", vec![vec!["d", "general"]], 100); + + let pubkeys: Vec = [&expired, &cleared, &emoji_only, &odd, &timed, &silent] + .iter() + .map(|k| k.public_key().to_hex()) + .collect(); + let statuses = read_statuses(&client, &pubkeys, NOW).await.unwrap(); + assert_eq!( + statuses, + vec![ + json!({"pubkey": pubkeys[2], "text": "", "emoji": "🎧", "expires_at": null, "updated_at": 100}), + json!({"pubkey": pubkeys[3], "text": "odd", "emoji": "", "expires_at": null, "updated_at": 100}), + json!({"pubkey": pubkeys[4], "text": "back soon", "emoji": "", "expires_at": NOW + 60, "updated_at": 100}), + ] + ); + + let filter = relay.lock().unwrap().queries.last().cloned().unwrap(); + assert_eq!(filter["kinds"], json!([30315])); + assert_eq!(filter["#d"], json!(["general"])); + assert_eq!(filter["limit"], json!(6)); + + // Default author is the caller. + let own = read_statuses(&client, &[], NOW).await.unwrap(); + assert_eq!( + own, + vec![json!({ + "pubkey": me.public_key().to_hex(), + "text": "writing docs", + "emoji": "📝", + "expires_at": null, + "updated_at": 100, + })] + ); + // The same status is hidden once its expiry passes. + seed_status( + &relay, + &me, + "meeting", + vec![vec!["expiration", &(NOW + 10).to_string()]], + 300, + ); + let before = read_statuses(&client, &[], NOW).await.unwrap(); + assert_eq!(before[0]["text"], "meeting"); + assert_eq!(before[0]["expires_at"], json!(NOW + 10)); + assert!(read_statuses(&client, &[], NOW + 10) + .await + .unwrap() + .is_empty()); + } + + #[tokio::test] + async fn status_read_picks_the_newest_event_and_breaks_ties_by_lower_id() { + let (client, relay) = setup().await; + let keys = Keys::generate(); + seed_status(&relay, &keys, "older", vec![], 100); + seed_status(&relay, &keys, "tie a", vec![], 200); + seed_status(&relay, &keys, "tie b", vec![], 200); + let events = relay.lock().unwrap().events.clone(); + let winner = events[1..] + .iter() + .min_by_key(|e| e["id"].as_str().unwrap().to_string()) + .unwrap()["content"] + .clone(); + let statuses = read_statuses(&client, &[keys.public_key().to_hex()], NOW) + .await + .unwrap(); + assert_eq!(statuses.len(), 1); + assert_eq!(statuses[0]["text"], winner); + assert_eq!(statuses[0]["updated_at"], 200); + } + + #[tokio::test] + async fn status_read_resolves_npub_and_name_and_bounds_input() { + let (client, relay) = setup().await; + let by_npub = Keys::generate(); + let by_name = Keys::generate(); + seed_status(&relay, &by_npub, "via npub", vec![], 100); + seed_status(&relay, &by_name, "via name", vec![], 100); + seed( + &relay, + &by_name, + 0, + r#"{"display_name":"Honey"}"#, + vec![], + 50, + ); + let npub = nostr::ToBech32::to_bech32(&by_npub.public_key()).unwrap(); + let statuses = read_statuses( + &client, + &[ + npub, + "honey".to_string(), + by_name.public_key().to_hex().to_uppercase(), + ], + NOW, + ) + .await + .unwrap(); + let texts: Vec<&str> = statuses + .iter() + .map(|s| s["text"].as_str().unwrap()) + .collect(); + assert_eq!(texts, vec!["via npub", "via name"]); + + let err = read_statuses(&client, &["nobody".to_string()], NOW) + .await + .unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + + let queries = relay.lock().unwrap().queries.len(); + let too_many: Vec = (0..101).map(|_| by_npub.public_key().to_hex()).collect(); + let err = read_statuses(&client, &too_many, NOW).await.unwrap_err(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + assert_eq!(relay.lock().unwrap().queries.len(), queries); + } + + #[tokio::test] + async fn status_read_fails_on_an_unreadable_relay_response() { + let (client, relay) = setup().await; + relay.lock().unwrap().raw_query_response = Some("not json".into()); + let err = read_statuses(&client, &[], NOW).await.unwrap_err(); + assert!(matches!(err, CliError::Other(_)), "{err:?}"); + } + + #[tokio::test] + async fn a_published_status_reads_back_with_its_expiry() { + let (client, _relay) = setup().await; + publish_status(&client, "lunch", Some("🥪"), Some("1h"), NOW) + .await + .unwrap(); + let statuses = read_statuses(&client, &[], NOW + 60).await.unwrap(); + assert_eq!(statuses.len(), 1); + assert_eq!(statuses[0]["text"], "lunch"); + assert_eq!(statuses[0]["emoji"], "🥪"); + assert_eq!(statuses[0]["expires_at"], json!(NOW + 3_600)); + assert!(read_statuses(&client, &[], NOW + 3_600) + .await + .unwrap() + .is_empty()); + } #[test] fn owned_agent_lookup_matches_exact_name_case_insensitively() { diff --git a/crates/buzz-cli/src/commands/workflows.rs b/crates/buzz-cli/src/commands/workflows.rs index 0028dfc7663..aa0f5f047b8 100644 --- a/crates/buzz-cli/src/commands/workflows.rs +++ b/crates/buzz-cli/src/commands/workflows.rs @@ -106,7 +106,7 @@ pub async fn cmd_create_workflow( let workflow_id = uuid::Uuid::new_v4(); let builder = buzz_sdk::build_workflow_def(channel_uuid, workflow_id, &yaml_definition) .map_err(sdk_err)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; let final_workflow_id = extract_relay_response_field(&resp, "workflow_id") @@ -141,7 +141,7 @@ pub async fn cmd_update_workflow( let builder = buzz_sdk::build_workflow_update(channel_uuid, wf_uuid, &yaml_definition, expected_revision) .map_err(sdk_err)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -151,11 +151,9 @@ pub async fn cmd_update_workflow( /// Delete a workflow — sign and submit a kind:5 deletion event. pub async fn cmd_delete_workflow(client: &BuzzClient, workflow_id: &str) -> Result<(), CliError> { let wf_uuid = parse_uuid(workflow_id)?; - let keys = client.keys(); - let builder = - buzz_sdk::build_workflow_delete(&keys.public_key().to_hex(), wf_uuid).map_err(sdk_err)?; - let event = client.sign_event(builder)?; + buzz_sdk::build_workflow_delete(&client.public_key().to_hex(), wf_uuid).map_err(sdk_err)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); @@ -190,12 +188,12 @@ pub async fn cmd_trigger_workflow( &content, ) .tags(tags); - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); } else { let builder = buzz_sdk::build_workflow_trigger(wf_uuid).map_err(sdk_err)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); } @@ -217,7 +215,7 @@ pub async fn cmd_approve_step( let token_hash = hex::encode(Sha256::digest(approval_token.as_bytes())); let builder = buzz_sdk::build_workflow_approval(&token_hash, approved, content).map_err(sdk_err)?; - let event = client.sign_event(builder)?; + let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; println!("{}", normalize_write_response(&resp)); diff --git a/crates/buzz-cli/src/credentials.rs b/crates/buzz-cli/src/credentials.rs new file mode 100644 index 00000000000..c042e3b4877 --- /dev/null +++ b/crates/buzz-cli/src/credentials.rs @@ -0,0 +1,860 @@ +//! The CLI's credential chain: which identity it acts as, how it signs, and +//! which NIP-FI evidence it presents to the relay. +//! +//! Every relay request goes through [`Credentials`]. Signing and NIP-44 go +//! through a [`NostrSigner`], so a credential link never has to hand the CLI a +//! secret key. [`Credentials::evidence`] supplies the `Nostr-Federated-Identity` +//! assertion when an evidence source is configured and `None` otherwise, so one +//! code path serves relays with and without NIP-FI. +//! +//! [`resolve`] tries each link in order; the first configured link wins. An +//! explicit key (`--private-key` / `BUZZ_PRIVATE_KEY`) is the first link, so a +//! caller that chooses a key always gets that key. + +use std::sync::Arc; + +use base64::engine::general_purpose::STANDARD as B64; +use base64::Engine; +use nostr::{Event, EventBuilder, JsonUtil, Keys, NostrSigner, PublicKey, Tag, UnsignedEvent}; +use sha2::{Digest, Sha256}; + +use crate::error::CliError; +pub use crate::federated_identity::{ + AdapterSession, FEDERATED_IDENTITY_ADAPTER_ENV, FEDERATED_IDENTITY_TOKEN_ENV, +}; + +/// Raw credential settings, from flags and the environment. +#[derive(Default)] +pub struct Settings { + /// `--private-key` / `BUZZ_PRIVATE_KEY`. + pub private_key: Option, + /// `--auth-tag` / `BUZZ_AUTH_TAG` (NIP-OA owner attestation). + pub auth_tag: Option, + /// `BUZZ_FEDERATED_IDENTITY_TOKEN` (NIP-FA adapter session token). + pub federated_identity_token: Option, + /// `BUZZ_FEDERATED_IDENTITY_ADAPTER` (NIP-FA adapter base URL). + pub federated_identity_adapter: Option, +} + +impl Settings { + /// Read the evidence-source settings from the environment. Flags for the + /// session token are deliberately absent: command lines are visible to + /// other local users. + pub fn with_env_evidence(mut self) -> Self { + let non_empty = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty()); + self.federated_identity_token = non_empty(FEDERATED_IDENTITY_TOKEN_ENV); + self.federated_identity_adapter = non_empty(FEDERATED_IDENTITY_ADAPTER_ENV); + self + } +} + +/// A verified NIP-OA auth tag and its canonical JSON for the `x-auth-tag` header. +pub struct AuthTag { + pub tag: Tag, + pub json: String, +} + +/// The identity the CLI acts as for this process. +pub struct Credentials { + public_key: PublicKey, + signer: Arc, + /// Key material, present only when the link holds the key locally. + local_keys: Option, + auth_tag: Option, + evidence: Option, + /// The Buzz desktop, when it is the link that holds the key. + #[cfg(unix)] + desktop: Option>, +} + +/// Walk the credential chain for `relay_url` and return the first link that +/// applies: the explicit key, then (on Unix) the Buzz desktop through an +/// inherited or paired token. +pub async fn resolve(settings: Settings, relay_url: &str) -> Result { + if let Some(credentials) = resolve_explicit(&settings, relay_url)? { + return Ok(credentials); + } + #[cfg(unix)] + if let Some(provider) = crate::desktop_provider::discover(relay_url).await? { + if let Some(warning) = ignored_headless_settings(&settings) { + eprintln!("{warning}"); + } + return Credentials::from_desktop(provider).await; + } + #[cfg(unix)] + let paired = crate::desktop_provider::paired_relays(); + #[cfg(not(unix))] + let paired = Vec::new(); + Err(no_credentials(relay_url, &paired)) +} + +/// The error for a relay no link serves, naming it and the relays this CLI +/// is paired for, so a missing `--relay` is plain. +fn no_credentials(relay_url: &str, paired: &[String]) -> CliError { + let fix = "set BUZZ_PRIVATE_KEY, pass --private-key, or run `buzz auth desktop pair` \ + with Buzz running"; + #[cfg(unix)] + let this_one = crate::desktop_provider::provider_relay_url(relay_url) + .is_ok_and(|relay| paired.contains(&relay)); + #[cfg(not(unix))] + let this_one = false; + CliError::Auth(if paired.is_empty() { + format!("no credentials for {relay_url}: {fix}") + } else if this_one { + format!( + "no credentials for {relay_url}: this CLI is paired for it, but no running Buzz \ + desktop accepts the pairing; open Buzz and retry, or check `buzz auth desktop list`" + ) + } else { + format!( + "no credentials for {relay_url}: this CLI is paired with Buzz only for {}; pass \ + --relay (or set BUZZ_RELAY_URL) to use a pairing, or {fix}", + paired.join(", ") + ) + }) +} + +/// The explicit-key link, with its headless evidence source. Without an +/// explicit key the evidence settings are not read: they belong to that key. +fn resolve_explicit(settings: &Settings, relay_url: &str) -> Result, CliError> { + if settings.private_key.is_none() { + return Ok(None); + } + let evidence = evidence_source(settings, relay_url)?; + explicit_key(settings, evidence) +} + +/// The warning for headless evidence settings a desktop link leaves unused. +#[cfg_attr(not(unix), allow(dead_code))] +fn ignored_headless_settings(settings: &Settings) -> Option { + let ignored: Vec<&str> = [ + ( + settings.federated_identity_token.is_some(), + FEDERATED_IDENTITY_TOKEN_ENV, + ), + ( + settings.federated_identity_adapter.is_some(), + FEDERATED_IDENTITY_ADAPTER_ENV, + ), + ] + .into_iter() + .filter_map(|(set, name)| set.then_some(name)) + .collect(); + (!ignored.is_empty()).then(|| { + format!( + "warning: the Buzz desktop link supplies this identity's evidence; ignoring {} \ + (set BUZZ_PRIVATE_KEY to use them)", + ignored.join(" and ") + ) + }) +} + +/// Link 1: an explicit key from `--private-key` or `BUZZ_PRIVATE_KEY`. +fn explicit_key( + settings: &Settings, + evidence: Option, +) -> Result, CliError> { + let Some(raw) = settings.private_key.as_deref() else { + return Ok(None); + }; + let keys = + Keys::parse(raw).map_err(|e| CliError::Key(format!("invalid BUZZ_PRIVATE_KEY: {e}")))?; + let auth_tag = settings + .auth_tag + .as_deref() + .filter(|input| !input.is_empty()) + .map(|input| parse_auth_tag(input, &keys.public_key())) + .transpose()?; + Ok(Some(Credentials { + auth_tag, + evidence, + ..Credentials::from_keys(keys) + })) +} + +/// The headless NIP-FI evidence source: a NIP-FA adapter session. Both +/// settings are required together; one without the other is a configuration +/// error rather than a silent fallback to no evidence. +fn evidence_source( + settings: &Settings, + relay_url: &str, +) -> Result, CliError> { + match ( + settings.federated_identity_token.as_deref(), + settings.federated_identity_adapter.as_deref(), + ) { + (None, None) => Ok(None), + (Some(token), Some(adapter)) => AdapterSession::new(adapter, token, relay_url).map(Some), + (Some(_), None) => Err(CliError::Auth(format!( + "{FEDERATED_IDENTITY_TOKEN_ENV} is set but {FEDERATED_IDENTITY_ADAPTER_ENV} is not" + ))), + (None, Some(_)) => Err(CliError::Auth(format!( + "{FEDERATED_IDENTITY_ADAPTER_ENV} is set but {FEDERATED_IDENTITY_TOKEN_ENV} is not" + ))), + } +} + +/// Parse and verify a NIP-OA auth tag for `public_key`. +/// +/// `BUZZ_AUTH_TAG` is hand-authored configuration, so the unquoted raw +/// shorthand `[auth,hex,,hex]` is normalized to JSON here — at this input +/// edge only. The SDK grammar and the `x-auth-tag` wire format stay strict +/// JSON; all validation and signature verification happen on the strict path. +fn parse_auth_tag(input: &str, public_key: &PublicKey) -> Result { + let json = crate::normalize_auth_tag_input(input); + let tag = buzz_sdk::nip_oa::parse_auth_tag(&json) + .map_err(|e| CliError::Auth(format!("BUZZ_AUTH_TAG is malformed: {e}")))?; + buzz_sdk::nip_oa::verify_auth_tag(&json, public_key).map_err(|e| { + CliError::Auth(format!( + "BUZZ_AUTH_TAG verification failed for pubkey {}: {e}", + public_key.to_hex() + )) + })?; + // Canonical wire form derives from the parsed-and-verified tag + // (same shape as buzz-acp's RestClient), never from raw input. + let canonical = serde_json::to_string(tag.as_slice()) + .map_err(|e| CliError::Auth(format!("BUZZ_AUTH_TAG serialization failed: {e}")))?; + Ok(AuthTag { + tag, + json: canonical, + }) +} + +/// The credentials' signer for NIP-42, keeping a desktop signing failure as +/// a [`CliError`]: protocol code carries only its text, and a throttled +/// desktop must stay retryable. +#[derive(Debug)] +pub struct CapturingSigner { + signer: Arc, + #[cfg(unix)] + desktop: Option>, + failure: std::sync::Mutex)>>, +} + +impl CapturingSigner { + pub fn new(credentials: &Credentials) -> Self { + Self { + signer: credentials.signer.clone(), + #[cfg(unix)] + desktop: credentials.desktop.clone(), + failure: std::sync::Mutex::new(None), + } + } + + /// The desktop signing failure, if one happened, with how long to wait + /// before a fresh sign-in when the desktop throttled one. + pub fn take_failure(&self) -> Option<(CliError, Option)> { + self.failure.lock().ok()?.take() + } +} + +impl NostrSigner for CapturingSigner { + fn backend(&self) -> nostr::signer::SignerBackend<'_> { + self.signer.backend() + } + + fn get_public_key( + &self, + ) -> nostr::util::BoxedFuture<'_, Result> { + self.signer.get_public_key() + } + + fn sign_event( + &self, + unsigned: UnsignedEvent, + ) -> nostr::util::BoxedFuture<'_, Result> { + #[cfg(unix)] + if let Some(provider) = &self.desktop { + return Box::pin(async move { + provider.sign_or_wait(unsigned).await.map_err(|e| { + let text = nostr::signer::SignerError::from(e.0.to_string()); + if let Ok(mut slot) = self.failure.lock() { + slot.get_or_insert(e); + } + text + }) + }); + } + self.signer.sign_event(unsigned) + } + + fn nip04_encrypt<'b>( + &'b self, + peer: &'b PublicKey, + content: &'b str, + ) -> nostr::util::BoxedFuture<'b, Result> { + self.signer.nip04_encrypt(peer, content) + } + + fn nip04_decrypt<'b>( + &'b self, + peer: &'b PublicKey, + payload: &'b str, + ) -> nostr::util::BoxedFuture<'b, Result> { + self.signer.nip04_decrypt(peer, payload) + } + + fn nip44_encrypt<'b>( + &'b self, + peer: &'b PublicKey, + content: &'b str, + ) -> nostr::util::BoxedFuture<'b, Result> { + self.signer.nip44_encrypt(peer, content) + } + + fn nip44_decrypt<'b>( + &'b self, + peer: &'b PublicKey, + payload: &'b str, + ) -> nostr::util::BoxedFuture<'b, Result> { + self.signer.nip44_decrypt(peer, payload) + } +} + +impl Credentials { + /// Credentials for an in-memory key with no auth tag and no evidence source. + pub fn from_keys(keys: Keys) -> Self { + Self { + public_key: keys.public_key(), + signer: Arc::new(keys.clone()), + local_keys: Some(keys), + auth_tag: None, + evidence: None, + #[cfg(unix)] + desktop: None, + } + } + + /// Credentials signing through `signer` alone, for tests. + #[cfg(test)] + pub(crate) fn from_signer(signer: Arc, public_key: PublicKey) -> Self { + Self { + public_key, + signer, + local_keys: None, + auth_tag: None, + evidence: None, + #[cfg(unix)] + desktop: None, + } + } + + /// Credentials backed by the Buzz desktop: it signs, encrypts and supplies + /// NIP-FI evidence; the private key never reaches this process. + #[cfg(unix)] + pub(crate) async fn from_desktop( + provider: Arc, + ) -> Result { + let public_key = provider.public_key(); + let auth_tag = provider + .auth_tag() + .await? + .map(|json| parse_auth_tag(&json, &public_key)) + .transpose()?; + Ok(Self { + public_key, + signer: provider.clone(), + local_keys: None, + auth_tag, + evidence: None, + desktop: Some(provider), + }) + } + + /// Attach a verified NIP-OA auth tag. + #[cfg(test)] + pub fn with_auth_tag(mut self, tag: Tag, json: String) -> Self { + self.auth_tag = Some(AuthTag { tag, json }); + self + } + + /// The local keys behind a [`Self::from_keys`] credential. + #[cfg(test)] + pub fn test_keys(&self) -> Keys { + self.local_keys + .clone() + .expect("test credentials hold local keys") + } + + /// Attach a NIP-FA evidence source. + #[cfg(test)] + pub fn with_evidence(mut self, evidence: AdapterSession) -> Self { + self.evidence = Some(evidence); + self + } + + /// The public key this process acts as. + pub fn public_key(&self) -> PublicKey { + self.public_key + } + + /// The NIP-OA auth tag, if configured. + pub fn auth_tag(&self) -> Option<&AuthTag> { + self.auth_tag.as_ref() + } + + /// The NIP-AE engram `d` tag for `slug` in the conversation with `peer`: + /// HMAC-SHA256 over the NIP-44 conversation key, so it needs the key + /// itself rather than a signature (`docs/nips/NIP-AE.md`). + pub async fn engram_d_tag(&self, peer: &PublicKey, slug: &str) -> Result { + #[cfg(unix)] + if let Some(provider) = &self.desktop { + return provider.engram_d_tag(peer, slug).await; + } + let keys = self.local_keys.as_ref().ok_or_else(|| { + CliError::Auth( + "buzz mem needs a local key: set BUZZ_PRIVATE_KEY or pass --private-key".into(), + ) + })?; + let k_c = buzz_core::engram::conversation_key(keys.secret_key(), peer); + Ok(buzz_core::engram::d_tag(&k_c, slug)) + } + + /// A stable, anonymous, relay-scoped id for the GIF provider (see + /// [`customer_id`]). A link without local key material gets a random + /// per-process id instead, as Buzz Desktop does per install. + pub fn relay_scoped_customer_id(&self, relay_url: &str) -> String { + match self.local_keys.as_ref() { + Some(keys) => customer_id(keys.secret_key().as_secret_bytes(), relay_url), + None => { + static PROCESS_ID: std::sync::OnceLock = std::sync::OnceLock::new(); + PROCESS_ID + .get_or_init(|| uuid::Uuid::new_v4().simple().to_string()) + .clone() + } + } + } + + /// Whether the Buzz desktop is the link that holds the key. + pub fn is_desktop(&self) -> bool { + #[cfg(unix)] + return self.desktop.is_some(); + #[cfg(not(unix))] + false + } + + /// Whether a NIP-FI evidence source is configured. + pub fn has_evidence_source(&self) -> bool { + #[cfg(unix)] + if self.desktop.is_some() { + return true; + } + self.evidence.is_some() + } + + /// The NIP-FI assertion for the relay the credentials were resolved + /// for, or `None` when no evidence source is configured. + pub async fn evidence(&self) -> Result, CliError> { + #[cfg(unix)] + if let Some(provider) = &self.desktop { + return provider.federated_identity().await; + } + match &self.evidence { + Some(source) => { + let keys = self.local_keys.as_ref().ok_or_else(|| { + CliError::Auth("a headless evidence source needs a local key".into()) + })?; + source.assertion(keys).await + } + None => Ok(None), + } + } + + /// Sign `builder` as this identity. Callers own the tags; auth-tag + /// injection is [`crate::client::BuzzClient::sign_event`]'s job. + pub async fn sign(&self, builder: EventBuilder) -> Result { + self.sign_unsigned(builder.build(self.public_key)).await + } + + /// Sign `unsigned` as this identity. A desktop failure keeps its own + /// error, so a throttled desktop stays retryable. + pub async fn sign_unsigned(&self, unsigned: UnsignedEvent) -> Result { + #[cfg(unix)] + if let Some(provider) = &self.desktop { + return provider.sign(unsigned).await; + } + let event = self + .signer + .sign_event(unsigned) + .await + .map_err(|e| CliError::Other(format!("signing failed: {e}")))?; + if event.pubkey != self.public_key || event.verify().is_err() { + return Err(CliError::Auth( + "signer returned an event that is not validly signed by this identity".into(), + )); + } + Ok(event) + } + + /// NIP-44 encrypt `plaintext` to `peer` as this identity. + pub async fn nip44_encrypt( + &self, + peer: &PublicKey, + plaintext: &str, + ) -> Result { + #[cfg(unix)] + if let Some(provider) = &self.desktop { + return provider.nip44_encrypt(peer, plaintext).await; + } + self.signer + .nip44_encrypt(peer, plaintext) + .await + .map_err(|e| CliError::Other(format!("NIP-44 encryption failed: {e}"))) + } + + /// NIP-44 decrypt `payload` from `peer` as this identity. + /// NIP-44 decrypt `payload` from `peer`. `Ok(None)` means the payload is + /// not valid ciphertext for this key; `Err` means the signer itself failed. + /// A local key decides that itself, and the desktop reports it as + /// `invalid_request`; any other signer's failure is `Err`, since it cannot + /// be told apart from an unavailable credential. + pub async fn nip44_decrypt( + &self, + peer: &PublicKey, + payload: &str, + ) -> Result, CliError> { + if let Some(keys) = &self.local_keys { + return Ok(nostr::nips::nip44::decrypt(keys.secret_key(), peer, payload).ok()); + } + #[cfg(unix)] + if let Some(provider) = &self.desktop { + return provider.nip44_decrypt(peer, payload).await; + } + self.signer + .nip44_decrypt(peer, payload) + .await + .map(Some) + .map_err(|e| CliError::Auth(format!("NIP-44 decryption failed: {e}"))) + } + + /// Sign a NIP-98 HTTP auth event (kind:27235) for `method` + `url` and + /// return it base64-encoded, ready for a `Nostr ` header. + /// + /// The event carries the `u`, `method` and (with a body) `payload` tags, + /// plus a nonce so rapid identical requests don't trip replay guards. + pub async fn nip98( + &self, + method: &str, + url: &str, + body: Option<&[u8]>, + ) -> Result { + let event = self + .sign(crate::federated_identity::nip98_event(method, url, body)?) + .await?; + Ok(B64.encode(event.as_json().as_bytes())) + } +} + +/// Derive a stable, relay-scoped anonymous `customer_id` from secret key material. +/// +/// KLIPY requires a per-installation identifier that is stable and anonymous. +/// Using SHA-256 of the *public* key would be stable but NOT anonymous — the +/// input is public, so the ID is computable by any observer, and the same value +/// would appear across all relays (cross-relay linkability). +/// +/// Instead, we domain-separate with the relay URL and sign with the *secret* key: +/// `SHA-256(secret_key_bytes || '\0' || relay_url_bytes)` +/// This is: +/// - **stable**: deterministic given the same keypair + relay. +/// - **relay-scoped**: different relay → different ID, no cross-relay correlation. +/// - **not computable from public data**: requires secret key material. +/// - **stateless**: no file I/O, no storage. +/// +/// The first 16 bytes (32 hex chars) give 128 bits of uniqueness, ample for +/// KLIPY's per-installation needs. +fn customer_id(secret_key_bytes: &[u8], relay_url: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(secret_key_bytes); + hasher.update(b"\0"); // domain separator + hasher.update(relay_url.as_bytes()); + let hash = hasher.finalize(); + hex::encode(&hash[..16]) // 16 bytes → 32 hex chars +} + +#[cfg(test)] +mod tests { + use super::*; + + // ----------------------------------------------------------------------- + // customer_id + // ----------------------------------------------------------------------- + + #[test] + fn customer_id_is_32_hex_chars_and_stable() { + let sk = [0xab_u8; 32]; + let id = customer_id(&sk, "https://relay.example"); + assert_eq!(id.len(), 32); + assert!(id.chars().all(|c| c.is_ascii_hexdigit())); + assert_eq!(id, customer_id(&sk, "https://relay.example")); + } + + #[test] + fn customer_id_is_relay_scoped() { + let sk = [0xcd_u8; 32]; + let id_a = customer_id(&sk, "https://relay-a.example"); + let id_b = customer_id(&sk, "https://relay-b.example"); + assert_ne!( + id_a, id_b, + "same key, different relay → different customer_id" + ); + } + + #[test] + fn customer_id_differs_for_different_keys() { + let id_a = customer_id(&[0xaa_u8; 32], "https://relay.example"); + let id_b = customer_id(&[0xbb_u8; 32], "https://relay.example"); + assert_ne!(id_a, id_b); + } + + #[test] + fn customer_id_not_equal_to_pubkey_hash() { + // The customer_id must NOT be derivable from the public key alone. + let sk = [0xde_u8; 32]; + // What the old pubkey-hash approach would have produced (approximately): + let naive_hash = hex::encode(&Sha256::digest(hex::encode(sk).as_bytes())[..16]); + let actual = customer_id(&sk, "https://relay.example"); + assert_ne!( + actual, naive_hash, + "customer_id must not equal SHA-256(pubkey_hex)[..16]" + ); + } + + fn explicit(settings: Settings) -> Result { + resolve_explicit(&settings, "https://relay.example").map(|c| c.expect("explicit key")) + } + + fn settings(key: Option<&str>, token: Option<&str>, adapter: Option<&str>) -> Settings { + Settings { + private_key: key.map(str::to_owned), + auth_tag: None, + federated_identity_token: token.map(str::to_owned), + federated_identity_adapter: adapter.map(str::to_owned), + } + } + + #[test] + fn explicit_key_is_the_first_link() { + let keys = Keys::generate(); + let nsec = keys.secret_key().to_secret_hex(); + let credentials = explicit(settings(Some(&nsec), None, None)).unwrap(); + assert_eq!(credentials.public_key(), keys.public_key()); + assert!(!credentials.has_evidence_source()); + } + + #[test] + fn no_link_is_an_auth_error_naming_the_settings() { + assert!( + resolve_explicit(&settings(None, None, None), "https://relay.example") + .unwrap() + .is_none() + ); + } + + /// Headless evidence settings belong to the explicit key: without one + /// they are passed over (and named in a warning), not an error. + #[test] + fn headless_settings_without_a_key_are_passed_over_and_named() { + for (token, adapter) in [(Some("t"), None), (Some("t"), Some("https://a.example"))] { + let unused = settings(None, token, adapter); + assert!(resolve_explicit(&unused, "https://relay.example") + .unwrap() + .is_none()); + let warning = ignored_headless_settings(&unused).unwrap(); + assert!(warning.contains(FEDERATED_IDENTITY_TOKEN_ENV), "{warning}"); + assert_eq!( + warning.contains(FEDERATED_IDENTITY_ADAPTER_ENV), + adapter.is_some(), + "{warning}" + ); + } + assert!(ignored_headless_settings(&settings(None, None, None)).is_none()); + } + + /// The evidence source is bound to the relay when credentials are + /// resolved, so a relay NIP-FA cannot serve fails then, not mid-command. + #[test] + fn the_evidence_source_binds_its_relay_at_resolution() { + let nsec = Keys::generate().secret_key().to_secret_hex(); + let headless = settings(Some(&nsec), Some("t"), Some("https://adapter.example")); + assert!(resolve_explicit(&headless, "https://relay.example").is_ok()); + let err = resolve_explicit(&headless, "https://relay.example:80") + .err() + .unwrap(); + assert!(matches!(err, CliError::Usage(_)), "{err:?}"); + } + + #[test] + fn evidence_settings_must_come_together() { + let nsec = Keys::generate().secret_key().to_secret_hex(); + for (token, adapter, missing) in [ + (Some("t"), None, FEDERATED_IDENTITY_ADAPTER_ENV), + ( + None, + Some("https://adapter.example"), + FEDERATED_IDENTITY_TOKEN_ENV, + ), + ] { + let err = explicit(settings(Some(&nsec), token, adapter)) + .err() + .unwrap(); + assert!( + matches!(&err, CliError::Auth(m) if m.contains(missing)), + "{token:?} {adapter:?}: {err}" + ); + } + let credentials = explicit(settings( + Some(&nsec), + Some("t"), + Some("https://adapter.example"), + )) + .unwrap(); + assert!(credentials.has_evidence_source()); + } + + #[tokio::test] + async fn key_derived_operations_match_the_protocol_definitions() { + let agent = Keys::generate(); + let owner = Keys::generate(); + let credentials = Credentials::from_keys(agent.clone()); + // NIP-AE: either side of the pair derives the same d tag. + let owner_side = buzz_core::engram::d_tag( + &buzz_core::engram::conversation_key(owner.secret_key(), &agent.public_key()), + "core", + ); + assert_eq!( + credentials + .engram_d_tag(&owner.public_key(), "core") + .await + .unwrap(), + owner_side + ); + assert_eq!( + credentials.relay_scoped_customer_id("https://a.example"), + customer_id(agent.secret_key().as_secret_bytes(), "https://a.example") + ); + } + + #[tokio::test] + async fn sign_rejects_events_from_another_key() { + #[derive(Debug)] + struct WrongKey(Keys); + impl NostrSigner for WrongKey { + fn backend(&self) -> nostr::signer::SignerBackend<'_> { + nostr::signer::SignerBackend::Custom("test".into()) + } + fn get_public_key( + &self, + ) -> nostr::util::BoxedFuture<'_, Result> + { + Box::pin(async move { Ok(self.0.public_key()) }) + } + fn sign_event( + &self, + unsigned: nostr::UnsignedEvent, + ) -> nostr::util::BoxedFuture<'_, Result> + { + let other = Keys::generate(); + Box::pin(async move { + EventBuilder::new(unsigned.kind, unsigned.content) + .sign_with_keys(&other) + .map_err(nostr::signer::SignerError::backend) + }) + } + fn nip04_encrypt<'a>( + &'a self, + _: &'a PublicKey, + _: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> + { + Box::pin(async { Err(nostr::signer::SignerError::from("unsupported")) }) + } + fn nip04_decrypt<'a>( + &'a self, + _: &'a PublicKey, + _: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> + { + Box::pin(async { Err(nostr::signer::SignerError::from("unsupported")) }) + } + fn nip44_encrypt<'a>( + &'a self, + _: &'a PublicKey, + _: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> + { + Box::pin(async { Err(nostr::signer::SignerError::from("unsupported")) }) + } + fn nip44_decrypt<'a>( + &'a self, + _: &'a PublicKey, + _: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> + { + Box::pin(async { Err(nostr::signer::SignerError::from("unsupported")) }) + } + } + + let keys = Keys::generate(); + let credentials = Credentials { + public_key: keys.public_key(), + signer: Arc::new(WrongKey(keys)), + local_keys: None, + auth_tag: None, + evidence: None, + #[cfg(unix)] + desktop: None, + }; + let err = credentials + .sign(EventBuilder::text_note("hi")) + .await + .err() + .unwrap(); + assert!(matches!(err, CliError::Auth(_)), "{err}"); + + // Without local key material: key-derived operations degrade or refuse. + let peer = Keys::generate().public_key(); + assert!(credentials.engram_d_tag(&peer, "core").await.is_err()); + let relay = "https://relay.example"; + let id = credentials.relay_scoped_customer_id(relay); + assert_eq!( + id, + credentials.relay_scoped_customer_id(relay), + "one id per process" + ); + assert_ne!( + id, + customer_id(&[0; 32], relay), + "no local key: a random id, not a key derivation" + ); + assert_eq!(id.len(), 32); + } + + #[test] + fn no_credentials_names_the_relay_and_the_paired_ones() { + let message = |relay: &str, paired: &[&str]| { + let paired: Vec = paired.iter().map(|r| (*r).to_owned()).collect(); + match no_credentials(relay, &paired) { + CliError::Auth(m) => m, + other => panic!("{other:?}"), + } + }; + let none = message("http://localhost:3000", &[]); + assert!(none.starts_with("no credentials for http://localhost:3000: set BUZZ_PRIVATE_KEY")); + + let elsewhere = message("http://localhost:3000", &["wss://team.example/"]); + assert!( + elsewhere.contains("paired with Buzz only for wss://team.example/"), + "{elsewhere}" + ); + assert!(elsewhere.contains("pass --relay"), "{elsewhere}"); + + #[cfg(unix)] + { + let here = message("https://team.example", &["wss://team.example/"]); + assert!( + here.contains("no running Buzz desktop accepts the pairing"), + "{here}" + ); + } + } +} diff --git a/crates/buzz-cli/src/desktop_provider.rs b/crates/buzz-cli/src/desktop_provider.rs new file mode 100644 index 00000000000..3fda8483954 --- /dev/null +++ b/crates/buzz-cli/src/desktop_provider.rs @@ -0,0 +1,2747 @@ +//! The desktop link of the credential chain: a running Buzz Desktop acts as +//! one identity over loopback (`docs/local-credential-provider.md`). +//! +//! The caller never holds the private key. It finds a provider through an +//! inherited `BUZZ_CREDENTIAL_PROVIDER` token or a paired token in the OS +//! keychain, and sends each request on a connection whose server side it has +//! confirmed belongs to the same OS user, for inherited and paired tokens +//! alike. +//! +//! Version 1 has no Windows transport, so the link is compiled for Unix only. + +use std::sync::Arc; +use std::time::Duration; + +use nostr::signer::{SignerBackend, SignerError}; +use nostr::{Event, JsonUtil, PublicKey, Tag, UnsignedEvent}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +use crate::error::CliError; + +mod ownership; +use ownership::{connect, current_uid}; + +/// Serializes same-user checks across in-process tests; see [`call`]. +#[cfg(test)] +static SAME_USER_TURN: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +pub const PROVIDER_ENV: &str = "BUZZ_CREDENTIAL_PROVIDER"; + +/// The protocol version this caller speaks. +const VERSION: u32 = 1; +const VERSION_HEADER: &str = "Buzz-Credential-Provider"; + +/// Methods the provider may hold open for a person's decision (up to 120s). +pub(crate) const HELD_TIMEOUT: Duration = Duration::from_secs(150); +const QUICK_TIMEOUT: Duration = Duration::from_secs(10); +/// Every result is built from a request's params, and the desktop reads at +/// most 2 MiB of request body, so no result is larger than that in bytes. +/// Escaping a result as a JSON string grows it at most sixfold: a decrypted +/// NIP-44 plaintext (extended lengths have no 64 KiB ceiling) may be all +/// control characters, each becoming `\u00XX`. The 64 KiB on top covers a +/// signed event's added `id`, `pubkey` and `sig`, the envelope and the headers. +const MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024; +const MAX_RESPONSE_BYTES: usize = 6 * MAX_REQUEST_BYTES + 64 * 1024; + +/// `rate_limited` refuses before acting, so the same envelope is re-sent: +/// up to this many times, each after `retry_after` capped at the wait below. +const RATE_LIMIT_RETRIES: u32 = 4; +const RATE_LIMIT_MAX_WAIT_SECS: u64 = 30; +/// One `retry_after` second; tests shorten it so throttling stays fast. +const RETRY_AFTER_UNIT: Duration = if cfg!(test) { + Duration::from_millis(10) +} else { + Duration::from_secs(1) +}; + +/// A provider failure, by the contract's error code. +#[derive(Debug)] +pub enum ProviderError { + /// `revoked`: a paired token is dropped and the next paired one tried; + /// an inherited one fails the command. + Revoked, + /// No common protocol version: the provider does not apply. + NoCommonVersion, + /// `unknown_method`: degrade where the caller can. + UnknownMethod, + /// Any other code. Unrecognized codes are reported as `denied`. + Code { + code: &'static str, + message: Option, + retry_after: Option, + }, + /// The provider could not be reached or answered outside the contract. + Transport(String), + /// The same-user check ran out of time before anything was sent. + Unconfirmed, + /// The provider port is held by another user, or no owner was found: + /// nothing was sent. + OtherUser, +} + +impl ProviderError { + fn into_cli(self, method: &str) -> CliError { + match self { + Self::Revoked => CliError::Auth( + "the Buzz desktop revoked this CLI's token; run `buzz auth desktop pair` again" + .into(), + ), + Self::NoCommonVersion => CliError::Auth( + "the Buzz desktop speaks no credential-provider version this CLI supports".into(), + ), + Self::UnknownMethod => CliError::Auth(format!( + "the Buzz desktop does not implement `{method}`; update Buzz" + )), + Self::Code { + code, + message, + retry_after, + } => { + let detail = message.map(|m| format!(": {m}")).unwrap_or_default(); + match code { + "approval_required" => { + CliError::Auth(format!("approve this request in Buzz, then retry{detail}")) + } + "rate_limited" => CliError::Throttled(format!( + "the Buzz desktop is rate-limiting this CLI; retry in {}s{detail}", + retry_after.unwrap_or(1) + )), + "unavailable" => { + CliError::Auth(format!("the Buzz desktop cannot act now{detail}")) + } + "invalid_request" => CliError::Other(format!( + "the Buzz desktop rejected `{method}` as malformed{detail}" + )), + _ => CliError::Auth(format!("the Buzz desktop refused `{method}`{detail}")), + } + } + Self::Transport(why) => CliError::Auth(format!("Buzz desktop: {why}")), + Self::Unconfirmed => CliError::Unavailable( + "Buzz desktop: the same-user check timed out; nothing was sent".into(), + ), + Self::OtherUser => CliError::Auth( + "Buzz desktop: could not confirm the provider runs as this user; nothing was sent" + .into(), + ), + } + } +} + +/// `unsigned` dated now, if it is a short-lived auth proof (NIP-42, NIP-98 +/// or Blossom); a Blossom `expiration` moves by the same amount. +fn renewed(mut unsigned: UnsignedEvent) -> UnsignedEvent { + if !matches!(unsigned.kind.as_u16(), 22242 | 27235 | 24242) { + return unsigned; + } + let now = nostr::Timestamp::now(); + let shift = now.as_secs().saturating_sub(unsigned.created_at.as_secs()); + if shift == 0 { + return unsigned; + } + let tags = unsigned + .tags + .clone() + .to_vec() + .into_iter() + .map(|tag| match tag.as_slice() { + [name, exp] if name == "expiration" => match exp.parse::() { + Ok(exp) => Tag::parse(["expiration", &(exp + shift).to_string()]).unwrap_or(tag), + Err(_) => tag, + }, + _ => tag, + }); + unsigned.tags = nostr::Tags::from_list(tags.collect()); + unsigned.created_at = now; + unsigned.id = None; + unsigned.ensure_id(); + unsigned +} + +/// The contract's codes; anything else is `denied`. +fn known_code(code: &str) -> &'static str { + match code { + "approval_required" => "approval_required", + "rate_limited" => "rate_limited", + "unavailable" => "unavailable", + "invalid_request" => "invalid_request", + "unsupported_version" => "unsupported_version", + _ => "denied", + } +} + +fn held(method: &str) -> bool { + matches!(method, "sign_event" | "nip44_decrypt" | "pair") +} + +/// A provider endpoint: `http://127.0.0.1:/`. +#[derive(Clone, Debug)] +pub struct Endpoint { + port: u16, + path: String, +} + +impl Endpoint { + pub fn parse(raw: &str) -> Result { + let invalid = + || CliError::Auth("credential provider URL must be http://127.0.0.1:/…".into()); + let url = url::Url::parse(raw).map_err(|_| invalid())?; + if url.scheme() != "http" + || url.host() != Some(url::Host::Ipv4(std::net::Ipv4Addr::LOCALHOST)) + || !url.username().is_empty() + || url.password().is_some() + || url.fragment().is_some() + { + return Err(invalid()); + } + let port = url.port().ok_or_else(invalid)?; + let mut path = url.path().to_owned(); + if let Some(query) = url.query() { + path = format!("{path}?{query}"); + } + Ok(Self { port, path }) + } +} + +/// Exchange one request on `stream` (one request per connection) and return +/// the HTTP status and body. +/// +/// This is a minimal HTTP/1.1 exchange rather than reqwest or hyper because +/// the same-user check in [`connect`] must vet the very TCP connection the +/// token is then sent on; a pooled client opens its own connections, which +/// the check never saw. +async fn exchange( + mut stream: TcpStream, + endpoint: &Endpoint, + token: Option<&str>, + version: u32, + body: &[u8], +) -> Result<(u16, Vec), ProviderError> { + let io = + |e: std::io::Error| ProviderError::Transport(format!("connection failed: {}", e.kind())); + let mut head = format!( + "POST {} HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\n{VERSION_HEADER}: {version}\r\nConnection: close\r\n", + endpoint.path, + endpoint.port, + body.len() + ); + if let Some(token) = token { + head.push_str(&format!("Authorization: Bearer {token}\r\n")); + } + head.push_str("\r\n"); + stream.write_all(head.as_bytes()).await.map_err(io)?; + stream.write_all(body).await.map_err(io)?; + let mut raw = Vec::new(); + (&mut stream) + .take(MAX_RESPONSE_BYTES as u64 + 1) + .read_to_end(&mut raw) + .await + .map_err(io)?; + if raw.len() > MAX_RESPONSE_BYTES { + return Err(ProviderError::Transport("response too large".into())); + } + parse_response(&raw).ok_or_else(|| ProviderError::Transport("malformed HTTP response".into())) +} + +/// Parse an HTTP/1.1 response read to EOF: status plus body, decoding +/// `Content-Length` or chunked framing. +fn parse_response(raw: &[u8]) -> Option<(u16, Vec)> { + let split = raw.windows(4).position(|w| w == b"\r\n\r\n")?; + let head = std::str::from_utf8(&raw[..split]).ok()?; + let rest = &raw[split + 4..]; + let mut lines = head.split("\r\n"); + let status: u16 = lines.next()?.split(' ').nth(1)?.parse().ok()?; + let mut length = None; + let mut chunked = false; + for line in lines { + let (name, value) = line.split_once(':')?; + let value = value.trim(); + if name.eq_ignore_ascii_case("content-length") { + length = Some(value.parse::().ok()?); + } else if name.eq_ignore_ascii_case("transfer-encoding") { + chunked = value.eq_ignore_ascii_case("chunked"); + } + } + if chunked { + let mut body = Vec::new(); + let mut at = rest; + loop { + let end = at.windows(2).position(|w| w == b"\r\n")?; + let size_hex = std::str::from_utf8(&at[..end]) + .ok()? + .split(';') + .next()? + .trim(); + let size = usize::from_str_radix(size_hex, 16).ok()?; + at = &at[end + 2..]; + if size == 0 { + return Some((status, body)); + } + body.extend_from_slice(at.get(..size)?); + at = at.get(size + 2..)?; + } + } + match length { + Some(n) => Some((status, rest.get(..n)?.to_vec())), + None => Some((status, rest.to_vec())), + } +} + +// --------------------------------------------------------------------------- +// Provider client +// --------------------------------------------------------------------------- + +#[derive(serde::Deserialize)] +struct Envelope { + #[serde(default)] + id: String, + #[serde(default)] + result: String, + error: Option, + message: Option, + retry_after: Option, + versions: Option>, +} + +/// Send one envelope and return its `result`, negotiating the version once +/// and waiting out `rate_limited` a bounded number of times. Transport +/// failures are never re-sent: the provider may have acted. +async fn call( + endpoint: &Endpoint, + token: Option<&str>, + same_user: bool, + method: &str, + params: &[String], +) -> Result { + call_with( + endpoint, + token, + same_user, + method, + RATE_LIMIT_RETRIES, + &|| params.to_vec(), + ) + .await +} + +/// [`call`], building `params` afresh for every envelope, so a re-send after +/// a refusal can carry a renewed auth proof. +async fn call_with( + endpoint: &Endpoint, + token: Option<&str>, + same_user: bool, + method: &str, + retries: u32, + params: &(dyn Fn() -> Vec + Sync), +) -> Result { + let mut version = VERSION; + let mut negotiated = false; + let mut throttled = 0; + loop { + let id = uuid::Uuid::new_v4().simple().to_string(); + let body = serde_json::to_vec(&serde_json::json!({ + "id": id, "method": method, "params": params(), + })) + .map_err(|_| ProviderError::Transport("request serialization failed".into()))?; + let timeout = if held(method) { + HELD_TIMEOUT + } else { + QUICK_TIMEOUT + }; + // In `cargo test`, the real same-user checks take turns, as the + // nextest group `desktop-same-user-check` makes them there. Waiting + // for a turn does not count against the request's timeout. + #[cfg(test)] + let turn = SAME_USER_TURN.lock().await; + let attempt = async { + let stream = connect(endpoint.port, same_user).await?; + #[cfg(test)] + drop(turn); + exchange(stream, endpoint, token, version, &body).await + }; + let (_, raw) = tokio::time::timeout(timeout, attempt) + .await + .map_err(|_| ProviderError::Transport(format!("`{method}` timed out")))??; + let envelope: Envelope = serde_json::from_slice(&raw) + .map_err(|_| ProviderError::Transport("unreadable response".into()))?; + if envelope.id != id { + return Err(ProviderError::Transport("response id mismatch".into())); + } + // Decide on `error`, never on the HTTP status. + let Some(code) = envelope.error.filter(|c| !c.is_empty()) else { + return Ok(envelope.result); + }; + match code.as_str() { + "revoked" => return Err(ProviderError::Revoked), + "unknown_method" => return Err(ProviderError::UnknownMethod), + "unsupported_version" if !negotiated => { + negotiated = true; + let common = envelope + .versions + .unwrap_or_default() + .into_iter() + .filter(|v| *v <= VERSION && *v != version) + .max(); + match common { + Some(v) => version = v, + None => return Err(ProviderError::NoCommonVersion), + } + } + "unsupported_version" => return Err(ProviderError::NoCommonVersion), + // A wait past the cap is reported at once, with its real length. + "rate_limited" + if throttled < retries + && envelope.retry_after.unwrap_or(1) <= RATE_LIMIT_MAX_WAIT_SECS => + { + throttled += 1; + tokio::time::sleep(throttle_wait(envelope.retry_after)).await; + } + other => { + return Err(ProviderError::Code { + code: known_code(other), + message: envelope.message, + retry_after: envelope.retry_after, + }) + } + } + } +} + +/// How long to wait out a `rate_limited` answer. +pub(crate) fn throttle_wait(retry_after: Option) -> Duration { + RETRY_AFTER_UNIT * retry_after.unwrap_or(1).clamp(1, RATE_LIMIT_MAX_WAIT_SECS) as u32 +} + +#[derive(serde::Deserialize)] +struct Describe { + pubkey: String, + #[serde(default)] + relays: Vec, + #[serde(default)] + methods: Vec, +} + +/// A connected provider acting as one identity. +pub struct Provider { + endpoint: Endpoint, + /// The relay it was opened for, as the desktop binds it. + relay: String, + token: String, + same_user: bool, + public_key: PublicKey, + methods: Vec, + cached: crate::cached_assertion::CachedAssertion, +} + +impl std::fmt::Debug for Provider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Provider") + .field("port", &self.endpoint.port) + .field("public_key", &self.public_key.to_hex()) + .finish_non_exhaustive() + } +} + +/// Why a provider was not used for this relay. +pub enum Skip { + /// The token was revoked: the caller drops it. + Revoked, + /// The provider does not apply (relay not bound, no common version). + NotApplicable, + /// The endpoint could not be reached: nothing was decided. + Unreachable, + /// The same-user check timed out before anything was sent. + Unconfirmed, +} + +/// A relay URL as the local provider binds it: `http`/`https` read as +/// `ws`/`wss`, then URL normalization (lowercase host, no default port, `/` +/// for an empty path). The path and query count: one host can serve several +/// communities. This is not NIP-FA's audience form; the desktop derives that. +pub fn provider_relay_url(raw: &str) -> Result { + let invalid = || CliError::Usage(format!("invalid relay URL: {raw}")); + let mut url = url::Url::parse(raw).map_err(|_| invalid())?; + let scheme = match url.scheme() { + "http" | "ws" => "ws", + "https" | "wss" => "wss", + _ => return Err(invalid()), + }; + if !url.username().is_empty() || url.password().is_some() || url.host().is_none() { + return Err(invalid()); + } + url.set_fragment(None); + // Changing between special schemes keeps host, port and path. + url.set_scheme(scheme).map_err(|()| invalid())?; + // Re-parse so a default port for the new scheme is dropped. + url::Url::parse(url.as_str()) + .map(|u| u.to_string()) + .map_err(|_| invalid()) +} + +fn same_relay(a: &str, b: &str) -> bool { + provider_relay_url(b).is_ok_and(|b| b == a) +} + +impl Provider { + /// Connect with `token` and confirm the provider acts for `relay_url`. + pub async fn open( + endpoint: Endpoint, + token: String, + same_user: bool, + relay_url: &str, + ) -> Result, Skip>, CliError> { + let raw = match call(&endpoint, Some(&token), same_user, "describe", &[]).await { + Ok(raw) => raw, + Err(ProviderError::Revoked) => return Ok(Err(Skip::Revoked)), + Err(ProviderError::NoCommonVersion) => return Ok(Err(Skip::NotApplicable)), + Err(ProviderError::Transport(_) | ProviderError::OtherUser) => { + return Ok(Err(Skip::Unreachable)) + } + Err(ProviderError::Unconfirmed) => return Ok(Err(Skip::Unconfirmed)), + Err(e) => return Err(e.into_cli("describe")), + }; + let describe: Describe = serde_json::from_str(&raw) + .map_err(|_| CliError::Auth("Buzz desktop: unreadable `describe` answer".into()))?; + let public_key = PublicKey::from_hex(&describe.pubkey) + .map_err(|_| CliError::Auth("Buzz desktop: invalid identity public key".into()))?; + let relay = provider_relay_url(relay_url)?; + if !describe.relays.iter().any(|r| same_relay(&relay, r)) { + return Ok(Err(Skip::NotApplicable)); + } + Ok(Ok(Arc::new(Self { + endpoint, + relay, + token, + same_user, + public_key, + methods: describe.methods, + cached: Default::default(), + }))) + } + + pub fn public_key(&self) -> PublicKey { + self.public_key + } + + /// Sign `unsigned` as this identity; the result is checked. + pub async fn sign(&self, unsigned: UnsignedEvent) -> Result { + self.sign_or_wait(unsigned).await.map_err(|(e, _)| e) + } + + /// [`Self::sign`], except that a throttled NIP-42 sign-in is not waited + /// out here: its challenge dies with the socket meanwhile, so it fails + /// at once with the wait, for the caller to reconnect after. + pub async fn sign_or_wait( + &self, + unsigned: UnsignedEvent, + ) -> Result)> { + let retries = if unsigned.kind == nostr::Kind::Authentication { + 0 + } else { + RATE_LIMIT_RETRIES + }; + // A re-sent auth proof is renewed so it is fresh when it reaches the + // relay; any other event is signed exactly as built. + let signed = call_with( + &self.endpoint, + Some(&self.token), + self.same_user, + "sign_event", + retries, + &|| vec![renewed(unsigned.clone()).as_json()], + ) + .await + .map_err(|e| { + let wait = match &e { + ProviderError::Code { + code: "rate_limited", + retry_after, + .. + } => Some(throttle_wait(*retry_after)), + _ => None, + }; + (e.into_cli("sign_event"), wait) + })?; + let refused = |why: &str| (CliError::Auth(format!("Buzz desktop returned {why}")), None); + let event = Event::from_json(&signed).map_err(|_| refused("an unreadable event"))?; + if event.pubkey != self.public_key || event.verify().is_err() { + return Err(refused("an invalid signature")); + } + Ok(event) + } + + /// NIP-44 encrypt `content` to `peer` as this identity. + pub async fn nip44_encrypt(&self, peer: &PublicKey, content: &str) -> Result { + self.call("nip44_encrypt", &[peer.to_hex(), content.to_owned()]) + .await + } + + async fn call(&self, method: &str, params: &[String]) -> Result { + call( + &self.endpoint, + Some(&self.token), + self.same_user, + method, + params, + ) + .await + .map_err(|e| e.into_cli(method)) + } + + /// The identity's NIP-OA `auth` tag JSON, if it has one. + pub async fn auth_tag(&self) -> Result, CliError> { + if !self.methods.iter().any(|m| m == "auth_tag") { + return Ok(None); + } + match call( + &self.endpoint, + Some(&self.token), + self.same_user, + "auth_tag", + &[], + ) + .await + { + Ok(tag) => Ok(Some(tag).filter(|t| !t.is_empty())), + Err(ProviderError::UnknownMethod) => Ok(None), + Err(e) => Err(e.into_cli("auth_tag")), + } + } + + /// The NIP-FI assertion for the relay it was opened for, cached until + /// shortly before its `exp`. `None` when the desktop has none for it. + pub async fn federated_identity(&self) -> Result, CliError> { + let params = [self.relay.clone()]; + self.cached + .get(async { + match call( + &self.endpoint, + Some(&self.token), + self.same_user, + "federated_identity", + ¶ms, + ) + .await + { + Ok(a) if a.is_empty() => Ok(None), + Ok(a) => Ok(Some(a)), + Err(ProviderError::UnknownMethod) => Ok(None), + Err(e) => Err(e.into_cli("federated_identity")), + } + }) + .await + } + + /// NIP-44 decrypt `payload` from `peer`. `Ok(None)` when the desktop + /// answers `invalid_request`: the payload is not valid ciphertext for this + /// identity (the CLI's params are always well formed). Any other failure, + /// such as revoked, denied or unreachable, is an error. + pub async fn nip44_decrypt( + &self, + peer: &PublicKey, + payload: &str, + ) -> Result, CliError> { + match call( + &self.endpoint, + Some(&self.token), + self.same_user, + "nip44_decrypt", + &[peer.to_hex(), payload.to_owned()], + ) + .await + { + Ok(plaintext) => Ok(Some(plaintext)), + Err(ProviderError::Code { + code: "invalid_request", + .. + }) => Ok(None), + Err(e) => Err(e.into_cli("nip44_decrypt")), + } + } + + /// The NIP-AE `d` tag for `slug`, derived by the desktop. + pub async fn engram_d_tag(&self, peer: &PublicKey, slug: &str) -> Result { + let tag = self + .call("engram_d_tag", &[peer.to_hex(), slug.to_owned()]) + .await?; + if tag.len() != 64 || !tag.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(CliError::Auth( + "Buzz desktop returned an invalid engram d tag".into(), + )); + } + Ok(tag) + } +} + +fn signer_error(e: CliError) -> SignerError { + SignerError::from(e.to_string()) +} + +impl nostr::NostrSigner for Provider { + fn backend(&self) -> SignerBackend<'_> { + SignerBackend::Custom("buzz-desktop".into()) + } + + fn get_public_key(&self) -> nostr::util::BoxedFuture<'_, Result> { + Box::pin(async move { Ok(self.public_key) }) + } + + fn sign_event( + &self, + unsigned: UnsignedEvent, + ) -> nostr::util::BoxedFuture<'_, Result> { + Box::pin(async move { Provider::sign(self, unsigned).await.map_err(signer_error) }) + } + + fn nip04_encrypt<'a>( + &'a self, + _: &'a PublicKey, + _: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + Box::pin(async { Err("the Buzz desktop provider does not offer NIP-04".into()) }) + } + + fn nip04_decrypt<'a>( + &'a self, + _: &'a PublicKey, + _: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + Box::pin(async { Err("the Buzz desktop provider does not offer NIP-04".into()) }) + } + + fn nip44_encrypt<'a>( + &'a self, + peer: &'a PublicKey, + content: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + Box::pin(async move { + Provider::nip44_encrypt(self, peer, content) + .await + .map_err(signer_error) + }) + } + + fn nip44_decrypt<'a>( + &'a self, + peer: &'a PublicKey, + payload: &'a str, + ) -> nostr::util::BoxedFuture<'a, Result> { + Box::pin(async move { + self.call("nip44_decrypt", &[peer.to_hex(), payload.to_owned()]) + .await + .map_err(signer_error) + }) + } +} + +// --------------------------------------------------------------------------- +// Discovery +// --------------------------------------------------------------------------- + +#[derive(serde::Deserialize)] +struct Inherited { + url: String, + token: String, +} + +/// The inherited token from `BUZZ_CREDENTIAL_PROVIDER`, if set. +pub fn inherited() -> Result, CliError> { + let Some(raw) = std::env::var(PROVIDER_ENV) + .ok() + .filter(|v| !v.trim().is_empty()) + else { + return Ok(None); + }; + let inherited: Inherited = serde_json::from_str(&raw) + .map_err(|_| CliError::Auth(format!("{PROVIDER_ENV} is not valid JSON")))?; + let endpoint = Endpoint::parse(&inherited.url)?; + if !usable_token(&inherited.token) { + return Err(CliError::Auth(format!( + "{PROVIDER_ENV} carries an unusable token" + ))); + } + Ok(Some((endpoint, inherited.token))) +} + +fn usable_token(token: &str) -> bool { + !token.is_empty() && token.bytes().all(|b| b.is_ascii_graphic()) +} + +#[derive(serde::Deserialize)] +struct Advertisement { + instance: String, + url: String, +} + +fn advertisement_dir() -> Option { + std::env::var_os("HOME") + .map(|home| std::path::Path::new(&home).join(".buzz-foundation/credential-providers")) +} + +/// Every advertisement that passes the ownership and permission checks: +/// a `0700` directory and files owned by this user with no group or other +/// bits. Anything else is ignored, so another user cannot plant one. +fn advertisements_in(dir: &std::path::Path) -> Vec<(String, Endpoint)> { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let uid = current_uid(); + let private = + |m: &std::fs::Metadata, mode: u32| m.uid() == uid && m.permissions().mode() & 0o777 == mode; + let Ok(meta) = std::fs::symlink_metadata(dir) else { + return Vec::new(); + }; + if !meta.is_dir() || !private(&meta, 0o700) { + return Vec::new(); + } + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut found: Vec<(String, Endpoint)> = entries + .flatten() + .filter(|e| { + let name = e.file_name(); + let name = name.to_string_lossy(); + !name.starts_with('.') && name.ends_with(".json") + }) + .filter_map(|e| { + let meta = std::fs::symlink_metadata(e.path()).ok()?; + if !meta.is_file() || meta.uid() != uid || meta.permissions().mode() & 0o077 != 0 { + return None; + } + let ad: Advertisement = serde_json::from_slice(&std::fs::read(e.path()).ok()?).ok()?; + Some((ad.instance, Endpoint::parse(&ad.url).ok()?)) + }) + .collect(); + found.sort_by(|a, b| a.0.cmp(&b.0)); + found +} + +fn advertisements() -> Vec<(String, Endpoint)> { + advertisement_dir().map_or_else(Vec::new, |d| advertisements_in(&d)) +} + +// --------------------------------------------------------------------------- +// Paired tokens, in the OS keychain +// --------------------------------------------------------------------------- + +const KEYCHAIN_SERVICE: &str = "buzz-cli"; +const KEYCHAIN_ACCOUNT: &str = "desktop-pairings"; + +/// One pairing per instance. +#[derive(serde::Serialize, serde::Deserialize, Default)] +struct Pairings(std::collections::BTreeMap); + +#[derive(serde::Serialize, serde::Deserialize, Clone)] +struct Pairing { + token: String, + pubkey: String, + relays: Vec, +} + +/// A held lock; dropping it releases the lock. +trait Held {} +impl Held for T {} + +/// Where the pairing map lives. Every change goes through [`update`], which +/// holds `lock` only for one reload-change-write. +trait PairingStore: Send + Sync { + fn read(&self) -> Result, CliError>; + /// Write `json`, or delete the entry for `None`. + fn write(&self, json: Option<&str>) -> Result<(), CliError>; + /// A cross-process lock, released when the guard drops. + fn lock(&self) -> Result, CliError>; +} + +struct Keychain; + +fn no_keychain(e: keyring::Error) -> CliError { + CliError::Auth(format!( + "no OS keychain is reachable ({e}); on Linux start a Secret Service such as \ + gnome-keyring, or set BUZZ_PRIVATE_KEY instead. Paired tokens are never written to files." + )) +} + +impl Keychain { + fn entry() -> Result { + keyring::Entry::new(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT).map_err(no_keychain) + } +} + +impl PairingStore for Keychain { + fn read(&self) -> Result, CliError> { + match Self::entry()?.get_password() { + Ok(json) => Ok(Some(json)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(no_keychain(e)), + } + } + + fn write(&self, json: Option<&str>) -> Result<(), CliError> { + let entry = Self::entry()?; + match json { + Some(json) => entry.set_password(json).map_err(no_keychain), + None => match entry.delete_credential() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(e) => Err(no_keychain(e)), + }, + } + } + + /// `flock` on `~/.buzz-foundation/cli-pairings.lock` (no secret in it). + fn lock(&self) -> Result, CliError> { + use std::os::fd::AsRawFd; + use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; + let failed = |e: std::io::Error| CliError::Other(format!("pairing lock failed: {e}")); + let dir = advertisement_dir() + .and_then(|d| d.parent().map(std::path::Path::to_path_buf)) + .ok_or_else(|| CliError::Other("HOME is not set".into()))?; + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&dir) + .map_err(failed)?; + // An existing directory keeps whatever mode it had; tighten it. + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).map_err(failed)?; + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .custom_flags(libc::O_NOFOLLOW) + .open(dir.join("cli-pairings.lock")) + .map_err(failed)?; + // SAFETY: a valid open descriptor; flock has no other preconditions. + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 { + return Err(failed(std::io::Error::last_os_error())); + } + Ok(Box::new(file)) + } +} + +/// The stored map. An unreadable entry is refused, never treated as empty, +/// so no write can replace it with less. +fn parse_pairings(json: Option) -> Result { + match json { + None => Ok(Pairings::default()), + Some(json) => serde_json::from_str(&json).map_err(|_| { + CliError::Auth( + "the CLI's paired tokens in the OS keychain are unreadable; \ + run `buzz auth desktop unpair` to clear them, then pair again" + .into(), + ) + }), + } +} + +/// Reload the map under the lock, apply `change`, and write it back. +fn update( + store: &dyn PairingStore, + change: impl FnOnce(&mut Pairings) -> R, +) -> Result { + let _guard = store.lock()?; + let mut pairings = parse_pairings(store.read()?)?; + let result = change(&mut pairings); + if pairings.0.is_empty() { + store.write(None)?; + } else { + let json = serde_json::to_string(&pairings) + .map_err(|e| CliError::Other(format!("pairing serialization failed: {e}")))?; + store.write(Some(&json))?; + } + Ok(result) +} + +/// Drop each revoked pairing, unless it was replaced since it was read. +fn forget_revoked(store: &dyn PairingStore, revoked: &[(String, String)]) { + if revoked.is_empty() { + return; + } + let _ = update(store, |pairings| { + for (instance, token) in revoked { + if pairings.0.get(instance).is_some_and(|p| &p.token == token) { + pairings.0.remove(instance); + } + } + }); +} + +// --------------------------------------------------------------------------- +// The chain link, and pairing +// --------------------------------------------------------------------------- + +/// The desktop link for `relay_url`. An inherited token decides the identity: +/// when it cannot serve, the command fails, and a paired token (which acts as +/// the human) is never tried, so an agent's process acts only as that agent +/// unless the owner approves pairing it. Without an +/// inherited token, the first paired token whose instance is advertised. +/// `None` when no paired token applies, so the chain moves on. +pub async fn discover(relay_url: &str) -> Result>, CliError> { + discover_with(inherited()?, &Keychain, advertisements, relay_url).await +} + +/// The relay an agent's inherited credential acts on, for a command given +/// none. `None` without an inherited token, or when `describe` fails (the +/// credential chain reports that); bad input when it acts on several relays. +pub async fn inherited_relay() -> Result, CliError> { + let Some((endpoint, token)) = inherited()? else { + return Ok(None); + }; + let Ok(raw) = call(&endpoint, Some(&token), true, "describe", &[]).await else { + return Ok(None); + }; + let relays = serde_json::from_str::(&raw) + .map(|d| d.relays) + .unwrap_or_default(); + let mut distinct: Vec = Vec::new(); + for relay in relays { + push_distinct(&mut distinct, relay); + } + match distinct.len() { + 0 => Ok(None), + 1 => Ok(distinct.pop()), + _ => Err(CliError::Usage(format!( + "this agent's Buzz credential acts on several relays ({}); pass --relay or set \ + BUZZ_RELAY_URL", + distinct.join(", ") + ))), + } +} + +/// Add `relay` to `list` in bound form, unless it is already there. +fn push_distinct(list: &mut Vec, relay: String) { + if !list.iter().any(|known| same_relay(known, &relay)) { + list.push(provider_relay_url(&relay).unwrap_or(relay)); + } +} + +/// The relay a paired person's command given none acts on: the one relay a +/// running desktop still accepts this CLI's pairing for, by its `describe`. +/// A stored pairing alone does not count, since its desktop may have revoked +/// it or stopped. `None` for an agent (its inherited token decides), or when +/// no relay or several qualify. +pub async fn paired_relay() -> Result, CliError> { + if inherited()?.is_some() { + return Ok(None); + } + accepted_relay(&Keychain, advertisements()).await +} + +async fn accepted_relay( + store: &dyn PairingStore, + advertised: Vec<(String, Endpoint)>, +) -> Result, CliError> { + let Ok(Ok(pairings)) = store.read().map(parse_pairings) else { + return Ok(None); + }; + let mut accepted = Vec::new(); + let mut transient = None; + for (instance, endpoint) in advertised { + let Some(pairing) = pairings.0.get(&instance) else { + continue; + }; + match probe(&endpoint, pairing, RATE_LIMIT_RETRIES).await { + Probe::Accepted(relays) => { + for relay in relays { + push_distinct(&mut accepted, relay); + } + } + Probe::NotAccepted | Probe::NotRunning => {} + // A desktop that answered with a refusal has decided. + Probe::Refused(e) => return Err(e), + Probe::Unconfirmed(e) | Probe::Throttled(e) => keep_transient(&mut transient, e), + } + } + match (accepted.len(), transient) { + // A desktop whose check failed may accept a relay of its own: report + // it rather than pick, or fall back to, a relay it might contradict. + (0 | 1, Some(e)) => Err(e), + (1, None) => Ok(accepted.pop()), + _ => Ok(None), + } +} + +/// Keep the first transient failure, except that a retryable one replaces an +/// identity mismatch: the command may succeed once that desktop answers. +fn keep_transient(kept: &mut Option, e: CliError) { + let better = kept.as_ref().is_none_or(|k| { + !crate::error::is_retryable_error(k) && crate::error::is_retryable_error(&e) + }); + if better { + *kept = Some(e); + } +} + +/// What a running desktop says about a stored pairing now. +enum Probe { + /// The pairing's relays it still binds for the token. + Accepted(Vec), + /// It answered: the token is revoked, or binds none of the relays. + NotAccepted, + /// The advertised endpoint could not be reached or did not answer. + NotRunning, + /// The same-user check timed out, or the port's owner is another user. + Unconfirmed(CliError), + /// It is still rate-limiting after `retries` waits. + Throttled(CliError), + /// It refused `describe` (`denied`, `unavailable`, ...): final. + Refused(CliError), +} + +/// Ask the desktop at `endpoint`, on a same-user connection, which of +/// `pairing`'s relays it binds for its token. The one check behind both the +/// default relay and `auth desktop list`. +async fn probe(endpoint: &Endpoint, pairing: &Pairing, retries: u32) -> Probe { + let raw = match call_with( + endpoint, + Some(&pairing.token), + true, + "describe", + retries, + &Vec::new, + ) + .await + { + Ok(raw) => raw, + Err(ProviderError::Revoked | ProviderError::NoCommonVersion) => return Probe::NotAccepted, + Err(ProviderError::Transport(_)) => return Probe::NotRunning, + Err(e @ (ProviderError::Unconfirmed | ProviderError::OtherUser)) => { + return Probe::Unconfirmed(e.into_cli("describe")) + } + Err( + e @ ProviderError::Code { + code: "rate_limited", + .. + }, + ) => return Probe::Throttled(e.into_cli("describe")), + Err(e) => return Probe::Refused(e.into_cli("describe")), + }; + let Ok(describe) = serde_json::from_str::(&raw) else { + return Probe::Refused(CliError::Auth( + "Buzz desktop: unreadable `describe` answer".into(), + )); + }; + let mut accepted = Vec::new(); + for relay in describe.relays { + let bound = provider_relay_url(&relay).is_ok_and(|bound| { + pairing + .relays + .iter() + .any(|paired| same_relay(&bound, paired)) + }); + if bound { + push_distinct(&mut accepted, relay); + } + } + if accepted.is_empty() { + Probe::NotAccepted + } else { + Probe::Accepted(accepted) + } +} + +/// This CLI's pairings, without their tokens, each with what a running +/// desktop says about it now: `accepted`, `not accepted` (revoked or no +/// longer bound), `not running`, `unconfirmed` (same-user check failed), +/// `rate limited` or `refused`. Local and read-only. Desktops are asked at +/// once, each without waiting out throttling. +pub async fn list() -> Result, CliError> { + list_with(&Keychain, advertisements()).await +} + +async fn list_with( + store: &dyn PairingStore, + advertised: Vec<(String, Endpoint)>, +) -> Result, CliError> { + let pairings = parse_pairings(store.read()?)?; + let rows = pairings.0.into_iter().map(|(instance, pairing)| { + let running = advertised + .iter() + .find(|(i, _)| *i == instance) + .map(|(_, e)| e.clone()); + async move { + let (status, error) = match running { + None => ("not running", None), + Some(endpoint) => match probe(&endpoint, &pairing, 0).await { + Probe::Accepted(_) => ("accepted", None), + Probe::NotAccepted => ("not accepted", None), + Probe::NotRunning => ("not running", None), + Probe::Unconfirmed(e) => ("unconfirmed", Some(e)), + Probe::Throttled(e) => ("rate limited", Some(e)), + Probe::Refused(e) => ("refused", Some(e)), + }, + }; + let mut row = serde_json::json!({ + "instance": instance, + "relays": pairing.relays, + "pubkey": pairing.pubkey, + "status": status, + }); + if let Some(e) = error { + row["error"] = e.to_string().into(); + } + row + } + }); + let asked: Vec<_> = rows.map(tokio::spawn).collect(); + let mut listed = Vec::with_capacity(asked.len()); + for row in asked { + listed.push( + row.await + .map_err(|e| CliError::Other(format!("listing failed: {e}")))?, + ); + } + Ok(listed) +} + +/// The relays this CLI's stored pairings are for, in bound form, without +/// asking any desktop. For error hints only: a stored pairing may be stale. +pub fn paired_relays() -> Vec { + // Tests never read the real keychain. + #[cfg(test)] + return Vec::new(); + #[cfg(not(test))] + paired_relays_in(&Keychain) +} + +fn paired_relays_in(store: &dyn PairingStore) -> Vec { + let Ok(Ok(pairings)) = store.read().map(parse_pairings) else { + return Vec::new(); + }; + let mut relays = Vec::new(); + for relay in pairings.0.into_values().flat_map(|p| p.relays) { + push_distinct(&mut relays, relay); + } + relays +} + +async fn discover_with( + inherited: Option<(Endpoint, String)>, + store: &dyn PairingStore, + advertised: impl FnOnce() -> Vec<(String, Endpoint)>, + relay_url: &str, +) -> Result>, CliError> { + match inherited { + Some((endpoint, token)) => inherited_link(endpoint, token, relay_url).await.map(Some), + None => paired_link(store, advertised(), relay_url).await, + } +} + +async fn inherited_link( + endpoint: Endpoint, + token: String, + relay_url: &str, +) -> Result, CliError> { + match Provider::open(endpoint, token, true, relay_url).await? { + Ok(provider) => Ok(provider), + Err(Skip::Revoked) => Err(CliError::Auth( + "the Buzz desktop revoked this agent's credential; restart the agent in Buzz".into(), + )), + Err(Skip::NotApplicable) => Err(CliError::Auth(format!( + "this agent's Buzz credential does not act on {relay_url}" + ))), + Err(Skip::Unreachable) => Err(CliError::Auth( + "the Buzz desktop that launched this agent is not reachable".into(), + )), + Err(Skip::Unconfirmed) => Err(ProviderError::Unconfirmed.into_cli("describe")), + } +} + +async fn paired_link( + store: &dyn PairingStore, + advertised: Vec<(String, Endpoint)>, + relay_url: &str, +) -> Result>, CliError> { + // A missing keychain only means there are no paired tokens to use here. + let Ok(Ok(pairings)) = store.read().map(parse_pairings) else { + return Ok(None); + }; + let relay = provider_relay_url(relay_url)?; + let mut revoked = Vec::new(); + let mut unconfirmed = false; + let mut found = Ok(None); + for (instance, endpoint) in advertised { + let Some(pairing) = pairings.0.get(&instance) else { + continue; + }; + if !pairing.relays.iter().any(|r| same_relay(&relay, r)) { + continue; + } + match Provider::open(endpoint, pairing.token.clone(), true, relay_url).await { + Ok(Ok(provider)) => { + found = Ok(Some(provider)); + break; + } + Ok(Err(Skip::Revoked)) => { + revoked.push((instance.clone(), pairing.token.clone())); + eprintln!( + "warning: Buzz ({instance}) revoked this CLI's pairing; \ + run `buzz auth desktop pair` to pair again" + ); + } + // A stale or unconfirmed advertisement decides nothing: skip it. + Ok(Err(Skip::NotApplicable | Skip::Unreachable)) => {} + // A same-user check that ran out of time decided nothing either, + // but if nothing else serves, the command is worth retrying. + Ok(Err(Skip::Unconfirmed)) => unconfirmed = true, + // The desktop answered (denied, unavailable, ...): that is final. + Err(e) => { + found = Err(e); + break; + } + } + } + forget_revoked(store, &revoked); + match found { + Ok(None) if unconfirmed => Err(ProviderError::Unconfirmed.into_cli("describe")), + found => found, + } +} + +#[derive(serde::Deserialize)] +struct Paired { + token: String, + instance: String, + pubkey: String, + relays: Vec, +} + +/// Ask the running desktop to pair this CLI for `relay_url`, or for its active +/// community when `None`, holding until the person decides, and store the +/// token in the OS keychain. +pub async fn pair( + relay_url: Option<&str>, + client_name: &str, + instance: Option<&str>, +) -> Result { + pair_among( + &Keychain, + advertisements(), + relay_url, + client_name, + instance, + ) + .await +} + +/// [`pair`] among the `found` desktops that are running, storing in `store`. +async fn pair_among( + store: &dyn PairingStore, + mut found: Vec<(String, Endpoint)>, + relay_url: Option<&str>, + client_name: &str, + instance: Option<&str>, +) -> Result { + if let Some(want) = instance { + found.retain(|(i, _)| i == want); + } + // A desktop that exited without removing its advertisement is not running. + let mut running = Vec::new(); + for (instance, endpoint) in found { + if is_running(&endpoint).await { + running.push((instance, endpoint)); + } + } + let mut found = running; + let (instance, endpoint) = match found.len() { + 0 => { + return Err(CliError::Auth( + "no running Buzz desktop found; open Buzz and try again".into(), + )) + } + 1 => found.remove(0), + _ => { + let names: Vec<_> = found.iter().map(|(i, _)| i.as_str()).collect(); + return Err(CliError::Usage(format!( + "several Buzz desktops are running ({}); pass --instance", + names.join(", ") + ))); + } + }; + pair_with(store, instance, endpoint, relay_url, client_name).await +} + +/// Whether a desktop answers at `endpoint`, by the same test as [`probe`]: +/// only a transport failure means it is not running. Without a token it +/// answers `revoked`. Nothing secret is sent, so this skips the same-user +/// check; the `pair` that follows makes it. +async fn is_running(endpoint: &Endpoint) -> bool { + !matches!( + call_with(endpoint, None, false, "describe", 0, &Vec::new).await, + Err(ProviderError::Transport(_)) + ) +} + +async fn pair_with( + store: &dyn PairingStore, + instance: String, + endpoint: Endpoint, + relay_url: Option<&str>, + client_name: &str, +) -> Result { + // Fail on a missing or unreadable keychain before asking for approval. + parse_pairings(store.read()?)?; + let mut params = vec![client_name.to_owned()]; + if let Some(relay_url) = relay_url { + params.push(provider_relay_url(relay_url)?); + } + let raw = call(&endpoint, None, true, "pair", ¶ms) + .await + .map_err(|e| match e { + // A desktop older than community-less pairing rejects it as malformed. + ProviderError::Code { + code: "invalid_request", + .. + } if relay_url.is_none() => { + CliError::Usage("this Buzz can't pick a community; pass --relay".into()) + } + e => e.into_cli("pair"), + })?; + let paired: Paired = serde_json::from_str(&raw) + .map_err(|_| CliError::Auth("Buzz desktop: unreadable `pair` answer".into()))?; + if paired.instance != instance + || !usable_token(&paired.token) + || PublicKey::from_hex(&paired.pubkey).is_err() + { + return Err(CliError::Auth( + "Buzz desktop returned an invalid pairing".into(), + )); + } + let summary = serde_json::json!({ + "instance": instance, + "pubkey": paired.pubkey, + "relays": paired.relays, + }); + // Reload at commit time: only this instance changes, and a new pairing + // replaces its old token. + update(store, |pairings| { + pairings.0.insert( + instance, + Pairing { + token: paired.token, + pubkey: paired.pubkey, + relays: paired.relays, + }, + ); + })?; + Ok(summary) +} + +/// Forget paired tokens: one instance's, or all of them. Local only. +pub fn unpair(instance: Option<&str>) -> Result { + unpair_with(&Keychain, instance) +} + +fn unpair_with( + store: &dyn PairingStore, + instance: Option<&str>, +) -> Result { + let removed = match instance { + Some(i) => update(store, |pairings| { + pairings + .0 + .remove(i) + .map(|_| vec![i.to_owned()]) + .unwrap_or_default() + })?, + // Clearing everything needs no read, so it also clears an unreadable entry. + None => { + let _guard = store.lock()?; + let removed = store + .read()? + .map(|json| parse_pairings(Some(json)).map(|p| p.0.into_keys().collect())) + .transpose() + .unwrap_or_default() + .unwrap_or_default(); + store.write(None)?; + removed + } + }; + Ok(serde_json::json!({ "removed": removed })) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::ownership::{lsof_uid, proc_net_tcp_uid}; + use super::*; + use crate::cached_assertion::unix_now; + + tokio::task_local! { + /// Pretend the caller runs as this user ID. + pub(crate) static CALLER_UID: u32; + /// Make every same-user check run out of time. + pub(crate) static SAME_USER_HANGS: (); + } + + use std::sync::Mutex as StdMutex; + + #[test] + fn endpoint_must_be_loopback_http_ipv4() { + assert!(Endpoint::parse("http://127.0.0.1:4100/rpc").is_ok()); + for bad in [ + "https://127.0.0.1:4100/rpc", + "http://localhost:4100/rpc", + "http://[::1]:4100/rpc", + "http://user@127.0.0.1:4100/rpc", + "http://10.0.0.1:4100/rpc", + "http://127.0.0.1/rpc", + ] { + assert!(Endpoint::parse(bad).is_err(), "{bad}"); + } + } + + #[test] + fn unrecognized_codes_are_denied() { + assert_eq!(known_code("approval_required"), "approval_required"); + assert_eq!(known_code("brand_new_code"), "denied"); + } + + #[test] + fn held_methods_get_the_long_timeout() { + assert!(held("sign_event") && held("nip44_decrypt") && held("pair")); + assert!(!held("describe") && !held("federated_identity")); + } + + /// Serves `body` as one raw HTTP response and returns what `exchange` makes of it. + async fn exchanged(body: Vec) -> Result<(u16, Vec), ProviderError> { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + // Read the whole request first: closing with any of it unread + // resets the connection and loses the reply. + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n{}") { + let mut chunk = [0u8; 4096]; + match tokio::io::AsyncReadExt::read(&mut stream, &mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => request.extend_from_slice(&chunk[..n]), + } + } + let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len()); + let _ = stream.write_all(head.as_bytes()).await; + let _ = stream.write_all(&body).await; + let _ = stream.shutdown().await; + }); + let endpoint = Endpoint::parse(&format!("http://127.0.0.1:{port}/rpc")).unwrap(); + let stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + let reply = exchange(stream, &endpoint, Some("t"), VERSION, b"{}").await; + server.abort(); + reply + } + + #[tokio::test] + async fn the_largest_signed_event_fits_and_more_is_refused() { + const CANVAS_BYTES: usize = 512 * 1024; + // An event at the desktop's limit whose content is all quotes, so + // every content byte doubles again when the event is the result string. + let shell = + r#"{"id":"","pubkey":"","created_at":0,"kind":40100,"tags":[],"content":"","sig":""}"#; + let content = "\"".repeat((CANVAS_BYTES - shell.len()) / 2); + let event = serde_json::json!({ + "id": "", "pubkey": "", "created_at": 0, "kind": 40100, "tags": [], + "content": content, "sig": "", + }) + .to_string(); + assert!(event.len() <= CANVAS_BYTES && event.len() > CANVAS_BYTES - 16); + // An agent note isn't bound by the relay frame: 64 KiB of content and + // 99 quote-filled 4 KiB tags, over the old Canvas-based cap once escaped. + let tags: Vec<_> = (0..99) + .map(|i| serde_json::json!(["t", format!("{i}{}", "\"".repeat(4000))])) + .collect(); + let note = serde_json::json!({ + "id": "", "pubkey": "", "created_at": 0, "kind": 30023, "tags": tags, + "content": "\"".repeat(64 * 1024), "sig": "", + }) + .to_string(); + // A decrypt whose base64 payload fills the request: its plaintext, + // three quarters of that, all control characters (`\u0001`, six bytes). + let plaintext = "\u{1}".repeat(MAX_REQUEST_BYTES / 4 * 3 - 64 * 1024); + for result in [event, note, plaintext] { + let body = serde_json::json!({ "id": "1", "result": result }) + .to_string() + .into_bytes(); + let (status, parsed) = exchanged(body.clone()).await.unwrap(); + assert_eq!((status, parsed), (200, body)); + } + let runaway = vec![b'x'; MAX_RESPONSE_BYTES]; + assert!(matches!( + exchanged(runaway).await, + Err(ProviderError::Transport(message)) if message == "response too large" + )); + } + + #[test] + fn parses_content_length_and_chunked_responses() { + let fixed = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhiEXTRA"; + assert_eq!(parse_response(fixed), Some((200, b"hi".to_vec()))); + let chunked = + b"HTTP/1.1 403 Forbidden\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n"; + assert_eq!(parse_response(chunked), Some((403, b"abcde".to_vec()))); + assert_eq!(parse_response(b"garbage"), None); + } + + #[test] + fn proc_net_tcp_finds_the_server_side_of_this_connection() { + let table = " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n\ + 0: 0100007F:1004 00000000:0000 0A 00000000:00000000 00:00000000 00000000 501 0 1\n\ + 1: 0100007F:1004 0100007F:C350 01 00000000:00000000 00:00000000 00000000 502 0 2\n\ + 2: 0100007F:C350 0100007F:1004 01 00000000:00000000 00:00000000 00000000 501 0 3\n"; + assert_eq!(proc_net_tcp_uid(table, 0x1004, 0xC350), Some(502)); + assert_eq!(proc_net_tcp_uid(table, 0x1004, 0xC351), None); + } + + #[test] + fn lsof_finds_the_server_side_of_this_connection() { + let out = "p100\nu501\nn127.0.0.1:50000->127.0.0.1:4100\np200\nu502\nn127.0.0.1:4100->127.0.0.1:50000\n"; + assert_eq!(lsof_uid(out, 4100, 50000), Some(502)); + assert_eq!(lsof_uid(out, 4100, 50001), None); + } + + #[test] + fn advertisements_require_private_ownership() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let ads = dir.path().join("providers"); + std::fs::create_dir(&ads).unwrap(); + let write = |name: &str, mode: u32| { + let path = ads.join(name); + std::fs::write( + &path, + r#"{"instance":"xyz.block.buzz","url":"http://127.0.0.1:4100/rpc"}"#, + ) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + }; + write("good.json", 0o600); + write("open.json", 0o644); + write(".partial.json", 0o600); + std::fs::set_permissions(&ads, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!( + advertisements_in(&ads).is_empty(), + "a group-readable directory is ignored" + ); + std::fs::set_permissions(&ads, std::fs::Permissions::from_mode(0o700)).unwrap(); + let found = advertisements_in(&ads); + assert_eq!(found.len(), 1); + assert_eq!(found[0].0, "xyz.block.buzz"); + assert_eq!(found[0].1.port, 4100); + } + + // ----------------------------------------------------------------------- + // Against a mock provider + // ----------------------------------------------------------------------- + + pub(crate) type Seen = Arc, String, serde_json::Value)>>>; + + /// A provider answering each envelope with `respond(version, request)`. + pub(crate) async fn provider(respond: F) -> (Endpoint, Seen) + where + F: Fn(&str, &serde_json::Value) -> serde_json::Value + Send + Sync + 'static, + { + use axum::http::HeaderMap; + let seen: Seen = Arc::default(); + let log = seen.clone(); + let respond = Arc::new(respond); + let app = axum::Router::new().route( + "/rpc", + axum::routing::post(move |headers: HeaderMap, body: axum::body::Bytes| { + let (log, respond) = (log.clone(), respond.clone()); + async move { + let request: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let header = |n: &str| { + headers + .get(n) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + }; + let version = header(VERSION_HEADER).unwrap_or_default(); + let mut answer = respond(&version, &request); + answer["id"] = request["id"].clone(); + log.lock() + .unwrap() + .push((header("authorization"), version, request)); + axum::Json(answer) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + ( + Endpoint::parse(&format!("http://127.0.0.1:{port}/rpc")).unwrap(), + seen, + ) + } + + const RELAY: &str = "wss://community.example"; + + fn describe(relays: &[&str]) -> serde_json::Value { + let pubkey = nostr::Keys::generate().public_key().to_hex(); + serde_json::json!({"result": serde_json::json!({ + "instance": "xyz.block.buzz", "pubkey": pubkey, "role": "owner", + "relays": relays, "methods": ["get_public_key", "sign_event"], + }).to_string()}) + } + + #[tokio::test] + async fn describe_sends_token_and_version_and_binds_the_relay() { + let (endpoint, seen) = provider(|_, _| describe(&[RELAY])).await; + let opened = Provider::open(endpoint, "tok".into(), false, RELAY) + .await + .unwrap(); + assert!(opened.is_ok()); + let seen = seen.lock().unwrap(); + assert_eq!(seen[0].0.as_deref(), Some("Bearer tok")); + assert_eq!(seen[0].1, "1"); + assert_eq!(seen[0].2["method"], "describe"); + } + + #[tokio::test] + async fn short_and_long_assertions_refresh_at_the_earlier_point() { + use base64::Engine; + for (lifetime, refresh) in [(20, 10), (300, 150)] { + crate::cached_assertion::test_clock::freeze(1_800_000_000); + let (endpoint, seen) = provider(move |_, request| match request["method"].as_str() { + Some("federated_identity") => { + let b64 = |v: serde_json::Value| { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v.to_string()) + }; + let jws = format!( + "{}.{}.c2ln", + b64(serde_json::json!({"alg": "ES256"})), + b64(serde_json::json!({"exp": unix_now() + lifetime})) + ); + serde_json::json!({ "result": jws }) + } + _ => describe(&[RELAY]), + }) + .await; + let Ok(Ok(provider)) = Provider::open(endpoint, "tok".into(), false, RELAY).await + else { + panic!("the provider should open"); + }; + let mints = || { + let seen = seen.lock().unwrap(); + seen.iter() + .filter(|s| s.2["method"] == "federated_identity") + .count() + }; + provider.federated_identity().await.unwrap(); + crate::cached_assertion::test_clock::advance(refresh - 1); + provider.federated_identity().await.unwrap(); + assert_eq!(mints(), 1, "lifetime {lifetime}"); + crate::cached_assertion::test_clock::advance(1); + provider.federated_identity().await.unwrap(); + assert_eq!(mints(), 2, "lifetime {lifetime}"); + } + } + + #[tokio::test] + async fn an_unbound_relay_or_revoked_token_falls_through() { + let (endpoint, _) = provider(|_, _| describe(&["wss://other.example"])).await; + let opened = Provider::open(endpoint, "tok".into(), false, RELAY) + .await + .unwrap(); + assert!(matches!(opened, Err(Skip::NotApplicable))); + let (endpoint, _) = + provider(|_, _| serde_json::json!({"result": "", "error": "revoked"})).await; + let opened = Provider::open(endpoint, "tok".into(), false, RELAY) + .await + .unwrap(); + assert!(matches!(opened, Err(Skip::Revoked))); + } + + #[tokio::test] + async fn version_negotiation_retries_once_or_gives_up() { + let (endpoint, seen) = provider(|_, _| { + serde_json::json!({"result": "", "error": "unsupported_version", "versions": [2, 3]}) + }) + .await; + let err = call(&endpoint, Some("tok"), false, "describe", &[]) + .await + .unwrap_err(); + assert!(matches!(err, ProviderError::NoCommonVersion)); + assert_eq!(seen.lock().unwrap().len(), 1); + } + + /// A throttled auth proof is re-sent dated now (its Blossom expiration + /// moved with it); a content event is re-sent exactly as built. + #[tokio::test] + async fn a_throttled_auth_proof_is_renewed_and_a_content_event_is_not() { + use std::sync::atomic::{AtomicBool, Ordering}; + let keys = nostr::Keys::generate(); + let answer = desktop_answers(keys.clone(), vec![RELAY.into()]); + let throttle = Arc::new(AtomicBool::new(false)); + let gate = throttle.clone(); + let (endpoint, seen) = provider(move |version, request| { + if request["method"] == "sign_event" && gate.swap(false, Ordering::SeqCst) { + // As long as a real throttle takes, at least a clock second. + std::thread::sleep(Duration::from_millis(1100)); + return serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 1}); + } + answer(version, request) + }) + .await; + let desktop = match Provider::open(endpoint, "tok".into(), false, RELAY) + .await + .unwrap() + { + Ok(p) => p, + Err(_) => panic!("provider not opened"), + }; + let expiration = |e: &Event| e.tags.expiration().map(|t| t.as_secs()); + + let proof = nostr::EventBuilder::new(nostr::Kind::from(24242), "Upload file") + .tags([Tag::parse(["expiration", &(unix_now() + 60).to_string()]).unwrap()]) + .build(keys.public_key()); + throttle.store(true, Ordering::SeqCst); + let signed = desktop.sign(proof.clone()).await.unwrap(); + assert!( + signed.created_at > proof.created_at, + "the proof kept its old date" + ); + assert_eq!( + expiration(&signed).unwrap() - signed.created_at.as_secs(), + 60, + "the expiration did not move with the date" + ); + + let mut content = + nostr::EventBuilder::new(nostr::Kind::TextNote, "hi").build(keys.public_key()); + let id = content.id(); + throttle.store(true, Ordering::SeqCst); + let signed = desktop.sign(content.clone()).await.unwrap(); + assert_eq!(signed.created_at, content.created_at); + assert_eq!(signed.id, id); + assert!(seen.lock().unwrap().len() >= 5); + } + + #[tokio::test] + async fn rate_limited_is_waited_out_then_reported_as_retryable() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let asked = Arc::new(AtomicUsize::new(0)); + let count = asked.clone(); + let (endpoint, seen) = provider(move |_, _| match count.fetch_add(1, Ordering::SeqCst) { + 0 => serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 1}), + _ => serde_json::json!({"result": "signed"}), + }) + .await; + let started = std::time::Instant::now(); + let result = call(&endpoint, Some("tok"), false, "sign_event", &[]).await; + assert_eq!(result.unwrap(), "signed"); + assert!(started.elapsed() >= RETRY_AFTER_UNIT, "honors retry_after"); + assert_eq!(seen.lock().unwrap().len(), 2); + + let (endpoint, seen) = provider( + |_, _| serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 0}), + ) + .await; + // `retry_after: 0` still waits the 1 s floor, so this takes a few seconds. + let err = call(&endpoint, Some("tok"), false, "sign_event", &[]) + .await + .unwrap_err(); + assert_eq!(seen.lock().unwrap().len(), 1 + RATE_LIMIT_RETRIES as usize); + let err = err.into_cli("sign_event"); + assert!(matches!(err, CliError::Throttled(_)), "{err:?}"); + assert!(crate::error::is_retryable_error(&err)); + } + + #[tokio::test] + async fn a_cooldown_past_the_cap_is_reported_without_retrying() { + let (endpoint, seen) = provider( + |_, _| serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 300}), + ) + .await; + let err = call(&endpoint, None, false, "pair", &[]).await.unwrap_err(); + assert_eq!(seen.lock().unwrap().len(), 1); + let err = err.into_cli("pair"); + assert!( + matches!(&err, CliError::Throttled(m) if m.contains("retry in 300s")), + "{err:?}" + ); + } + + #[tokio::test] + async fn an_error_envelope_for_another_request_is_refused() { + let (endpoint, _) = + provider(|_, _| serde_json::json!({"result": "", "error": "revoked"})).await; + // The mock echoes the request id; a raw server that does not is below. + assert!(matches!( + call(&endpoint, Some("tok"), false, "describe", &[]).await, + Err(ProviderError::Revoked) + )); + let app = axum::Router::new().route( + "/rpc", + axum::routing::post(|| async { + axum::Json(serde_json::json!({"id": "other", "result": "", "error": "revoked"})) + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let endpoint = Endpoint::parse(&format!("http://127.0.0.1:{port}/rpc")).unwrap(); + assert!(matches!( + call(&endpoint, Some("tok"), false, "describe", &[]).await, + Err(ProviderError::Transport(_)) + )); + } + + #[tokio::test] + async fn an_unknown_error_code_is_denied() { + let (endpoint, _) = + provider(|_, _| serde_json::json!({"result": "", "error": "brand_new"})).await; + let err = call(&endpoint, Some("tok"), false, "sign_event", &[]) + .await + .unwrap_err(); + assert!(matches!(err, ProviderError::Code { code: "denied", .. })); + } + + #[tokio::test] + async fn same_user_check_accepts_this_users_provider() { + let (endpoint, _) = provider(|_, _| describe(&[RELAY])).await; + let opened = Provider::open(endpoint, "tok".into(), true, RELAY) + .await + .unwrap(); + assert!(opened.is_ok()); + } + + // ----------------------------------------------------------------------- + // A desktop holding a real key, and an in-memory pairing store + // ----------------------------------------------------------------------- + + /// The assertion the mock desktop hands out for any relay. + pub(crate) fn mock_assertion() -> String { + assertion(600) + } + + /// An assertion that expires `lifetime` s from now. + pub(crate) fn assertion(lifetime: u64) -> String { + use base64::Engine; + let b64 = |v: serde_json::Value| { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v.to_string()) + }; + format!( + "{}.{}.c2ln", + b64(serde_json::json!({"alg": "ES256", "typ": "nip-fi+jwt"})), + b64(serde_json::json!({"exp": unix_now() + lifetime})) + ) + } + + /// A desktop acting as `keys` for `relays`: it signs, encrypts, decrypts + /// (answering `invalid_request` for bad ciphertext, as #2260 does), + /// derives engram `d` tags and hands out [`mock_assertion`]. + pub(crate) async fn desktop(keys: nostr::Keys, relays: Vec) -> (Endpoint, Seen) { + provider(desktop_answers(keys, relays)).await + } + + /// [`desktop`]'s answers, for a provider that wraps them. + pub(crate) fn desktop_answers( + keys: nostr::Keys, + relays: Vec, + ) -> impl Fn(&str, &serde_json::Value) -> serde_json::Value + Send + Sync + 'static { + move |_, request| { + let params: Vec = + serde_json::from_value(request["params"].clone()).unwrap_or_default(); + let peer = || PublicKey::from_hex(¶ms[0]).unwrap(); + let ok = |result: String| serde_json::json!({ "result": result }); + match request["method"].as_str().unwrap_or_default() { + "describe" => ok(serde_json::json!({ + "instance": "xyz.block.buzz", "pubkey": keys.public_key().to_hex(), + "role": "owner", "relays": relays, + "methods": ["sign_event", "nip44_decrypt", "federated_identity"], + }) + .to_string()), + "sign_event" => { + let unsigned = UnsignedEvent::from_json(¶ms[0]).unwrap(); + ok(unsigned.sign_with_keys(&keys).unwrap().as_json()) + } + "nip44_encrypt" => ok(nostr::nips::nip44::encrypt( + keys.secret_key(), + &peer(), + ¶ms[1], + nostr::nips::nip44::Version::V2, + ) + .unwrap()), + "nip44_decrypt" => { + match nostr::nips::nip44::decrypt(keys.secret_key(), &peer(), ¶ms[1]) { + Ok(plain) => ok(plain), + Err(_) => serde_json::json!({"result": "", "error": "invalid_request"}), + } + } + "engram_d_tag" => { + let k_c = buzz_core::engram::conversation_key(keys.secret_key(), &peer()); + ok(buzz_core::engram::d_tag(&k_c, ¶ms[1])) + } + "federated_identity" => ok(mock_assertion()), + _ => serde_json::json!({"result": "", "error": "unknown_method"}), + } + } + } + + #[derive(Default)] + struct MemoryStore { + json: StdMutex>, + lock: StdMutex<()>, + } + + impl MemoryStore { + fn with(pairings: &[(&str, &str, &[&str])]) -> Self { + let map: std::collections::BTreeMap<_, _> = pairings + .iter() + .map(|(instance, token, relays)| { + let pairing = Pairing { + token: (*token).into(), + pubkey: nostr::Keys::generate().public_key().to_hex(), + relays: relays.iter().map(|r| (*r).to_owned()).collect(), + }; + ((*instance).to_owned(), pairing) + }) + .collect(); + let store = Self::default(); + *store.json.lock().unwrap() = Some(serde_json::to_string(&Pairings(map)).unwrap()); + store + } + + fn instances(&self) -> Vec { + parse_pairings(self.json.lock().unwrap().clone()) + .unwrap() + .0 + .into_keys() + .collect() + } + } + + impl PairingStore for MemoryStore { + fn read(&self) -> Result, CliError> { + Ok(self.json.lock().unwrap().clone()) + } + fn write(&self, json: Option<&str>) -> Result<(), CliError> { + *self.json.lock().unwrap() = json.map(str::to_owned); + Ok(()) + } + fn lock(&self) -> Result, CliError> { + Ok(Box::new(self.lock.lock().unwrap())) + } + } + + fn methods(seen: &Seen) -> Vec { + seen.lock() + .unwrap() + .iter() + .map(|(_, _, r)| r["method"].as_str().unwrap_or_default().to_owned()) + .collect() + } + + /// An agent whose inherited token is revoked or not bound to the relay + /// fails, even with a valid owner pairing advertised: the owner's + /// desktop gets no request at all. + #[tokio::test] + async fn an_agent_never_falls_back_to_the_owner_pairing() { + let (owner, owner_seen) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let store = MemoryStore::with(&[("xyz.block.buzz", "owner-token", &[RELAY])]); + let (revoked, _) = + provider(|_, _| serde_json::json!({"result": "", "error": "revoked"})).await; + let (unbound, _) = provider(|_, _| describe(&["wss://other.example"])).await; + for agent in [revoked, unbound] { + let ads = || vec![("xyz.block.buzz".to_owned(), owner.clone())]; + let result = discover_with(Some((agent, "agent".into())), &store, ads, RELAY).await; + assert!(matches!(result, Err(CliError::Auth(_))), "{result:?}"); + } + assert!(owner_seen.lock().unwrap().is_empty(), "the owner was asked"); + // Without an inherited token the same pairing is used. + let ads = || vec![("xyz.block.buzz".to_owned(), owner.clone())]; + assert!(discover_with(None, &store, ads, RELAY) + .await + .unwrap() + .is_some()); + assert_eq!( + owner_seen.lock().unwrap()[0].0.as_deref(), + Some("Bearer owner-token") + ); + } + + #[test] + fn relay_urls_bind_whole_after_normalization() { + let norm = |u: &str| provider_relay_url(u).unwrap(); + assert_eq!(norm("https://Host.example"), "wss://host.example/"); + assert_eq!(norm("wss://host.example:443/"), "wss://host.example/"); + assert_eq!(norm("http://127.0.0.1:3000"), "ws://127.0.0.1:3000/"); + assert_eq!(norm("ws://127.0.0.1:80/a"), "ws://127.0.0.1/a"); + assert_eq!(norm("wss://host.example/a?x=1"), "wss://host.example/a?x=1"); + assert_ne!(norm("wss://host.example/a"), norm("wss://host.example/b")); + assert_ne!(norm("ws://host.example"), norm("wss://host.example")); + assert!(provider_relay_url("ftp://host.example").is_err()); + } + + #[tokio::test] + async fn a_token_binds_its_relay_path_and_plain_ws() { + let bound = vec![ + "wss://host.example/a".to_owned(), + "ws://127.0.0.1:7000".to_owned(), + ]; + let (endpoint, _) = desktop(nostr::Keys::generate(), bound).await; + let open = |relay: &'static str| { + let endpoint = endpoint.clone(); + async move { + Provider::open(endpoint, "t".into(), false, relay) + .await + .unwrap() + } + }; + assert!(open("https://host.example/a").await.is_ok()); + assert!(matches!( + open("https://host.example/b").await, + Err(Skip::NotApplicable) + )); + assert!(matches!( + open("https://host.example").await, + Err(Skip::NotApplicable) + )); + assert!(open("http://127.0.0.1:7000/").await.is_ok()); + } + + #[tokio::test] + async fn bad_ciphertext_is_invalid_but_a_credential_failure_is_an_error() { + let keys = nostr::Keys::generate(); + let peer = nostr::Keys::generate(); + let (endpoint, _) = desktop(keys.clone(), vec![RELAY.into()]).await; + let p = Provider::open(endpoint, "t".into(), false, RELAY) + .await + .unwrap() + .ok() + .unwrap(); + let good = nostr::nips::nip44::encrypt( + peer.secret_key(), + &keys.public_key(), + "hi", + nostr::nips::nip44::Version::V2, + ) + .unwrap(); + let plain = p.nip44_decrypt(&peer.public_key(), &good).await.unwrap(); + assert_eq!(plain.as_deref(), Some("hi")); + assert!(p + .nip44_decrypt(&peer.public_key(), "AAAA") + .await + .unwrap() + .is_none()); + for code in ["revoked", "denied", "unavailable"] { + let (endpoint, _) = provider(move |_, r| match r["method"].as_str() { + Some("describe") => describe(&[RELAY]), + _ => serde_json::json!({"result": "", "error": code}), + }) + .await; + let p = Provider::open(endpoint, "t".into(), false, RELAY) + .await + .unwrap() + .ok() + .unwrap(); + assert!( + p.nip44_decrypt(&peer.public_key(), &good).await.is_err(), + "{code}" + ); + } + } + + #[tokio::test] + async fn a_paired_desktop_that_refuses_fails_and_revoked_entries_are_forgotten() { + let (denied, _) = + provider(|_, _| serde_json::json!({"result": "", "error": "denied"})).await; + let store = MemoryStore::with(&[("a", "ta", &[RELAY])]); + let ads = || vec![("a".to_owned(), denied)]; + assert!(discover_with(None, &store, ads, RELAY).await.is_err()); + + let (revoked, _) = + provider(|_, _| serde_json::json!({"result": "", "error": "revoked"})).await; + let (good, _) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let store = MemoryStore::with(&[("a", "ta", &[RELAY]), ("b", "tb", &[RELAY])]); + let ads = || vec![("a".to_owned(), revoked), ("b".to_owned(), good)]; + assert!(discover_with(None, &store, ads, RELAY) + .await + .unwrap() + .is_some()); + assert_eq!(store.instances(), ["b"]); + } + + /// A pairing waiting for approval does not hold the store, and its commit + /// reloads: a concurrent unpair stays unpaired and a concurrent pairing + /// is kept. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn concurrent_pair_and_unpair_keep_each_others_changes() { + let pubkey = nostr::Keys::generate().public_key().to_hex(); + // `started` says the approval is pending; `release` lets it answer. + let (started_tx, started) = std::sync::mpsc::channel::<()>(); + let (release, release_rx) = std::sync::mpsc::channel::<()>(); + let (started_tx, release_rx) = (StdMutex::new(started_tx), StdMutex::new(release_rx)); + let (slow, _) = provider(move |_, _| { + started_tx.lock().unwrap().send(()).unwrap(); + release_rx.lock().unwrap().recv().unwrap(); + serde_json::json!({"result": serde_json::json!({ + "token": "tb", "instance": "b", "pubkey": pubkey, "relays": [RELAY], + }).to_string()}) + }) + .await; + let store = Arc::new(MemoryStore::with(&[("a", "ta", &[RELAY])])); + let pairing = { + let store = store.clone(); + tokio::spawn(async move { + pair_with(store.as_ref(), "b".into(), slow, Some(RELAY), "cli").await + }) + }; + // Fail, not hang, if the pair request never reaches the desktop. + tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(60))) + .await + .unwrap() + .expect("the pair request never reached the desktop"); + unpair_with(store.as_ref(), Some("a")).unwrap(); + update(store.as_ref(), |p| { + assert!(!p.0.contains_key("b")); + p.0.insert( + "c".into(), + Pairing { + token: "tc".into(), + pubkey: String::new(), + relays: vec![], + }, + ); + }) + .unwrap(); + release.send(()).unwrap(); + pairing.await.unwrap().unwrap(); + assert_eq!(store.instances(), ["b", "c"]); + } + + /// Through the CLI's own wiring of `--relay`, a community ending in a + /// slash reaches the desktop exactly as configured, for inherited + /// discovery, evidence and pairing. + #[tokio::test] + async fn a_non_root_trailing_slash_relay_reaches_the_desktop_unchanged() { + use clap::Parser; + const TEAM: &str = "wss://host.example/team/"; + let parse = |args: &[&str]| crate::Cli::try_parse_from(args).unwrap(); + let store = MemoryStore::default(); + + let (endpoint, seen) = desktop(nostr::Keys::generate(), vec![TEAM.into()]).await; + let cli = parse(&["buzz", "--relay", TEAM, "users", "get"]); + let (_, client) = crate::connect( + cli.relay.as_deref(), + cli.command, + async |_, _| unreachable!(), + { + let store = &store; + async move |relay| { + let provider = + discover_with(Some((endpoint, "agent".into())), store, Vec::new, relay) + .await? + .unwrap(); + crate::credentials::Credentials::from_desktop(provider).await + } + }, + ) + .await + .unwrap() + .unwrap(); + client.credentials().evidence().await.unwrap(); + let asked = seen.lock().unwrap().last().unwrap().2.clone(); + assert_eq!(asked["params"], serde_json::json!([TEAM])); + + let pubkey = nostr::Keys::generate().public_key().to_hex(); + let (endpoint, seen) = provider(move |_, _| { + serde_json::json!({"result": serde_json::json!({ + "token": "tok", "instance": "i", "pubkey": pubkey, "relays": [TEAM], + }).to_string()}) + }) + .await; + let cli = parse(&[ + "buzz", "--relay", TEAM, "auth", "desktop", "pair", "--name", "cli", + ]); + let paired = crate::connect( + cli.relay.as_deref(), + cli.command, + async |sub, relay| { + let crate::AuthCmd::Desktop(crate::DesktopAuthCmd::Pair { name, .. }) = sub else { + unreachable!() + }; + pair_with(&store, "i".into(), endpoint, relay, &name) + .await + .map(drop) + }, + async |_| unreachable!(), + ) + .await + .unwrap(); + assert!(paired.is_none()); + let asked = seen.lock().unwrap()[0].2.clone(); + assert_eq!(asked["params"], serde_json::json!(["cli", TEAM])); + } + + #[tokio::test] + async fn an_unreadable_store_is_refused_not_overwritten() { + let (endpoint, seen) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let store = MemoryStore::default(); + *store.json.lock().unwrap() = Some("not json".into()); + assert!(pair_with( + &store, + "xyz.block.buzz".into(), + endpoint, + Some(RELAY), + "cli" + ) + .await + .is_err()); + assert!(seen.lock().unwrap().is_empty(), "approval was requested"); + assert!(unpair_with(&store, Some("a")).is_err()); + assert_eq!(store.json.lock().unwrap().as_deref(), Some("not json")); + unpair_with(&store, None).unwrap(); + assert!(store.json.lock().unwrap().is_none()); + } + + /// `pair` sends the whole bound URL, and the token it gets back is stored. + #[tokio::test] + async fn pair_sends_the_bound_url_and_stores_the_token() { + let pubkey = nostr::Keys::generate().public_key().to_hex(); + let (endpoint, seen) = provider(move |_, _| { + serde_json::json!({"result": serde_json::json!({ + "token": "tok", "instance": "i", "pubkey": pubkey, + "relays": ["wss://host.example/a"], + }).to_string()}) + }) + .await; + let store = MemoryStore::default(); + pair_with( + &store, + "i".into(), + endpoint, + Some("https://host.example/a"), + "cli", + ) + .await + .unwrap(); + let request = seen.lock().unwrap()[0].2.clone(); + assert_eq!( + request["params"], + serde_json::json!(["cli", "wss://host.example/a"]) + ); + assert_eq!(store.instances(), ["i"]); + unpair_with(&store, Some("i")).unwrap(); + assert!(store.json.lock().unwrap().is_none()); + } + + /// A paired desktop whose user cannot be confirmed is skipped without a + /// byte sent, so the chain moves on; a check that only ran out of time + /// leaves the command retryable rather than without credentials. + #[tokio::test] + async fn an_unconfirmed_paired_desktop_is_skipped() { + let (endpoint, seen) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let store = MemoryStore::with(&[("a", "ta", &[RELAY])]); + let ads = || vec![("a".to_owned(), endpoint.clone())]; + let found = CALLER_UID + .scope(u32::MAX - 1, discover_with(None, &store, ads, RELAY)) + .await + .unwrap(); + assert!(found.is_none()); + + let ads = || vec![("a".to_owned(), endpoint.clone())]; + let err = SAME_USER_HANGS + .scope((), discover_with(None, &store, ads, RELAY)) + .await + .unwrap_err(); + assert!(crate::error::is_retryable_error(&err), "{err:?}"); + assert_eq!(crate::error::exit_code(&err), 2); + assert!(seen.lock().unwrap().is_empty()); + assert_eq!(store.instances(), ["a"]); + } + + /// A command given no relay uses the one relay a running desktop still + /// accepts a pairing for, never a stored pairing alone. + #[tokio::test] + async fn the_default_relay_is_the_one_a_running_desktop_accepts() { + const OTHER: &str = "wss://other.example/"; + let (good, _) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let (other, _) = desktop(nostr::Keys::generate(), vec![OTHER.into()]).await; + let (revoked, _) = + provider(|_, _| serde_json::json!({"result": "", "error": "revoked"})).await; + let gone = Endpoint::parse("http://127.0.0.1:1/rpc").unwrap(); + let store = MemoryStore::with(&[ + ("a", "ta", &[RELAY]), + ("b", "tb", &[OTHER]), + ("c", "tc", &[OTHER]), + ("d", "td", &[OTHER]), + ]); + let ad = |i: &str, e: &Endpoint| (i.to_owned(), e.clone()); + + let one = vec![ad("a", &good), ad("c", &revoked), ad("d", &gone)]; + assert_eq!( + accepted_relay(&store, one).await.unwrap().as_deref(), + Some("wss://community.example/") + ); + // Several accepted relays, or none, keep the built-in default. + let two = vec![ad("a", &good), ad("b", &other)]; + assert_eq!(accepted_relay(&store, two).await.unwrap(), None); + let none = vec![ad("c", &revoked), ad("d", &gone)]; + assert_eq!(accepted_relay(&store, none).await.unwrap(), None); + // A desktop that no longer binds the paired relay does not count. + let rebound = vec![ad("b", &good)]; + assert_eq!(accepted_relay(&store, rebound).await.unwrap(), None); + + assert_eq!( + paired_relays_in(&store), + ["wss://community.example/", OTHER] + ); + } + + /// With no relay given, a desktop that refuses is final, and a check that + /// may pass on retry stays retryable, never a fallback to localhost. + #[tokio::test] + async fn the_default_relay_keeps_desktop_failures() { + let store = MemoryStore::with(&[("a", "ta", &[RELAY])]); + let (denied, _) = provider( + |_, _| serde_json::json!({"result": "", "error": "denied", "message": "locked"}), + ) + .await; + let err = accepted_relay(&store, vec![("a".into(), denied)]) + .await + .unwrap_err(); + assert!(!crate::error::is_retryable_error(&err), "{err:?}"); + assert!(err.to_string().contains("locked"), "{err}"); + + let (throttled, _) = provider( + |_, _| serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 1}), + ) + .await; + let err = accepted_relay(&store, vec![("a".into(), throttled)]) + .await + .unwrap_err(); + assert!(crate::error::is_retryable_error(&err), "{err:?}"); + + let (good, _) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let err = SAME_USER_HANGS + .scope((), accepted_relay(&store, vec![("a".into(), good.clone())])) + .await + .unwrap_err(); + assert_eq!(crate::error::exit_code(&err), 2, "{err:?}"); + + // A still-throttled desktop might add a second relay, so one + // accepted relay elsewhere does not settle the choice. + let (throttled, _) = provider( + |_, _| serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 1}), + ) + .await; + let store = MemoryStore::with(&[("a", "ta", &[RELAY]), ("b", "tb", &[RELAY])]); + let ads = vec![("a".into(), good), ("b".into(), throttled)]; + let err = accepted_relay(&store, ads).await.unwrap_err(); + assert_eq!(crate::error::exit_code(&err), 2, "{err:?}"); + } + + /// With no usable relay, a retryable failure is reported over an + /// identity mismatch, in either order. + #[test] + fn a_retryable_failure_outranks_an_identity_mismatch() { + let mismatch = || ProviderError::OtherUser.into_cli("describe"); + let timeout = || ProviderError::Unconfirmed.into_cli("describe"); + for order in [[mismatch(), timeout()], [timeout(), mismatch()]] { + let mut kept = None; + for e in order { + keep_transient(&mut kept, e); + } + assert_eq!(crate::error::exit_code(&kept.unwrap()), 2); + } + let mut kept = None; + keep_transient(&mut kept, mismatch()); + assert_eq!(crate::error::exit_code(&kept.unwrap()), 3); + } + + /// Through the command's relay selection with no `--relay`: a desktop's + /// refusal and a retryable failure both fail the command. + #[tokio::test] + async fn a_command_given_no_relay_reports_desktop_failures() { + use clap::Parser; + let cli = crate::Cli::try_parse_from(["buzz", "users", "get"]).unwrap(); + assert!(cli.relay.is_none()); + let store = MemoryStore::with(&[("a", "ta", &[RELAY])]); + let (denied, _) = provider( + |_, _| serde_json::json!({"result": "", "error": "denied", "message": "locked"}), + ) + .await; + let paired = accepted_relay(&store, vec![("a".into(), denied)]); + let err = crate::default_relay_with(&cli.command, false, async { Ok(None) }, paired) + .await + .unwrap_err(); + assert!(err.to_string().contains("locked"), "{err}"); + + let (good, _) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let paired = accepted_relay(&store, vec![("a".into(), good.clone())]); + let err = SAME_USER_HANGS + .scope( + (), + crate::default_relay_with(&cli.command, false, async { Ok(None) }, paired), + ) + .await + .unwrap_err(); + assert_eq!(crate::error::exit_code(&err), 2, "{err:?}"); + + let paired = accepted_relay(&store, vec![("a".into(), good)]); + let relay = crate::default_relay_with(&cli.command, false, async { Ok(None) }, paired) + .await + .unwrap(); + assert_eq!(relay.as_deref(), Some("wss://community.example/")); + } + + /// `auth desktop pair --instance b` with no `--relay`, through relay + /// selection and command dispatch: desktop A, which would refuse, is + /// never asked, and B gets one pair request naming no community. + #[tokio::test] + async fn pairing_a_chosen_desktop_ignores_another_desktops_refusal() { + use clap::Parser; + let cli = + crate::Cli::try_parse_from(["buzz", "auth", "desktop", "pair", "--instance", "b"]) + .unwrap(); + let store = MemoryStore::with(&[("a", "ta", &[RELAY])]); + let (refusing, refused) = provider( + |_, _| serde_json::json!({"result": "", "error": "denied", "message": "locked"}), + ) + .await; + let pubkey = nostr::Keys::generate().public_key().to_hex(); + let answer = serde_json::json!({ + "token": "tok", "instance": "b", "pubkey": pubkey, "relays": [RELAY], + }); + let reply = answer.to_string(); + let (b, seen) = provider(move |_, _| serde_json::json!({ "result": reply })).await; + let found = vec![("a".to_owned(), refusing.clone()), ("b".to_owned(), b)]; + + let paired = accepted_relay(&store, vec![("a".into(), refusing)]); + let relay = crate::default_relay_with(&cli.command, false, async { Ok(None) }, paired) + .await + .unwrap(); + let result = std::cell::RefCell::new(None); + assert!(relay.is_none()); + let connected = crate::connect( + None, + cli.command, + async |sub, relay| { + let crate::AuthCmd::Desktop(crate::DesktopAuthCmd::Pair { name, instance }) = sub + else { + unreachable!() + }; + let out = pair_among(&store, found, relay, &name, instance.as_deref()).await?; + *result.borrow_mut() = Some(out); + Ok(()) + }, + async |_| unreachable!(), + ) + .await + .unwrap(); + assert!(connected.is_none()); + + assert!(refused.lock().unwrap().is_empty(), "A was asked"); + let asked = seen.lock().unwrap(); + let pairs: Vec<_> = asked.iter().filter(|a| a.2["method"] == "pair").collect(); + assert_eq!(pairs.len(), 1); + assert_eq!(pairs[0].2["params"], serde_json::json!(["buzz CLI"])); + assert_eq!( + result.into_inner().unwrap(), + serde_json::json!({"instance": "b", "pubkey": pubkey, "relays": [RELAY]}) + ); + } + + /// A desktop that exited and left its advertisement behind is not counted, + /// so `pair` reaches the one that is running without `--instance`. + #[tokio::test] + async fn pair_skips_a_desktop_that_is_not_running() { + let stale = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + Endpoint::parse(&format!("http://127.0.0.1:{port}/rpc")).unwrap() + }; + let pubkey = nostr::Keys::generate().public_key().to_hex(); + let (live, seen) = provider(move |_, request| { + if request["method"] == "describe" { + return serde_json::json!({"result": "", "error": "revoked"}); + } + serde_json::json!({"result": serde_json::json!({ + "token": "tok", "instance": "live", "pubkey": pubkey, "relays": [RELAY], + }).to_string()}) + }) + .await; + let store = MemoryStore::default(); + let found = vec![("live".to_owned(), live), ("stale".to_owned(), stale)]; + pair_among(&store, found, Some(RELAY), "cli", None) + .await + .unwrap(); + assert_eq!(store.instances(), ["live"]); + assert_eq!(seen.lock().unwrap().last().unwrap().2["method"], "pair"); + + let none = pair_among(&store, Vec::new(), None, "cli", None).await; + assert!(none + .unwrap_err() + .to_string() + .contains("no running Buzz desktop")); + } + + /// A desktop that predates community-less pairing rejects it as malformed; + /// the CLI says to pass `--relay` instead of reporting a parse error. + #[tokio::test] + async fn an_older_desktop_asks_for_a_relay() { + let (endpoint, _) = provider(|_, _| { + serde_json::json!({ + "result": "", "error": "invalid_request", "message": "Wrong parameters for pair", + }) + }) + .await; + let store = MemoryStore::default(); + let err = pair_with(&store, "i".into(), endpoint.clone(), None, "cli") + .await + .unwrap_err(); + assert_eq!( + err.to_string(), + "this Buzz can't pick a community; pass --relay" + ); + let err = pair_with(&store, "i".into(), endpoint, Some(RELAY), "cli") + .await + .unwrap_err(); + assert!(err.to_string().contains("malformed"), "{err}"); + } + + /// A crashed desktop's leftover advertisement reads as not running, and + /// a throttled one is reported at once, not waited out. + #[tokio::test] + async fn list_tells_a_stale_advertisement_from_a_rejection() { + let closed = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + Endpoint::parse(&format!("http://127.0.0.1:{port}/rpc")).unwrap() + }; + // Timed from the desktop's first answer, so waiting for a turn on the + // same-user check is not counted. + let answered = Arc::new(StdMutex::new(None)); + let (throttled, seen) = provider({ + let answered = answered.clone(); + move |_, _| { + answered + .lock() + .unwrap() + .get_or_insert_with(std::time::Instant::now); + serde_json::json!({"result": "", "error": "rate_limited", "retry_after": 30}) + } + }) + .await; + let store = MemoryStore::with(&[("a", "ta", &[RELAY]), ("b", "tb", &[RELAY])]); + let ads = vec![("a".to_owned(), closed), ("b".to_owned(), throttled)]; + let listed = list_with(&store, ads).await.unwrap(); + let answered = answered.lock().unwrap().expect("b was asked"); + assert!( + answered.elapsed() < Duration::from_secs(5), + "waited out retry_after" + ); + assert_eq!(listed[0]["status"], "not running"); + assert_eq!(listed[1]["status"], "rate limited"); + assert_eq!(seen.lock().unwrap().len(), 1, "no retries"); + } + + /// The listing never shows a token and reports each pairing's state the + /// way the default relay judges it. + #[tokio::test] + async fn list_shows_each_pairing_without_its_token() { + assert!(list_with(&MemoryStore::default(), Vec::new()) + .await + .unwrap() + .is_empty()); + let (good, _) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let (revoked, _) = + provider(|_, _| serde_json::json!({"result": "", "error": "revoked"})).await; + let store = MemoryStore::with(&[ + ("a", "secret-a", &[RELAY]), + ("b", "secret-b", &[RELAY]), + ("c", "secret-c", &[RELAY]), + ]); + let ads = vec![("a".to_owned(), good), ("b".to_owned(), revoked)]; + let listed = list_with(&store, ads).await.unwrap(); + let text = serde_json::to_string(&listed).unwrap(); + assert!(!text.contains("secret"), "{text}"); + let status: Vec<_> = listed.iter().map(|p| p["status"].clone()).collect(); + assert_eq!(status, ["accepted", "not accepted", "not running"]); + assert_eq!(listed[0]["relays"], serde_json::json!([RELAY])); + assert_eq!( + store.instances(), + ["a", "b", "c"], + "listing changes nothing" + ); + } + + /// When this user cannot be confirmed on the server side, not one byte + /// (so no token) reaches the endpoint. + #[tokio::test] + async fn an_unconfirmed_user_gets_nothing_sent() { + let (endpoint, seen) = desktop(nostr::Keys::generate(), vec![RELAY.into()]).await; + let opened = CALLER_UID + .scope( + u32::MAX - 1, + Provider::open(endpoint, "secret".into(), true, RELAY), + ) + .await + .unwrap(); + assert!(matches!(opened, Err(Skip::Unreachable))); + assert!(seen.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn signing_goes_through_the_desktop_and_is_verified() { + use nostr::NostrSigner; + let keys = nostr::Keys::generate(); + let (endpoint, seen) = desktop(keys.clone(), vec![RELAY.into()]).await; + let p = Provider::open(endpoint, "t".into(), false, RELAY) + .await + .unwrap() + .ok() + .unwrap(); + let unsigned = + nostr::EventBuilder::new(nostr::Kind::Custom(9), "hi").build(keys.public_key()); + let event = p.sign_event(unsigned).await.unwrap(); + assert!(event.verify().is_ok() && event.pubkey == keys.public_key()); + assert_eq!(methods(&seen), ["describe", "sign_event"]); + } + + /// The desktop's bare compact assertion reaches the relay with exactly + /// one `Bearer` scheme (the shape #2260's `federated_identity` returns). + #[tokio::test] + async fn the_desktop_assertion_is_sent_with_one_bearer_prefix() { + use axum::http::HeaderMap; + let seen: Arc>> = Arc::default(); + let log = seen.clone(); + let app = axum::Router::new().fallback(move |headers: HeaderMap| { + let log = log.clone(); + async move { + let value = headers + .get("nostr-federated-identity") + .and_then(|v| v.to_str().ok()); + log.lock() + .unwrap() + .push(value.unwrap_or_default().to_owned()); + axum::Json(serde_json::json!([])) + } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let relay = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let (endpoint, _) = desktop(nostr::Keys::generate(), vec![relay.clone()]).await; + let p = Provider::open(endpoint, "t".into(), false, &relay) + .await + .unwrap() + .ok() + .unwrap(); + let credentials = crate::credentials::Credentials::from_desktop(p) + .await + .unwrap(); + let client = crate::client::BuzzClient::new(relay, credentials).unwrap(); + client + .query(&serde_json::json!({"kinds": [9]})) + .await + .unwrap(); + let header = seen.lock().unwrap()[0].clone(); + assert_eq!(header.matches("Bearer").count(), 1, "{header}"); + assert_eq!( + header.strip_prefix("Bearer ").unwrap().split('.').count(), + 3 + ); + } +} diff --git a/crates/buzz-cli/src/desktop_provider/ownership.rs b/crates/buzz-cli/src/desktop_provider/ownership.rs new file mode 100644 index 00000000000..260eeec715f --- /dev/null +++ b/crates/buzz-cli/src/desktop_provider/ownership.rs @@ -0,0 +1,448 @@ +use super::{ProviderError, QUICK_TIMEOUT}; +#[cfg(test)] +use std::sync::Arc; +use std::time::Duration; +#[cfg(any(not(target_os = "linux"), test))] +use tokio::io::AsyncReadExt; +use tokio::net::TcpStream; + +/// `lsof` can take seconds on a busy Mac. +const SAME_USER_TIMEOUT: Duration = Duration::from_secs(5); +const SAME_USER_RETRY_DELAY: Duration = Duration::from_millis(50); +#[cfg(any(not(target_os = "linux"), test))] +const MAX_LSOF_BYTES: u64 = 1024 * 1024; + +// --------------------------------------------------------------------------- +// Same-user check +// --------------------------------------------------------------------------- + +/// Connect to the provider port. With `check`, confirm by numeric user ID that +/// a process of this user holds the server side of this very connection, and +/// refuse to use the connection otherwise. +pub(super) async fn connect(port: u16, check: bool) -> Result { + let stream = tokio::time::timeout(QUICK_TIMEOUT, TcpStream::connect(("127.0.0.1", port))) + .await + .map_err(|_| ProviderError::Transport("connection timed out".into()))? + .map_err(|e| ProviderError::Transport(format!("not reachable: {}", e.kind())))?; + if check { + let local = stream + .local_addr() + .map_err(|_| ProviderError::Transport("no local address".into()))? + .port(); + #[cfg(test)] + if crate::desktop_provider::tests::SAME_USER_HANGS + .try_with(|_| ()) + .is_ok() + { + return Err(ProviderError::Unconfirmed); + } + confirm_same_user(|| server_side_uid(port, local)).await?; + } + Ok(stream) +} + +/// The accepted socket may not be observable yet. Retry only missing proof, +/// on the same open connection and within one deadline; errors and wrong UIDs are final. +async fn confirm_same_user(mut owner: impl FnMut() -> F) -> Result<(), ProviderError> +where + F: std::future::Future, ()>>, +{ + let deadline = tokio::time::Instant::now() + SAME_USER_TIMEOUT; + let proof = async { + loop { + if tokio::time::Instant::now() >= deadline { + return Err(ProviderError::Unconfirmed); + } + let found = owner().await; + if tokio::time::Instant::now() >= deadline { + return Err(ProviderError::Unconfirmed); + } + match found { + Ok(Some(uid)) if uid == current_uid() => return Ok(()), + Ok(None) => tokio::time::sleep(SAME_USER_RETRY_DELAY).await, + _ => return Err(ProviderError::OtherUser), + } + } + }; + tokio::time::timeout_at(deadline, proof) + .await + .unwrap_or(Err(ProviderError::Unconfirmed)) +} + +pub(super) fn current_uid() -> u32 { + #[cfg(test)] + if let Ok(uid) = crate::desktop_provider::tests::CALLER_UID.try_with(|uid| *uid) { + return uid; + } + // SAFETY: getuid has no preconditions and cannot fail. + unsafe { libc::getuid() } +} + +/// The owner UID of the socket `127.0.0.1:server -> 127.0.0.1:client`. +async fn server_side_uid(server: u16, client: u16) -> Result, ()> { + #[cfg(test)] + if let Ok(lookup) = tests::OWNER_LOOKUP.try_with(Arc::clone) { + return lookup(server, client).await; + } + platform_server_side_uid(server, client).await +} + +#[cfg(target_os = "linux")] +async fn platform_server_side_uid(server: u16, client: u16) -> Result, ()> { + let table = tokio::fs::read_to_string("/proc/net/tcp") + .await + .map_err(|_| ())?; + Ok(proc_net_tcp_uid(&table, server, client)) +} + +#[cfg(any(target_os = "linux", test))] +pub(super) fn proc_net_tcp_uid(table: &str, server: u16, client: u16) -> Option { + let local = format!("0100007F:{server:04X}"); + let remote = format!("0100007F:{client:04X}"); + table.lines().skip(1).find_map(|line| { + let cols: Vec<&str> = line.split_whitespace().collect(); + (cols.get(1) == Some(&local.as_str()) && cols.get(2) == Some(&remote.as_str())) + .then(|| cols.get(7)?.parse().ok()) + .flatten() + }) +} + +/// macOS: `lsof` lists the socket's owning process with its UID. +#[cfg(not(target_os = "linux"))] +async fn platform_server_side_uid(server: u16, client: u16) -> Result, ()> { + let mut command = tokio::process::Command::new("/usr/sbin/lsof"); + command.args(["-nP", "-F", "un", &format!("-iTCP@127.0.0.1:{server}")]); + lsof_server_side_uid(command, server, client).await +} + +#[cfg(any(not(target_os = "linux"), test))] +async fn lsof_server_side_uid( + mut command: tokio::process::Command, + server: u16, + client: u16, +) -> Result, ()> { + let mut child = command + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|_| ())?; + let mut output = Vec::new(); + child + .stdout + .take() + .ok_or(())? + .take(MAX_LSOF_BYTES + 1) + .read_to_end(&mut output) + .await + .map_err(|_| ())?; + if output.len() as u64 > MAX_LSOF_BYTES || !child.wait().await.map_err(|_| ())?.success() { + return Err(()); + } + Ok(lsof_uid(&String::from_utf8_lossy(&output), server, client)) +} + +#[cfg(any(not(target_os = "linux"), test))] +pub(super) fn lsof_uid(output: &str, server: u16, client: u16) -> Option { + let want = format!("n127.0.0.1:{server}->127.0.0.1:{client}"); + let mut uid = None; + for line in output.lines() { + if let Some(value) = line.strip_prefix('u') { + uid = value.parse().ok(); + } else if line.strip_prefix('p').is_some() { + uid = None; + } else if line == want { + return uid; + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::desktop_provider::{call, Endpoint}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use tokio::io::AsyncWriteExt; + + type OwnerFuture = + std::pin::Pin, ()>> + Send>>; + type OwnerLookup = Arc OwnerFuture + Send + Sync>; + tokio::task_local! { + pub(super) static OWNER_LOOKUP: OwnerLookup; + } + + #[tokio::test(start_paused = true)] + async fn missing_proof_shares_one_deadline_and_errors_are_final() { + let started = tokio::time::Instant::now(); + let mut attempts = 0; + let result = confirm_same_user(|| { + attempts += 1; + std::future::ready(Ok(None)) + }) + .await; + assert!(matches!(result, Err(ProviderError::Unconfirmed))); + assert_eq!(started.elapsed(), SAME_USER_TIMEOUT); + assert!(attempts > 1 && attempts <= 101); + + for answer in [Ok(Some(current_uid().wrapping_add(1))), Err(())] { + let mut attempts = 0; + let result = confirm_same_user(|| { + attempts += 1; + std::future::ready(answer) + }) + .await; + assert!(matches!(result, Err(ProviderError::OtherUser))); + assert_eq!(attempts, 1); + } + + let result = confirm_same_user(|| async { + tokio::time::sleep(SAME_USER_TIMEOUT).await; + Ok(Some(current_uid())) + }) + .await; + assert!( + matches!(result, Err(ProviderError::Unconfirmed)), + "proof at the deadline is too late" + ); + + assert!(confirm_same_user(|| async { + tokio::time::sleep(Duration::from_secs(4)).await; + Ok(Some(current_uid())) + }) + .await + .is_ok()); + } + + #[tokio::test] + async fn delayed_socket_proof_gates_the_production_request_on_the_same_connection() { + for answer in [ + Ok(Some(current_uid())), + Ok(Some(current_uid().wrapping_add(1))), + Err(()), + Ok(None), + ] { + let listener = Arc::new(tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap()); + let port = listener.local_addr().unwrap().port(); + let accepted = Arc::new(tokio::sync::Mutex::new(None::)); + let proven = Arc::new(tokio::sync::Notify::new()); + let attempts = Arc::new(AtomicUsize::new(0)); + let lookup = { + let (accepted, proven, attempts) = + (accepted.clone(), proven.clone(), attempts.clone()); + Arc::new(move |server, client| { + let (listener, accepted, proven, attempts) = ( + listener.clone(), + accepted.clone(), + proven.clone(), + attempts.clone(), + ); + Box::pin(async move { + let mut slot = accepted.lock().await; + if slot.is_none() { + *slot = Some(listener.accept().await.unwrap().0); + } + let stream = slot.as_ref().unwrap(); + assert_eq!( + (server, client), + ( + stream.local_addr().unwrap().port(), + stream.peer_addr().unwrap().port() + ) + ); + let mut byte = [0]; + assert_eq!( + stream.try_read(&mut byte).unwrap_err().kind(), + std::io::ErrorKind::WouldBlock, + "no header, token or provider payload may precede proof" + ); + if attempts.fetch_add(1, Ordering::SeqCst) < 2 { + Ok(None) + } else { + if answer == Ok(Some(current_uid())) { + proven.notify_one(); + } + answer + } + }) as OwnerFuture + }) as OwnerLookup + }; + let responder = if answer == Ok(Some(current_uid())) { + let (accepted, proven) = (accepted.clone(), proven.clone()); + Some(tokio::spawn(async move { + proven.notified().await; + let mut stream = accepted.lock().await.take().unwrap(); + let mut request = Vec::new(); + let body_at = loop { + let mut byte = [0]; + stream.read_exact(&mut byte).await.unwrap(); + request.push(byte[0]); + if request.ends_with(b"\r\n\r\n") { + break request.len(); + } + assert!(request.len() < 4096); + }; + let header = String::from_utf8(request.clone()).unwrap(); + assert!(header.contains("Authorization: Bearer test-key-do-not-use\r\n")); // sadscan:disable np.http.2 + let length: usize = header + .lines() + .find_map(|line| line.strip_prefix("Content-Length: ")) + .unwrap() + .parse() + .unwrap(); + assert!(length < 4096); + request.resize(body_at + length, 0); + stream.read_exact(&mut request[body_at..]).await.unwrap(); + let body: serde_json::Value = + serde_json::from_slice(&request[body_at..]).unwrap(); + assert_eq!(body["params"], serde_json::json!(["synthetic-payload"])); + let response = + serde_json::json!({"id": body["id"], "result": "ok"}).to_string(); + stream + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{response}", + response.len() + ) + .as_bytes(), + ) + .await + .unwrap(); + })) + } else { + None + }; + let endpoint = Endpoint::parse(&format!("http://127.0.0.1:{port}/rpc")).unwrap(); + let result = OWNER_LOOKUP + .scope( + lookup, + call( + &endpoint, + Some("test-key-do-not-use"), + true, + "nip44_encrypt", + &["synthetic-payload".into()], + ), + ) + .await; + if answer == Ok(None) { + assert!(attempts.load(Ordering::SeqCst) > 3); + } else { + assert_eq!(attempts.load(Ordering::SeqCst), 3); + } + if let Some(responder) = responder { + assert_eq!(result.unwrap(), "ok"); + responder.await.unwrap(); + } else { + if answer == Ok(None) { + assert!(matches!(result, Err(ProviderError::Unconfirmed))); + } else { + assert!(matches!(result, Err(ProviderError::OtherUser))); + } + let mut bytes = Vec::new(); + accepted + .lock() + .await + .as_mut() + .unwrap() + .read_to_end(&mut bytes) + .await + .unwrap(); + assert!(bytes.is_empty()); + } + } + } + + #[tokio::test] + async fn lsof_failure_and_output_overflow_are_not_missing_proof() { + let mut command = tokio::process::Command::new("/bin/sh"); + command.args(["-c", "exit 1"]); + assert_eq!(lsof_server_side_uid(command, 1, 2).await, Err(())); + let mut command = tokio::process::Command::new("/bin/sh"); + command.args(["-c", "exec yes x"]); + assert_eq!(lsof_server_side_uid(command, 1, 2).await, Err(())); + } + #[tokio::test] + async fn proof_timeout_and_cancellation_close_the_socket_and_kill_lsof() { + for cancel in [false, true] { + let scratch = tempfile::tempdir().unwrap(); + let pid_file = scratch.path().join("lookup.pid"); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = Endpoint::parse(&format!( + "http://127.0.0.1:{}/rpc", + listener.local_addr().unwrap().port() + )) + .unwrap(); + let lookup = Arc::new(move |server, client| { + let pid_file = pid_file.clone(); + Box::pin(async move { + let mut command = tokio::process::Command::new("/bin/sh"); + command.args(["-c", "echo $$ > \"$1\"; exec sleep 30", "lookup"]); + command.arg(pid_file); + lsof_server_side_uid(command, server, client).await + }) as OwnerFuture + }) as OwnerLookup; + let request = tokio::spawn(OWNER_LOOKUP.scope(lookup, async move { + call( + &endpoint, + Some("test-key-do-not-use"), + true, + "nip44_encrypt", + &["synthetic-payload".into()], + ) + .await + })); + let (mut stream, _) = listener.accept().await.unwrap(); + let pid_file = scratch.path().join("lookup.pid"); + let pid = tokio::time::timeout(Duration::from_secs(2), async { + loop { + if let Ok(pid) = tokio::fs::read_to_string(&pid_file).await { + if let Ok(pid) = pid.trim().parse::() { + break pid; + } + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + if cancel { + request.abort(); + assert!(request.await.unwrap_err().is_cancelled()); + } else { + let result = tokio::time::timeout(Duration::from_secs(7), request) + .await + .unwrap() + .unwrap(); + assert!(matches!(result, Err(ProviderError::Unconfirmed))); + } + let mut bytes = Vec::new(); + tokio::time::timeout(Duration::from_secs(1), stream.read_to_end(&mut bytes)) + .await + .unwrap() + .unwrap(); + assert!( + bytes.is_empty(), + "no bytes before failed or cancelled proof" + ); + tokio::time::timeout(Duration::from_secs(2), async { + loop { + let alive = tokio::process::Command::new("/bin/kill") + .args(["-0", &pid.to_string()]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .await + .unwrap() + .success(); + if !alive { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("owned lookup child survived proof cancellation"); + } + } +} diff --git a/crates/buzz-cli/src/error.rs b/crates/buzz-cli/src/error.rs index 2edcd6aa9d4..1cd3855a37c 100644 --- a/crates/buzz-cli/src/error.rs +++ b/crates/buzz-cli/src/error.rs @@ -39,6 +39,25 @@ pub enum CliError { #[error("delivery unknown: {0}")] DeliveryUnknown(String), + /// The NIP-FA identity adapter stayed unavailable through its bounded + /// retries. Nothing was sent to the relay, so the command is safe to + /// re-run later; relay retry loops never repeat it. + #[error("identity adapter error: {0}")] + Adapter(String), + + /// The local credential provider stayed `rate_limited` through its + /// bounded waits. It refused before acting, so a later re-run is safe. + /// Only the Unix desktop provider reports it. + #[cfg_attr(not(unix), allow(dead_code))] + #[error("rate limited: {0}")] + Throttled(String), + + /// The relay or the Buzz desktop could not be used now (the relay kept + /// closing the WebSocket before sign-in, or the desktop's same-user check + /// timed out). Nothing was sent, so a later re-run is safe. + #[error("unavailable: {0}")] + Unavailable(String), + /// Catch-all for unexpected failures #[error("{0}")] Other(String), @@ -47,7 +66,7 @@ pub enum CliError { /// Walk the full `std::error::Error::source()` chain on a `reqwest::Error` /// and render it as a colon-separated string, e.g. /// `error sending request: dns error: failed to lookup address information: ...` -fn fmt_reqwest_error(e: &reqwest::Error) -> String { +pub(crate) fn fmt_reqwest_error(e: &reqwest::Error) -> String { let mut msg = e.to_string(); let mut source: &dyn std::error::Error = e; while let Some(cause) = source.source() { @@ -65,7 +84,9 @@ fn fmt_reqwest_error(e: &reqwest::Error) -> String { /// /// Transport-level network errors (connect failure, timeout, mid-request, /// mid-body transfer, or body decode failure) and relay overload responses -/// (429 / 502 / 503 / 504) are retryable. `DeliveryUnknown` is never +/// (429 / 502 / 503 / 504) are retryable, as are a desktop that stayed +/// `rate_limited` (`Throttled`) and an adapter that stayed +/// unavailable (`Adapter`: nothing reached the relay). `DeliveryUnknown` is never /// retryable: the operation may already have executed. All other errors /// indicate a permanent failure: auth, bad input, builder errors, or logic /// errors. @@ -79,6 +100,7 @@ pub fn is_retryable_error(e: &CliError) -> bool { || net_err.is_decode() } CliError::Relay { status, .. } => matches!(status, 429 | 502 | 503 | 504), + CliError::Adapter(_) | CliError::Throttled(_) | CliError::Unavailable(_) => true, CliError::DeliveryUnknown(_) => false, _ => false, } @@ -103,6 +125,7 @@ pub fn exit_code(e: &CliError) -> i32 { CliError::Conflict(_) => 5, CliError::NotFound(_) => 1, CliError::DeliveryUnknown(_) => 2, + CliError::Adapter(_) | CliError::Throttled(_) | CliError::Unavailable(_) => 2, CliError::Other(_) => 4, } } @@ -125,6 +148,9 @@ pub fn print_error(e: &CliError) { CliError::Conflict(_) => "conflict", CliError::NotFound(_) => "not_found", CliError::DeliveryUnknown(_) => "delivery_unknown", + CliError::Adapter(_) => "adapter_error", + CliError::Throttled(_) => "rate_limited", + CliError::Unavailable(_) => "unavailable", CliError::Other(_) => "error", }; let obj = serde_json::json!({ diff --git a/crates/buzz-cli/src/federated_identity.rs b/crates/buzz-cli/src/federated_identity.rs new file mode 100644 index 00000000000..3affddd1ee9 --- /dev/null +++ b/crates/buzz-cli/src/federated_identity.rs @@ -0,0 +1,993 @@ +//! Headless NIP-FI evidence: mint relay assertions from a NIP-FA adapter +//! session (`docs/nips/NIP-FA.md` §Relay assertion). +//! +//! The adapter session token (`BUZZ_FEDERATED_IDENTITY_TOKEN`) proves who the +//! user is; a NIP-98 proof proves the CLI controls the key. The adapter answers +//! with a short-lived assertion that the CLI attaches as +//! `Nostr-Federated-Identity: Bearer …` on every protected relay request. +//! +//! One assertion is cached per process and re-minted shortly before it +//! expires. The session token is sent only to the adapter's origin, never +//! through a redirect, and never appears in errors. +//! +//! A mint retries network failures, 429 and any 5xx with bounded backoff +//! (NIP-FA §Denials), then fails as [`CliError::Adapter`]: a pre-send failure +//! that relay retry loops never repeat and never report as possibly +//! delivered. A refusal is never retried, even when its body is unreadable. + +use std::time::Duration; + +use nostr::{EventBuilder, JsonUtil, Keys, Kind, Tag}; +use sha2::{Digest, Sha256}; + +use crate::cached_assertion::{unix_now, CachedAssertion}; +use crate::error::CliError; + +/// Environment variable carrying a NIP-FA adapter session token. +pub const FEDERATED_IDENTITY_TOKEN_ENV: &str = "BUZZ_FEDERATED_IDENTITY_TOKEN"; +/// Environment variable carrying the NIP-FA adapter base URL. +pub const FEDERATED_IDENTITY_ADAPTER_ENV: &str = "BUZZ_FEDERATED_IDENTITY_ADAPTER"; + +/// NIP-FA assertion endpoint, relative to the adapter base. +const ASSERTIONS_PATH: &str = "/v1/identity/assertions"; + +/// Largest adapter response body the CLI reads. +const MAX_RESPONSE_BYTES: usize = 64 * 1024; + +/// Attempts per mint, and the backoff ceiling before each retry. +const MINT_ATTEMPTS: usize = 3; +const MINT_BACKOFF: [Duration; MINT_ATTEMPTS - 1] = + [Duration::from_millis(250), Duration::from_millis(750)]; +/// The longest adapter `Retry-After` the CLI waits out before a retry. +const MINT_RETRY_AFTER_MAX: Duration = Duration::from_secs(30); + +/// A NIP-FA adapter session that mints NIP-FI assertions. +pub struct AdapterSession { + endpoint: url::Url, + /// The relay it mints for, in NIP-FA form, bound at creation. + relay_url: String, + token: String, + http: reqwest::Client, + cached: CachedAssertion, +} + +impl std::fmt::Debug for AdapterSession { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AdapterSession") + .field("endpoint", &self.endpoint.as_str()) + .finish_non_exhaustive() + } +} + +#[derive(serde::Deserialize)] +struct AssertionResponse { + assertion: String, + nostr_pubkey: String, + expires_at: u64, +} + +#[derive(serde::Deserialize)] +struct DenialBody { + error: String, +} + +/// The NIP-FA canonical relay URL: `wss://host[:port]`, default port omitted, +/// no trailing slash, path, query or fragment. +pub fn canonical_relay_url(relay_url: &str) -> Result { + // `wss://host` means 443, so an explicit `:80` would silently alias it; + // NIP-FA has no relay on port 80. The URL parser drops `:80` for + // `http`/`ws`, so read the authority as written. + if explicit_port(relay_url) == Some(80) { + return Err(CliError::Usage(format!( + "NIP-FA does not support a relay on port 80: {relay_url}" + ))); + } + let authority = buzz_core::tenant::relay_url_authority(relay_url); + if authority.is_empty() { + return Err(CliError::Usage(format!("invalid relay URL: {relay_url}"))); + } + Ok(format!("wss://{authority}")) +} + +/// The port written in `url`'s authority, as a number, if any. +fn explicit_port(url: &str) -> Option { + let rest = url.split_once("://")?.1; + let authority = rest.split(['/', '?', '#']).next()?; + let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h); + let (host, port) = host_port.rsplit_once(':')?; + if host.is_empty() || port.contains(']') { + return None; + } + port.parse().ok() +} + +/// An adapter `Retry-After`: delta-seconds or an HTTP-date in any of the +/// three RFC 9110 formats. +fn parse_retry_after(value: &str, now: u64) -> Option { + let value = value.trim(); + if let Ok(secs) = value.parse() { + return Some(Duration::from_secs(secs)); + } + let at = httpdate::parse_http_date(value) + .ok()? + .duration_since(std::time::UNIX_EPOCH) + .ok()? + .as_secs(); + Some(Duration::from_secs(at.saturating_sub(now))) +} + +/// Read at most `MAX_RESPONSE_BYTES` of the body; `None` when it is larger. +async fn bounded_body(mut resp: reqwest::Response) -> Result>, reqwest::Error> { + let mut body = Vec::new(); + while let Some(chunk) = resp.chunk().await? { + if body.len() + chunk.len() > MAX_RESPONSE_BYTES { + return Ok(None); + } + body.extend_from_slice(&chunk); + } + Ok(Some(body)) +} + +fn refused(detail: impl std::fmt::Display) -> CliError { + CliError::Auth(format!( + "the identity adapter refused the assertion request ({detail})" + )) +} + +/// Map a NIP-FA denial to the error the CLI reports (NIP-FA §Denials). +/// Retryable statuses (429, 5xx) are handled before this runs. +fn denial(status: u16, code: Option<&str>, relay_url: &str) -> CliError { + match (status, code) { + (401, Some("session_required" | "session_expired")) => CliError::Auth(format!( + "the identity adapter session is missing, invalid or expired ({}): sign in again \ + and update {FEDERATED_IDENTITY_TOKEN_ENV}", + code.unwrap_or_default() + )), + (403, Some("authorization_denied")) => CliError::Auth(format!( + "the identity adapter denied an assertion for this key on {relay_url} \ + (authorization_denied)" + )), + (403, Some("binding_mismatch")) => CliError::Auth( + "the identity adapter has bound this user to a different Nostr key \ + (binding_mismatch)" + .into(), + ), + (403, Some("invalid_proof")) => { + CliError::Auth("the identity adapter rejected the NIP-98 proof (invalid_proof)".into()) + } + (400, Some(code @ "invalid_request")) | (413, Some(code @ "request_too_large")) => { + refused(code) + } + (status, _) => refused(format!("HTTP {status}")), + } +} + +impl AdapterSession { + /// A session minting for `relay_url` from the adapter at `adapter_base`. + /// The base must be `https` (or `http` on a loopback host, for local + /// development) with no query, fragment or credentials. + pub fn new(adapter_base: &str, token: &str, relay_url: &str) -> Result { + let relay_url = canonical_relay_url(relay_url)?; + let invalid = |why: &str| CliError::Auth(format!("{FEDERATED_IDENTITY_ADAPTER_ENV} {why}")); + let base = url::Url::parse(adapter_base.trim()).map_err(|_| invalid("is not a URL"))?; + let loopback = match base.host() { + Some(url::Host::Ipv4(ip)) => ip.is_loopback(), + Some(url::Host::Ipv6(ip)) => ip.is_loopback(), + Some(url::Host::Domain(name)) => name == "localhost", + None => false, + }; + match base.scheme() { + "https" => {} + "http" if loopback => {} + _ => return Err(invalid("must use https")), + } + if base.query().is_some() + || base.fragment().is_some() + || !base.username().is_empty() + || base.password().is_some() + { + return Err(invalid("must not carry a query, fragment or credentials")); + } + let endpoint = url::Url::parse(&format!( + "{}{ASSERTIONS_PATH}", + base.as_str().trim_end_matches('/') + )) + .map_err(|_| invalid("is not a URL"))?; + let token = token.trim(); + if token.is_empty() || token.contains(['\r', '\n']) { + return Err(CliError::Auth(format!( + "{FEDERATED_IDENTITY_TOKEN_ENV} is not a usable token" + ))); + } + let http = reqwest::Client::builder() + // NIP-FA: never replay the session token or proof to a redirect target. + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(15)) + .connect_timeout(Duration::from_secs(10)) + .build()?; + Ok(Self { + endpoint, + relay_url, + token: token.to_owned(), + http, + cached: CachedAssertion::default(), + }) + } + + /// The assertion for its relay, minted with `keys` on first use and + /// re-minted at its refresh point. Concurrent callers share one mint. + pub async fn assertion(&self, keys: &Keys) -> Result, CliError> { + self.cached + .get(async { self.mint(&self.relay_url, keys).await.map(Some) }) + .await + } + + /// Mint with bounded retries; a refusal or a definitive error returns at once. + async fn mint(&self, relay_url: &str, keys: &Keys) -> Result { + let mut attempt = 0; + loop { + match self.mint_once(relay_url, keys).await? { + Ok(issued) => return Ok(issued), + Err(transient) if attempt + 1 == MINT_ATTEMPTS => { + return Err(CliError::Adapter(format!( + "the identity adapter could not issue an assertion after \ + {MINT_ATTEMPTS} attempts ({transient}); retry later" + ))); + } + Err(transient) => { + let wait = transient.retry_after.map_or_else( + || MINT_BACKOFF[attempt].mul_f64(rand::random::()), + |d| d.min(MINT_RETRY_AFTER_MAX), + ); + tokio::time::sleep(wait).await; + attempt += 1; + } + } + } + } + + /// One mint attempt. The outer `Err` ends the mint; the inner `Err` is a + /// transient failure worth another attempt. + async fn mint_once( + &self, + relay_url: &str, + keys: &Keys, + ) -> Result, CliError> { + let pubkey = keys.public_key().to_hex(); + let body = serde_json::to_vec(&serde_json::json!({ + "relay_url": relay_url, + "nostr_pubkey": pubkey, + })) + .map_err(|e| CliError::Other(format!("assertion request serialization failed: {e}")))?; + + // A fresh proof per attempt: NIP-FA proofs are single-use. + let proof = nip98_event("POST", self.endpoint.as_str(), Some(&body))? + .sign_with_keys(keys) + .map_err(|e| CliError::Other(format!("NIP-98 signing failed: {e}")))?; + use base64::Engine; + let proof = base64::engine::general_purpose::STANDARD.encode(proof.as_json()); + let mut proof = reqwest::header::HeaderValue::try_from(format!("Nostr {proof}")) + .map_err(|_| CliError::Other("NIP-98 proof is not a valid header value".into()))?; + proof.set_sensitive(true); + let sent = self + .http + .post(self.endpoint.clone()) + .bearer_auth(&self.token) + .header("Nostr-Authorization", proof) + .header("Content-Type", "application/json") + .header("Accept", "application/json") + .body(body) + .send() + .await; + let resp = match sent { + Ok(resp) => resp, + Err(e) if e.is_builder() => return Err(CliError::Network(e.without_url())), + Err(e) => return Ok(Err(Transient::from(e))), + }; + let status = resp.status().as_u16(); + if status == 429 || resp.status().is_server_error() { + // NIP-FA: honor `Retry-After` (delta-seconds) on 429 and 503. + let retry_after = matches!(status, 429 | 503) + .then(|| resp.headers().get(reqwest::header::RETRY_AFTER)) + .flatten() + .and_then(|v| parse_retry_after(v.to_str().ok()?, unix_now())); + return Ok(Err(Transient { + why: format!("HTTP {status}"), + retry_after, + })); + } + let body = bounded_body(resp).await; + if status != 200 { + // The status is the answer; a lost or unreadable body only loses the code. + let code = body + .ok() + .flatten() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .map(|d| d.error); + return Err(denial(status, code.as_deref(), relay_url)); + } + match body { + Ok(body) => accept(body.as_deref(), &pubkey).map(Ok), + // A 200 whose body never arrived is a transport failure, not a rejected 200. + Err(e) => Ok(Err(Transient::from(e))), + } + } +} + +/// A mint failure worth another attempt, after `retry_after` when the +/// adapter gave one. +struct Transient { + why: String, + retry_after: Option, +} + +impl From for Transient { + fn from(e: reqwest::Error) -> Self { + Self { + why: crate::error::fmt_reqwest_error(&e.without_url()), + retry_after: None, + } + } +} + +impl std::fmt::Display for Transient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.why) + } +} + +/// Validate a 200 response (NIP-FA: a rejected 200 is a refusal). +fn accept(body: Option<&[u8]>, pubkey: &str) -> Result { + let response: AssertionResponse = body + .and_then(|b| serde_json::from_slice(b).ok()) + .ok_or_else(|| refused("unreadable assertion response"))?; + if response.nostr_pubkey != pubkey { + return Err(refused("assertion names a different key")); + } + if response.expires_at <= unix_now() { + return Err(refused("assertion already expired")); + } + match crate::cached_assertion::jws_exp(&response.assertion) { + None => return Err(refused("assertion is not a compact JWS")), + Some(exp) if exp != response.expires_at => { + return Err(refused("assertion exp does not match expires_at")); + } + Some(_) => {} + } + Ok(response.assertion) +} + +/// The NIP-98 HTTP auth event (kind:27235) for `method` + `url`: `u`, +/// `method`, a nonce (so rapid identical requests don't trip replay guards) +/// and, with a body, its `payload` hash. Mints and relay requests sign it. +pub(crate) fn nip98_event( + method: &str, + url: &str, + body: Option<&[u8]>, +) -> Result { + let tag = |parts: &[&str]| { + Tag::parse(parts.iter().copied()).map_err(|e| CliError::Other(format!("tag error: {e}"))) + }; + let mut tags = vec![ + tag(&["u", url])?, + tag(&["method", method])?, + tag(&["nonce", &uuid::Uuid::new_v4().to_string()])?, + ]; + if let Some(body) = body { + tags.push(tag(&["payload", &hex::encode(Sha256::digest(body))])?); + } + Ok(EventBuilder::new(Kind::HttpAuth, "").tags(tags)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const RELAY: &str = "https://relay.example.com/"; + + #[test] + fn canonical_relay_url_follows_nip_fa() { + for (input, expected) in [ + ("https://relay.example.com", "wss://relay.example.com"), + ("https://Relay.Example.com/", "wss://relay.example.com"), + ("https://relay.example.com:443", "wss://relay.example.com"), + ( + "https://relay.example.com:8443/x?y", + "wss://relay.example.com:8443", + ), + ("http://localhost:3000", "wss://localhost:3000"), + ("https://[2001:db8::1]:8443", "wss://[2001:db8::1]:8443"), + ] { + assert_eq!(canonical_relay_url(input).unwrap(), expected, "{input}"); + } + assert!(canonical_relay_url("not a url").is_err()); + for port_80 in [ + "wss://relay.example.com:80", + "https://relay.example.com:80/x", + "http://relay.example.com:80", + "ws://user@relay.example.com:80", + "http://[::1]:80", + "http://relay.example.com:080", + ] { + assert!( + matches!(canonical_relay_url(port_80), Err(CliError::Usage(_))), + "{port_80}" + ); + } + assert!(canonical_relay_url("http://[::80]").is_ok()); + assert!(canonical_relay_url("http://relay.example.com:8080").is_ok()); + } + + #[test] + fn retry_after_takes_seconds_or_an_http_date() { + let now = 784_111_777; // Sun, 06 Nov 1994 08:49:37 GMT + assert_eq!(parse_retry_after(" 7 ", now), Some(Duration::from_secs(7))); + assert_eq!( + parse_retry_after("Sun, 06 Nov 1994 08:50:07 GMT", now), + Some(Duration::from_secs(30)) + ); + assert_eq!( + parse_retry_after("Sun, 06 Nov 1994 08:49:00 GMT", now), + Some(Duration::ZERO) + ); + assert_eq!( + parse_retry_after("Sunday, 06-Nov-94 08:50:07 GMT", now), + Some(Duration::from_secs(30)) + ); + assert_eq!( + parse_retry_after("Sun Nov 6 08:50:07 1994", now), + Some(Duration::from_secs(30)) + ); + assert_eq!(parse_retry_after("soon", now), None); + } + + #[test] + fn adapter_base_must_be_https_or_loopback_http() { + for ok in [ + "https://adapter.example", + "https://adapter.example/base/", + "http://127.0.0.1:8080", + "http://[::1]:8080", + "http://localhost:8080", + ] { + assert!(AdapterSession::new(ok, "token", RELAY).is_ok(), "{ok}"); + } + for bad in [ + "http://adapter.example", + "ftp://adapter.example", + "https://adapter.example/?q=1", + "https://adapter.example/#f", + "https://user:pw@adapter.example", + "adapter.example", + ] { + assert!(AdapterSession::new(bad, "token", RELAY).is_err(), "{bad}"); + } + assert!(AdapterSession::new("https://adapter.example", " ", RELAY).is_err()); + assert!(AdapterSession::new("https://adapter.example", "a\nb", RELAY).is_err()); + let session = AdapterSession::new("https://adapter.example/base/", "token", RELAY).unwrap(); + assert_eq!( + session.endpoint.as_str(), + "https://adapter.example/base/v1/identity/assertions" + ); + } + + // ----------------------------------------------------------------------- + // Mint against a mock NIP-FA adapter + // ----------------------------------------------------------------------- + + use std::sync::{Arc, Mutex as StdMutex}; + + use axum::http::{HeaderMap, StatusCode}; + use axum::response::IntoResponse; + use base64::Engine; + use nostr::{JsonUtil, Keys}; + + use super::test_support::{self, count, raw_adapter}; + + const TOKEN: &str = "adapter-session-token"; + + /// What the adapter saw: request headers and the JSON body. + type Seen = Arc>>; + + /// A mock adapter answering every assertion request with `respond(seen + /// request body)`. Returns the adapter base URL and the request log. + async fn adapter(respond: F) -> (String, Seen) + where + F: Fn(&serde_json::Value) -> (StatusCode, String) + Send + Sync + 'static, + { + let seen: Seen = Arc::default(); + let log = seen.clone(); + let respond = Arc::new(respond); + let app = axum::Router::new().route( + ASSERTIONS_PATH, + axum::routing::post(move |headers: HeaderMap, body: axum::body::Bytes| { + let log = log.clone(); + let respond = respond.clone(); + async move { + let json: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); + let (status, body) = respond(&json); + log.lock().unwrap().push((headers, json)); + (status, [("content-type", "application/json")], body).into_response() + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (format!("http://{addr}"), seen) + } + + /// A realistic NIP-FI assertion for `pubkey` expiring at `expires_at`. + fn issued(pubkey: &str, expires_at: u64) -> (StatusCode, String) { + issued_as( + pubkey, + expires_at, + &test_support::assertion(pubkey, expires_at), + ) + } + + fn issued_as(pubkey: &str, expires_at: u64, assertion: &str) -> (StatusCode, String) { + ( + StatusCode::OK, + serde_json::json!({ + "assertion": assertion, + "nostr_pubkey": pubkey, + "expires_at": expires_at, + }) + .to_string(), + ) + } + + fn denied(status: StatusCode, code: &str) -> (StatusCode, String) { + ( + status, + serde_json::json!({"error": code, "message": "denied"}).to_string(), + ) + } + + #[tokio::test] + async fn mint_sends_the_nip_fa_request_and_caches_per_relay() { + let (base, seen) = + adapter(|req| issued(req["nostr_pubkey"].as_str().unwrap(), unix_now() + 300)).await; + let keys = Keys::generate(); + let credentials = keys.clone(); + let session = AdapterSession::new(&base, TOKEN, RELAY).unwrap(); + + let first = session.assertion(&credentials).await.unwrap(); + assert!(first + .as_deref() + .and_then(crate::cached_assertion::jws_exp) + .is_some()); + for _ in 0..2 { + let assertion = session.assertion(&credentials).await.unwrap(); + assert_eq!(assertion, first); + } + assert_eq!(seen.lock().unwrap().len(), 1, "one mint serves the process"); + + let (headers, body) = seen.lock().unwrap()[0].clone(); + assert_eq!( + body, + serde_json::json!({ + "relay_url": "wss://relay.example.com", + "nostr_pubkey": keys.public_key().to_hex(), + }) + ); + assert_eq!(headers["authorization"], format!("Bearer {TOKEN}")); + // NIP-98 proof bound to the endpoint, method and body. + let proof = headers["nostr-authorization"] + .to_str() + .unwrap() + .strip_prefix("Nostr ") + .unwrap() + .to_owned(); + let proof = base64::engine::general_purpose::STANDARD + .decode(proof) + .unwrap(); + let proof = nostr::Event::from_json(proof).unwrap(); + proof.verify().unwrap(); + assert_eq!(proof.kind, nostr::Kind::HttpAuth); + assert_eq!(proof.pubkey, keys.public_key()); + let tag = |name: &str| { + proof + .tags + .iter() + .find(|t| t.kind().to_string() == name) + .and_then(|t| t.content()) + .map(str::to_owned) + }; + assert_eq!(tag("u").unwrap(), format!("{base}{ASSERTIONS_PATH}")); + assert_eq!(tag("method").unwrap(), "POST"); + let sent = serde_json::to_vec(&body).unwrap(); + assert_eq!( + tag("payload").unwrap(), + hex::encode(::digest(&sent)) + ); + } + + #[tokio::test] + async fn an_assertion_near_expiry_is_reminted() { + // A 2 s lifetime refreshes at half-life, so the second call re-mints. + let (base, seen) = + adapter(|req| issued(req["nostr_pubkey"].as_str().unwrap(), unix_now() + 2)).await; + let credentials = Keys::generate(); + let session = AdapterSession::new(&base, TOKEN, RELAY).unwrap(); + session.assertion(&credentials).await.unwrap(); + tokio::time::sleep(Duration::from_millis(2_100)).await; + session.assertion(&credentials).await.unwrap(); + assert_eq!(seen.lock().unwrap().len(), 2); + } + + #[tokio::test] + async fn short_and_long_assertions_refresh_at_the_earlier_point() { + // 20 s refreshes at half-life (10 s); 300 s at half-life (150 s), + // earlier than 30 s before expiry. + for (lifetime, refresh) in [(20, 10), (300, 150)] { + crate::cached_assertion::test_clock::freeze(1_800_000_000); + let (base, seen) = adapter(move |req| { + issued(req["nostr_pubkey"].as_str().unwrap(), unix_now() + lifetime) + }) + .await; + let keys = Keys::generate(); + let session = AdapterSession::new(&base, TOKEN, RELAY).unwrap(); + session.assertion(&keys).await.unwrap(); + crate::cached_assertion::test_clock::advance(refresh - 1); + session.assertion(&keys).await.unwrap(); + assert_eq!(seen.lock().unwrap().len(), 1, "lifetime {lifetime}"); + crate::cached_assertion::test_clock::advance(1); + session.assertion(&keys).await.unwrap(); + assert_eq!(seen.lock().unwrap().len(), 2, "lifetime {lifetime}"); + } + } + + /// NIP-FA §Denials: every status/code the adapter can answer, plus the + /// 200 responses a client must refuse. Retryable answers stay retryable + /// (`CliError::Relay` with the status) for the request's retry loop; + /// everything else is an auth error. No error ever carries the token. + #[tokio::test] + async fn denial_table() { + let other = Keys::generate().public_key().to_hex(); + type Respond = Box (StatusCode, String) + Send + Sync>; + let cases: Vec<(&str, Respond, Option, &str)> = vec![ + ( + "invalid_request", + Box::new(|_| denied(StatusCode::BAD_REQUEST, "invalid_request")), + None, + "invalid_request", + ), + ( + "session_required", + Box::new(|_| denied(StatusCode::UNAUTHORIZED, "session_required")), + None, + FEDERATED_IDENTITY_TOKEN_ENV, + ), + ( + "session_expired", + Box::new(|_| denied(StatusCode::UNAUTHORIZED, "session_expired")), + None, + FEDERATED_IDENTITY_TOKEN_ENV, + ), + ( + "authorization_denied", + Box::new(|_| denied(StatusCode::FORBIDDEN, "authorization_denied")), + None, + "authorization_denied", + ), + ( + "invalid_proof", + Box::new(|_| denied(StatusCode::FORBIDDEN, "invalid_proof")), + None, + "invalid_proof", + ), + ( + "binding_mismatch", + Box::new(|_| denied(StatusCode::FORBIDDEN, "binding_mismatch")), + None, + "binding_mismatch", + ), + ( + "request_too_large", + Box::new(|_| denied(StatusCode::PAYLOAD_TOO_LARGE, "request_too_large")), + None, + "request_too_large", + ), + ( + "unknown 4xx", + Box::new(|_| (StatusCode::IM_A_TEAPOT, "{}".into())), + None, + "HTTP 418", + ), + ( + "rate_limited", + Box::new(|_| denied(StatusCode::TOO_MANY_REQUESTS, "rate_limited")), + Some(429), + "HTTP 429", + ), + ( + "internal error", + Box::new(|_| (StatusCode::INTERNAL_SERVER_ERROR, String::new())), + Some(500), + "HTTP 500", + ), + ( + "not implemented", + Box::new(|_| (StatusCode::NOT_IMPLEMENTED, "".into())), + Some(501), + "HTTP 501", + ), + ( + "issuance_unavailable", + Box::new(|_| denied(StatusCode::SERVICE_UNAVAILABLE, "issuance_unavailable")), + Some(503), + "HTTP 503", + ), + ( + "exp disagrees with expires_at", + Box::new(|pk| { + let exp = unix_now() + 300; + issued_as(pk, exp, &test_support::assertion(pk, exp + 60)) + }), + None, + "does not match expires_at", + ), + ( + "empty signature", + Box::new(|pk| { + let exp = unix_now() + 300; + let jws = test_support::assertion(pk, exp); + let unsigned = &jws[..=jws.rfind('.').unwrap()]; + issued_as(pk, exp, unsigned) + }), + None, + "compact JWS", + ), + ( + "four segments", + Box::new(|pk| { + let exp = unix_now() + 300; + issued_as( + pk, + exp, + &format!("{}.c2ln", test_support::assertion(pk, exp)), + ) + }), + None, + "compact JWS", + ), + ( + "header is not JSON", + Box::new(|pk| issued_as(pk, unix_now() + 300, "bm90LWpzb24.e30.c2ln")), + None, + "compact JWS", + ), + ( + "wrong pubkey", + Box::new(move |_| issued(&other, unix_now() + 300)), + None, + "different key", + ), + ( + "expired", + Box::new(|pk| issued(pk, unix_now() - 1)), + None, + "expired", + ), + ( + "not a compact JWS", + Box::new(|pk| issued_as(pk, unix_now() + 300, "not-a-jws")), + None, + "compact JWS", + ), + ( + "unreadable", + Box::new(|_| (StatusCode::OK, "{\"assertion\":".into())), + None, + "unreadable", + ), + ( + "oversized", + Box::new(|_| (StatusCode::OK, "x".repeat(MAX_RESPONSE_BYTES + 1))), + None, + "unreadable", + ), + ]; + for (name, respond, retry_status, expected) in cases { + let (base, seen) = + adapter(move |req| respond(req["nostr_pubkey"].as_str().unwrap_or_default())).await; + let credentials = Keys::generate(); + let session = AdapterSession::new(&base, TOKEN, RELAY).unwrap(); + let err = session.assertion(&credentials).await.unwrap_err(); + let message = err.to_string(); + assert!(message.contains(expected), "{name}: {message}"); + assert!(!message.contains(TOKEN), "{name}: token leaked: {message}"); + // Transient answers are retried, then fail as a retryable + // adapter error; refusals are a single attempt. + let attempts = match (retry_status, &err) { + (Some(_), CliError::Adapter(_)) => MINT_ATTEMPTS, + (None, CliError::Auth(_)) => 1, + _ => panic!("{name}: unexpected error class {err:?}"), + }; + assert_eq!( + crate::error::is_retryable_error(&err), + retry_status.is_some(), + "{name}" + ); + assert_eq!(seen.lock().unwrap().len(), attempts, "{name}: attempts"); + // A failed mint is not cached: the next call asks again. + let _ = session.assertion(&credentials).await; + assert_eq!( + seen.lock().unwrap().len(), + 2 * attempts, + "{name}: failure not cached" + ); + } + } + + /// NIP-FA: the token and proof never follow a redirect. + #[tokio::test] + async fn a_redirect_is_refused_and_never_followed() { + let (target, target_seen) = + adapter(|req| issued(req["nostr_pubkey"].as_str().unwrap(), unix_now() + 300)).await; + let location = format!("{target}{ASSERTIONS_PATH}"); + let app = axum::Router::new().route( + ASSERTIONS_PATH, + axum::routing::post(move || { + let location = location.clone(); + async move { + ( + StatusCode::TEMPORARY_REDIRECT, + [("location", location)], + String::new(), + ) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let session = AdapterSession::new(&base, TOKEN, RELAY).unwrap(); + let err = session.assertion(&Keys::generate()).await.unwrap_err(); + assert!( + matches!(&err, CliError::Auth(m) if m.contains("HTTP 307")), + "{err:?}" + ); + assert!(target_seen.lock().unwrap().is_empty(), "redirect followed"); + } + + #[tokio::test] + async fn an_unreachable_adapter_is_retried_then_a_retryable_adapter_error_without_the_token() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let session = AdapterSession::new(&base, TOKEN, RELAY).unwrap(); + let err = session.assertion(&Keys::generate()).await.unwrap_err(); + assert!( + matches!(&err, CliError::Adapter(m) if m.contains("3 attempts")), + "{err:?}" + ); + assert!(crate::error::is_retryable_error(&err)); + assert!(!format!("{err:?}").contains(TOKEN)); + } + + /// A refusal whose body is cut off is still a refusal: one attempt, not + /// retryable. A cut-off 200 is a transport failure and is retried. + #[tokio::test] + async fn a_truncated_body_keeps_the_status_meaning() { + let credentials = Keys::generate(); + let (base, seen) = raw_adapter(test_support::TRUNCATED_403).await; + let err = AdapterSession::new(&base, TOKEN, RELAY) + .unwrap() + .assertion(&credentials) + .await + .unwrap_err(); + assert!( + matches!(&err, CliError::Auth(m) if m.contains("HTTP 403")), + "{err:?}" + ); + assert!(!crate::error::is_retryable_error(&err)); + assert_eq!(count(&seen), 1, "a refusal is not retried"); + + let (base, seen) = raw_adapter( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 200\r\nconnection: close\r\n\r\n{\"assert", + ) + .await; + let err = AdapterSession::new(&base, TOKEN, RELAY) + .unwrap() + .assertion(&credentials) + .await + .unwrap_err(); + assert!(matches!(&err, CliError::Adapter(_)), "{err:?}"); + assert_eq!(count(&seen), MINT_ATTEMPTS); + } + + #[test] + fn debug_output_never_contains_the_token() { + let session = + AdapterSession::new("https://adapter.example", "s3cr3t-token", RELAY).unwrap(); + assert!(!format!("{session:?}").contains("s3cr3t-token")); + } +} + +/// Fixtures shared with the relay-client tests. +#[cfg(test)] +pub(crate) mod test_support { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + /// A NIP-FI human assertion shaped like a real adapter's: ES256 header + /// with `typ: nip-fi+jwt`, the NIP-FI claims, and a 64-byte signature. + /// The CLI never verifies the signature; the relay does. + pub(crate) fn assertion(pubkey: &str, exp: u64) -> String { + let segment = |v: serde_json::Value| URL_SAFE_NO_PAD.encode(v.to_string()); + format!( + "{}.{}.{}", + segment(serde_json::json!({"alg": "ES256", "typ": "nip-fi+jwt", "kid": "k1"})), + segment(serde_json::json!({ + "iss": "https://adapter.example", + "sub": "user-1", + "aud": "https://relay.example.com", + "iat": exp.saturating_sub(300), + "exp": exp, + "jti": "a1b2c3", + "nostr_pubkey": pubkey, + })), + URL_SAFE_NO_PAD.encode([7u8; 64]), + ) + } + + /// An adapter that answers every connection with the raw HTTP bytes + /// `response` and then closes it, so a short body is a truncated one. + /// Returns the base URL and the number of requests it answered. + pub(crate) async fn raw_adapter(response: &'static str) -> (String, Arc) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let count = Arc::new(AtomicUsize::new(0)); + let seen = count.clone(); + tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + seen.fetch_add(1, Ordering::SeqCst); + let mut request = Vec::new(); + let mut buf = [0u8; 4096]; + // Read the head and the (small) body before answering. + while let Ok(n) = socket.read(&mut buf).await { + if n == 0 { + break; + } + request.extend_from_slice(&buf[..n]); + let text = String::from_utf8_lossy(&request); + if let Some(head_end) = text.find("\r\n\r\n") { + let length = text[..head_end] + .lines() + .find_map(|l| { + l.to_ascii_lowercase() + .strip_prefix("content-length:") + .and_then(|v| v.trim().parse::().ok()) + }) + .unwrap_or(0); + if request.len() >= head_end + 4 + length { + break; + } + } + } + let _ = socket.write_all(response.as_bytes()).await; + let _ = socket.shutdown().await; + } + }); + (base, count) + } + + /// Raw responses for [`raw_adapter`]. + pub(crate) const HTTP_500: &str = + "HTTP/1.1 500 Internal Server Error\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"; + pub(crate) const HTTP_503: &str = + "HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"; + /// A 403 whose body is cut off after a few bytes. + pub(crate) const TRUNCATED_403: &str = "HTTP/1.1 403 Forbidden\r\ncontent-type: application/json\r\ncontent-length: 200\r\nconnection: close\r\n\r\n{\"error\":\"auth"; + + pub(crate) fn count(counter: &AtomicUsize) -> usize { + counter.load(Ordering::SeqCst) + } +} diff --git a/crates/buzz-cli/src/lib.rs b/crates/buzz-cli/src/lib.rs index ac14a0bd058..0ab7fc36ea4 100644 --- a/crates/buzz-cli/src/lib.rs +++ b/crates/buzz-cli/src/lib.rs @@ -1,7 +1,12 @@ pub mod agent_management; +mod cached_assertion; mod client; mod commands; +mod credentials; +#[cfg(unix)] +mod desktop_provider; mod error; +mod federated_identity; mod help_tree; mod links; mod validate; @@ -9,7 +14,6 @@ mod validate; use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum}; use client::BuzzClient; use error::CliError; -use nostr::Keys; use uuid::Uuid; /// Run the Buzz CLI from raw arguments (including `argv[0]`). @@ -124,9 +128,20 @@ fn env_output_format(value: Option<&std::ffi::OsStr>) -> OutputFormat { Buzz CLI — interact with a Buzz relay Configuration (flags override env vars): - BUZZ_RELAY_URL Relay base URL [default: http://localhost:3000] - BUZZ_PRIVATE_KEY Nostr private key (hex or nsec) [required] + BUZZ_RELAY_URL Relay base URL [default: the relay an agent's inherited + Buzz desktop credential acts on; else, with no private key, + the one relay a running Buzz desktop accepts this CLI's + pairing for (see `buzz auth desktop list`); else + http://localhost:3000. `auth desktop pair` given none + pairs for the desktop's active community. A bare host + means https://] + BUZZ_PRIVATE_KEY Nostr private key (hex or nsec) [unless a Buzz desktop provides it] BUZZ_AUTH_TAG NIP-OA auth tag JSON [optional] + BUZZ_FEDERATED_IDENTITY_TOKEN Your NIP-FA sign-in session token [optional] + BUZZ_FEDERATED_IDENTITY_ADAPTER NIP-FA adapter base URL [optional] + Set both for relays that enforce federated identity (NIP-FI). The token + is a human session for your own key, not an agent grant. The CLI requests + an assertion, the adapter mints it, and the CLI sends it on every request. BUZZ_OUTPUT_FORMAT Default --format; unknown values fall back to json [optional] The 'pack' subcommand runs locally and does not require a relay connection. @@ -135,9 +150,14 @@ Exit codes: 0=ok 1=bad input 2=relay/network error 3=auth error 4=other 5=w Errors are JSON on stderr: {\"error\": \"\", \"message\": \"\"}" )] struct Cli { - /// Relay URL (http:// or https://). Overrides BUZZ_RELAY_URL env var. - #[arg(long, env = "BUZZ_RELAY_URL", default_value = "http://localhost:3000")] - relay: String, + /// Relay URL; a bare host means https://. Overrides BUZZ_RELAY_URL env + /// var. Without either, the relay an agent's inherited Buzz desktop + /// credential acts on; else, with no private key, the one relay a running + /// Buzz desktop accepts this CLI's pairing for; otherwise + /// http://localhost:3000. Pairing given none uses the desktop's active + /// community. + #[arg(long, global = true, env = "BUZZ_RELAY_URL")] + relay: Option, /// Nostr private key (hex or nsec). This is the CLI's identity. #[arg(long, env = "BUZZ_PRIVATE_KEY", hide_env_values = true)] @@ -272,6 +292,9 @@ enum Cmd { /// Get and set channel canvas documents #[command(subcommand)] Canvas(CanvasCmd), + /// Organize your own sidebar: sections, sort modes, stars, mutes, and project pins + #[command(subcommand)] + Sidebar(SidebarCmd), /// Add, remove, and list emoji reactions #[command(subcommand)] Reactions(ReactionsCmd), @@ -284,6 +307,9 @@ enum Cmd { /// List, open, and manage direct messages #[command(subcommand)] Dms(DmsCmd), + /// List huddles and their participants (read-only) + #[command(subcommand)] + Huddles(HuddlesCmd), /// Look up users and manage profiles and presence #[command(subcommand)] Users(UsersCmd), @@ -326,11 +352,150 @@ enum Cmd { /// Persona pack operations (local, no relay connection needed) #[command(subcommand)] Pack(PackCmd), + /// Credentials: pair this CLI with the running Buzz desktop + #[command(subcommand)] + Auth(AuthCmd), /// Community moderation — reports queue, bans, timeouts, audit trail #[command(subcommand)] Moderation(ModerationCmd), } +#[derive(Subcommand)] +enum AuthCmd { + /// The Buzz desktop as a credential provider (macOS and Linux) + #[command(subcommand)] + Desktop(DesktopAuthCmd), +} + +#[derive(Subcommand)] +enum DesktopAuthCmd { + /// Ask the running Buzz desktop to let this CLI act as you on --relay, + /// or, given none, on its active community. Approve in Buzz; the token + /// is stored in the OS keychain. + Pair { + /// Name shown in the desktop's approval prompt + #[arg(long, default_value = "buzz CLI")] + name: String, + /// Desktop instance, when more than one is running + #[arg(long)] + instance: Option, + }, + /// Forget paired tokens (all instances unless --instance). Local only. + Unpair { + #[arg(long)] + instance: Option, + }, + /// List this CLI's pairings: instance, relays, pubkey, and whether a + /// running Buzz desktop accepts each now. Never prints tokens; needs no + /// relay. + List, +} + +/// The relay for a command given none: the one an agent's inherited Buzz +/// desktop credential acts on; else, without an explicit key, the one relay +/// a running Buzz desktop still accepts this CLI's pairing for; else `None`, +/// which [`connect`] reads as [`FALLBACK_RELAY`] and pairing as the +/// desktop's active community. Local-only unpairing never asks the desktop, +/// and pairing never asks for other pairings. +async fn default_relay(command: &Cmd, explicit_key: bool) -> Result, CliError> { + #[cfg(unix)] + let (inherited, paired) = ( + desktop_provider::inherited_relay(), + desktop_provider::paired_relay(), + ); + #[cfg(not(unix))] + let (inherited, paired) = (async { Ok(None) }, async { Ok(None) }); + default_relay_with(command, explicit_key, inherited, paired).await +} + +/// [`default_relay`], with the agent and paired-person selectors (each +/// awaited only when needed) parameters so a test can run it against a fake +/// desktop. +pub(crate) async fn default_relay_with( + command: &Cmd, + explicit_key: bool, + inherited: impl std::future::Future, CliError>>, + paired: impl std::future::Future, CliError>>, +) -> Result, CliError> { + #[cfg(unix)] + if !matches!( + command, + Cmd::Auth(AuthCmd::Desktop(DesktopAuthCmd::Unpair { .. })) + ) { + if let Some(relay) = inherited.await? { + return Ok(Some(relay)); + } + // Pairing asks its own desktop; another desktop's answer is moot. + let pairing = matches!( + command, + Cmd::Auth(AuthCmd::Desktop(DesktopAuthCmd::Pair { .. })) + ); + if !explicit_key && !pairing { + if let Some(relay) = paired.await? { + return Ok(Some(relay)); + } + } + } + #[cfg(not(unix))] + let _ = (command, explicit_key, inherited, paired); + Ok(None) +} + +/// The relay a command given none, and found none, acts on. +const FALLBACK_RELAY: &str = "http://localhost:3000"; + +/// `raw` as a relay URL: a bare host means `https://`; any scheme stays. +fn relay_url(raw: &str) -> String { + if raw.contains("://") { + raw.to_owned() + } else { + format!("https://{raw}") + } +} + +#[cfg(unix)] +async fn run_auth(cmd: AuthCmd, relay_url: Option<&str>) -> Result<(), CliError> { + let AuthCmd::Desktop(cmd) = cmd; + let out = match cmd { + DesktopAuthCmd::Pair { name, instance } => { + desktop_provider::pair(relay_url, &name, instance.as_deref()).await? + } + DesktopAuthCmd::Unpair { instance } => desktop_provider::unpair(instance.as_deref())?, + DesktopAuthCmd::List => unreachable!("listing runs before any relay is chosen"), + }; + println!("{out}"); + Ok(()) +} + +/// `auth desktop list`, in `format`: `compact` drops the pubkey. +#[cfg(unix)] +async fn list_pairings(format: &OutputFormat) -> Result<(), CliError> { + let mut listed = desktop_provider::list().await?; + if matches!(format, OutputFormat::Compact) { + for pairing in &mut listed { + if let Some(fields) = pairing.as_object_mut() { + fields.remove("pubkey"); + } + } + } + println!("{}", serde_json::Value::Array(listed)); + Ok(()) +} + +#[cfg(not(unix))] +async fn list_pairings(_: &OutputFormat) -> Result<(), CliError> { + Err(CliError::Usage( + "the Buzz desktop credential provider is not available on Windows yet".into(), + )) +} + +#[cfg(not(unix))] +async fn run_auth(_: AuthCmd, _: Option<&str>) -> Result<(), CliError> { + Err(CliError::Usage( + "the Buzz desktop credential provider is not available on Windows yet".into(), + )) +} + #[derive(Clone, Copy, clap::ValueEnum)] pub enum RespondToArg { #[value(name = "owner-only")] @@ -353,7 +518,8 @@ impl RespondToArg { pub enum AgentsCmd { /// Open a prefilled create-agent form in the owner's Buzz Desktop DraftCreate { - /// Current channel UUID; the new agent is added here after save + /// Current channel UUID; the new agent is added here after save (from a + /// DM: a new DM of the same people plus the agent) #[arg(long)] channel: String, /// Proposed agent name @@ -460,7 +626,7 @@ buzz agents archived" pub enum MessagesCmd { /// Send a message to a channel #[command( - after_help = "Examples:\n buzz messages send --channel --content \"hello\"\n buzz messages send --channel --content \"@alice check this\"\n echo \"hello from stdin\" | buzz messages send --channel --content -\n buzz messages send --channel --content-file message.md # UTF-8 file; use this on Windows" + after_help = "Examples:\n buzz messages send --channel --content \"hello\"\n buzz messages send --channel --content \"@alice check this\"\n echo \"hello from stdin\" | buzz messages send --channel --content -\n buzz messages send --channel --content-file message.md # UTF-8 file; use this on Windows\n buzz messages send --channel --content \"decision: ship it\" --from-thread " )] Send { /// Channel UUID (from 'buzz channels list') @@ -479,6 +645,9 @@ pub enum MessagesCmd { /// Event ID to reply to (creates a thread) #[arg(long)] reply_to: Option, + /// Thread root event ID: send this as a new top-level message tagged as sent from that thread (like desktop's "Send to channel") + #[arg(long, conflicts_with_all = ["reply_to", "broadcast"])] + from_thread: Option, /// Also publish to the Nostr network #[arg(long, default_value_t = false)] broadcast: bool, @@ -528,7 +697,7 @@ pub enum MessagesCmd { #[arg(long)] reply_to: Option, }, - /// Edit a previously sent message + /// Edit a previously sent message, retaining its current attachments Edit { /// Event ID of the message to edit (64-char hex) #[arg(long)] @@ -536,6 +705,9 @@ pub enum MessagesCmd { /// New message content #[arg(long)] content: String, + /// Remove all attachments on kinds 9/40002/40008/45001/45003 (later edits keep them removed) + #[arg(long)] + clear_attachments: bool, }, /// Delete a message by event ID Delete { @@ -552,6 +724,31 @@ pub enum MessagesCmd { #[arg(long)] public_reason: Option, }, + /// Report a message or user to the community moderators (NIP-56) + #[command( + group = clap::ArgGroup::new("target").required(true).args(["event", "pubkey"]), + after_help = "Examples:\n buzz messages report --event --reason spam\n buzz messages report --channel --event --reason other --note \"off-topic ads\"\n buzz messages report --pubkey --reason impersonation\n\nReasons: illegal, nudity, malware, spam, impersonation, profanity, other.\nA report goes to the moderation queue only; it is never shown in the channel." + )] + Report { + /// Channel UUID the message is in; checked against the message when given + #[arg(long, conflicts_with = "pubkey")] + channel: Option, + /// Event ID of the message to report (64-char hex) + #[arg(long)] + event: Option, + /// Pubkey of a user to report without a message (64-char hex) + #[arg(long)] + pubkey: Option, + /// Why you are reporting + #[arg( + long, + value_parser = clap::builder::PossibleValuesParser::new(buzz_sdk::REPORT_TYPES) + )] + reason: String, + /// Optional note for the moderators + #[arg(long)] + note: Option, + }, /// Retrieve messages from a channel #[command( after_help = "Examples:\n buzz messages get --channel \n buzz messages get --channel --limit 50 --kinds 1,1984" @@ -596,7 +793,7 @@ pub enum MessagesCmd { }, /// Full-text search across messages #[command( - after_help = "Examples:\n buzz messages search --query checkout\n buzz messages search --author npub1... --since 1783497600\n buzz messages search --author Aaron --query checkout --limit 20" + after_help = "Examples:\n buzz messages search --query checkout\n buzz messages search --author npub1... --since 1783497600\n buzz messages search --author Aaron --query checkout --limit 20\n buzz messages search --author npub1... --before 1783584000 --before-id --limit 100" )] Search { /// Search query string (optional when --author is given) @@ -608,6 +805,14 @@ pub enum MessagesCmd { /// Unix timestamp — return messages after this time #[arg(long)] since: Option, + /// Unix timestamp cursor — return messages created at or before this time. + /// To page back, pass the last result's `created_at` here and its `id` as --before-id. + #[arg(long)] + before: Option, + /// Event ID cursor — with --before, resume after this event, so events from the + /// same second are neither repeated nor skipped. Not allowed with --query. + #[arg(long, requires = "before")] + before_id: Option, /// Maximum number of results to return #[arg(long)] limit: Option, @@ -640,6 +845,19 @@ pub enum ChannelsCmd { #[arg(long)] limit: Option, }, + /// Unread message counts from your synced read state (read-only) + #[command( + after_help = "Examples:\n buzz channels unread\n buzz channels unread --channel --channel \n buzz channels unread --limit 20\n\nOutput: [{channel_id, name, last_read_at, unread_count, capped}]. `capped: true` means unread_count is a lower bound. When more channels exist than --limit (at most 200), the rest are listed in a stderr warning count and not counted. Fails if a read-state slot cannot be decrypted or decoded." + )] + Unread { + /// Count only these channels (repeatable, at most 200). Default: every + /// non-archived channel you are a member of + #[arg(long)] + channel: Vec, + /// Most channels to count [default: 200, max: 200] + #[arg(long)] + limit: Option, + }, /// Get details for a single channel Get { /// Channel UUID @@ -703,9 +921,9 @@ pub enum ChannelsCmd { #[arg(long, value_name = "PATH")] templates_file: Option, }, - /// Update channel name, description, visibility, join role, unlisted, or ephemeral TTL + /// Update channel name, description, visibility, join role, unlisted, auto-join, or ephemeral TTL #[command( - after_help = "Examples:\n buzz channels update --channel --name general\n buzz channels update --channel --visibility open\n buzz channels update --channel --visibility private\n buzz channels update --channel --join-role guest\n buzz channels update --channel --visibility open --unlisted true" + after_help = "Examples:\n buzz channels update --channel --name general\n buzz channels update --channel --visibility open\n buzz channels update --channel --visibility private\n buzz channels update --channel --join-role guest\n buzz channels update --channel --visibility open --unlisted true\n buzz channels update --channel --auto-join true" )] Update { /// Channel UUID @@ -739,6 +957,11 @@ pub enum ChannelsCmd { /// does not advertise `buzz-unlisted-channels`. #[arg(long, value_name = "BOOL", action = clap::ArgAction::Set)] unlisted: Option, + /// Whether the relay joins every new community member into this + /// channel (a default channel). Relay owner/admin only; accepted only + /// on an open, unarchived stream channel. + #[arg(long, value_name = "true|false")] + auto_join: Option, }, /// Set the channel topic Topic { @@ -901,6 +1124,156 @@ pub enum ReactionsCmd { }, } +#[derive(Subcommand)] +pub enum SidebarCmd { + /// List, create, and arrange your channel sections (synced with Buzz desktop) + /// + /// Each edit reads your current sections and publishes the full result. + /// Concurrent edits from another CLI run or another client can overwrite + /// each other, and the last publish wins. + #[command(subcommand)] + Sections(SidebarSectionsCmd), + /// List and set how each sidebar group is sorted (synced with Buzz desktop) + #[command(subcommand)] + Sort(SidebarSortCmd), + /// List, star, and unstar your channels (synced with Buzz desktop) + #[command(subcommand)] + Stars(SidebarChannelFlagCmd), + /// List, mute, and unmute your channels (synced with Buzz desktop) + #[command(subcommand)] + Mutes(SidebarChannelFlagCmd), + /// List, pin, and unpin your sidebar projects (synced with Buzz desktop) + #[command(subcommand)] + Projects(SidebarProjectsCmd), +} + +/// How a sidebar group orders its channels. +#[derive(Clone, Copy, clap::ValueEnum)] +pub enum SidebarSortMode { + /// By name, A to Z + Alpha, + /// By last message, newest first + Recent, +} + +/// `--group` takes `starred`, `channels`, `forums`, `dms`, `section:`, or +/// the name of a section. +#[derive(Subcommand)] +pub enum SidebarSortCmd { + /// List the groups that have a sort mode set + List, + /// Sort a group by name or by recent activity + Set { + /// Group to sort + #[arg(long)] + group: String, + /// Sort mode + #[arg(long, value_enum)] + mode: SidebarSortMode, + }, + /// Return a group to the default sort (alpha) + Reset { + /// Group to reset + #[arg(long)] + group: String, + }, +} + +/// Shared by `sidebar stars` and `sidebar mutes`. +#[derive(Subcommand)] +pub enum SidebarChannelFlagCmd { + /// List the channels that are set + List, + /// Set one or more channels + Add { + /// Channel UUID (repeatable) + #[arg(long = "channel", required = true)] + channels: Vec, + }, + /// Clear one or more channels + Remove { + /// Channel UUID (repeatable) + #[arg(long = "channel", required = true)] + channels: Vec, + }, +} + +#[derive(Subcommand)] +pub enum SidebarProjectsCmd { + /// List the projects pinned to your sidebar + List, + /// Pin one or more projects + Add { + /// Project address `30621::` (repeatable) + #[arg(long = "project", required = true)] + projects: Vec, + }, + /// Unpin one or more projects + Remove { + /// Project address `30621::` (repeatable) + #[arg(long = "project", required = true)] + projects: Vec, + }, +} + +/// `--section` takes a section id, or a section name that is unique. +#[derive(Subcommand)] +pub enum SidebarSectionsCmd { + /// List your sections and the channels assigned to each one + List, + /// Create a section at the end of your sidebar + Create { + /// Section name + #[arg(long)] + name: String, + /// Emoji shown next to the section name + #[arg(long)] + icon: Option, + }, + /// Rename a section or change its icon + Update { + /// Section id or unique name + #[arg(long)] + section: String, + /// New section name + #[arg(long)] + name: Option, + /// New emoji icon + #[arg(long, conflicts_with = "clear_icon")] + icon: Option, + /// Remove the section icon + #[arg(long, default_value_t = false)] + clear_icon: bool, + }, + /// Delete a section; its channels return to the default channel list + Delete { + /// Section id or unique name + #[arg(long)] + section: String, + }, + /// Put sections in order; unlisted sections keep their order after them + Reorder { + /// Section id or unique name, in the new order (repeatable) + #[arg(long = "section", required = true)] + sections: Vec, + }, + /// Move one or more channels into a section + Move { + /// Channel UUID (repeatable) + #[arg(long = "channel", required = true)] + channels: Vec, + /// Section id or unique name + #[arg(long)] + section: String, + }, + /// Return one or more channels to the default channel list + Unassign { + /// Channel UUID (repeatable) + #[arg(long = "channel", required = true)] + channels: Vec, + }, +} + #[derive(Subcommand)] pub enum EmojiCmd { /// List the workspace custom emoji palette (union of every member's set) @@ -1052,8 +1425,18 @@ pub enum UsersCmd { #[arg(long)] emoji: Option, /// Remove your status entirely - #[arg(long, conflicts_with_all = ["text", "emoji"])] + #[arg(long, conflicts_with_all = ["text", "emoji", "expires"])] clear: bool, + /// Clear the status automatically: a future unix timestamp or a + /// duration such as 30m, 2h, 1d, 1w + #[arg(long)] + expires: Option, + }, + /// Read user statuses (NIP-38 kind:30315); expired or cleared statuses are omitted + Status { + /// Pubkey (hex or npub) or exact display name (repeatable, max 100; default: you) + #[arg(long = "pubkey")] + pubkeys: Vec, }, } @@ -1136,6 +1519,31 @@ pub enum WorkflowsCmd { }, } +#[derive(Subcommand)] +pub enum HuddlesCmd { + /// List a channel's huddles with their state and start/end times + List { + /// Channel UUID the huddles were started in + #[arg(long)] + channel: String, + /// Only huddles that are still active + #[arg(long)] + active: bool, + /// Maximum number of huddles to return, newest first + #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u32).range(1..=200))] + limit: u32, + }, + /// Show who is currently in a huddle + Participants { + /// Channel UUID the huddle was started in + #[arg(long)] + channel: String, + /// Huddle ID (the `huddle` field of `huddles list`) + #[arg(long)] + huddle: String, + }, +} + #[derive(Subcommand)] pub enum FeedCmd { /// Get recent activity feed entries @@ -2201,7 +2609,7 @@ pub enum ModerationCmd { /// and the BIP-340 signature. Inputs that are already valid JSON — or not /// recognizable as the shorthand — are returned unchanged so the strict /// parser reports the error on the original bytes. -fn normalize_auth_tag_input(input: &str) -> String { +pub(crate) fn normalize_auth_tag_input(input: &str) -> String { let trimmed = input.trim(); if serde_json::from_str::(trimmed).is_ok() { return trimmed.to_owned(); @@ -2222,9 +2630,30 @@ fn normalize_auth_tag_input(input: &str) -> String { trimmed.to_owned() } -async fn run(cli: Cli) -> Result<(), CliError> { - let relay_url = client::normalize_relay_url(&cli.relay); +/// Binds the configured community: `auth` pairs it (`None`: the desktop's +/// active one), anything else builds the client ([`FALLBACK_RELAY`] for +/// `None`). A desktop binds the whole community URL, trailing slash +/// included, so pairing and the credential chain take it as configured; only +/// requests use the trimmed base, which the client derives. The two steps are parameters so a test can +/// run them against a fake desktop. +pub(crate) async fn connect( + configured: Option<&str>, + command: Cmd, + pair: impl AsyncFnOnce(AuthCmd, Option<&str>) -> Result<(), CliError>, + credentials: impl AsyncFnOnce(&str) -> Result, +) -> Result, CliError> { + // Pairing runs before any credential exists. + if let Cmd::Auth(sub) = command { + pair(sub, configured).await?; + return Ok(None); + } + let configured = configured.unwrap_or(FALLBACK_RELAY); + let credentials = credentials(configured).await?; + let client = BuzzClient::new(configured.to_owned(), credentials)?; + Ok(Some((command, client))) +} +async fn run(cli: Cli) -> Result<(), CliError> { // Pack commands are local-only — no relay connection needed. if let Cmd::Pack(ref sub) = cli.command { return match sub { @@ -2233,52 +2662,42 @@ async fn run(cli: Cli) -> Result<(), CliError> { }; } - // Auth: private key is required for all relay operations. - // The keypair IS the identity — no tokens, no other auth. - let private_key_str = cli.private_key.ok_or_else(|| { - CliError::Auth("BUZZ_PRIVATE_KEY is required (use --private-key or set env var)".into()) - })?; - let keys = Keys::parse(&private_key_str) - .map_err(|e| CliError::Key(format!("invalid BUZZ_PRIVATE_KEY: {e}")))?; - - // NIP-OA: parse and verify the auth tag if provided. - // - // `BUZZ_AUTH_TAG` is hand-authored configuration, so the unquoted raw - // shorthand `[auth,hex,,hex]` is normalized to JSON here — at this input - // edge only. The SDK grammar and the `x-auth-tag` wire format stay strict - // JSON; all validation and signature verification happen on the strict - // path below, unchanged. - let (auth_tag, auth_tag_json) = match cli.auth_tag { - Some(ref input) if !input.is_empty() => { - let json = normalize_auth_tag_input(input); - let tag = buzz_sdk::nip_oa::parse_auth_tag(&json) - .map_err(|e| CliError::Auth(format!("BUZZ_AUTH_TAG is malformed: {e}")))?; - buzz_sdk::nip_oa::verify_auth_tag(&json, &keys.public_key()).map_err(|e| { - CliError::Auth(format!( - "BUZZ_AUTH_TAG verification failed for pubkey {}: {e}", - keys.public_key().to_hex() - )) - })?; - // Canonical wire form derives from the parsed-and-verified tag - // (same shape as buzz-acp's RestClient), never from raw input. - let canonical = serde_json::to_string(tag.as_slice()) - .map_err(|e| CliError::Auth(format!("BUZZ_AUTH_TAG serialization failed: {e}")))?; - (Some(tag), Some(canonical)) - } - _ => (None, None), + // Credential chain: the first link that applies to this relay is the + // identity (see `credentials`). + let settings = credentials::Settings { + private_key: cli.private_key, + auth_tag: cli.auth_tag, + ..Default::default() + } + .with_env_evidence(); + // Listing pairings is local: it needs no relay and runs no discovery. + if let Cmd::Auth(AuthCmd::Desktop(DesktopAuthCmd::List)) = cli.command { + return list_pairings(&cli.format).await; + } + let explicit_key = settings.private_key.is_some(); + let relay = match cli.relay { + Some(relay) => Some(relay_url(&relay)), + None => default_relay(&cli.command, explicit_key).await?, + }; + let Some((command, client)) = connect(relay.as_deref(), cli.command, run_auth, async |relay| { + credentials::resolve(settings, relay).await + }) + .await? + else { + return Ok(()); }; - let client = BuzzClient::new(relay_url, keys, auth_tag, auth_tag_json)?; - - match cli.command { + match command { Cmd::Agents(sub) => commands::agents::dispatch(sub, &client).await, Cmd::Messages(sub) => commands::messages::dispatch(sub, &client, &cli.format).await, Cmd::Channels(sub) => commands::channels::dispatch(sub, &client, &cli.format).await, Cmd::Canvas(sub) => commands::channels::dispatch_canvas(sub, &client).await, + Cmd::Sidebar(sub) => commands::sidebar::dispatch(sub, &client).await, Cmd::Reactions(sub) => commands::reactions::dispatch(sub, &client).await, Cmd::Emoji(sub) => commands::emoji::dispatch(sub, &client).await, Cmd::Gifs(sub) => commands::gifs::dispatch(sub, &client).await, Cmd::Dms(sub) => commands::dms::dispatch(sub, &client).await, + Cmd::Huddles(sub) => commands::huddles::dispatch(sub, &client).await, Cmd::Users(sub) => commands::users::dispatch(sub, &client, &cli.format).await, Cmd::Workflows(sub) => commands::workflows::dispatch(sub, &client).await, Cmd::Feed(sub) => commands::feed::dispatch(sub, &client, &cli.format).await, @@ -2293,7 +2712,7 @@ async fn run(cli: Cli) -> Result<(), CliError> { Cmd::Upload(sub) => commands::upload::dispatch(sub, &client).await, Cmd::Mem(sub) => commands::mem::dispatch(sub, &client).await, Cmd::Moderation(sub) => commands::moderation::dispatch(sub, &client, &cli.format).await, - Cmd::Pack(_) => unreachable!("handled above"), + Cmd::Pack(_) | Cmd::Auth(_) => unreachable!("handled above"), } } @@ -2371,6 +2790,85 @@ mod tests { Cli::command().debug_assert(); } + /// Relay selection asks only what a command needs: an explicit key never + /// asks for a pairing, unpairing asks nothing, pairing asks for no other + /// pairing, and an agent's inherited relay comes first. `None` for + /// `inherited` means it must not be asked; the paired lookup never is. + #[cfg(unix)] + #[tokio::test] + async fn relay_selection_asks_only_what_a_command_needs() { + use clap::Parser; + const INHERITED: &str = "wss://inherited.example/"; + let cases = [ + ("users get", true, Some(None), None), + ("auth desktop unpair", false, None, None), + ("auth desktop pair", false, Some(None), None), + ( + "auth desktop pair", + false, + Some(Some(INHERITED)), + Some(INHERITED), + ), + ("users get", false, Some(Some(INHERITED)), Some(INHERITED)), + ]; + for (args, explicit_key, inherited, want) in cases { + let argv = std::iter::once("buzz").chain(args.split(' ')); + let cli = Cli::try_parse_from(argv).unwrap(); + let inherited = async move { + Ok(inherited + .unwrap_or_else(|| panic!("`{args}` asked for an inherited relay")) + .map(str::to_owned)) + }; + let paired = async { panic!("`{args}` asked for a paired relay") }; + let relay = default_relay_with(&cli.command, explicit_key, inherited, paired) + .await + .unwrap(); + assert_eq!(relay.as_deref(), want, "`{args}`"); + } + } + + /// `--relay` is accepted after the subcommand, and a bare host means + /// `https://` while an explicit scheme stays as typed. + #[test] + fn relay_flag_is_global_and_a_bare_host_means_https() { + use clap::Parser; + let cli = Cli::try_parse_from(["buzz", "auth", "desktop", "pair", "--relay", "h.example"]) + .unwrap(); + assert_eq!(cli.relay.as_deref(), Some("h.example")); + assert_eq!(relay_url("h.example"), "https://h.example"); + assert_eq!(relay_url("h.example/team"), "https://h.example/team"); + for kept in [ + "http://localhost:3000", + "ws://h.example", + "wss://h.example/", + ] { + assert_eq!(relay_url(kept), kept); + } + } + + #[test] + fn messages_send_from_thread_conflicts_with_reply_and_broadcast() { + let base = [ + "buzz", + "messages", + "send", + "--channel", + "123e4567-e89b-12d3-a456-426614174000", + "--content", + "x", + "--from-thread", + ]; + let with = |extra: &[&'static str]| { + let mut args = base.to_vec(); + args.push("a"); + args.extend(extra); + Cli::try_parse_from(args) + }; + assert!(with(&[]).is_ok()); + assert!(with(&["--reply-to", "b"]).is_err()); + assert!(with(&["--broadcast"]).is_err()); + } + #[test] fn messages_thread_accepts_link_or_explicit_identifiers() { let channel = "123e4567-e89b-12d3-a456-426614174000"; @@ -2392,6 +2890,26 @@ mod tests { .is_ok()); } + #[test] + fn messages_search_parses_cursor_and_requires_before_for_before_id() { + let search = |extra: &[&str]| { + let mut argv = vec!["buzz", "messages", "search", "--author", "x"]; + argv.extend_from_slice(extra); + Cli::try_parse_from(argv) + }; + let id = "a".repeat(64); + match search(&["--before", "200", "--before-id", &id]).map(|c| c.command) { + Ok(Cmd::Messages(MessagesCmd::Search { + before, before_id, .. + })) => { + assert_eq!(before, Some(200)); + assert_eq!(before_id.as_deref(), Some(id.as_str())); + } + _ => panic!("messages search should parse --before and --before-id"), + } + assert!(search(&["--before-id", &id]).is_err()); + } + #[test] fn messages_thread_rejects_partial_or_mixed_targets() { let channel = "123e4567-e89b-12d3-a456-426614174000"; @@ -2486,12 +3004,14 @@ mod tests { fn command_inventory_is_stable() { let expected_groups: Vec<&str> = vec![ "agents", + "auth", "canvas", "channels", "dms", "emoji", "feed", "gifs", + "huddles", "issues", "media", "mem", @@ -2504,6 +3024,7 @@ mod tests { "projects", "reactions", "repos", + "sidebar", "social", "upload", "users", @@ -2565,6 +3086,7 @@ mod tests { "delete", "edit", "get", + "report", "search", "send", "send-diff", @@ -2590,6 +3112,7 @@ mod tests { "set-add-policy", "topic", "unarchive", + "unread", "update" ] ); @@ -2613,7 +3136,8 @@ mod tests { "presence", "set-presence", "set-profile", - "set-status" + "set-status", + "status" ] ); assert_eq!( @@ -2701,13 +3225,14 @@ mod tests { let expected: Vec<(&str, usize)> = vec![ ("agents", 5), ("canvas", 4), - ("channels", 16), + ("channels", 17), ("dms", 4), ("emoji", 5), ("feed", 1), + ("huddles", 2), ("issues", 6), ("media", 1), - ("messages", 8), + ("messages", 9), ("pack", 2), ("patches", 4), ("pr", 5), @@ -2716,7 +3241,7 @@ mod tests { ("repos", 6), ("social", 7), ("upload", 1), - ("users", 5), + ("users", 6), ("workflows", 8), ]; diff --git a/crates/buzz-cli/tests/fixtures/huddle_sequences.json b/crates/buzz-cli/tests/fixtures/huddle_sequences.json new file mode 100644 index 00000000000..6d8caa1be88 --- /dev/null +++ b/crates/buzz-cli/tests/fixtures/huddle_sequences.json @@ -0,0 +1,949 @@ +[ + { + "name": "rejoin_with_late_stale_leave", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000005", + "kind": 48102, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 104, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 2, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000004", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 103, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 3, \"admission_id\": \"a2\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000003", + "kind": 48102, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 102, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 2, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000002", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000001", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ], + "expected_ended": false + }, + { + "name": "rejoin_on_second_device", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000009", + "kind": 48102, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 103, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 3, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000008", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 102, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 2, \"admission_id\": \"a2\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000007", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000006", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ], + "expected_ended": false + }, + { + "name": "leave_without_join", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "000000000000000000000000000000000000000000000000000000000000000c", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 102, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 2, \"admission_id\": \"a2\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000000b", + "kind": 48102, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000000a", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ], + "expected_ended": false + }, + { + "name": "join_older_than_recorded_leave", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "000000000000000000000000000000000000000000000000000000000000000f", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 102, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000000e", + "kind": 48102, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 2, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000000d", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [], + "expected_ended": false + }, + { + "name": "ended_by_relay", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000013", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 120, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 2, \"admission_id\": \"a2\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000012", + "kind": 48103, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 110, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000011", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000010", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [], + "expected_ended": true + }, + { + "name": "ended_by_creator", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000016", + "kind": 48103, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 110, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000015", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000014", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [], + "expected_ended": true + }, + { + "name": "end_from_stranger_ignored", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000019", + "kind": 48103, + "pubkey": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + "created_at": 110, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000018", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000017", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ], + "expected_ended": false + }, + { + "name": "forged_join_ignored", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "000000000000000000000000000000000000000000000000000000000000001b", + "kind": 48101, + "pubkey": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"admission_id\": \"x\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000001a", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [], + "expected_ended": false + }, + { + "name": "same_second_revision_order", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "000000000000000000000000000000000000000000000000000000000000001e", + "kind": 48102, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 2, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000001d", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000001c", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [], + "expected_ended": false + }, + { + "name": "stale_generation_cleared_by_newer_join", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000022", + "kind": 48102, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 103, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 6, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000021", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 102, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a2\", \"generation\": \"2\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000020", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 5, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000001f", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ], + "expected_ended": false + }, + { + "name": "stale_generation_end_ignored", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000025", + "kind": 48103, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 110, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000024", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"2\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000023", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ], + "expected_ended": false + }, + { + "name": "relay_restart_lower_revision_clears", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000028", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 102, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a2\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000027", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 7, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000026", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ], + "expected_ended": false + }, + { + "name": "legacy_events_without_admission", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "000000000000000000000000000000000000000000000000000000000000002c", + "kind": 48102, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 103, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000002b", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 102, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000002a", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000029", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ], + "expected_ended": false + }, + { + "name": "restart_with_new_start", + "relay_self": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "huddle": "11111111-1111-4111-8111-111111111111", + "events": [ + { + "id": "0000000000000000000000000000000000000000000000000000000000000031", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 121, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a2\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "0000000000000000000000000000000000000000000000000000000000000030", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 120, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000002f", + "kind": 48103, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 110, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000002e", + "kind": 48101, + "pubkey": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "created_at": 101, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ], + [ + "p", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\", \"roster_revision\": 1, \"admission_id\": \"a1\", \"generation\": \"1\"}", + "sig": "" + }, + { + "id": "000000000000000000000000000000000000000000000000000000000000002d", + "kind": 48100, + "pubkey": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "created_at": 100, + "tags": [ + [ + "h", + "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50" + ] + ], + "content": "{\"ephemeral_channel_id\": \"11111111-1111-4111-8111-111111111111\"}", + "sig": "" + } + ], + "expected_participants": [ + "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + ], + "expected_ended": false + } +] \ No newline at end of file diff --git a/crates/buzz-cli/tests/huddle_interop.mjs b/crates/buzz-cli/tests/huddle_interop.mjs new file mode 100644 index 00000000000..3af5e0ed51d --- /dev/null +++ b/crates/buzz-cli/tests/huddle_interop.mjs @@ -0,0 +1,24 @@ +// Replays the recorded huddle sequences through desktop's own tracker and +// checks it agrees with the rosters the CLI tests expect. +// node --import ./desktop/test-loader.mjs --experimental-strip-types \ +// crates/buzz-cli/tests/huddle_interop.mjs +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; + +const { HuddlePresenceTracker, applyHuddleLifecycleHistory } = await import( + new URL("../../../desktop/src/features/huddle/lib/huddlePresence.ts", import.meta.url) +); +const sequences = JSON.parse( + readFileSync(new URL("./fixtures/huddle_sequences.json", import.meta.url), "utf8"), +); + +for (const sequence of sequences) { + const tracker = new HuddlePresenceTracker(sequence.relay_self); + applyHuddleLifecycleHistory(tracker, sequence.events); + const roster = [...tracker.snapshot()].sort(); + const ended = Boolean(tracker.sessions.get(sequence.huddle)?.endState); + assert.deepEqual(roster, sequence.expected_participants, `${sequence.name}: roster`); + assert.equal(ended, sequence.expected_ended, `${sequence.name}: ended`); + console.log(`ok ${sequence.name}`); +} +console.log("INTEROP OK"); diff --git a/crates/buzz-core/src/artifact.rs b/crates/buzz-core/src/artifact.rs index 74f33c08d8a..50e8f6070db 100644 --- a/crates/buzz-core/src/artifact.rs +++ b/crates/buzz-core/src/artifact.rs @@ -248,6 +248,8 @@ mod tests { ); let query = parse_query(&json!({"artifact":"current","#project":["p"]})).unwrap(); assert_eq!(query.view, ArtifactView::Current); + let head = parse_query(&json!({"artifact":"head","#d":["x"]})).unwrap(); + assert_eq!(head.view, ArtifactView::Head); for invalid in [ json!({"artifact":"lookup","#d":["x"]}), json!({"artifact":"history"}), @@ -256,6 +258,8 @@ mod tests { json!({"artifact":"current","limit":1001}), json!({"artifact":"current","#assignee":[]}), json!({"artifact":"history","#d":[]}), + json!({"artifact":"head"}), + json!({"artifact":"sync","#h":["c"]}), ] { assert!(parse_query(&invalid).is_err(), "{invalid}"); } @@ -276,6 +280,9 @@ pub enum ArtifactView { Current, /// Every stored, unredacted revision of the artifacts named by `#d`. History, + /// The current revision of each artifact named by `#d`, including a + /// deletion. + Head, } /// Explicit HTTP artifact query. All `#name` predicates compare the first /// value of the same tag. @@ -331,8 +338,38 @@ pub fn parse_query(value: &serde_json::Value) -> Result ArtifactView::Current, Some("history") => ArtifactView::History, - _ => return Err("artifact must be \"current\" or \"history\""), + Some("head") => ArtifactView::Head, + _ => return Err("artifact must be \"current\", \"history\" or \"head\""), }; + let tags = parse_predicates(object, &["artifact", "kinds", "limit", "offset"])?; + let number = |name: &str, default: u64| { + object + .get(name) + .map(|v| v.as_u64().ok_or("invalid limit or offset")) + .transpose() + .map(|v| v.unwrap_or(default)) + }; + let limit = number("limit", 100)?; + let offset = number("offset", 0)?; + if limit == 0 || limit > MAX_PAGE_SIZE as u64 || offset > MAX_OFFSET { + return Err("artifact page limit exceeded"); + } + if view != ArtifactView::Current && !tags.iter().any(|(n, _)| n == "d") { + return Err("history and head require #d"); + } + Ok(ArtifactQuery { + view, + tags, + limit: limit as i64, + offset: offset as i64, + }) +} +/// Parse the `kinds` and `#name` predicates shared by every artifact filter. +/// Keys outside `#name` and `allowed` are rejected. +pub(crate) fn parse_predicates( + object: &serde_json::Map, + allowed: &[&str], +) -> Result)>, &'static str> { if let Some(kinds) = object.get("kinds") { if kinds.as_array().map(Vec::as_slice) != Some(&[serde_json::json!(45010)]) { return Err("artifact queries accept only kinds [45010]"); @@ -361,32 +398,12 @@ pub fn parse_query(value: &serde_json::Value) -> Result MAX_PREDICATES || total > MAX_QUERY_VALUES || bytes > MAX_TAG_BYTES { return Err("artifact predicate limits exceeded"); } - let number = |name: &str, default: u64| { - object - .get(name) - .map(|v| v.as_u64().ok_or("invalid limit or offset")) - .transpose() - .map(|v| v.unwrap_or(default)) - }; - let limit = number("limit", 100)?; - let offset = number("offset", 0)?; - if limit == 0 || limit > MAX_PAGE_SIZE as u64 || offset > MAX_OFFSET { - return Err("artifact page limit exceeded"); - } - if view == ArtifactView::History && !tags.iter().any(|(n, _)| n == "d") { - return Err("history requires #d"); - } - Ok(ArtifactQuery { - view, - tags, - limit: limit as i64, - offset: offset as i64, - }) + Ok(tags) } diff --git a/crates/buzz-core/src/artifact_sync.rs b/crates/buzz-core/src/artifact_sync.rs new file mode 100644 index 00000000000..87f63d417eb --- /dev/null +++ b/crates/buzz-core/src/artifact_sync.rs @@ -0,0 +1,132 @@ +//! NIP-AR sync filter: `{"artifact":"current", "#h":[...], ...}` on a `REQ`. +//! The same current-state filter as HTTP `/query`; the `REQ` transport makes +//! it a sync (complete set, `EOSE`, then live heads). +use crate::artifact::{canonical_uuid, parse_predicates}; +use uuid::Uuid; + +/// Largest set one sync serves: it bounds each initial read and the held +/// list of changed artifacts. Advertised in NIP-11 as `sync.max_events`. +pub const MAX_SYNC_EVENTS: usize = 4096; + +/// A parsed sync filter. `channels` are the `#h` values; `tags` holds every +/// `#name` predicate, `#h` included, with NIP-AR match semantics. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ArtifactSyncFilter { + /// Named channels (`#h`), deduplicated in request order. Never empty. + pub channels: Vec, + /// Exact tag-name/value predicates (AND across names, OR within one). + pub tags: Vec<(String, Vec)>, +} + +impl ArtifactSyncFilter { + /// Whether `head` matches every predicate with the NIP-AR match rule: a + /// tag with that name whose first value is one of the requested values. + /// The same rule the current-state query applies (NIP-AR sync rule 3). + pub fn matches(&self, head: &nostr::Event) -> bool { + self.tags.iter().all(|(name, values)| { + head.tags.iter().any(|tag| match tag.as_slice() { + [tag_name, value, ..] => tag_name == name && values.contains(value), + _ => false, + }) + }) + } +} + +/// Whether a raw `REQ` filter is a sync: the current-state view. Other +/// artifact views have no live form and stay HTTP-only. +pub fn is_sync_filter(value: &serde_json::Value) -> bool { + value.get("artifact").and_then(|v| v.as_str()) == Some("current") +} + +/// Parse a sync filter. It requires `#h` with canonical channel UUIDs and +/// accepts the current-state predicates and `kinds: [45010]`, but no `limit` +/// or `offset`: a sync always serves the whole set. +pub fn parse_sync(value: &serde_json::Value) -> Result { + let object = value + .as_object() + .ok_or("artifact filter must be an object")?; + if !is_sync_filter(value) { + return Err("artifact must be \"current\""); + } + let tags = parse_predicates(object, &["artifact", "kinds"])?; + let mut channels = Vec::new(); + for (_, values) in tags.iter().filter(|(name, _)| name == "h") { + for value in values { + let id = canonical_uuid(value).map_err(|_| "#h values must be channel UUIDs")?; + if !channels.contains(&id) { + channels.push(id); + } + } + } + if channels.is_empty() { + return Err("sync requires #h"); + } + Ok(ArtifactSyncFilter { channels, tags }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn sync_filter_requires_channels_and_rejects_paging() { + let a = Uuid::new_v4().to_string(); + let parsed = parse_sync( + &json!({"artifact":"current","#h":[a, a],"#type":["buzz.task"],"kinds":[45010]}), + ) + .unwrap(); + assert_eq!(parsed.channels.len(), 1); + assert_eq!(parsed.tags.len(), 2); + for invalid in [ + json!({"artifact":"current"}), + json!({"artifact":"current","#type":["buzz.task"]}), + json!({"artifact":"current","#h":[a],"limit":10}), + json!({"artifact":"current","#h":[a],"offset":0}), + json!({"artifact":"current","#h":[a],"kinds":[45011]}), + json!({"artifact":"current","#h":["not-a-uuid"]}), + json!({"artifact":"current","#h":[a],"since":1}), + json!({"artifact":"history","#h":[a]}), + ] { + assert!(parse_sync(&invalid).is_err(), "{invalid}"); + } + } + + #[test] + fn matches_applies_every_predicate() { + let h = Uuid::new_v4().to_string(); + let filter = parse_sync( + &json!({"artifact":"current","#h":[h],"#type":["work.set"],"#status":["open"]}), + ) + .unwrap(); + let keys = nostr::Keys::generate(); + let head = |tags: &[[&str; 2]]| { + nostr::EventBuilder::new(nostr::Kind::Custom(45010), "") + .tags(tags.iter().map(|t| nostr::Tag::parse(t.to_vec()).unwrap())) + .sign_with_keys(&keys) + .unwrap() + }; + assert!(filter.matches(&head(&[ + ["h", &h], + ["type", "work.set"], + ["status", "open"] + ]))); + // A mutable tag that does not match, a missing tag, another type or + // another channel: not in scope. + for tags in [ + &[["h", &h], ["type", "work.set"], ["status", "done"]][..], + &[["h", &h], ["type", "work.set"]][..], + &[["h", &h], ["type", "work.goals"], ["status", "open"]][..], + &[["h", "other"], ["type", "work.set"], ["status", "open"]][..], + ] { + assert!(!filter.matches(&head(tags)), "{tags:?}"); + } + // Any tag of the name can match, as in the query. + assert!(filter.matches(&head(&[ + ["h", &h], + ["type", "work.set"], + ["status", "done"], + ["status", "open"] + ]))); + } +} diff --git a/crates/buzz-core/src/engram.rs b/crates/buzz-core/src/engram.rs index 7f38347f808..f2f30c3b6e3 100644 --- a/crates/buzz-core/src/engram.rs +++ b/crates/buzz-core/src/engram.rs @@ -438,6 +438,27 @@ pub fn build_event( body: &Body, created_at: u64, ) -> Result { + let plaintext = encode_body(body)?; + let k_c = conversation_key(agent_keys.secret_key(), owner_pubkey); + let ciphertext = nip44::encrypt( + agent_keys.secret_key(), + owner_pubkey, + &plaintext, + Version::V2, + ) + .map_err(|e| EngramError::Encrypt(e.to_string()))?; + let d = d_tag(&k_c, body.slug()); + event_builder(owner_pubkey, &d, ciphertext, created_at)? + .sign_with_keys(agent_keys) + .map_err(|e| EngramError::Sign(e.to_string())) +} + +/// The NIP-44 plaintext for `body`. Returns `BodyTooLarge` if it exceeds +/// 65,535 bytes. +/// +/// Together with [`event_builder`], this lets a caller whose key lives behind +/// a signer build an engram from separate encrypt, `d`-tag and sign steps. +pub fn encode_body(body: &Body) -> Result { let plaintext = body.to_json_bytes(); if plaintext.len() > NIP44_PLAINTEXT_MAX { return Err(EngramError::BodyTooLarge(plaintext.len())); @@ -446,30 +467,28 @@ pub fn build_event( // this is always Ok. We still verify rather than `.expect()` so a future // change to the serializer can't silently introduce a panic on the hot // path. - let plaintext_str = std::str::from_utf8(&plaintext) - .map_err(|e| EngramError::Encrypt(format!("body JSON not UTF-8: {e}")))?; - - let k_c = conversation_key(agent_keys.secret_key(), owner_pubkey); - let ciphertext = nip44::encrypt( - agent_keys.secret_key(), - owner_pubkey, - plaintext_str, - Version::V2, - ) - .map_err(|e| EngramError::Encrypt(e.to_string()))?; + String::from_utf8(plaintext) + .map_err(|e| EngramError::Encrypt(format!("body JSON not UTF-8: {e}"))) +} - let d = d_tag(&k_c, body.slug()); +/// The unsigned `kind:30174` event for an already-encrypted body: `d` is the +/// slug's [`d_tag`], `ciphertext` the NIP-44 payload to the owner. +pub fn event_builder( + owner_pubkey: &PublicKey, + d: &str, + ciphertext: String, + created_at: u64, +) -> Result { let tags = vec![ - Tag::parse(["d", &d]).map_err(|e| EngramError::Encrypt(e.to_string()))?, + Tag::parse(["d", d]).map_err(|e| EngramError::Encrypt(e.to_string()))?, Tag::parse(["p", &owner_pubkey.to_hex()]) .map_err(|e| EngramError::Encrypt(e.to_string()))?, ]; - - EventBuilder::new(Kind::Custom(KIND_AGENT_ENGRAM as u16), ciphertext) - .tags(tags) - .custom_created_at(nostr::Timestamp::from(created_at)) - .sign_with_keys(agent_keys) - .map_err(|e| EngramError::Sign(e.to_string())) + Ok( + EventBuilder::new(Kind::Custom(KIND_AGENT_ENGRAM as u16), ciphertext) + .tags(tags) + .custom_created_at(nostr::Timestamp::from(created_at)), + ) } /// Validate an event against *Head selection* rules (1) and (5) and return @@ -492,6 +511,40 @@ pub fn validate_and_decrypt( my_seckey: &SecretKey, their_pubkey: &PublicKey, ) -> Result { + let d_value = validate_envelope(event, expected_agent, expected_owner)?; + + // Decrypt. `K_c` is symmetric per NIP-44, so the caller's `(my_seckey, + // their_pubkey)` pair yields the same conversation key regardless of + // whether the caller is the agent or the owner. + let plaintext = nip44::decrypt(my_seckey, their_pubkey, &event.content) + .map_err(|_| EngramError::Decrypt)?; + let body = Body::from_json_bytes(plaintext.as_bytes())?; + + // Rule (4): body slug re-derives to the event's d tag. + let k_c = conversation_key(my_seckey, their_pubkey); + check_d_tag(&d_value, &d_tag(&k_c, body.slug()))?; + Ok(body) +} + +/// Rule (4): the decrypted body's slug must re-derive (`derived`) to the +/// event's `d` tag (`d_value`, from [`validate_envelope`]). +pub fn check_d_tag(d_value: &str, derived: &str) -> Result<(), EngramError> { + if derived != d_value { + return Err(EngramError::InvalidEnvelope( + "body slug does not re-derive to d tag".into(), + )); + } + Ok(()) +} + +/// The envelope half of [`validate_and_decrypt`]: kind, author, exactly one +/// canonical `d` tag and exactly one `p` tag naming the owner. Returns the +/// `d` value for [`check_d_tag`] once the content is decrypted. +pub fn validate_envelope( + event: &Event, + expected_agent: &PublicKey, + expected_owner: &PublicKey, +) -> Result { if event.kind.as_u16() as u32 != KIND_AGENT_ENGRAM { return Err(EngramError::InvalidEnvelope(format!( "wrong kind: {}", @@ -537,23 +590,7 @@ pub fn validate_and_decrypt( "p tag != expected_owner".into(), )); } - - // Decrypt. `K_c` is symmetric per NIP-44, so the caller's `(my_seckey, - // their_pubkey)` pair yields the same conversation key regardless of - // whether the caller is the agent or the owner. - let plaintext = nip44::decrypt(my_seckey, their_pubkey, &event.content) - .map_err(|_| EngramError::Decrypt)?; - let body = Body::from_json_bytes(plaintext.as_bytes())?; - - // Rule (4): body slug re-derives to the event's d tag. - let k_c = conversation_key(my_seckey, their_pubkey); - let derived = d_tag(&k_c, body.slug()); - if derived != d_value { - return Err(EngramError::InvalidEnvelope( - "body slug does not re-derive to d tag".into(), - )); - } - Ok(body) + Ok(d_value) } /// Pick the head from a set of events targeting the same slug — greatest diff --git a/crates/buzz-core/src/filter.rs b/crates/buzz-core/src/filter.rs index 2a0ef391f23..6d8b23094cf 100644 --- a/crates/buzz-core/src/filter.rs +++ b/crates/buzz-core/src/filter.rs @@ -7,6 +7,22 @@ use nostr::Filter; use crate::channel::LEGACY_CHANNEL_TYPES; use crate::event::StoredEvent; +/// Whether `tag` attributes a workflow message to its owner instead of +/// mentioning them: `["p", , "", "owner"]` on an event marked +/// `["buzz:workflow", "true"]`. The relay names the owner that way so clients +/// can show who owns the message, and adds a plain `p` tag when the workflow +/// does mention its owner. `#p` matching, the mention index and other mention +/// consumers skip the attribution. The workflow marker keeps the rule off +/// other `p` tags with a fourth field, such as NIP-29 roster roles. An author +/// who marks a tag only withholds a mention they could have left out. +pub fn is_workflow_owner_attribution(event: &nostr::Event, tag: &nostr::Tag) -> bool { + matches!(tag.as_slice(), [name, _, _, marker, ..] if name == "p" && marker == "owner") + && event + .tags + .iter() + .any(|tag| tag.as_slice() == ["buzz:workflow", "true"]) +} + /// Returns `true` if the event matches any of the provided NIP-01 filters. pub fn filters_match(filters: &[Filter], event: &StoredEvent) -> bool { filters.iter().any(|f| filter_match_one(f, event)) @@ -138,7 +154,10 @@ fn filter_match_one(f: &Filter, ev: &StoredEvent) -> bool { ev.event .tags .iter() - .filter(|t| t.kind().to_string() == tag_key_str) + .filter(|t| { + t.kind().to_string() == tag_key_str + && !is_workflow_owner_attribution(&ev.event, t) + }) .filter_map(|t| t.content()) .any(|event_val| event_val == filter_val.as_str()) }); @@ -170,6 +189,15 @@ fn filter_match_one(f: &Filter, ev: &StoredEvent) -> bool { true } +/// Resolves a requested result limit: `default` when absent, otherwise the +/// request saturated to `max`. `Some(0)` stays `0` (NIP-01 "no results"). +/// +/// Saturates before narrowing, so a huge `usize` limit cannot wrap to `0` +/// through `as u32` or turn negative through `as i64`. +pub fn clamp_limit(limit: Option, default: u32, max: u32) -> u32 { + limit.map_or(default, |l| u32::try_from(l).unwrap_or(u32::MAX).min(max)) +} + #[cfg(test)] mod tests { use super::*; @@ -177,6 +205,24 @@ mod tests { use chrono::Utc; use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + #[test] + fn clamp_limit_table() { + let cases: &[(Option, u32, u32, u32)] = &[ + (None, 20, 100, 20), + (Some(0), 20, 100, 0), + (Some(7), 20, 100, 7), + (Some(100), 20, 100, 100), + (Some(101), 20, 100, 100), + (Some(u32::MAX as usize), 20, 100, 100), + (Some(u32::MAX as usize + 1), 20, 100, 100), + (Some(usize::MAX), 20, 100, 100), + (Some(usize::MAX), 1000, u32::MAX, u32::MAX), + ]; + for &(limit, default, max, want) in cases { + assert_eq!(clamp_limit(limit, default, max), want, "{limit:?}"); + } + } + fn stored_with_tag(tag: Tag) -> StoredEvent { let keys = Keys::generate(); let event = EventBuilder::new(Kind::TextNote, "test") @@ -186,6 +232,39 @@ mod tests { StoredEvent::with_received_at(event, Utc::now(), None, true) } + #[test] + fn a_workflow_owner_attribution_does_not_match_p_filters() { + let owner = Keys::generate().public_key().to_hex(); + let by_p: Filter = serde_json::from_value(serde_json::json!({"#p": [owner]})).unwrap(); + let attribution: &[&str] = &["p", &owner, "", "owner"]; + let workflow: &[&str] = &["buzz:workflow", "true"]; + let mention: &[&str] = &["p", &owner]; + // (tags, matches `#p: [owner]`) + let cases: [(&[&[&str]], bool); 4] = [ + (&[attribution, workflow], false), + (&[attribution, workflow, mention], true), + // Without the workflow marker the fourth field is something + // else, such as a NIP-29 roster role, and the tag still matches. + (&[attribution], true), + (&[mention], true), + ]; + for (tags, matches) in cases { + let event = EventBuilder::new(Kind::Custom(9), "run") + .tags( + tags.iter() + .map(|tag| Tag::parse(tag.iter().copied()).unwrap()), + ) + .sign_with_keys(&Keys::generate()) + .expect("sign"); + let stored = StoredEvent::with_received_at(event, Utc::now(), None, true); + assert_eq!( + filters_match(std::slice::from_ref(&by_p), &stored), + matches, + "{tags:?}" + ); + } + } + #[test] fn a_notice_matches_only_filters_that_know_its_channel_type() { let relay = Keys::generate(); diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 759e2f45d23..3b7c1cae0ff 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -119,6 +119,15 @@ pub const KIND_PUSH_LEASE: u32 = 30350; /// the owner's key to itself and contains the runnable identity/configuration /// plus exact public projection bindings. See `docs/nips/NIP-PMA.md`. pub const KIND_PRIVATE_MANAGED_AGENT: u32 = 30179; +/// Custom emoji entry (parameterized replaceable) — one event per emoji. +/// +/// User-owned, keyed by `(pubkey, kind, d_tag)` where `d` is the normalized +/// shortcode. `content` is the shortcode with `_` and `-` turned into spaces (the +/// search text); one `["emoji", shortcode, url]` tag carries the image. Unlike +/// the kind:30030 set, the catalog scales without any client loading it whole: +/// clients resolve names with `#d` filters and search with NIP-50 prefix mode. +/// See `docs/nips/NIP-CE.md`. +pub const KIND_EMOJI_ENTRY: u32 = 30180; /// Kinds whose stored events are readable only by their author. /// @@ -483,6 +492,12 @@ pub const KIND_WINDOW_BOUNDS: u32 = 39006; /// NIP-CW thread-mode query-time bounds, bound to a normalized newest-first thread request. pub const KIND_THREAD_WINDOW_BOUNDS: u32 = 39007; +/// NIP-CL: request-bound compact viewer membership overlay; query-time only, never stored. +pub const KIND_MEMBERSHIP_SNAPSHOT: u32 = 39008; + +/// NIP-CL: request-bound public membership overlay; query-time only, never stored. +pub const KIND_MEMBERSHIP_PUBLIC: u32 = 39009; + /// Workflow definition (parameterized replaceable, d=workflow_uuid). pub const KIND_WORKFLOW_DEF: u32 = 30620; @@ -721,6 +736,7 @@ pub const ALL_KINDS: &[u32] = &[ KIND_FOLLOW_SET, KIND_BOOKMARK_SET, KIND_EMOJI_SET, + KIND_EMOJI_ENTRY, KIND_CHANNEL_METADATA, KIND_DELETION, KIND_REACTION, @@ -770,6 +786,8 @@ pub const ALL_KINDS: &[u32] = &[ KIND_THREAD_SUMMARY, KIND_WINDOW_BOUNDS, KIND_THREAD_WINDOW_BOUNDS, + KIND_MEMBERSHIP_SNAPSHOT, + KIND_MEMBERSHIP_PUBLIC, KIND_PRESENCE_UPDATE, KIND_TYPING_INDICATOR, KIND_AGENT_PRESENCE, @@ -850,6 +868,18 @@ pub const ALL_KINDS: &[u32] = &[ KIND_PROJECT, ]; +/// Metric label for an event kind: the decimal kind when it is registered in +/// [`ALL_KINDS`], otherwise `"other"`. +/// +/// The registry bounds the label set, so the label is safe on metrics whose +/// kind comes from client events. +pub fn registered_kind_label(kind: i32) -> String { + match u32::try_from(kind) { + Ok(kind) if ALL_KINDS.contains(&kind) => kind.to_string(), + _ => "other".to_owned(), + } +} + /// Returns `true` if `kind` is in the ephemeral range (20000–29999). pub const fn is_ephemeral(kind: u32) -> bool { kind >= EPHEMERAL_KIND_MIN && kind <= EPHEMERAL_KIND_MAX @@ -910,12 +940,16 @@ pub const fn is_command_kind(kind: u32) -> bool { ) } +/// NIP-85 relay-signed NIP-FI verified profile (output only). +pub const KIND_VERIFIED_PROFILE: u32 = 30382; + /// Returns `true` if `kind` may only be authored by the relay. /// Client submission of these kinds must be rejected. pub const fn is_relay_only_kind(kind: u32) -> bool { matches!( kind, - KIND_ARTIFACT_REMOVAL + KIND_VERIFIED_PROFILE + | KIND_ARTIFACT_REMOVAL | KIND_NIP43_MEMBERSHIP_LIST | KIND_CHANNEL_SUMMARY | KIND_PRESENCE_SNAPSHOT @@ -923,6 +957,8 @@ pub const fn is_relay_only_kind(kind: u32) -> bool { | KIND_THREAD_SUMMARY | KIND_WINDOW_BOUNDS | KIND_THREAD_WINDOW_BOUNDS + | KIND_MEMBERSHIP_SNAPSHOT + | KIND_MEMBERSHIP_PUBLIC ) } @@ -945,6 +981,7 @@ const _: () = assert!(is_parameterized_replaceable(KIND_TEAM)); // 30176 ∈ 300 const _: () = assert!(is_parameterized_replaceable(KIND_MANAGED_AGENT)); // 30177 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_TEAM_CATALOG)); // 30178 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_PRIVATE_MANAGED_AGENT)); // 30179 ∈ 30000–39999 +const _: () = assert!(is_parameterized_replaceable(KIND_EMOJI_ENTRY)); // 30180 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_WORKFLOW_DEF)); // 30620 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_EVENT_REMINDER)); // 30300 ∈ 30000–39999 const _: () = assert!(is_parameterized_replaceable(KIND_DM_VISIBILITY)); // 30622 ∈ 30000–39999 @@ -996,6 +1033,18 @@ mod tests { } } + #[test] + fn registered_kind_label_bounds_unregistered_kinds() { + assert_eq!( + registered_kind_label(KIND_NIP43_MEMBERSHIP_LIST as i32), + "13534" + ); + assert_eq!(registered_kind_label(KIND_PROFILE as i32), "0"); + assert!(!ALL_KINDS.contains(&30999)); + assert_eq!(registered_kind_label(30999), "other"); + assert_eq!(registered_kind_label(-1), "other"); + } + #[test] fn nip43_membership_snapshot_is_relay_only() { assert!(is_relay_only_kind(KIND_NIP43_MEMBERSHIP_LIST)); @@ -1008,6 +1057,15 @@ mod tests { assert!(is_relay_only_kind(KIND_THREAD_WINDOW_BOUNDS)); } + #[test] + fn compact_membership_snapshot_is_relay_only() { + assert_eq!(KIND_MEMBERSHIP_SNAPSHOT, 39008); + assert!(is_relay_only_kind(KIND_MEMBERSHIP_SNAPSHOT)); + assert_eq!(KIND_MEMBERSHIP_PUBLIC, 39009); + assert!(is_relay_only_kind(KIND_MEMBERSHIP_PUBLIC)); + assert!(ALL_KINDS.contains(&KIND_MEMBERSHIP_PUBLIC)); + } + #[test] fn parameterized_replaceable_range() { assert!(!is_parameterized_replaceable(29999)); diff --git a/crates/buzz-core/src/lib.rs b/crates/buzz-core/src/lib.rs index ba2a991084d..f028a95f6fd 100644 --- a/crates/buzz-core/src/lib.rs +++ b/crates/buzz-core/src/lib.rs @@ -86,3 +86,8 @@ pub mod test_helpers { /// NIP-AR channel artifact envelope and limits. pub mod artifact; +/// NIP-AR sync filter parsing and limits. +pub mod artifact_sync; + +/// Local media reference extraction. +pub mod media; diff --git a/crates/buzz-core/src/media.rs b/crates/buzz-core/src/media.rs new file mode 100644 index 00000000000..d88c4337a77 --- /dev/null +++ b/crates/buzz-core/src/media.rs @@ -0,0 +1,347 @@ +//! A shared vocabulary for local media references on reads and publications. +use nostr::Event; +use std::collections::BTreeSet; + +/// Original event kinds whose latest live edit replaces attachment references. +/// Shared by clients, the effective-edit lookup and media-read authorization. +pub const EDIT_GOVERNED_KINDS: [u16; 5] = [9, 40002, 40008, 45001, 45003]; + +/// Parse a local media URL, returning its parent hash (also for thumbnails). +/// Only the tenant's canonical base and root-relative paths count. +pub fn local_hash(value: &str, base: &str) -> Option { + let alternate = if let Some(rest) = base.strip_prefix("https://") { + format!("http://{rest}") + } else if let Some(rest) = base.strip_prefix("http://") { + format!("https://{rest}") + } else { + base.to_owned() + }; + let prefix = format!("{}/", base.trim_end_matches('/')); + let alternate_prefix = format!("{}/", alternate.trim_end_matches('/')); + let rest = value + .strip_prefix("/media/") + .or_else(|| value.strip_prefix(&prefix)) + .or_else(|| value.strip_prefix(&alternate_prefix))?; + let mut parts = rest.split('.'); + let hash = parts.next()?; + if hash.len() != 64 + || !hash + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return None; + } + let safe_ext = |s: &str| { + !s.is_empty() + && s.len() <= 8 + && s.bytes() + .all(|b| b.is_ascii_digit() || b.is_ascii_lowercase()) + }; + match (parts.next(), parts.next(), parts.next()) { + (None, None, None) => {} + (Some(ext), None, None) if safe_ext(ext) => {} + (Some("thumb"), Some("jpg" | "webp"), None) => {} + _ => return None, + } + Some(hash.to_owned()) +} + +/// Decode the desktop's animated-avatar descriptor into its poster and animation. +/// Each URL still needs its own tenant check. Malformed escapes never become URLs. +pub fn animated_avatar_urls(value: &str) -> Option<(String, String)> { + let (poster, encoded) = value.split_once("#buzz-anim=")?; + if encoded.is_empty() { + return None; + } + let bytes = encoded.as_bytes(); + for (i, byte) in bytes.iter().enumerate() { + if *byte == b'%' + && (i + 2 >= bytes.len() + || !bytes[i + 1].is_ascii_hexdigit() + || !bytes[i + 2].is_ascii_hexdigit()) + { + return None; + } + } + let animation = percent_encoding::percent_decode_str(encoded) + .decode_utf8() + .ok()? + .into_owned(); + for candidate in [poster, animation.as_str()] { + let parsed = url::Url::parse(candidate).ok()?; + if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() { + return None; + } + } + Some((poster.to_owned(), animation)) +} + +fn avatar_hashes(value: &str, base: &str, out: &mut BTreeSet) { + if let Some((poster, animation)) = animated_avatar_urls(value) { + out.extend(local_hash(&poster, base)); + out.extend(local_hash(&animation, base)); + } else { + out.extend(local_hash(value, base)); + } +} + +/// Extract counted references. imeta URL/image fields cover attachments, +/// previews and posters. Profile pictures/banners, group pictures and emoji +/// are the explicitly supported non-message references. Free text grants nothing. +pub fn reference_hashes(event: &Event, base: &str) -> BTreeSet { + let mut out = BTreeSet::new(); + let preview_suppressed = event + .tags + .iter() + .any(|tag| matches!(tag.as_slice(),[name,value] if name=="link-preview" && value=="none")); + for tag in event.tags.iter() { + let parts = tag.as_slice(); + match parts.first().map(String::as_str) { + Some("imeta") => { + for part in &parts[1..] { + if let Some(("url" | "image", value)) = part.split_once(' ') { + out.extend(local_hash(value, base)); + } + } + } + Some("link-preview") + if !preview_suppressed + && parts.len() == 11 + && parts[1] == "snapshot" + && parts[2] == "1" => + { + for value in [&parts[7], &parts[9]] { + out.extend(local_hash(value, base)); + } + } + Some("picture") if event.kind.as_u16() == 39000 => { + if let Some(value) = parts.get(1) { + out.extend(local_hash(value, base)); + } + } + Some("emoji") if matches!(event.kind.as_u16(), 10030 | 30030 | 30180) => { + if let Some(value) = parts.get(2) { + out.extend(local_hash(value, base)); + } + } + _ => {} + } + } + if matches!(event.kind.as_u16(), 0 | 30175) { + if let Ok(profile) = serde_json::from_str::(&event.content) { + let fields = if event.kind.as_u16() == 30175 { + [profile.get("avatar_url"), None] + } else { + [ + profile.get("picture").or_else(|| profile.get("image")), + profile.get("banner"), + ] + }; + for value in fields.into_iter().flatten() { + if let Some(value) = value.as_str() { + avatar_hashes(value, base, &mut out); + } + } + } + } + out +} + +/// All local URLs in structured command payloads as well as counted event +/// references must be authorized before dispatch. This also covers metadata +/// commands whose accepted payload later becomes relay-signed state. +pub fn publication_hashes(event: &Event, base: &str) -> BTreeSet { + fn visit(value: &serde_json::Value, base: &str, out: &mut BTreeSet) { + match value { + serde_json::Value::String(value) => { + avatar_hashes(value, base, out); + } + serde_json::Value::Array(values) => { + for value in values { + visit(value, base, out); + } + } + serde_json::Value::Object(values) => { + for value in values.values() { + visit(value, base, out); + } + } + _ => {} + } + } + let mut out = reference_hashes(event, base); + if let Ok(value) = serde_json::from_str(&event.content) { + visit(&value, base, &mut out); + } + for tag in event.tags.iter() { + for part in tag.as_slice().iter().skip(1) { + out.extend(local_hash(part, base)); + } + } + out +} + +/// First valid edit target in signed tag order, accepting all ASCII hex casing. +pub fn first_edit_target(event: &nostr::Event) -> Option> { + event.tags.iter().find_map(|tag| { + let parts = tag.as_slice(); + let value = parts.get(1)?; + if parts.first().map(String::as_str) == Some("e") + && value.len() == 64 + && value.bytes().all(|c| c.is_ascii_hexdigit()) + { + hex::decode(value).ok() + } else { + None + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use nostr::{EventBuilder, Keys, Kind, Tag}; + #[test] + fn aliases_and_foreign_hosts() { + let hash = "a".repeat(64); + for suffix in ["", ".png", ".thumb.jpg", ".thumb.webp"] { + assert_eq!( + local_hash(&format!("/media/{hash}{suffix}"), "https://local/media"), + Some(hash.clone()) + ); + } + for value in [ + format!("https://foreign/media/{hash}.jpg"), + format!("/media/{hash}0"), + format!("/media/{hash}.png?x=1"), + ] { + assert_eq!(local_hash(&value, "https://local/media"), None); + } + } + #[test] + fn animated_profiles_check_each_url_and_reject_malformed_descriptors() { + let a = "a".repeat(64); + let b = "b".repeat(64); + for (poster, animation, expected) in [ + ( + format!("https://local/media/{a}.png"), + format!("https://local/media/{b}.png"), + BTreeSet::from([a.clone(), b.clone()]), + ), + ( + format!("https://foreign/media/{a}.png"), + format!("https://local/media/{b}.png"), + BTreeSet::from([b]), + ), + ( + format!("https://local/media/{a}.png"), + format!("https://foreign/media/{}.png", "c".repeat(64)), + BTreeSet::from([a.clone()]), + ), + ] { + let descriptor = format!( + "{poster}#buzz-anim={}", + percent_encoding::utf8_percent_encode( + &animation, + percent_encoding::NON_ALPHANUMERIC + ) + ); + let event = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":descriptor}).to_string(), + ) + .sign_with_keys(&Keys::generate()) + .unwrap(); + assert_eq!(reference_hashes(&event, "https://local/media"), expected); + assert_eq!(publication_hashes(&event, "https://local/media"), expected); + } + for value in [ + "https://local/a#buzz-anim=%xx", + "https://local/a#buzz-anim=%ff", + "https://local/a#buzz-anim=", + "https://local/a#buzz-anim=javascript:foo", + ] { + assert!(animated_avatar_urls(value).is_none(), "{value}"); + } + } + #[test] + fn snapshot_media_counts_only_image_and_favicon_urls() { + let a = "a".repeat(64); + let b = "b".repeat(64); + let c = "c".repeat(64); + for (image, favicon, expected) in [ + ( + format!("/media/{a}.png"), + format!("https://local/media/{b}.png"), + BTreeSet::from([a.clone(), b.clone()]), + ), + ( + format!("https://foreign/media/{a}.png"), + String::new(), + BTreeSet::new(), + ), + ] { + let event = EventBuilder::new(Kind::Custom(9), "") + .tags([Tag::parse([ + "link-preview", + "snapshot", + "1", + &format!("https://local/media/{c}.png"), + "title", + "site", + "description", + &image, + &a, + &favicon, + &b, + ]) + .unwrap()]) + .sign_with_keys(&Keys::generate()) + .unwrap(); + assert_eq!(reference_hashes(&event, "https://local/media"), expected); + } + } + #[test] + fn profile_image_fallback_matches_materialization() { + let a = "a".repeat(64); + let b = "b".repeat(64); + for (content, expected) in [ + ( + serde_json::json!({"image":format!("/media/{a}.png")}), + BTreeSet::from([a.clone()]), + ), + ( + serde_json::json!({"picture":format!("/media/{b}.png"),"image":format!("/media/{a}.png")}), + BTreeSet::from([b]), + ), + ( + serde_json::json!({"picture":null,"image":format!("/media/{a}.png")}), + BTreeSet::new(), + ), + ] { + let event = EventBuilder::new(Kind::Metadata, content.to_string()) + .sign_with_keys(&Keys::generate()) + .unwrap(); + assert_eq!(reference_hashes(&event, "https://local/media"), expected); + } + } + #[test] + fn profile_and_imeta_share_the_publication_extractor() { + let hash = "b".repeat(64); + let event = EventBuilder::new( + Kind::Metadata, + format!(r#"{{"picture":"https:\/\/local\/media\/{hash}.jpg"}}"#), + ) + .tags([Tag::parse(["imeta", &format!("url /media/{hash}.jpg")]).unwrap()]) + .sign_with_keys(&Keys::generate()) + .unwrap(); + assert_eq!( + reference_hashes(&event, "https://local/media"), + BTreeSet::from([hash]) + ); + assert_eq!( + publication_hashes(&event, "https://local/media"), + reference_hashes(&event, "https://local/media") + ); + } +} diff --git a/crates/buzz-core/src/pairing/mod.rs b/crates/buzz-core/src/pairing/mod.rs index 4b5e03eff8e..f50734f2882 100644 --- a/crates/buzz-core/src/pairing/mod.rs +++ b/crates/buzz-core/src/pairing/mod.rs @@ -25,7 +25,7 @@ pub mod session; pub mod types; pub use qr::QrPayload; -pub use session::{PairingSession, Role, SessionState}; +pub use session::{PairingBinding, PairingSession, Role, SessionState}; pub use types::{AbortReason, PairingMessage, PayloadType}; use thiserror::Error; diff --git a/crates/buzz-core/src/pairing/session.rs b/crates/buzz-core/src/pairing/session.rs index 606315beadd..042958af83b 100644 --- a/crates/buzz-core/src/pairing/session.rs +++ b/crates/buzz-core/src/pairing/session.rs @@ -62,6 +62,20 @@ pub enum Role { Target, } +/// Public channel binding for independently authenticated application approval. +/// This identifies the locked peers and transcript, not their account identity. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PairingBinding { + /// Identifier derived from this QR session's random secret. + pub session_id: [u8; 32], + /// The initiating device's ephemeral public key. + pub source_pubkey: PublicKey, + /// The receiving device's ephemeral public key. + pub target_pubkey: PublicKey, + /// The commitment verified by `sas-confirm`. + pub transcript_hash: [u8; 32], +} + /// Protocol state. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SessionState { @@ -115,6 +129,8 @@ pub struct PairingSession { desktop_code_requested: bool, desktop_code: Option>, code_attempts: u8, + /// Strict target-side code-entry negotiation and request correlation. + target_desktop_code: Option, } impl PairingSession { @@ -150,6 +166,7 @@ impl PairingSession { desktop_code_requested: false, desktop_code: None, code_attempts: 0, + target_desktop_code: None, }; (session, qr) @@ -357,6 +374,13 @@ impl PairingSession { /// /// Returns the session and the `offer` event to publish. pub fn new_target(qr: &QrPayload) -> Result<(Self, Event), PairingError> { + Self::new_target_with_confirmation(qr, false) + } + + fn new_target_with_confirmation( + qr: &QrPayload, + desktop_code: bool, + ) -> Result<(Self, Event), PairingError> { let keys = Keys::generate(); let session_id = derive_session_id(&qr.session_secret); @@ -383,13 +407,14 @@ impl PairingSession { desktop_code_requested: false, desktop_code: None, code_attempts: 0, + target_desktop_code: desktop_code.then(desktop_code::TargetDesktopCode::default), }; // Build and return the offer event. let msg = PairingMessage::Offer { session_id: hex::encode(session_id), version: 1, - confirmation: None, + confirmation: desktop_code.then(|| "desktop-code-v1".into()), }; let event = session.build_event(&msg)?; session.state = SessionState::Confirming; @@ -408,6 +433,14 @@ impl PairingSession { self.expect_state(SessionState::Confirming)?; self.expect_role(Role::Target)?; self.validate_event_from_peer(event)?; + if let Some(code) = &self.target_desktop_code { + if !code.challenged || code.pending_request_id.is_none() { + return Err(PairingError::UnexpectedMessage { + expected: "desktop code challenge and submission".into(), + got: "sas-confirm".into(), + }); + } + } let msg = self.decrypt_message(event)?; let received_hash = match &msg { @@ -443,6 +476,9 @@ impl PairingSession { } self.state = SessionState::AwaitingConfirmation; + if let Some(code) = &mut self.target_desktop_code { + code.pending_request_id = None; + } self.record_event(event); let code = self.sas_code.ok_or(PairingError::SasMismatch)?; Ok(format_sas(code)) @@ -487,13 +523,23 @@ impl PairingSession { /// (Target) Build the `complete` event to publish. pub fn send_complete(&mut self) -> Result { + self.send_complete_with_result(true) + } + + /// (Target) Acknowledge whether the received payload was durably imported. + /// Call only after the application has completed its secure-storage attempt. + pub fn send_complete_with_result(&mut self, success: bool) -> Result { self.check_expired()?; self.expect_state(SessionState::PayloadExchanged)?; self.expect_role(Role::Target)?; - let msg = PairingMessage::Complete { success: true }; + let msg = PairingMessage::Complete { success }; let event = self.build_event(&msg)?; - self.state = SessionState::Completed; + self.state = if success { + SessionState::Completed + } else { + SessionState::Aborted + }; Ok(event) } } @@ -608,6 +654,45 @@ impl PairingSession { relays: self.relay_urls.clone(), })) } + + /// Capture the live exchange's public channel binding, in source/target + /// order on both devices. Source must first accept an offer. Applications + /// submit this independently through each user's authenticated session; + /// no application credential needs to travel over the pairing protocol. + /// This method does not authorize exporting identity material. + pub fn binding(&self) -> Result { + self.check_expired()?; + if !matches!( + self.state, + SessionState::Confirming + | SessionState::AwaitingConfirmation + | SessionState::Transferring + ) { + return Err(PairingError::UnexpectedMessage { + expected: "live pairing with a locked peer".into(), + got: "unbound or terminal session".into(), + }); + } + let peer = self.peer_pubkey.ok_or(PairingError::SasMismatch)?; + let sas_input = self.sas_input.ok_or(PairingError::SasMismatch)?; + let own = self.keys.public_key(); + let (source_pubkey, target_pubkey) = match self.role { + Role::Source => (own, peer), + Role::Target => (peer, own), + }; + Ok(PairingBinding { + session_id: self.session_id, + source_pubkey, + target_pubkey, + transcript_hash: derive_transcript_hash( + &self.session_id, + &source_pubkey.to_bytes(), + &target_pubkey.to_bytes(), + &sas_input, + &self.session_secret, + ), + }) + } } #[cfg(test)] diff --git a/crates/buzz-core/src/pairing/session_code_entry_tests.rs b/crates/buzz-core/src/pairing/session_code_entry_tests.rs index 09d902cea5b..a1e7239f290 100644 --- a/crates/buzz-core/src/pairing/session_code_entry_tests.rs +++ b/crates/buzz-core/src/pairing/session_code_entry_tests.rs @@ -194,3 +194,29 @@ fn readiness_delay_and_late_scan_share_the_original_deadline() { Err(PairingError::SessionExpired) )); } + +#[test] +fn strict_target_expiry_and_cancellation_block_every_entry_point() { + for cancel in [false, true] { + let (mut source, qr) = PairingSession::new_source("wss://relay.test".into()); + let (mut target, offer) = PairingSession::new_target_with_desktop_code(&qr).unwrap(); + source.handle_offer_with_confirmation(&offer).unwrap(); + let (code, challenge) = source.start_desktop_code().unwrap(); + target.handle_desktop_code(&challenge).unwrap(); + let submission = target.submit_desktop_code(Zeroizing::new(code)).unwrap(); + let (proof, _) = source.handle_target_code(&submission).unwrap(); + if cancel { + target.abort(AbortReason::UserDenied).unwrap(); + } else { + target.created_at = Instant::now() - target.timeout - Duration::from_secs(1); + } + assert!(target.handle_desktop_code(&challenge).is_err()); + assert!(target + .submit_desktop_code(Zeroizing::new("123456".into())) + .is_err()); + assert!(target.handle_code_rejected(&proof).is_err()); + assert!(target.handle_sas_confirm(&proof).is_err()); + assert!(target.confirm_target_sas().is_err()); + assert!(target.send_complete_with_result(true).is_err()); + } +} diff --git a/crates/buzz-core/src/pairing/session_desktop_code.rs b/crates/buzz-core/src/pairing/session_desktop_code.rs index 0ffd1c60d88..cc06bb711de 100644 --- a/crates/buzz-core/src/pairing/session_desktop_code.rs +++ b/crates/buzz-core/src/pairing/session_desktop_code.rs @@ -55,3 +55,117 @@ impl PairingSession { Ok((rejection, false)) } } + +/// Target-only state. The source never learns the pending code locally. +#[derive(Default)] +pub(super) struct TargetDesktopCode { + pub(super) challenged: bool, + pub(super) pending_request_id: Option, + remaining_attempts: Option, +} + +impl PairingSession { + /// Create a target that requires `desktop-code-v1`, with no SAS fallback. + /// + /// The caller must handle the source challenge, submit the user-entered code, + /// verify the source proof, and call `confirm_target_sas` before importing. + pub fn new_target_with_desktop_code(qr: &QrPayload) -> Result<(Self, Event), PairingError> { + Self::new_target_with_confirmation(qr, true) + } + + /// Validate the locked source's code-entry challenge. It contains no code. + /// Duplicate or replacement challenges never reset an outstanding attempt. + pub fn handle_desktop_code(&mut self, event: &Event) -> Result<(), PairingError> { + self.check_expired()?; + self.expect_role(Role::Target)?; + self.expect_state(SessionState::Confirming)?; + self.validate_event_from_peer(event)?; + let code = self + .target_desktop_code + .as_ref() + .ok_or(PairingError::SasMismatch)?; + if code.challenged { + return Err(PairingError::SasMismatch); + } + match self.decrypt_message(event)? { + PairingMessage::DesktopCode {} => {} + other => return Err(unexpected("desktop-code", &other)), + } + if let Some(code) = &mut self.target_desktop_code { + code.challenged = true; + } + self.record_event(event); + Ok(()) + } + + /// Encrypt one six-ASCII-digit user submission with a fresh request ID. + /// + /// Only one request may be outstanding. A correlated rejection allows the + /// next submission; callers must not retry a pending guess with a new ID. + pub fn submit_desktop_code(&mut self, code: Zeroizing) -> Result { + self.check_expired()?; + self.expect_role(Role::Target)?; + self.expect_state(SessionState::Confirming)?; + let target = self + .target_desktop_code + .as_ref() + .ok_or(PairingError::SasMismatch)?; + if !target.challenged + || target.pending_request_id.is_some() + || code.len() != 6 + || !code.bytes().all(|b| b.is_ascii_digit()) + { + return Err(PairingError::SasMismatch); + } + let request_id = hex::encode(rand::random::<[u8; 16]>()); + let mut message = PairingMessage::CodeSubmit { + code: (*code).clone(), + request_id: request_id.clone(), + }; + let result = self.build_event(&message); + if let PairingMessage::CodeSubmit { code, .. } = &mut message { + code.zeroize(); + } + let event = result?; + if let Some(target) = &mut self.target_desktop_code { + target.pending_request_id = Some(request_id); + } + Ok(event) + } + + /// Validate a rejection for the pending request and return guesses remaining. + /// + /// Unrelated, stale, duplicate and non-decreasing budgets leave the pending + /// request unchanged. Zero remaining guesses permanently aborts the session. + pub fn handle_code_rejected(&mut self, event: &Event) -> Result { + self.check_expired()?; + self.expect_role(Role::Target)?; + self.expect_state(SessionState::Confirming)?; + self.validate_event_from_peer(event)?; + let (request_id, remaining_attempts) = match self.decrypt_message(event)? { + PairingMessage::CodeRejected { + request_id, + remaining_attempts, + } => (request_id, remaining_attempts), + other => return Err(unexpected("code-rejected", &other)), + }; + let target = self + .target_desktop_code + .as_ref() + .ok_or(PairingError::SasMismatch)?; + if target.pending_request_id.as_deref() != Some(request_id.as_str()) + || remaining_attempts >= target.remaining_attempts.unwrap_or(5) + { + return Err(PairingError::SasMismatch); + } + if let Some(target) = &mut self.target_desktop_code { + target.pending_request_id = None; + target.remaining_attempts = Some(remaining_attempts); + } + self.record_event(event); + if remaining_attempts == 0 { + self.state = SessionState::Aborted; + } + Ok(remaining_attempts) + } +} diff --git a/crates/buzz-core/src/tenant.rs b/crates/buzz-core/src/tenant.rs index 46c7e71c56f..d7a0d50df0f 100644 --- a/crates/buzz-core/src/tenant.rs +++ b/crates/buzz-core/src/tenant.rs @@ -97,6 +97,14 @@ impl TenantContext { } } +/// Longest host a community can have, in characters: `communities.host` is +/// `VARCHAR(255)`. A longer host maps to no community. +/// +/// Provisioning checks count bytes instead, which is stricter for non-ASCII +/// input and identical for the ASCII authorities they accept. Keep both: the +/// lookup side must not refuse any host the column can store. +pub const MAX_HOST_LEN: usize = 255; + /// Normalize a connection `Host` into the canonical form used as the community /// lookup key. /// diff --git a/crates/buzz-core/tests/pairing_code_entry.rs b/crates/buzz-core/tests/pairing_code_entry.rs new file mode 100644 index 00000000000..aafa4af71b0 --- /dev/null +++ b/crates/buzz-core/tests/pairing_code_entry.rs @@ -0,0 +1,244 @@ +//! Public-API interoperability journeys for strict NIP-AB code entry. +use buzz_core::pairing::{PairingError, PairingSession, PayloadType, SessionState}; +use nostr::{nips::nip44, Event, EventBuilder, Keys, Kind, Tag, Timestamp}; +use zeroize::Zeroizing; + +fn setup() -> (PairingSession, PairingSession) { + let (mut source, qr) = PairingSession::new_source("wss://relay.test".into()); + let (target, offer) = PairingSession::new_target_with_desktop_code(&qr).unwrap(); + assert!(source.handle_offer_with_confirmation(&offer).unwrap().1); + (source, target) +} + +fn input(code: &str) -> Zeroizing { + Zeroizing::new(code.into()) +} + +#[test] +fn both_devices_bind_authorization_to_the_same_live_exchange() { + let (mut source, qr) = PairingSession::new_source("wss://relay.test".into()); + assert!(source.binding().is_err()); + let (mut target, offer) = PairingSession::new_target_with_desktop_code(&qr).unwrap(); + source.handle_offer_with_confirmation(&offer).unwrap(); + let expected = source.binding().unwrap(); + assert_eq!(expected, target.binding().unwrap()); + assert_eq!(expected.source_pubkey, source.pubkey()); + assert_eq!(expected.target_pubkey, target.pubkey()); + let (other, _) = PairingSession::new_target_with_desktop_code(&qr).unwrap(); + assert_ne!( + expected.transcript_hash, + other.binding().unwrap().transcript_hash + ); + let (code, challenge) = source.start_desktop_code().unwrap(); + target.handle_desktop_code(&challenge).unwrap(); + let submission = target.submit_desktop_code(input(&code)).unwrap(); + let (proof, _) = source.handle_target_code(&submission).unwrap(); + target.handle_sas_confirm(&proof).unwrap(); + assert_eq!(expected, source.binding().unwrap()); + assert_eq!(expected, target.binding().unwrap()); + target.confirm_target_sas().unwrap(); + let payload = source + .send_payload(PayloadType::Custom, input("test")) + .unwrap(); + assert!(source.binding().is_err()); + target.handle_payload(&payload).unwrap(); + assert!(target.binding().is_err()); + source + .handle_complete(&target.send_complete().unwrap()) + .unwrap(); + assert!(source.binding().is_err()); + assert!(target.binding().is_err()); +} + +#[test] +fn cancelled_exchange_cannot_produce_an_authorization_binding() { + let (mut source, mut target) = setup(); + let abort = source + .abort(buzz_core::pairing::AbortReason::UserDenied) + .unwrap() + .unwrap(); + target.handle_abort(&abort).unwrap(); + assert!(source.binding().is_err()); + assert!(target.binding().is_err()); +} + +fn wrong(code: &str) -> &'static str { + if code == "000000" { + "000001" + } else { + "000000" + } +} + +fn resign(source: &PairingSession, event: &Event) -> Event { + source + .sign_event( + EventBuilder::new(event.kind, &event.content) + .tags(event.tags.iter().cloned()) + .custom_created_at(Timestamp::from(event.created_at.as_secs() + 1)), + ) + .unwrap() +} + +#[test] +fn code_entry_retries_then_import_requires_explicit_intent_and_durable_ack() { + let (mut source, mut target) = setup(); + let (code, challenge) = source.start_desktop_code().unwrap(); + assert!(target.submit_desktop_code(input(&code)).is_err()); + target.handle_desktop_code(&challenge).unwrap(); + assert!(target.handle_desktop_code(&challenge).is_err()); + for invalid in ["", "12345", "1234567", "abcdef", "123456"] { + assert!(target.submit_desktop_code(input(invalid)).is_err()); + } + let submission = target.submit_desktop_code(input(wrong(&code))).unwrap(); + assert!(target.submit_desktop_code(input(&code)).is_err()); + let (rejection, accepted) = source.handle_target_code(&submission).unwrap(); + assert!(!accepted); + assert_eq!(target.handle_code_rejected(&rejection).unwrap(), 4); + let correct = target.submit_desktop_code(input(&code)).unwrap(); + // Even re-signed stale content must not resolve the new pending request. + assert!(target + .handle_code_rejected(&resign(&source, &rejection)) + .is_err()); + assert!(target.submit_desktop_code(input(&code)).is_err()); + let (proof, accepted) = source.handle_target_code(&correct).unwrap(); + assert!(accepted); + target.handle_sas_confirm(&proof).unwrap(); + let payload = source + .send_payload(PayloadType::Nsec, input("identity-secret")) + .unwrap(); + assert!( + target.handle_payload(&payload).is_err(), + "local import approval is mandatory" + ); + assert!( + target.send_complete().is_err(), + "cannot acknowledge an unreceived secret" + ); + target.confirm_target_sas().unwrap(); + let (kind, received) = target.handle_payload(&payload).unwrap(); + assert_eq!(kind, PayloadType::Nsec); + assert_eq!(&*received, "identity-secret"); + assert!( + target.handle_payload(&payload).is_err(), + "import is single use" + ); + let complete = target.send_complete_with_result(true).unwrap(); + source.handle_complete(&complete).unwrap(); + assert_eq!(source.state(), SessionState::Completed); + assert_eq!(target.state(), SessionState::Completed); +} + +#[test] +fn strict_target_rejects_legacy_proof_before_challenge_or_code_submission() { + for challenge_first in [false, true] { + let (mut source, mut target) = setup(); + if challenge_first { + let (_, challenge) = source.start_desktop_code().unwrap(); + target.handle_desktop_code(&challenge).unwrap(); + } + let legacy_proof = source.confirm_sas().unwrap(); + assert!(target.handle_sas_confirm(&legacy_proof).is_err()); + assert_eq!(target.state(), SessionState::Confirming); + assert!(target.confirm_target_sas().is_err()); + } + // The legacy constructor still negotiates the existing explicit SAS flow. + let (mut source, qr) = PairingSession::new_source("wss://relay.test".into()); + let (mut target, offer) = PairingSession::new_target(&qr).unwrap(); + assert!(!source.handle_offer_with_confirmation(&offer).unwrap().1); + assert!(target.submit_desktop_code(input("123456")).is_err()); + target + .handle_sas_confirm(&source.confirm_sas().unwrap()) + .unwrap(); + target.confirm_target_sas().unwrap(); +} + +#[test] +fn five_rejections_end_both_peers_and_replays_cannot_reset_the_budget() { + let (mut source, mut target) = setup(); + let (code, challenge) = source.start_desktop_code().unwrap(); + target.handle_desktop_code(&challenge).unwrap(); + for remaining in (0..5).rev() { + let submission = target.submit_desktop_code(input(wrong(&code))).unwrap(); + let (rejection, accepted) = source.handle_target_code(&submission).unwrap(); + assert!(!accepted); + assert!(source.handle_target_code(&submission).is_err()); + assert_eq!(target.handle_code_rejected(&rejection).unwrap(), remaining); + assert!(target.handle_code_rejected(&rejection).is_err()); + assert!(target + .handle_desktop_code(&resign(&source, &challenge)) + .is_err()); + assert!(source.start_desktop_code().is_err()); + } + assert_eq!(source.state(), SessionState::Aborted); + assert_eq!(target.state(), SessionState::Aborted); + assert!(target.submit_desktop_code(input(&code)).is_err()); + assert!(target.confirm_target_sas().is_err()); +} + +#[test] +fn authenticated_peer_and_recipient_checks_preserve_a_valid_challenge() { + let (mut source, mut target) = setup(); + let (code, challenge) = source.start_desktop_code().unwrap(); + let attacker = Keys::generate(); + let ciphertext = nip44::encrypt( + attacker.secret_key(), + &target.pubkey(), + "{\"type\":\"desktop-code\"}", + nip44::Version::V2, + ) + .unwrap(); + let wrong_peer = EventBuilder::new(Kind::Custom(24134), ciphertext) + .tags([Tag::public_key(target.pubkey())]) + .sign_with_keys(&attacker) + .unwrap(); + let wrong_recipient = source + .sign_event( + EventBuilder::new(challenge.kind, &challenge.content) + .tags([Tag::public_key(attacker.public_key())]), + ) + .unwrap(); + let wrong_kind = source + .sign_event( + EventBuilder::new(Kind::TextNote, &challenge.content) + .tags([Tag::public_key(target.pubkey())]), + ) + .unwrap(); + let mut tampered = challenge.clone(); + tampered.content.push('x'); + for candidate in [wrong_peer.clone(), wrong_recipient, wrong_kind, tampered] { + assert!(target.handle_desktop_code(&candidate).is_err()); + } + target.handle_desktop_code(&challenge).unwrap(); + let submission = target.submit_desktop_code(input(&code)).unwrap(); + assert!(target.handle_code_rejected(&wrong_peer).is_err()); + let (proof, accepted) = source.handle_target_code(&submission).unwrap(); + assert!(accepted); + target.handle_sas_confirm(&proof).unwrap(); +} + +#[test] +fn failed_secure_import_is_reported_without_success_or_retry() { + let (mut source, mut target) = setup(); + let (code, challenge) = source.start_desktop_code().unwrap(); + target.handle_desktop_code(&challenge).unwrap(); + let submission = target.submit_desktop_code(input(&code)).unwrap(); + let (proof, _) = source.handle_target_code(&submission).unwrap(); + target.handle_sas_confirm(&proof).unwrap(); + target.confirm_target_sas().unwrap(); + let payload = source + .send_payload(PayloadType::Nsec, input("identity-secret")) + .unwrap(); + target.handle_payload(&payload).unwrap(); + let failed = target.send_complete_with_result(false).unwrap(); + assert!(matches!( + source.handle_complete(&failed), + Err(PairingError::UnexpectedMessage { .. }) + )); + assert_eq!(source.state(), SessionState::Aborted); + assert_eq!(target.state(), SessionState::Aborted); + assert!(target.send_complete().is_err()); + assert!(source + .send_payload(PayloadType::Nsec, input("identity-secret")) + .is_err()); +} diff --git a/crates/buzz-db/TESTING.md b/crates/buzz-db/TESTING.md index bebe09dd98e..518c0ecb80f 100644 --- a/crates/buzz-db/TESTING.md +++ b/crates/buzz-db/TESTING.md @@ -21,6 +21,12 @@ The wrapper isolates destructive tests by dropping the entire per-test database after the process exits. It does not `DELETE` rows or `TRUNCATE` shared tables, so tests may run concurrently without coordinating cleanup. +The wrapper drops only that per-test database. A test that needs another +database or role on the server creates it with `test_support::ScratchDb` or +`test_support::ScratchRole`, whose `Drop` removes it even when the test +panics. Do not end a test with a manual `DROP DATABASE` or `DROP ROLE`: a +failed assertion skips it and leaves the object behind. + ## Choose the schema intentionally Most tests use the committed desired-state schema from `schema/schema.sql`, @@ -63,3 +69,10 @@ membership in `pg_read_all_stats`, or an ephemeral superuser as CI uses. The runner creates one desired-state source database per invocation and clones it for ordinary tests. Migration-mode tests start empty. Cleanup retries transient disconnect races before reporting a warning. + +Invite upgrade tests start from the complete schema through migration 0074, +including channel join roles, entity deletion approval, the unlisted channel setting and the user deletion target and fences. They exercise the +invitation schema expansion (migration 0075) through both migration and +desired-state paths against populated +data, retaining a non-default channel join role. Historical repair is validated +separately from the application/schema change. diff --git a/crates/buzz-db/src/concurrency_gate.rs b/crates/buzz-db/src/concurrency_gate.rs new file mode 100644 index 00000000000..ed7ccf90376 --- /dev/null +++ b/crates/buzz-db/src/concurrency_gate.rs @@ -0,0 +1,320 @@ +//! A FIFO concurrency cap whose limit an operator can change at runtime. +//! +//! The gate is created with a ceiling, its startup limit. [`ConcurrencyGate::set_limit`] +//! moves the limit anywhere in `1..=ceiling` without a restart: +//! +//! - Raising it releases permits to waiting callers at once. +//! - Lowering it takes back permits nobody holds at once. Permits still held +//! above the new limit are retired as their holders release them, so no +//! in-flight work is cancelled and no new work is admitted until the count +//! held falls under the new limit. +//! +//! Every limit change, every permit release and every admission settles +//! against the shrink debt under one lock, so a newer limit always supersedes +//! an older one: there is no background resize to race, and a permit tokio +//! returns from a cancelled waiter is retired rather than admitted. + +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; + +/// A concurrency cap with a runtime-adjustable limit. Clones share one cap. +#[derive(Clone, Debug)] +pub struct ConcurrencyGate { + inner: Arc, +} + +#[derive(Debug)] +struct Inner { + permits: Arc, + ceiling: usize, + state: Mutex, +} + +#[derive(Debug)] +struct LimitState { + /// The limit last set: the permits that exist, held or free, once `debt` + /// is repaid. + limit: usize, + /// Permits held above the current limit. Each release retires one of them + /// instead of returning it to the semaphore. + debt: usize, +} + +impl Inner { + fn state(&self) -> MutexGuard<'_, LimitState> { + // The guarded section never panics, but a poisoned lock must not + // wedge admission for the rest of the process. + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +impl ConcurrencyGate { + /// A gate whose ceiling and startup limit are `ceiling`, raised to at + /// least one and clamped to [`Semaphore::MAX_PERMITS`]. + pub fn new(ceiling: usize) -> Self { + let ceiling = ceiling.clamp(1, Semaphore::MAX_PERMITS); + Self { + inner: Arc::new(Inner { + permits: Arc::new(Semaphore::new(ceiling)), + ceiling, + state: Mutex::new(LimitState { + limit: ceiling, + debt: 0, + }), + }), + } + } + + /// A gate with no practical limit until one is set. + pub fn unbounded() -> Self { + Self::new(Semaphore::MAX_PERMITS) + } + + /// The highest limit this gate accepts: its startup limit. + pub fn ceiling(&self) -> usize { + self.inner.ceiling + } + + /// The current limit. + pub fn limit(&self) -> usize { + self.inner.state().limit + } + + /// Set the limit to `requested`, clamped to `1..=ceiling`, and return the + /// limit applied. + pub fn set_limit(&self, requested: usize) -> usize { + let target = requested.clamp(1, self.inner.ceiling); + let mut state = self.inner.state(); + if target < state.limit { + let excess = state.limit - target; + let retired = self.inner.permits.forget_permits(excess); + state.debt += excess - retired; + } else if target > state.limit { + let added = target - state.limit; + let repaid = added.min(state.debt); + state.debt -= repaid; + self.inner.permits.add_permits(added - repaid); + } + state.limit = target; + target + } + + /// Wait up to `wait` for a permit, in arrival order. `None` means the + /// caller must be shed. + pub async fn admit(&self, wait: Duration) -> Option { + let deadline = tokio::time::Instant::now() + wait; + loop { + let permit = + tokio::time::timeout_at(deadline, Arc::clone(&self.inner.permits).acquire_owned()) + .await + .ok()? + .ok()?; + let mut state = self.inner.state(); + if state.debt == 0 { + drop(state); + return Some(GatePermit { + permit: Some(permit), + inner: Arc::clone(&self.inner), + }); + } + // While there is debt every permit should be held, so this one + // leaked back without a `GatePermit` release: tokio returns a + // permit it had assigned to a waiter that was then cancelled. + // Retire it and keep waiting. + state.debt -= 1; + permit.forget(); + } + } + + /// Permits free to admit right now (tests). + #[cfg(test)] + pub(crate) fn available(&self) -> usize { + self.inner.permits.available_permits() + } +} + +/// One admission through a [`ConcurrencyGate`], released on drop. +#[derive(Debug)] +pub struct GatePermit { + permit: Option, + inner: Arc, +} + +impl Drop for GatePermit { + fn drop(&mut self) { + let Some(permit) = self.permit.take() else { + return; + }; + let mut state = self.inner.state(); + if state.debt > 0 { + state.debt -= 1; + permit.forget(); + } else { + // Release under the lock so a concurrent `set_limit` sees either + // the debt or the returned permit, never neither. + drop(permit); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const WAIT: Duration = Duration::from_secs(1); + + #[test] + fn set_limit_clamps_to_one_through_the_ceiling() { + let gate = ConcurrencyGate::new(4); + assert_eq!(gate.set_limit(0), 1); + assert_eq!(gate.set_limit(9), 4); + assert_eq!(gate.limit(), 4); + assert_eq!(ConcurrencyGate::new(0).ceiling(), 1); + } + + #[tokio::test(start_paused = true)] + async fn a_full_gate_sheds_after_the_wait_and_reopens_on_release() { + let gate = ConcurrencyGate::new(1); + let held = gate.admit(WAIT).await.expect("first caller is admitted"); + let started = tokio::time::Instant::now(); + assert!(gate.admit(WAIT).await.is_none(), "a full gate sheds"); + assert_eq!(started.elapsed(), WAIT); + drop(held); + assert!(gate.admit(WAIT).await.is_some(), "a release admits again"); + } + + /// Each row lowers or raises the limit while `held` permits are out, then + /// releases them all. `admits` is how many more callers get in right after + /// the change; `settled` is the free count once every holder has left. + #[tokio::test(start_paused = true)] + async fn limit_changes_respect_permits_already_held() { + struct Case { + name: &'static str, + held: usize, + limits: &'static [usize], + admits: usize, + settled: usize, + } + let cases = [ + Case { + name: "lower while idle", + held: 0, + limits: &[2], + admits: 2, + settled: 2, + }, + Case { + name: "lower below the count held", + held: 4, + limits: &[2], + admits: 0, + settled: 2, + }, + Case { + name: "lower, then raise before holders leave", + held: 4, + limits: &[1, 3], + admits: 0, + settled: 3, + }, + Case { + name: "lower, then raise past the count held", + held: 3, + limits: &[1, 5], + admits: 2, + settled: 5, + }, + Case { + name: "raise back to the ceiling", + held: 2, + limits: &[2, 6], + admits: 4, + settled: 6, + }, + ]; + for case in cases { + let gate = ConcurrencyGate::new(6); + let mut held = Vec::new(); + for _ in 0..case.held { + held.push(gate.admit(WAIT).await.expect("under the ceiling")); + } + for &limit in case.limits { + gate.set_limit(limit); + } + let mut admitted = Vec::new(); + while let Some(permit) = gate.admit(WAIT).await { + admitted.push(permit); + } + assert_eq!(admitted.len(), case.admits, "{}: admitted", case.name); + drop(admitted); + drop(held); + assert_eq!(gate.available(), case.settled, "{}: settled", case.name); + assert_eq!( + gate.limit(), + case.settled, + "{}: limit matches the permits that exist", + case.name + ); + } + } + + #[tokio::test(start_paused = true)] + async fn raising_the_limit_wakes_a_waiting_caller() { + let gate = ConcurrencyGate::new(2); + gate.set_limit(1); + let _held = gate.admit(WAIT).await.expect("one permit"); + let waiter = tokio::spawn({ + let gate = gate.clone(); + async move { gate.admit(WAIT).await.is_some() } + }); + tokio::task::yield_now().await; + gate.set_limit(2); + assert!(waiter.await.expect("join"), "the raise admits the waiter"); + } + + /// Tokio hands a released permit to the first waiter before that waiter + /// runs. If the waiter is cancelled after a shrink, tokio returns the + /// permit to the semaphore directly, never through `GatePermit::drop`; + /// the next admission must retire it against the debt instead. + #[tokio::test(start_paused = true)] + async fn a_cancelled_waiter_cannot_reopen_a_lowered_gate() { + let gate = ConcurrencyGate::new(2); + let first = gate.admit(WAIT).await.expect("first holder"); + let second = gate.admit(WAIT).await.expect("second holder"); + let waiter = tokio::spawn({ + let gate = gate.clone(); + async move { gate.admit(WAIT).await.is_some() } + }); + tokio::task::yield_now().await; // the waiter queues + drop(first); // tokio assigns this permit to the queued waiter + gate.set_limit(1); // nothing free to forget: one permit of debt + waiter.abort(); // cancelled before it runs again + assert!(waiter.await.expect_err("aborted").is_cancelled()); + + assert!( + gate.admit(WAIT).await.is_none(), + "one holder already fills limit 1" + ); + drop(second); + let admitted = gate.admit(WAIT).await.expect("the holder left"); + assert!(gate.admit(WAIT).await.is_none(), "limit 1 holds"); + drop(admitted); + assert_eq!( + gate.available(), + 1, + "the permits that exist match the limit" + ); + } + + #[test] + fn an_unbounded_gate_can_be_capped() { + let gate = ConcurrencyGate::unbounded(); + assert_eq!(gate.ceiling(), Semaphore::MAX_PERMITS); + assert_eq!(gate.set_limit(3), 3); + assert_eq!(gate.available(), 3); + } +} diff --git a/crates/buzz-db/src/error.rs b/crates/buzz-db/src/error.rs index d0a2ffcb224..a85470e8491 100644 --- a/crates/buzz-db/src/error.rs +++ b/crates/buzz-db/src/error.rs @@ -5,6 +5,10 @@ use thiserror::Error; /// Errors produced by database operations. #[derive(Debug, Error)] pub enum DbError { + /// Media authorization could not reserve capacity within its bounded wait. + #[error("media authorization capacity exceeded")] + MediaAuthorizationCapacity, + /// A SQLx driver-level error. #[error("database error: {0}")] Sqlx(#[from] sqlx::Error), @@ -25,6 +29,11 @@ pub enum DbError { #[error("channel not found: {0}")] ChannelNotFound(uuid::Uuid), + /// Another listed open channel in the community already has this name + /// (the `idx_channels_listed_name` index, migration 0083). + #[error("an open channel named \"{0}\" already exists")] + ChannelNameTaken(String), + /// The requested member is not in the channel. #[error("member not found in channel {0}")] MemberNotFound(uuid::Uuid), @@ -37,6 +46,22 @@ pub enum DbError { #[error("access denied: {0}")] AccessDenied(String), + /// Required initial policy cannot be created without issuer bindings. + #[error("required community creation needs NIP-FI issuer bindings")] + NipFiBindingRequired, + + /// Invitation admission or minting was denied by authoritative restrictions. + #[error("invitation principal is restricted")] + InviteRestricted, + + /// The invitation issuer is not an owner or admin at mint time. + #[error("invitation issuer is not an owner or admin")] + InviteIssuerNotAdmin, + + /// A verified invitation owner conflicts with the recorded owner. + #[error("invitation owner does not match the recorded owner")] + InviteOwnerMismatch, + /// JSON serialization or deserialization failed. #[error("serialization error: {0}")] Serde(#[from] serde_json::Error), @@ -69,10 +94,18 @@ pub enum DbError { #[error("deletion safety error: {0}")] DeletionSafety(String), + /// An artifact sync page exceeds its resource limit. + #[error("artifact sync limit exceeded")] + ArtifactSyncLimit, + /// A complete read-state snapshot exceeds its bounded resource budget. #[error("read-state snapshot exceeds event or byte limit")] ReadStateSnapshotTooLarge, + /// A complete membership snapshot exceeds its bounded resource budget. + #[error("membership snapshot exceeds channel or byte limit")] + MembershipSnapshotTooLarge, + /// A complete thread window exceeds its request-wide work allowance. #[error("thread window exceeds {0} budget")] ThreadWindowBudgetExceeded(&'static str), @@ -81,6 +114,13 @@ pub enum DbError { #[error("invalid timestamp: {0}")] InvalidTimestamp(i64), + /// A channel event is too old for replica-fence completeness. Retrying the + /// same signed event cannot make its timestamp newer. Like the mixed-version + /// trigger's SQLx error, this remains a database error at the relay boundary + /// (WS OK false / HTTP 500), rather than a different ingest rejection class. + #[error("database error: events.created_at is below the replica-fence floor")] + CreatedAtFloorRejected, + /// A roster mutation would remove the last effective relay Operator, /// leaving no one able to administer the deployment through the API. /// The transaction is rolled back and the caller must add a replacement @@ -123,6 +163,45 @@ impl DbError { /// Convenience alias for `Result`. pub type Result = std::result::Result; +/// A fixed description of a driver error for log lines. Postgres primary +/// messages can repeat a bound value (`invalid input syntax for type uuid: +/// ""`), so only the SQLSTATE code is kept. +pub fn sqlx_error_kind(e: &sqlx::Error) -> String { + let kind = match e { + sqlx::Error::Database(db) => { + return format!("database:{}", db.code().as_deref().unwrap_or("unknown")) + } + sqlx::Error::RowNotFound => "row_not_found", + sqlx::Error::PoolTimedOut => "pool_timed_out", + sqlx::Error::PoolClosed => "pool_closed", + sqlx::Error::Io(_) => "io", + sqlx::Error::Tls(_) => "tls", + sqlx::Error::Protocol(_) => "protocol", + sqlx::Error::ColumnDecode { .. } | sqlx::Error::Decode(_) => "decode", + sqlx::Error::Encode(_) => "encode", + _ => "other", + }; + kind.to_owned() +} + +impl DbError { + /// A fixed description of this error for log lines: never the + /// message, which can repeat bound values. + pub fn kind(&self) -> String { + use DbError as E; + let kind = match self { + E::Sqlx(e) => return sqlx_error_kind(e), + E::Serde(_) => "serde", + E::InvalidData(_) => "invalid_data", + E::NotFound(_) | E::ChannelNotFound(_) | E::MemberNotFound(_) => "not_found", + E::AccessDenied(_) => "access_denied", + E::NipFiBindingRequired => "nip_fi_binding_required", + _ => "other", + }; + kind.to_owned() + } +} + #[cfg(test)] mod tests { use super::DbError; diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index c85b7dc6b99..49809b98aeb 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -21,9 +21,34 @@ //! Existing crate-root modules, records, and [`Db`] methods remain the public //! API. The internal `runtime` and `store` namespaces are not public APIs. +/// Wrap `$retire`, an `UPDATE`/`DELETE` on `events` that retires a +/// coordinate's previous head, so the same statement drops those rows' mention +/// index entries. Mention-index reads (`#p` filters and feeds) never return a +/// retired row, so its mention rows are dead weight they must walk and +/// discard: one per member for every kind:39002 roster republish. `$1` must +/// bind the community. +/// +/// The three replacement paths that index mentions (NIP-33 parameterized, +/// addressable, and the relay's member snapshot) go through this, so a head +/// and its mention rows leave together on those paths. +macro_rules! superseded_with_mentions_sql { + ($retire:expr) => { + concat!( + "WITH superseded AS (", + $retire, + " RETURNING id) \ + DELETE FROM event_mentions mention USING superseded \ + WHERE mention.community_id = $1 AND mention.event_id = superseded.id" + ) + }; +} + mod runtime; mod store; +/// Concurrency caps whose limit can change at runtime. +pub mod concurrency_gate; + /// Database error types. pub mod error; @@ -37,7 +62,7 @@ pub use runtime::{ }; /// Valid low-cardinality `(pool_role, operation)` pairs for pool-acquisition telemetry. -pub const DB_POOL_ACQUIRE_VALID_PAIRS: [(&str, &str); 12] = +pub const DB_POOL_ACQUIRE_VALID_PAIRS: [(&str, &str); 11] = runtime::observability::POOL_ACQUIRE_VALID_PAIRS; /// Raw Prometheus series ceiling per relay pod for the operation-aware contract. @@ -65,11 +90,12 @@ pub(crate) use runtime::{ sweep_admitted_communities, ReadSessionInner, RouteDecision, RoutePredicate, }; pub use store::{ - admin_moderation, allowlist, api_token, archived_identities, artifact, channel, - channel_members, community, deletion, dm, entity_deletion, event, feed, git_repo, moderation, - nip_fi_binding, operator_listener, partition, personal_read, product_feedback, push, reaction, - read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, - replaceable, storage_accounting, thread, thread_window, usage, user, user_deletion, workflow, + admin_moderation, allowlist, api_token, archived_identities, artifact, artifact_sync, channel, + channel_members, community, community_auth, deletion, dm, entity_deletion, event, feed, + git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding, + operator_listener, partition, personal_read, product_feedback, push, reaction, read_state, + relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, replaceable, + storage_accounting, thread, thread_window, user, user_deletion, user_deletion_fences, workflow, }; pub use allowlist::AllowlistEntry; @@ -79,12 +105,32 @@ pub use community::{ CreatedCommunityRecord, EnsuredCommunityRecord, OwnedCommunityRecord, UnarchiveCommunityResult, UnarchivedCommunityRecord, }; +pub use concurrency_gate::{ConcurrencyGate, GatePermit}; pub use error::{DbError, Result}; -pub use event::{ChannelHeadPrecondition, ChannelHeadWriteStatus}; +pub use event::{ChannelHeadPrecondition, ChannelHeadWriteStatus, DeletionTarget}; pub use event::{EventQuery, DEFAULT_MAX_PAGE_LIMIT}; +pub use leader_lock::SessionLeader; pub use nip_fi_binding::{NipFiBindingRecord, NipFiUnbind, RowCapExceeded}; pub use reaction::ReactionEventInsertOutcome; pub use reminder::DueReminder; -pub use usage::SessionLeader; +pub use store::{ArtifactSnapshot, SnapshotDenied}; + +/// A value read from the database, with when its reading connection was +/// checked out of the pool. +/// +/// The statement that produced `value` started after `read_at`, so its +/// snapshot is no older than `read_at`. A cache that serves `value` for a +/// bound after `read_at` is never staler than that bound, however long the +/// read waited for a connection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ReadAt { + /// The value as read. + pub value: T, + /// When the connection that read `value` was checked out. + pub read_at: std::time::Instant, +} use buzz_core::CommunityId; + +/// Durable NIP-FI verified-profile projection state. +pub use store::verified_profiles; diff --git a/crates/buzz-db/src/runtime/admitted_tx.rs b/crates/buzz-db/src/runtime/admitted_tx.rs index 2e4ce60a758..d70512c233c 100644 --- a/crates/buzz-db/src/runtime/admitted_tx.rs +++ b/crates/buzz-db/src/runtime/admitted_tx.rs @@ -3,6 +3,7 @@ use std::collections::BTreeSet; use buzz_core::CommunityId; +use chrono::{DateTime, Utc}; use sqlx::{PgConnection, Postgres, Transaction}; use uuid::Uuid; @@ -75,7 +76,12 @@ pub struct AdmittedTx { /// Channels whose TTL deadline [`AdmittedTx::commit`] refreshes. ttl_refresh_channels: BTreeSet, push_enqueue: Option, - push_events: Vec>, + push_events: Vec, +} + +struct StagedPushEvent { + event_id: Vec, + created_at: DateTime, } impl AdmittedTx { @@ -118,13 +124,21 @@ impl AdmittedTx { self.push_enqueue = producer; } - pub(crate) fn record_push_event(&mut self, event_id: &[u8], kind: i32) { + pub(crate) fn record_push_event( + &mut self, + event_id: &[u8], + created_at: DateTime, + kind: i32, + ) { if self.push_enqueue.is_some() && crate::store::event_follow_up::PUSH_MATCH_KINDS.contains(&kind) { // Bound transaction-local staging as well as the shared worker queue. if self.push_events.len() < super::push_enqueue::CAPACITY { - self.push_events.push(event_id.to_vec()); + self.push_events.push(StagedPushEvent { + event_id: event_id.to_vec(), + created_at, + }); } else { super::push_enqueue::record_drop("transaction_full"); } @@ -170,8 +184,8 @@ impl AdmittedTx { } self.tx.commit().await?; if let Some(producer) = self.push_enqueue { - for event_id in self.push_events { - producer.submit(self.community, event_id); + for event in self.push_events { + producer.submit(self.community, event.event_id, event.created_at); } } Ok(()) @@ -191,3 +205,7 @@ impl std::fmt::Debug for AdmittedTx { .finish_non_exhaustive() } } + +#[cfg(test)] +#[path = "admitted_tx/postgres_tests.rs"] +mod postgres_tests; diff --git a/crates/buzz-db/src/runtime/admitted_tx/postgres_tests.rs b/crates/buzz-db/src/runtime/admitted_tx/postgres_tests.rs new file mode 100644 index 00000000000..873fdce0ff0 --- /dev/null +++ b/crates/buzz-db/src/runtime/admitted_tx/postgres_tests.rs @@ -0,0 +1,123 @@ +//! Inspect staging at the real savepoint writer boundary, before a missing +//! database row could hide incorrectly staged work from the enqueue worker. + +use super::*; +use crate::replaceable::{ParameterizedReplacePrecondition, ParameterizedReplaceStatus}; +use crate::{Db, DbConfig}; +use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn savepoint_failure_and_duplicate_preserve_only_surviving_timestamp_pairs() { + let db = Db::new(&DbConfig { + database_url: crate::test_support::database_url(), + push_enabled: true, + ..DbConfig::default() + }) + .await + .unwrap(); + let community = CommunityId::from_uuid(Uuid::new_v4()); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(format!("push-savepoint-{community}.example")) + .execute(db.pool()) + .await + .unwrap(); + let keys = Keys::generate(); + let mention = Keys::generate().public_key().to_hex(); + // The generic transaction-bound replacement seam supports arbitrary kinds. + // Use a push-eligible kind here so staging before savepoint release is + // observable; ordinary NIP-33 kinds are not push eligible. + let event = |slot: &str, timestamp: u64| { + EventBuilder::new(Kind::Custom(9), slot) + .tags([ + Tag::identifier(slot), + Tag::parse(["p", mention.as_str()]).unwrap(), + ]) + .custom_created_at(Timestamp::from(timestamp)) + .sign_with_keys(&keys) + .unwrap() + }; + let retained = event("retained", 1_769_904_000); + let failed = event("failed", 1_772_323_200); + let duplicate = event("duplicate", 1_775_001_600); + let later = event("later", 1_777_593_600); + // A tombstoned row makes the replacement's insert take its actual + // ON CONFLICT / ROLLBACK TO SAVEPOINT arm, not its early live-head no-op. + crate::event::insert_event(db.pool(), community, &duplicate, None) + .await + .unwrap(); + sqlx::query("UPDATE events SET deleted_at = now() WHERE community_id = $1 AND id = $2") + .bind(community.as_uuid()) + .bind(duplicate.id.as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + // Test-local constraint injects an indexing failure after the event INSERT, + // without changing production triggers or any persistent schema contract. + sqlx::query(sqlx::AssertSqlSafe(format!( + "ALTER TABLE event_mentions ADD CONSTRAINT reject_failed_timestamp_test \ + CHECK (event_id <> decode('{}', 'hex'))", + hex::encode(failed.id.as_bytes()), + ))) + .execute(db.pool()) + .await + .unwrap(); + let mut tx = db.begin_event_write_transaction(community).await.unwrap(); + assert!( + crate::event::insert_event_in_transaction(&mut tx, &retained, None) + .await + .unwrap() + .1 + ); + assert_eq!(tx.push_events.len(), 1); + let error = db + .replace_parameterized_event_in_transaction( + &mut tx, + &failed, + "failed", + None, + ParameterizedReplacePrecondition::Unconditional, + ) + .await + .expect_err("index failure rolls replacement back to savepoint"); + assert!(error.to_string().contains("reject_failed_timestamp_test")); + assert_eq!(tx.push_events.len(), 1, "failed savepoint stages nothing"); + let replay = db + .replace_parameterized_event_in_transaction( + &mut tx, + &duplicate, + "duplicate", + None, + ParameterizedReplacePrecondition::Unconditional, + ) + .await + .unwrap(); + assert_eq!(replay.status, ParameterizedReplaceStatus::Duplicate); + assert_eq!( + tx.push_events.len(), + 1, + "duplicate savepoint stages nothing" + ); + let result = db + .replace_parameterized_event_in_transaction( + &mut tx, + &later, + "later", + None, + ParameterizedReplacePrecondition::Unconditional, + ) + .await + .unwrap(); + assert_eq!(result.status, ParameterizedReplaceStatus::Inserted); + assert_eq!(tx.push_events.len(), 2); + for (staged, event) in tx.push_events.iter().zip([&retained, &later]) { + assert_eq!(staged.event_id, event.id.as_bytes().as_slice()); + assert_eq!( + staged.created_at.timestamp(), + event.created_at.as_secs() as i64 + ); + } + tx.commit().await.unwrap(); + db.push_enqueue.as_ref().unwrap().flush().await; +} diff --git a/crates/buzz-db/src/runtime/history_reads.rs b/crates/buzz-db/src/runtime/history_reads.rs new file mode 100644 index 00000000000..6942f4d2082 --- /dev/null +++ b/crates/buzz-db/src/runtime/history_reads.rs @@ -0,0 +1,93 @@ +//! Per-pod admission for replica-served subscription-history reads. +//! +//! History pages are the heaviest routed reads. Unbounded, a burst of them +//! fills the reader pool, every further routed read misses its reader acquire +//! budget, and before this gate those misses fell back to the writer, where +//! they starved the authentication, tenant and moderation lookups that only +//! the writer can serve. The gate holds running history transactions below the +//! reader pool's size, and a history read that cannot get a reader is rejected +//! as retryable instead of moved to the writer (see [`super::Db::route_read`]). +//! +//! The cap bounds history transactions, not reader connections. A permit is +//! released when its transaction is dropped, while sqlx still returns the +//! connection asynchronously through the pool's release check. Released +//! connections can therefore briefly hold the slots the cap leaves free for +//! authorization reads: usually one round trip, at most the release check's +//! timeout when reader sockets stall. Authorization reads that miss a reader +//! in that window fall back to the writer as before; history reads on the +//! saturated pool are rejected, not moved to the writer. + +use std::time::Duration; + +use crate::concurrency_gate::{ConcurrencyGate, GatePermit}; + +/// How long a history read waits for a permit before it is rejected. The +/// gate is FIFO, so this bounds queueing delay under a burst; a read that +/// would wait longer is shed and the client retries. +pub(crate) const PERMIT_WAIT: Duration = Duration::from_secs(1); + +/// History transactions allowed at once: the pool less one fifth (at least +/// one) left to authorization and bootstrap reads, and never below one. +/// 25 → 20, 5 → 4, 2 → 1, 1 → 1. This is the gate's ceiling: an operator may +/// lower the limit at runtime but never raise it past the share that keeps +/// readers free for authorization. +pub(crate) fn cap(read_max_connections: u32) -> u32 { + read_max_connections + .saturating_sub((read_max_connections / 5).max(1)) + .max(1) +} + +/// The history-read gate for a reader pool of `read_max_connections`, one per +/// `Db` (shared by its clones, so one per relay process). +pub(crate) fn gate_for_read_pool(read_max_connections: u32) -> ConcurrencyGate { + ConcurrencyGate::new(cap(read_max_connections) as usize) +} + +/// A proved reader transaction plus the history permit it was admitted +/// under, if any. The permit is released when the transaction is dropped, +/// wherever the transaction travels: a per-call routed read, or a +/// [`super::ReadSession`] the relay keeps for follow-up queries. The reader +/// connection itself returns to the pool asynchronously after that (see the +/// module docs). +pub(crate) struct ReaderTx { + tx: sqlx::Transaction<'static, sqlx::Postgres>, + _permit: Option, +} + +impl ReaderTx { + pub(crate) fn new( + tx: sqlx::Transaction<'static, sqlx::Postgres>, + permit: Option, + ) -> Self { + Self { + tx, + _permit: permit, + } + } +} + +impl std::ops::Deref for ReaderTx { + type Target = sqlx::Transaction<'static, sqlx::Postgres>; + + fn deref(&self) -> &Self::Target { + &self.tx + } +} + +impl std::ops::DerefMut for ReaderTx { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.tx + } +} + +#[cfg(test)] +mod tests { + use super::cap; + + #[test] + fn cap_leaves_a_fifth_of_the_reader_pool_and_never_reaches_zero() { + for (pool, expected) in [(25, 20), (10, 8), (5, 4), (4, 3), (2, 1), (1, 1), (0, 1)] { + assert_eq!(cap(pool), expected, "pool={pool}"); + } + } +} diff --git a/crates/buzz-db/src/runtime/media_index_prebuild_postgres_tests.rs b/crates/buzz-db/src/runtime/media_index_prebuild_postgres_tests.rs new file mode 100644 index 00000000000..e42a737ff5c --- /dev/null +++ b/crates/buzz-db/src/runtime/media_index_prebuild_postgres_tests.rs @@ -0,0 +1,104 @@ +//! Exercise the shipped psql procedure with real old-snapshot waits. +use sqlx::Executor; +use std::{path::Path, process::Stdio, time::Duration}; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_media_prebuild_waits_for_old_transactions_during_creation_and_cleanup() { + let url = crate::test_support::database_url(); + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + // This migration-mode fixture owns an empty per-test database. Keep only + // the columns the operator procedure uses, including its final 0086 guard. + pool.execute("CREATE TABLE events (community_id bytea, channel_id bytea, tags jsonb, created_at bigint, id bytea, kind int, deleted_at bigint) PARTITION BY RANGE(created_at); CREATE TABLE events_p PARTITION OF events FOR VALUES FROM (0) TO (100); INSERT INTO events(tags,created_at,kind) VALUES ('[]',1,40003)").await.unwrap(); + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let expression = crate::store::media::MEDIA_EDIT_TARGET_SQL; + for cleanup in [false, true] { + if cleanup { + pool.execute("DROP INDEX idx_events_media_edit_target") + .await + .unwrap(); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE INDEX idx_events_media_edit_target ON ONLY events(community_id,channel_id,({expression}),created_at DESC,id DESC) WHERE kind=40003 AND deleted_at IS NULL"))).execute(&pool).await.unwrap(); + } + let mut old = pool.begin().await.unwrap(); + old.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ") + .await + .unwrap(); + old.execute("SELECT * FROM events").await.unwrap(); + if cleanup { + let mut conn = pool.acquire().await.unwrap(); + conn.execute("SET lock_timeout = '50ms'").await.unwrap(); + let error = sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE INDEX CONCURRENTLY ON events_p(community_id,channel_id,({expression}),created_at DESC,id DESC) WHERE kind=40003 AND deleted_at IS NULL"))).execute(&mut *conn).await.unwrap_err(); + assert!(error.to_string().contains("lock timeout"), "{error}"); + conn.execute("RESET lock_timeout").await.unwrap(); + let invalid: i64 = sqlx::query_scalar("SELECT count(*) FROM pg_index WHERE indrelid='events_p'::regclass AND NOT indisvalid").fetch_one(&pool).await.unwrap(); + assert_eq!( + invalid, 1, + "cleanup starts with a real failed concurrent build" + ); + } + let name = format!("media_prebuild_{}", uuid::Uuid::new_v4().simple()); + let mut script = tokio::process::Command::new("psql") + .args(["-X", "-v", "ON_ERROR_STOP=1", "-f"]) + .arg(root.join("scripts/maintenance/prebuild-media-edit-index.sql")) + .arg("--dbname") + .arg(&url) + .env("PGAPPNAME", &name) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let waiting = tokio::time::timeout(Duration::from_secs(10), async { + loop { + let waiting: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND application_name=$1 AND wait_event_type='Lock' AND wait_event='virtualxid')") + .bind(&name).fetch_one(&pool).await.unwrap(); + if waiting { break; } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }).await; + if waiting.is_err() { + old.rollback().await.unwrap(); + let result = script.wait_with_output().await.unwrap(); + panic!( + "cleanup={cleanup}: script did not reach old-transaction wait: {} {}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); + } + // Keep the old snapshot until the original one-second deadline has + // passed. An early exit here catches both CREATE and DROP regressions. + assert!( + tokio::time::timeout(Duration::from_millis(1300), script.wait()) + .await + .is_err(), + "cleanup={cleanup}: concurrent operation must outlive the short metadata lock budget" + ); + old.commit().await.unwrap(); + let result = tokio::time::timeout(Duration::from_secs(10), script.wait_with_output()) + .await + .unwrap() + .unwrap(); + assert!( + result.status.success(), + "cleanup={cleanup}: {}", + String::from_utf8_lossy(&result.stderr) + ); + let valid: i64 = sqlx::query_scalar("SELECT count(*) FROM pg_index WHERE indrelid IN ('events'::regclass,'events_p'::regclass) AND indisvalid AND indisready").fetch_one(&pool).await.unwrap(); + assert_eq!(valid, 2); + let invalid: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_index WHERE indrelid='events_p'::regclass AND NOT indisvalid", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + invalid, 0, + "retry must remove the unusable child, not leave it beside a replacement" + ); + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM events") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(rows, 1); + } +} diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index ccbd8615ab3..7a9a2b7bf8a 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -14,6 +14,10 @@ use crate::Result; static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("../../migrations"); +#[cfg(test)] +#[path = "tests/schema_fence_bootstrap_postgres_tests.rs"] +mod schema_fence_bootstrap_postgres_tests; + /// Run all pending Buzz database migrations. /// /// The entire run holds the exclusive [`SCHEMA_DESTRUCTION_LOCK_KEY`] session @@ -49,6 +53,10 @@ pub(crate) async fn run_migrations_through(pool: &PgPool, target: i64) -> Result async fn run_migrations_locked(conn: &mut PgConnection) -> Result<()> { reject_legacy_nip_rs_cardinality_ambiguity(conn).await?; + for (version, doc, indexes) in INLINE_INDEX_BUILDS { + MIGRATOR.run_to(version - 1, &mut *conn).await?; + build_indexes_before_migration(conn, *version, doc, indexes).await?; + } MIGRATOR.run(&mut *conn).await?; // The replica-fence proof (see `replica_fence`) requires the commit-time // `created_at` floor trigger from migration 0021 — correctly shaped — on @@ -58,10 +66,125 @@ async fn run_migrations_locked(conn: &mut PgConnection) -> Result<()> { // guard, so migration fails closed if any is missing. (The fence probe // re-runs this same check at startup on non-migrating relays.) crate::replica_fence::verify_floor_guard_catalog(&mut *conn).await?; - crate::channel::verify_channel_roster_fence_catalog(&mut *conn).await?; Ok(()) } +/// Indexes that a migration verifies but refuses to build on a populated +/// table, keyed by that migration's version, with the document that describes +/// its concurrent prebuild, as `(name, definition)`. +/// +/// Migrations 0076, 0078 and 0081 are checksum-frozen and expect every +/// populated database to prebuild these indexes with `CREATE INDEX +/// CONCURRENTLY`. Startup migration builds a missing index here instead, under +/// the same bounded budgets 0049 uses, so a small populated database upgrades +/// like an empty one and a large one still fails closed. `CONCURRENTLY` is not +/// used: a replica blocked on the migration lock holds a snapshot that a +/// concurrent build would wait for. New migrations build their own indexes +/// inline (docs/database.md Rule 6); the `frozen_prebuild_guards_have_inline_builds` +/// test keeps this list equal to the migrations that refuse populated tables. +type InlineIndexBuilds = &'static [(&'static str, &'static str)]; + +const INLINE_INDEX_BUILDS: &[(i64, &str, InlineIndexBuilds)] = &[ + ( + 76, + "docs/artifact-sync-deployment.md", + &[( + "idx_artifact_revisions_artifact", + "CREATE INDEX idx_artifact_revisions_artifact \ + ON public.artifact_revisions (community_id, artifact_id)", + )], + ), + ( + 78, + "docs/artifact-sync-deployment.md", + &[ + ( + "artifact_heads_modified", + "CREATE INDEX artifact_heads_modified \ + ON public.artifact_heads (community_id, modified_at, artifact_id)", + ), + ( + "artifact_heads_channel", + "CREATE INDEX artifact_heads_channel \ + ON public.artifact_heads (community_id, channel_id, artifact_id)", + ), + ( + "channel_members_sync", + "CREATE INDEX channel_members_sync \ + ON public.channel_members (community_id, pubkey, sync_modified_at, channel_id)", + ), + ( + "artifact_revisions_moves", + "CREATE INDEX artifact_revisions_moves \ + ON public.artifact_revisions (community_id, modified_at, event_id) \ + WHERE source_channel_id IS NOT NULL", + ), + ], + ), + ( + 81, + "docs/profile-search.md", + &[( + "idx_nip_fi_profile_heads_names", + // The exact pg_get_indexdef form migration 0081 verifies. + r#"CREATE INDEX idx_nip_fi_profile_heads_names ON public.nip_fi_profile_heads USING gin (to_tsvector('simple'::regconfig, ((((COALESCE((jsonb_path_query_first(event, 'strict $."tags"[*]?(@[0] == "display_name")[1]'::jsonpath, '{}'::jsonb, true) #>> '{}'::text[]), ''::text) || ' '::text) || COALESCE((jsonb_path_query_first(event, 'strict $."tags"[*]?(@[0] == "username")[1]'::jsonpath, '{}'::jsonb, true) #>> '{}'::text[]), ''::text)) || ' '::text) || COALESCE((jsonb_path_query_first(event, 'strict $."tags"[*]?(@[0] == "full_name")[1]'::jsonpath, '{}'::jsonb, true) #>> '{}'::text[]), ''::text))))"#, + )], + ), +]; + +/// Build each missing index in `indexes` in its own bounded transaction +/// unless migration `version` is already recorded, so no build holds its +/// writer-conflicting lock past its own budget. An existing index, valid or +/// not, is left for the migration to verify, and is skipped before +/// `CREATE INDEX` so a prebuilt deployment never requests that lock. +async fn build_indexes_before_migration( + conn: &mut PgConnection, + version: i64, + doc: &str, + indexes: InlineIndexBuilds, +) -> Result<()> { + let applied: bool = + sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM _sqlx_migrations WHERE version = $1)") + .bind(version) + .fetch_one(&mut *conn) + .await?; + if applied { + return Ok(()); + } + let build = async { + for (name, definition) in indexes { + let exists: bool = sqlx::query_scalar("SELECT to_regclass($1) IS NOT NULL") + .bind(format!("public.{name}")) + .fetch_one(&mut *conn) + .await?; + if !exists { + let mut tx = conn.begin().await?; + sqlx::raw_sql("SET LOCAL lock_timeout = '1s'; SET LOCAL statement_timeout = '5s'") + .execute(&mut *tx) + .await?; + sqlx::raw_sql(*definition).execute(&mut *tx).await?; + tx.commit().await?; + } + } + Ok::<(), sqlx::Error>(()) + }; + build.await.map_err(|error| { + // Only a lock or statement timeout means the table is too large or + // too busy for the startup budget; pass any other failure through. + let over_budget = error + .as_database_error() + .and_then(|db| db.code()) + .is_some_and(|code| code == "55P03" || code == "57014"); + if !over_budget { + return error.into(); + } + crate::DbError::InvalidData(format!( + "migration {version} blocked: building its indexes within the startup budget failed \ + ({error}); prebuild them concurrently as described in {doc}, then retry" + )) + }) +} + /// Run `op` while holding the exclusive schema/destruction session lock. /// /// `op` receives ownership of the detached connection that owns the advisory @@ -189,9 +312,14 @@ async fn reject_legacy_nip_rs_cardinality_ambiguity(conn: &mut PgConnection) -> #[path = "follow_up_retirement_tests.rs"] mod retirement_postgres_tests; +#[cfg(test)] +#[path = "media_index_prebuild_postgres_tests.rs"] +mod media_index_prebuild_postgres_tests; + #[cfg(test)] mod postgres_tests { use super::*; + use crate::test_support::ScratchDb; use std::{ collections::BTreeSet, fs, @@ -546,6 +674,7 @@ mod postgres_tests { "entity_deletion_approvals", "entity_deletion_requests", "entity_deletion_stage_history", + "user_deletion_fences", "community_deletion_approvals", "community_deletion_checkpoints", "community_deletion_manifest_keys", @@ -559,6 +688,7 @@ mod postgres_tests { "storage_accounting_snapshots", "operator_listener_pubkeys", "operator_listener_outbox", + "community_auth_upgrades", ] { if normalized[insert_pos..].contains(&format!("'{value}'")) { globals.insert(value.to_owned()); @@ -772,16 +902,50 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 73); - assert_eq!(migrations[72].version, 73); - assert_eq!(migrations[71].version, 72); - assert_eq!(migrations[70].version, 71); + assert_eq!(migrations.len(), 88); + assert!(migrations[83] + .sql + .as_str() + .contains("ADD COLUMN auto_join_pending UUID")); + assert!(migrations[84] + .sql + .as_str() + .contains("ADD COLUMN requested_requires_nip_fi BOOLEAN NOT NULL DEFAULT true")); + assert!(migrations[85] + .sql + .as_str() + .contains("CREATE TABLE media_uploaders")); + assert!(migrations[86] + .sql + .as_str() + .contains("ADD COLUMN cause_source TEXT")); + assert!(migrations[87] + .sql + .as_str() + .contains("VALIDATE CONSTRAINT workflow_runs_cause_pubkey_check")); + for (index, migration) in migrations.iter().enumerate() { + assert_eq!(migration.version, (index + 1) as i64); + } + assert!(migrations[79] + .sql + .as_str() + .contains("ADD COLUMN auto_join BOOLEAN NOT NULL DEFAULT false")); + // Listed channel names (0083): a bounded contract index that refuses + // to build over unrepaired duplicates. The desired schema carries the + // same plain index. + assert_eq!(migrations[82].version, 83); + let listed_names = strip_sql_comments(migrations[82].sql.as_str()); + assert!(listed_names.contains("SET LOCAL lock_timeout = '1s';")); + assert!(listed_names.contains("SET LOCAL statement_timeout = '5s';")); + assert!(listed_names.contains("CREATE UNIQUE INDEX idx_channels_listed_name")); + assert!(!listed_names.contains("CONCURRENTLY")); + assert!(crate::test_support::desired_state_schema_sql().contains( + "CREATE UNIQUE INDEX idx_channels_listed_name ON channels (community_id, lower(name))" + )); assert!(migrations[70] .sql .as_str() .contains("ADD COLUMN unlisted BOOLEAN NOT NULL DEFAULT FALSE")); - assert_eq!(migrations[69].version, 70); - assert_eq!(migrations[68].version, 69); assert_eq!(migrations[67].version, 68); assert!(migrations[67] .sql @@ -799,6 +963,26 @@ mod postgres_tests { let desired_schema = crate::test_support::desired_state_schema_sql(); assert!(!desired_schema.contains("events_refresh_channel_ttl")); assert!(!desired_schema.contains("refresh_channel_ttl_after_event_insert")); + assert!(desired_schema.contains("legacy_admission BOOLEAN NOT NULL DEFAULT true")); + assert_eq!(migrations[65].version, 66); + assert!(migrations[65] + .sql + .as_str() + .contains("CREATE TABLE community_nip_fi_issuers")); + assert_eq!(migrations[74].version, 75); + let invite_migration = strip_sql_comments(migrations[74].sql.as_str()); + assert!(invite_migration.contains("SET LOCAL lock_timeout = '5s'")); + assert!(invite_migration.contains("SET LOCAL statement_timeout = '30s'")); + assert!( + invite_migration.contains("ADD COLUMN legacy_admission BOOLEAN NOT NULL DEFAULT true") + ); + assert!(invite_migration.contains("ADD COLUMN revoked_at TIMESTAMPTZ")); + assert!(!invite_migration.to_ascii_uppercase().contains("UPDATE ")); + assert!(!invite_migration + .to_ascii_uppercase() + .contains("CREATE FUNCTION")); + assert!(!desired_schema.contains("invite_admission_lock")); + assert_eq!(migrations[58].version, 59); assert!(migrations[58].sql.as_str().contains("buzz.push_enabled")); assert_eq!(migrations[59].version, 60); @@ -818,11 +1002,6 @@ mod postgres_tests { .sql .as_str() .contains("CREATE FUNCTION profile_name_fields")); - assert_eq!(migrations[65].version, 66); - assert!(migrations[65] - .sql - .as_str() - .contains("CREATE TABLE community_nip_fi_issuers")); assert_eq!(migrations[55].version, 56); assert!(migrations[55] .sql @@ -2039,9 +2218,9 @@ mod postgres_tests { if *path == this_file { assert_eq!( (macro_hits, run_hits, run_to_hits), - (1, 1, 1), + (1, 1, 2), "migration.rs must embed the migrator once, run it once in production, \ - and expose exactly one test-only bounded run" + and have one test-only and one production bounded run" ); } else if *path == push_gateway_exception { continue; @@ -2078,9 +2257,16 @@ mod postgres_tests { source[entry..locked].contains("with_exclusive_schema_destruction_lock("), "run_migrations must delegate through the exclusive schema/destruction lock" ); + let production_run_to_site = source[run_to_site + 1..] + .find(&migrator_run_to) + .map(|offset| run_to_site + 1 + offset) + .expect("production bounded migrator run site"); assert!( - run_site > locked && run_site < wrapper, - "the production migrator run site must live inside run_migrations_locked" + run_site > locked + && run_site < wrapper + && production_run_to_site > locked + && production_run_to_site < run_site, + "the production migrator run sites must live inside run_migrations_locked" ); assert!( run_to_site > entry @@ -2550,23 +2736,13 @@ mod postgres_tests { async fn cancelled_migration_cannot_expose_shared_lock_while_ddl_backend_lives() { use std::time::Instant; - use sqlx::AssertSqlSafe; - // Dedicated database: the probe table and the orphaned backend must // stay invisible to concurrent tests in the shared database. let base_url = std::env::var("BUZZ_TEST_DATABASE_URL") .or_else(|_| std::env::var("DATABASE_URL")) .unwrap_or_else(|_| TEST_DB_URL.to_owned()); - let admin = PgPool::connect(&base_url) - .await - .expect("connect admin database"); - let probe_db = format!("buzz_lock_cancel_{}", uuid::Uuid::new_v4().simple()); - sqlx::query(AssertSqlSafe(format!("CREATE DATABASE {probe_db}"))) - .execute(&admin) - .await - .expect("create probe database"); - let (base_prefix, _) = base_url.rsplit_once('/').expect("database url has a path"); - let pool = PgPool::connect(&format!("{base_prefix}/{probe_db}")) + let probe_db = ScratchDb::create(&base_url, "buzz_lock_cancel").await; + let pool = PgPool::connect(probe_db.url()) .await .expect("connect probe database"); sqlx::query("CREATE TABLE schema_lock_cancel_probe (id int)") @@ -2699,14 +2875,6 @@ mod postgres_tests { committed, "orphaned migration DDL commits after cancellation; the lock must cover it" ); - - pool.close().await; - sqlx::query(AssertSqlSafe(format!( - "DROP DATABASE {probe_db} WITH (FORCE)" - ))) - .execute(&admin) - .await - .expect("drop probe database"); } pub(super) async fn connect_test_pool() -> PgPool { @@ -2770,8 +2938,6 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn admin_schema_parity_between_desired_state_and_migrations() { - use sqlx::AssertSqlSafe; - async fn columns( pool: &PgPool, table: &str, @@ -2852,25 +3018,13 @@ mod postgres_tests { .or_else(|_| std::env::var("DATABASE_URL")) .unwrap_or_else(|_| TEST_DB_URL.to_owned()); let conn = parse_pg_url(&base_url); - let admin = PgPool::connect(&base_url) - .await - .expect("connect admin database"); - let (base_prefix, _) = base_url.rsplit_once('/').expect("database url has a path"); - let desired_db = format!("buzz_admin_desired_{}", uuid::Uuid::new_v4().simple()); - let migrated_db = format!("buzz_admin_migrated_{}", uuid::Uuid::new_v4().simple()); - sqlx::query(AssertSqlSafe(format!("CREATE DATABASE {desired_db}"))) - .execute(&admin) - .await - .expect("create desired-state probe database"); - sqlx::query(AssertSqlSafe(format!("CREATE DATABASE {migrated_db}"))) - .execute(&admin) - .await - .expect("create migrated probe database"); + let desired_db = ScratchDb::create(&base_url, "buzz_admin_desired").await; + let migrated_db = ScratchDb::create(&base_url, "buzz_admin_migrated").await; // Bootstrap the desired-state probe the way the test-relay launchers do: // the real pgschema binary, then the post-apply reconcile script. - let apply = pgschema(&conn, &desired_db, &["apply", "--auto-approve"]); + let apply = pgschema(&conn, desired_db.name(), &["apply", "--auto-approve"]); assert!( apply.status.success(), "pgschema apply failed: {}\n{}", @@ -2878,7 +3032,7 @@ mod postgres_tests { String::from_utf8_lossy(&apply.stderr), ); - let desired = PgPool::connect(&format!("{base_prefix}/{desired_db}")) + let desired = PgPool::connect(desired_db.url()) .await .expect("connect desired-state probe database"); sqlx::raw_sql(include_str!( @@ -2887,7 +3041,7 @@ mod postgres_tests { .execute(&desired) .await .expect("reconcile desired-state probe database"); - let migrated = PgPool::connect(&format!("{base_prefix}/{migrated_db}")) + let migrated = PgPool::connect(migrated_db.url()) .await .expect("connect migrated probe database"); MIGRATOR @@ -2896,12 +3050,22 @@ mod postgres_tests { .expect("apply migrations for schema parity"); for table in [ + "media_uploaders", + "media_publications", + "relay_members", "relay_admin_actions", "relay_admin_outbox", "relay_operator_audit", + "community_auth_upgrades", "entity_deletion_approvals", "entity_deletion_requests", + "artifact_heads", + "artifact_revisions", + "channel_members", + "communities", "entity_deletion_stage_history", + "user_deletion_fences", + "workflow_runs", ] { assert_eq!( columns(&desired, table).await, @@ -2918,6 +3082,14 @@ mod postgres_tests { migration and schema.sql must both use a representable shape." ); } + async fn media_edit_index(pool: &PgPool) -> (String, String, String) { + sqlx::query_as("SELECT pg_get_indexdef(indexrelid),indoption::text,pg_get_expr(indexprs,indrelid) FROM pg_index WHERE indexrelid='public.idx_events_media_edit_target'::regclass AND indisvalid AND indisready AND indislive") + .fetch_one(pool).await.expect("valid media edit index") + } + assert_eq!( + media_edit_index(&desired).await, + media_edit_index(&migrated).await + ); // `channels` columns only: pgschema re-emits `idx_channels_id_live` // without its `INCLUDE (community_id)`, an index drift that predates // this check. @@ -2927,6 +3099,21 @@ mod postgres_tests { "column parity mismatch for channels: schema.sql desired state has drifted \ from the migrations; update schema/tables/public/channels.sql to match" ); + // The listed-name index (0083) is compared on its own for that reason. + let listed_name = |shapes: Vec<(String, String, String)>| { + shapes + .into_iter() + .filter(|(name, _, _)| name == "idx_channels_listed_name") + .collect::>() + }; + let desired_listed_name = listed_name(index_shapes(&desired, "channels").await); + assert_eq!(desired_listed_name.len(), 1, "desired state has the index"); + assert_eq!( + desired_listed_name, + listed_name(index_shapes(&migrated, "channels").await), + "idx_channels_listed_name parity mismatch: update \ + schema/tables/public/channels.sql to match migration 0083" + ); assert_eq!( events_key_defs(&desired).await, events_key_defs(&migrated).await, @@ -2936,9 +3123,13 @@ mod postgres_tests { ); for table in [ + "communities", + "community_auth_upgrades", "entity_deletion_requests", "entity_deletion_stage_history", + "user_deletion_fences", "entity_deletion_approvals", + "workflow_runs", ] { assert_eq!( constraints(&desired, table).await, @@ -2946,17 +3137,6 @@ mod postgres_tests { "constraint parity mismatch for {table}" ); } - - desired.close().await; - migrated.close().await; - for probe_db in [desired_db, migrated_db] { - sqlx::query(AssertSqlSafe(format!( - "DROP DATABASE {probe_db} WITH (FORCE)" - ))) - .execute(&admin) - .await - .expect("drop probe database"); - } } /// Re-applying `schema/schema.sql` to a database bootstrapped the way every @@ -2978,27 +3158,18 @@ mod postgres_tests { use crate::store::partition::{ maintain_partitions, PartitionMaintenancePolicy, PARTITION_MANAGER_MONTHS_AHEAD, }; - use sqlx::AssertSqlSafe; let base_url = crate::test_support::database_url(); let conn = parse_pg_url(&base_url); - let admin = PgPool::connect(&base_url) - .await - .expect("connect admin database"); - let (base_prefix, _) = base_url.rsplit_once('/').expect("database url has a path"); - let database = format!("buzz_pgschema_reapply_{}", uuid::Uuid::new_v4().simple()); - sqlx::query(AssertSqlSafe(format!("CREATE DATABASE {database}"))) - .execute(&admin) - .await - .expect("create probe database"); + let database = ScratchDb::create(&base_url, "buzz_pgschema_reapply").await; - let pool = PgPool::connect(&format!("{base_prefix}/{database}")) + let pool = PgPool::connect(database.url()) .await .expect("connect probe database"); // The bootstrap every pgschema caller runs; the reconcile script // attaches the declared children. let bootstrap = |round: &str| { - let apply = pgschema(&conn, &database, &["apply", "--auto-approve"]); + let apply = pgschema(&conn, database.name(), &["apply", "--auto-approve"]); assert!( apply.status.success(), "{round} pgschema apply failed: {}\n{}", @@ -3083,7 +3254,7 @@ mod postgres_tests { ); } - let plan = pgschema(&conn, &database, &["plan", "--output-sql", "stdout"]); + let plan = pgschema(&conn, database.name(), &["plan", "--output-sql", "stdout"]); let plan_sql = String::from_utf8_lossy(&plan.stdout); assert!( plan.status.success(), @@ -3098,14 +3269,346 @@ mod postgres_tests { bootstrap("second") .await .expect("second post-apply reconciliation"); - pool.close().await; + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn policy_receipt_expand_preserves_populated_rows_and_legacy_inserts() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations_through(&pool, 84).await.unwrap(); + let insert = "INSERT INTO community_auth_upgrades + (operation_id,target_community_id,expected_host,actor_pubkey,expected_owner_pubkey, + expected_issuer,operator_pubkey,policy_generation) + VALUES ($1,$2,'team.example.org','actor','owner','https://issuer.example.org','operator',1)"; + let first = uuid::Uuid::new_v4(); + sqlx::query(insert) + .bind(first) + .bind(uuid::Uuid::new_v4()) + .execute(&pool) + .await + .unwrap(); + run_migrations(&pool).await.unwrap(); + let second = uuid::Uuid::new_v4(); + sqlx::query(insert) + .bind(second) + .bind(uuid::Uuid::new_v4()) + .execute(&pool) + .await + .unwrap(); + for id in [first, second] { + let row: (bool, Option, Option, i64) = sqlx::query_as( + "SELECT requested_requires_nip_fi, expected_policy_generation, + expected_requires_nip_fi, policy_generation + FROM community_auth_upgrades WHERE operation_id=$1", + ) + .bind(id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(row, (true, None, None, 1)); + } + } - sqlx::query(AssertSqlSafe(format!( - "DROP DATABASE {database} WITH (FORCE)" - ))) - .execute(&admin) + /// 0087 adds the run-cause columns and NOT VALID checks without scanning + /// existing runs, and 0088 validates them. Runs written before the upgrade, + /// and inserts from an older relay that omits both columns, keep no cause. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn workflow_run_cause_upgrade_preserves_populated_rows_and_legacy_inserts() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + run_migrations_through(&pool, 86).await.unwrap(); + let community_id = uuid::Uuid::new_v4(); + let workflow_id = uuid::Uuid::new_v4(); + let owner = vec![7u8; 32]; + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community_id) + .bind(format!("run-cause-{}.example", community_id.simple())) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2)") + .bind(community_id) + .bind(&owner) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO workflows (community_id, id, name, owner_pubkey, definition, definition_hash) \ + VALUES ($1, $2, 'cause', $3, '{}', $4)", + ) + .bind(community_id) + .bind(workflow_id) + .bind(&owner) + .bind(vec![0u8; 32]) + .execute(&pool) + .await + .unwrap(); + let legacy_insert = + "INSERT INTO workflow_runs (community_id, id, workflow_id) VALUES ($1, $2, $3)"; + let insert_legacy_run = |id| { + sqlx::query(legacy_insert) + .bind(community_id) + .bind(id) + .bind(workflow_id) + .execute(&pool) + }; + let before = uuid::Uuid::new_v4(); + insert_legacy_run(before).await.unwrap(); + run_migrations(&pool).await.unwrap(); + let after = uuid::Uuid::new_v4(); + insert_legacy_run(after).await.unwrap(); + + for id in [before, after] { + let cause: (Option, Option>) = sqlx::query_as( + "SELECT cause_source, cause_pubkey FROM workflow_runs WHERE id = $1", + ) + .bind(id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(cause, (None, None)); + } + let unvalidated: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_constraint \ + WHERE conrelid = 'public.workflow_runs'::regclass AND contype = 'c' \ + AND conname LIKE 'workflow_runs_%' AND NOT convalidated", + ) + .fetch_one(&pool) .await - .expect("drop probe database"); + .unwrap(); + assert_eq!(unvalidated, 0, "0088 validates every cause check"); + let unknown_source = sqlx::query( + "INSERT INTO workflow_runs (community_id, id, workflow_id, cause_source) \ + VALUES ($1, $2, $3, 'relay')", + ) + .bind(community_id) + .bind(uuid::Uuid::new_v4()) + .bind(workflow_id) + .execute(&pool) + .await; + assert!(unknown_source.is_err(), "the trigger source check holds"); + } + + /// Migrations 0076 and 0078 refuse a populated table whose index was not + /// prebuilt concurrently. A relay that auto-migrated through earlier + /// releases and holds artifact data must still boot through every migration. When a + /// bounded inline build cannot take its lock it must fail closed without + /// recording that migration, keeping earlier migrations and each index + /// already built in its own transaction. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn populated_artifact_tables_auto_migrate_through_every_migration() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + MIGRATOR + .run_to(75, &pool) + .await + .expect("apply migrations 1-75"); + + let community_id = uuid::Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community_id) + .bind(format!("artifact-{}.example", community_id.simple())) + .execute(&pool) + .await + .expect("insert community"); + let artifact_id = uuid::Uuid::new_v4(); + sqlx::query( + "INSERT INTO artifact_revisions (community_id, event_id, artifact_id) \ + VALUES ($1, $2, $3)", + ) + .bind(community_id) + .bind(vec![1_u8; 32]) + .bind(artifact_id) + .execute(&pool) + .await + .expect("insert artifact revision"); + sqlx::query( + "INSERT INTO artifact_heads \ + (community_id, artifact_id, event_id, channel_id, artifact_type) \ + VALUES ($1, $2, $3, $4, 'doc')", + ) + .bind(community_id) + .bind(artifact_id) + .bind(vec![1_u8; 32]) + .bind(uuid::Uuid::new_v4()) + .execute(&pool) + .await + .expect("insert artifact head"); + + let mut holder = pool.begin().await.expect("begin lock holder"); + sqlx::query("LOCK TABLE artifact_revisions IN ROW EXCLUSIVE MODE") + .execute(&mut *holder) + .await + .expect("hold a writer lock"); + let blocked = run_migrations(&pool) + .await + .expect_err("a build that cannot take its lock must fail closed") + .to_string(); + assert!( + blocked.contains("migration 76 blocked") + && blocked.contains("docs/artifact-sync-deployment.md"), + "unexpected error: {blocked}" + ); + assert_eq!(applied_versions(&pool).await.last().copied(), Some(75)); + holder.rollback().await.expect("release writer lock"); + + // A prebuilt index is skipped without requesting the build lock, so + // the same held writer lock first blocks 0077's ALTER TABLE instead. + sqlx::query( + "CREATE INDEX idx_artifact_revisions_artifact \ + ON public.artifact_revisions (community_id, artifact_id)", + ) + .execute(&pool) + .await + .expect("prebuild the 0076 index"); + let mut holder = pool.begin().await.expect("begin second lock holder"); + sqlx::query("LOCK TABLE artifact_revisions IN ROW EXCLUSIVE MODE") + .execute(&mut *holder) + .await + .expect("hold a writer lock again"); + let blocked = run_migrations(&pool) + .await + .expect_err("0077 cannot alter a table under a held writer lock") + .to_string(); + assert!( + !blocked.contains("migration 76 blocked"), + "a prebuilt index must not be rebuilt: {blocked}" + ); + assert_eq!(applied_versions(&pool).await.last().copied(), Some(76)); + holder.rollback().await.expect("release second writer lock"); + + // Block the third 0078 build. The two artifact_heads builds before it + // commit separately, so neither holds its lock while the third waits. + run_migrations_through(&pool, 77) + .await + .expect("apply migration 77"); + let mut holder = pool.begin().await.expect("begin third lock holder"); + sqlx::query("LOCK TABLE channel_members IN ROW EXCLUSIVE MODE") + .execute(&mut *holder) + .await + .expect("hold a channel_members writer lock"); + let blocked = run_migrations(&pool) + .await + .expect_err("a blocked 0078 build must fail closed") + .to_string(); + assert!( + blocked.contains("migration 78 blocked"), + "unexpected error: {blocked}" + ); + assert_eq!(applied_versions(&pool).await.last().copied(), Some(77)); + let committed: bool = + sqlx::query_scalar("SELECT to_regclass('public.artifact_heads_modified') IS NOT NULL") + .fetch_one(&pool) + .await + .expect("read earlier 0078 build"); + assert!( + committed, + "an earlier build must commit before the next one" + ); + holder.rollback().await.expect("release third writer lock"); + + run_migrations(&pool) + .await + .expect("populated small database auto-migrates"); + assert_boots_through_every_migration(&pool).await; + assert_eq!( + valid_indexes( + &pool, + &[ + "idx_artifact_revisions_artifact", + "artifact_heads_modified", + "artifact_heads_channel", + "channel_members_sync", + "artifact_revisions_moves", + ] + ) + .await, + 5 + ); + } + + /// Migration 0081 refuses a populated `nip_fi_profile_heads`. A relay that + /// has published NIP-FI verified profiles must still boot through every + /// migration. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn populated_verified_profiles_auto_migrate_through_every_migration() { + let pool = connect_test_pool().await; + reset_public_schema(&pool).await; + MIGRATOR + .run_to(80, &pool) + .await + .expect("apply migrations 1-80"); + sqlx::query( + "INSERT INTO nip_fi_profile_heads (community_id, pubkey, issuer, issued_at, event) \ + VALUES ($1, $2, $3, 1, $4)", + ) + .bind(uuid::Uuid::new_v4()) + .bind("a".repeat(64)) + .bind("b".repeat(64)) + .bind(serde_json::json!({"tags": [["display_name", "Wes Johnson"]]})) + .execute(&pool) + .await + .expect("insert verified profile head"); + + run_migrations(&pool) + .await + .expect("database with verified profiles auto-migrates"); + assert_boots_through_every_migration(&pool).await; + assert_eq!( + valid_indexes(&pool, &["idx_nip_fi_profile_heads_names"]).await, + 1 + ); + } + + async fn assert_boots_through_every_migration(pool: &PgPool) { + let embedded: Vec = MIGRATOR.iter().map(|migration| migration.version).collect(); + assert_eq!( + applied_versions(pool).await, + embedded, + "a populated database must boot through every embedded migration" + ); + } + + async fn valid_indexes(pool: &PgPool, names: &[&str]) -> i64 { + sqlx::query_scalar( + "SELECT count(*) FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid \ + WHERE c.relname = ANY($1) AND i.indisvalid AND i.indisready AND i.indislive", + ) + .bind(names) + .fetch_one(pool) + .await + .expect("read index flags") + } + + /// A migration that refuses a populated table crash-loops every + /// auto-migrating relay with data. Only the frozen ones may, and each must + /// have an inline build the startup runner applies first. + #[test] + fn frozen_prebuild_guards_have_inline_builds() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../migrations"); + let mut guarded: Vec = std::fs::read_dir(&dir) + .expect("read migrations dir") + .filter_map(|entry| { + let path = entry.expect("read migration entry").path(); + let name = path.file_name()?.to_str()?.to_owned(); + let version: i64 = name.split('_').next()?.parse().ok()?; + let sql = std::fs::read_to_string(&path).expect("read migration"); + sql.contains("RAISE EXCEPTION 'prebuild ") + .then_some(version) + }) + .collect(); + guarded.sort_unstable(); + let inline: Vec = INLINE_INDEX_BUILDS.iter().map(|(v, _, _)| *v).collect(); + assert_eq!( + guarded, inline, + "a migration must build its own index instead of refusing a populated table \ + (docs/database.md Rule 6); only frozen guards listed in INLINE_INDEX_BUILDS may remain" + ); + assert_eq!(inline, [76, 78, 81], "do not add new prebuild guards"); } #[tokio::test] @@ -3172,6 +3675,7 @@ mod postgres_tests { .execute(&pool) .await .expect("repair ambiguous row"); + crate::test_support::prebuild_media_edit_index(&pool).await; run_migrations(&pool) .await .expect("retry succeeds after operator repair"); @@ -3251,6 +3755,7 @@ mod postgres_tests { vec![(1, Some(true)), (30_179, Some(true)), (30_350, None)] ); + crate::test_support::prebuild_media_edit_index(&pool).await; run_migrations(&pool) .await .expect("apply remaining migrations to populated database"); @@ -3678,4 +4183,112 @@ mod postgres_tests { .await .is_err()); } + /// Small populated upgrades build inline; contention stays bounded and a + /// verified prebuild avoids requesting the writer-conflicting index lock. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn media_edit_index_upgrade_builds_inline_or_verifies_prebuild() { + let pool = connect_test_pool().await; + for prebuilt in [false, true] { + reset_public_schema(&pool).await; + run_migrations_through(&pool, 85).await.unwrap(); + let community = uuid::Uuid::new_v4(); + sqlx::query( + "INSERT INTO communities(id,host) VALUES($1,'media-index-upgrade.example')", + ) + .bind(community) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig) VALUES($1,decode(repeat('a',64),'hex'),decode(repeat('b',64),'hex'),now(),9,'[]','media',decode(repeat('c',128),'hex'))") + .bind(community).execute(&pool).await.unwrap(); + if prebuilt { + sqlx::query("CREATE INDEX idx_events_media_edit_target ON events(community_id,id)") + .execute(&pool) + .await + .unwrap(); + let error = run_migrations(&pool).await.unwrap_err(); + assert!( + error.to_string().contains("invalid or wrong definition"), + "{error}" + ); + sqlx::query("DROP INDEX idx_events_media_edit_target") + .execute(&pool) + .await + .unwrap(); + crate::test_support::prebuild_media_edit_index(&pool).await; + } + let mut writer = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE public.events IN ROW EXCLUSIVE MODE") + .execute(&mut *writer) + .await + .unwrap(); + if prebuilt { + run_migrations(&pool) + .await + .expect("verified prebuild does not request an index-build lock"); + writer.rollback().await.unwrap(); + } else { + let error = run_migrations(&pool).await.unwrap_err(); + assert!( + error.to_string().contains("lock timeout"), + "index build must obey its lock budget: {error}" + ); + let applied: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM _sqlx_migrations WHERE version>=86)", + ) + .fetch_one(&pool) + .await + .unwrap(); + assert!( + !applied, + "failed first new migration must leave version 85 intact" + ); + let old_migrator = sqlx::migrate::Migrator { + migrations: std::borrow::Cow::Owned( + MIGRATOR + .iter() + .filter(|migration| migration.version <= 85) + .cloned() + .collect(), + ), + ..sqlx::migrate::Migrator::DEFAULT + }; + with_exclusive_schema_destruction_lock(&pool, |mut conn| async move { + let result = old_migrator + .run(&mut conn) + .await + .map_err(crate::DbError::from); + (conn, result) + }) + .await + .expect("old binary's migrator must still restart after the failed index build"); + let tables: bool = sqlx::query_scalar("SELECT to_regclass('public.media_uploaders') IS NOT NULL OR to_regclass('public.media_publications') IS NOT NULL") + .fetch_one(&pool).await.unwrap(); + assert!( + !tables, + "media table expansion must follow the fallible index build" + ); + let recovery_column: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name='relay_members' AND column_name='auto_join_pending')") + .fetch_one(&pool).await.unwrap(); + assert!(recovery_column, "main's migration 84 must remain intact"); + let policy_columns: i64 = sqlx::query_scalar("SELECT count(*) FROM information_schema.columns WHERE table_schema='public' AND table_name='community_auth_upgrades' AND column_name IN ('requested_requires_nip_fi','expected_policy_generation','expected_requires_nip_fi')") + .fetch_one(&pool).await.unwrap(); + assert_eq!(policy_columns, 3, "base migration 85 must remain intact"); + writer.rollback().await.unwrap(); + run_migrations(&pool).await.expect( + "small populated database builds its index without operator intervention", + ); + } + run_migrations(&pool).await.unwrap(); + let valid: bool = sqlx::query_scalar("SELECT indisvalid AND indisready FROM pg_index WHERE indexrelid='public.idx_events_media_edit_target'::regclass") + .fetch_one(&pool).await.unwrap(); + assert!(valid, "both upgrade paths must leave a valid index"); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM events") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 1, "upgrade preserves old relay rows"); + } + } } diff --git a/crates/buzz-db/src/runtime/mod.rs b/crates/buzz-db/src/runtime/mod.rs index fa3f06961f7..5158954db5e 100644 --- a/crates/buzz-db/src/runtime/mod.rs +++ b/crates/buzz-db/src/runtime/mod.rs @@ -1,6 +1,7 @@ mod admitted_tx; mod cold_start; mod connection_observability; +mod history_reads; pub mod migration; pub(crate) mod observability; pub(crate) mod push_enqueue; @@ -64,7 +65,10 @@ pub(crate) async fn insert_mentions_in_transaction( .iter() .filter_map(|tag| { let tag_vec = tag.as_slice(); - if tag_vec.len() >= 2 && tag_vec[0] == "p" { + if tag_vec.len() >= 2 + && tag_vec[0] == "p" + && !buzz_core::filter::is_workflow_owner_attribution(event, tag) + { Some(tag_vec[1].as_str()) } else { None @@ -260,6 +264,9 @@ where #[derive(Clone, Debug)] pub struct Db { pub(crate) pool: PgPool, + /// Shared across clones; media authorization may use at most a quarter of + /// the writer pool (capped at eight), leaving capacity for ordinary writes. + pub(crate) media_authorization_slots: std::sync::Arc, /// Optional bounded post-commit producer, shared across handle clones. pub(crate) push_enqueue: Option, /// Maximum connections configured for this pool (from [`DbConfig::max_connections`]). @@ -292,10 +299,9 @@ pub struct Db { /// bounded-stale read semantics are a product decision, not an /// invariant, so the gate ships off. pub(crate) replica_read_max_age: Option, - /// Replica freshness budget used only by the leader's fleet telemetry - /// queries. This is independent of serving-read rollout policy: telemetry - /// may be stale or skipped, but it must never fall back to the writer. - pub(crate) usage_metrics_replica_max_age: Option, + /// Interval at which [`Db::spawn_fence_probe`]'s probe commits + /// heartbeat tokens ([`DbConfig::replica_fence_probe_interval_ms`]). + pub(crate) fence_probe_interval: Duration, /// Whether the reader endpoint supports the Aurora PostgreSQL identity /// function ([`replica_fence::AURORA_IDENTITY_FN`]) — probed /// once per process on the first routed read (on a plain autocommit @@ -303,6 +309,10 @@ pub struct Db { /// not yet probed (or the probe hit a transient error and will retry). /// Shared across `Db` clones. pub(crate) reader_aurora_identity: std::sync::Arc>, + /// Concurrency cap on replica-served subscription-history reads, sized + /// from [`Db::read_max_connections`] (see [`history_reads`]). Shared + /// across `Db` clones. + pub(crate) history_reads: crate::concurrency_gate::ConcurrencyGate, } /// The session that served (or will serve) a routed read, so follow-up @@ -330,7 +340,7 @@ pub(crate) enum ReadSessionInner { /// to the writer instead of surfacing an error: degraded capacity, /// never holes — and never a 500 the writer could have served. Replica { - tx: sqlx::Transaction<'static, sqlx::Postgres>, + tx: history_reads::ReaderTx, writer: PgPool, }, /// The writer pool (cheap clone; Arc-backed). @@ -352,7 +362,7 @@ impl ReadSession { pub async fn query_events(&mut self, q: &EventQuery) -> Result> { let degraded = match &mut self.inner { ReadSessionInner::Replica { tx, writer } => { - match event::query_events_on(tx, q).await { + match event::query_events_on(tx, q, event::ReadDeadline::Session).await { Ok(rows) => return Ok(rows), // Surface a cancel instead of re-running it on the writer; see // `DbError::is_statement_cancelled` for the trade-off. @@ -393,8 +403,11 @@ pub(crate) enum RouteDecision { /// replica, so a post-verification writer re-run or a mid-query replica /// failure emits exactly one `buzz_db_route_decision` event per request /// (the offload percentage is read straight off `decision="replica"`). + /// + /// A history read's transaction carries its [`history_reads`] permit, so + /// the permit is released when the transaction is dropped. Replica( - sqlx::Transaction<'static, sqlx::Postgres>, + history_reads::ReaderTx, replica_fence::TokenEntry, &'static str, ), @@ -569,6 +582,18 @@ fn read_budget_from_ms(ms: u64) -> Option { } } +/// Outcome of one reader-pool warm pass (see [`Db::warm_read_pool`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ReaderWarmReport { + /// Connections the pass aimed to hold: the pool's ceiling. + target: u32, + /// Connections held at the end of the pass, then released back to idle: + /// the ones it dialed plus any idle floor connections it reused. + held: u32, + /// Acquires that errored or timed out. + failed: u32, +} + /// Snapshot of Postgres connection pool utilisation. #[derive(Debug, Clone, Copy)] pub struct DbPoolStats { @@ -678,10 +703,14 @@ pub struct DbConfig { /// than the staleness gate never routes anyway, so a larger budget /// would only misrepresent the config. pub replica_read_max_age_ms: u64, - /// Replica freshness budget for usage telemetry, in milliseconds - /// (`BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS`). `0` disables fleet database - /// telemetry. This does not enable replica routing for serving reads. - pub usage_metrics_replica_max_age_ms: u64, + /// Replica fence heartbeat interval in milliseconds (env + /// `BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS`). `0` selects + /// [`replica_fence::DEFAULT_PROBE_INTERVAL`]; other values are clamped + /// to [`replica_fence::MIN_PROBE_INTERVAL`]..= + /// [`replica_fence::MAX_PROBE_INTERVAL`]. Only used when a read pool is + /// configured. The bounded-read budget should be at least + /// [`replica_fence::min_read_budget`] of this interval. + pub replica_fence_probe_interval_ms: u64, /// Session `lock_timeout` in milliseconds for writer connections (env /// `BUZZ_DB_LOCK_TIMEOUT_MS`). `0` disables the timeout. pub lock_timeout_ms: u64, @@ -714,10 +743,10 @@ impl Default for DbConfig { read_max_connections: None, min_connections: 2, acquire_timeout_secs: 3, - max_lifetime_secs: 1800, + max_lifetime_secs: 300, idle_timeout_secs: 600, replica_read_max_age_ms: 0, - usage_metrics_replica_max_age_ms: 30_000, + replica_fence_probe_interval_ms: 0, lock_timeout_ms: DEFAULT_LOCK_TIMEOUT_MS, idle_txn_timeout_ms: DEFAULT_IDLE_TXN_TIMEOUT_MS, statement_timeout_ms: DEFAULT_STATEMENT_TIMEOUT_MS, @@ -801,12 +830,24 @@ impl Db { None => None, }; let replica_read_max_age = read_budget_from_ms(config.replica_read_max_age_ms); - let usage_metrics_replica_max_age = - read_budget_from_ms(config.usage_metrics_replica_max_age_ms); + let fence_probe_interval = + replica_fence::probe_interval_from_ms(config.replica_fence_probe_interval_ms); + let min_read_budget = replica_fence::min_read_budget(fence_probe_interval); + if let Some(budget) = replica_read_max_age.filter(|b| *b < min_read_budget) { + tracing::warn!( + budget_ms = budget.as_millis() as u64, + probe_interval_ms = fence_probe_interval.as_millis() as u64, + recommended_min_ms = min_read_budget.as_millis() as u64, + "BUZZ_REPLICA_READ_MAX_AGE_MS cannot absorb one fence heartbeat that waits out \ + its lock timeout; bounded replica reads will spill to the writer whenever \ + a beat is late" + ); + } let push_enqueue = config .push_enabled .then(|| push_enqueue::PushEnqueue::new(&pool)); Ok(Self { + media_authorization_slots: media_authorization_slots(&pool), push_enqueue, pool, max_connections: config.max_connections, @@ -814,8 +855,9 @@ impl Db { read_max_connections, fence: std::sync::Arc::new(replica_fence::ReplicaFence::new()), replica_read_max_age, - usage_metrics_replica_max_age, + fence_probe_interval, reader_aurora_identity: std::sync::Arc::new(std::sync::OnceLock::new()), + history_reads: history_reads::gate_for_read_pool(read_max_connections), }) } @@ -827,6 +869,19 @@ impl Db { /// Additional writer pools, including the relay audit pool, must use this /// constructor so they inherit the timeout, floor-guard, and isolation /// policy installed by [`Db::new`]. + /// + /// Two single-connection side pools deliberately do not, so serving-pool + /// saturation cannot delay their work. Neither inserts into `events`, so + /// neither needs the `buzz.created_at_floor` guard, and each installs + /// its own shorter timeouts so it fails fast instead of queueing: + /// - [`replica_fence::connect_probe_pool`]: the fence probe takes the + /// floor lock itself (exclusive) and writes only `replica_heartbeat`. + /// - the push-enqueue pool (`push_enqueue::PushEnqueue::new`): it writes + /// only `push_match_queue`, and is lazy so relay startup never depends + /// on push. + /// + /// New pools follow the rule above unless they have a reason as specific + /// as these. pub async fn connect_writer_pool(config: &DbConfig) -> Result { use connection_observability::{ classify_pool_outcome, record_milestone, DbConnectionStep, DbConnectionStepAttempt, @@ -961,12 +1016,14 @@ impl Db { } /// Reader acquire timeout — deliberately far below the writer's - /// (seconds-denominated) timeout. Failing closed to the writer must be - /// fast: a saturated reader pool that made routed reads wait the full - /// writer-style timeout would add dead latency during exactly the load - /// spike the offload exists for. A miss here surfaces as - /// `writer/reader_acquire_timeout` (see [`Db::proved_reader`] for why - /// the reason names the mechanism rather than a diagnosis). + /// (seconds-denominated) timeout. A miss must resolve fast: a saturated + /// reader pool that made routed reads wait the full writer-style timeout + /// would add dead latency during exactly the load spike the offload + /// exists for. A miss surfaces as `writer/reader_acquire_timeout`, or as + /// `rejected/reader_acquire_timeout` for a history read, which is not + /// moved to the writer (see [`Db::route_read`], and + /// [`Db::proved_reader`] for why the reason names the mechanism rather + /// than a diagnosis). const READER_ACQUIRE_TIMEOUT: Duration = Duration::from_millis(150); /// Client-side bound on a routed read's fence proof (Aurora capability @@ -986,8 +1043,11 @@ impl Db { /// (the reader logs `could not accept SSL connection: EOF detected`), the /// read falls back to the writer, and the next read dials again. Under a /// fleet-wide burst that loop turns brief reader slowness into writer pool - /// exhaustion. The floor is per relay process: size the reader's - /// `max_connections` for the floor times the number of relay processes. + /// exhaustion. The floor is per relay process, but every boot also + /// warms the pool to its ceiling ([`Db::warm_read_pool`]) and keeps the + /// surplus until `idle_timeout` reaps it: size the reader's + /// `max_connections` for the ceiling times the number of relay + /// processes, counting old and new pods that overlap in a rolling deploy. fn reader_min_connections(max_connections: u32) -> u32 { (max_connections / 5).max(1).min(max_connections) } @@ -1040,40 +1100,30 @@ impl Db { options.options([("default_transaction_isolation", "read committed")]) } - /// Upper bound on a reader connection's release check (see - /// [`Db::read_pool_options`]); matches sqlx's own close-on-drop bound. - const READER_RELEASE_TIMEOUT: Duration = Duration::from_secs(5); + /// Leave headroom inside SQLx's five-second whole-return deadline so this + /// check records the reason before SQLx cancels the release future. + const READER_RELEASE_TIMEOUT: Duration = Duration::from_secs(4); /// Reader pool options apart from connection lifetimes (see /// [`Db::connect_read_pool`]). /// /// Every checkout that goes back to the pool first passes a release - /// check bounded by [`Db::READER_RELEASE_TIMEOUT`]. sqlx's own release - /// ping has no timeout, so a socket whose reader stopped answering - /// without closing it (a failover, a partition) would otherwise hold its - /// slot until the kernel gives up on it; with every slot held that way, - /// the pool cannot dial the reader that replaced it. A check that times - /// out or errors closes the socket and frees the slot, and sqlx's floor - /// maintenance dials a replacement. + /// check bounded by [`Db::READER_RELEASE_TIMEOUT`]. A check that times + /// out or errors records the reason, closes the socket, and frees the + /// slot. SQLx bounds the whole return, including its subsequent ping, + /// so a reader that stops answering without closing cannot strand pool + /// capacity. Its floor maintenance dials a replacement. /// /// The check also closes, rather than returns, a connection still inside - /// a transaction. A checkout dropped while its `BEGIN` was in flight (a - /// timed-out proof, a cancelled caller) has no `ROLLBACK` queued: sqlx - /// counts the transaction only once `BEGIN` is acknowledged. Once the - /// reader answers, that connection would otherwise go back to the pool + /// a transaction. sqlx rolls back a checkout dropped while its `BEGIN` + /// was in flight (a timed-out proof, a cancelled caller) since + /// transact-rs/sqlx#4394, so this is a backstop: a connection that still + /// came back inside a transaction would otherwise go back to the pool /// `idle in transaction`. Closing it ends the session, and the server /// rolls the transaction back. Routed reads only begin `REPEATABLE READ` /// (see [`Db::proved_reader`]) and reader sessions default to `READ /// COMMITTED` (see [`Db::reader_connect_options`]), so an isolation level /// other than the session default means a transaction is still open. - /// - /// Residual window: after the check passes, sqlx sends its own release - /// ping, which has no timeout. A reader that goes silent in that one - /// round trip strands that one slot until the socket fails. That is - /// bounded by the releases in flight at that instant, and later checkouts - /// of silent connections go through the proof timeout and this check. - /// Checkouts that must never strand a slot use `close_on_drop` (see - /// `ReaderOperation::bounded_release`). pub(crate) fn read_pool_options(max_connections: u32) -> PgPoolOptions { PgPoolOptions::new() .max_connections(max_connections) @@ -1081,14 +1131,7 @@ impl Db { .test_before_acquire(false) .acquire_timeout(Self::READER_ACQUIRE_TIMEOUT) .after_connect(|conn, _meta| { - Box::pin(async move { - sqlx::query(crate::event::TIGHTEN_STATEMENT_TIMEOUT_SQL) - .bind(crate::event::READ_STATEMENT_TIMEOUT) - .bind(false) - .execute(&mut *conn) - .await - .map(|_| ()) - }) + Box::pin(crate::event::tighten_session_read_statement_timeout(conn)) }) .after_release(|conn, _meta| Box::pin(Self::reader_release_check(conn))) } @@ -1135,6 +1178,9 @@ impl Db { /// pool up to [`Db::reader_min_connections`] in the background, so a /// freshly started pod does not meet its first traffic with an empty /// reader pool and pay every dial inside the 150ms request budget. + /// It then warms the pool toward its ceiling ([`Db::warm_read_pool`]), + /// still in the spawned task: a failed or partial warm only logs and + /// never affects startup or readiness. /// Probe acquires that overrun that budget are retried with /// [`Db::READER_BOOT_PROBE_BACKOFF`]. /// @@ -1150,7 +1196,150 @@ impl Db { return; }; let aurora_identity = self.reader_aurora_identity.clone(); - tokio::spawn(Self::read_pool_boot_ping_once(read_pool, aurora_identity)); + tokio::spawn(Self::read_pool_boot_ping_then_warm( + read_pool, + aurora_identity, + )); + } + + /// Connections each warm wave dials at once. Small enough that a pod + /// starting alongside its peers does not stampede the reader with + /// simultaneous TCP+TLS+SCRAM handshakes (a stampede is what pushes a + /// dial past [`Db::READER_ACQUIRE_TIMEOUT`]), large enough that a full + /// pool is warm within a handful of dial times. sqlx's floor maintenance, + /// triggered by the boot ping, dials alongside the first wave, so a + /// booting pod can have up to the floor plus this many dials in flight. + const READER_WARM_CONCURRENCY: u32 = 5; + + /// Connections the next warm wave should open: the remaining shortfall, + /// at most [`Db::READER_WARM_CONCURRENCY`]. + fn reader_warm_wave_size(target: u32, held: u32) -> u32 { + target + .saturating_sub(held) + .min(Self::READER_WARM_CONCURRENCY) + } + + /// The boot ping, then (only if the reader answered) a warm pass. + /// + /// Returns `None` when the ping found the reader unreachable: warming a + /// pool whose reader is down would only add abandoned dials. + async fn read_pool_boot_ping_then_warm( + read_pool: PgPool, + aurora_identity: std::sync::Arc>, + ) -> Option { + if !Self::read_pool_boot_ping_once(read_pool.clone(), aurora_identity).await { + return None; + } + let started = std::time::Instant::now(); + let report = Self::warm_read_pool(&read_pool).await; + let elapsed_ms = started.elapsed().as_millis() as u64; + if report.held < report.target { + tracing::warn!( + ceiling = report.target, + held = report.held, + failed = report.failed, + elapsed_ms, + "read pool warm-up holds fewer connections than its ceiling; \ + the rest dial on demand (warm-up is best effort)" + ); + } else { + tracing::info!( + ceiling = report.target, + held = report.held, + failed = report.failed, + elapsed_ms, + "read pool warmed to its ceiling" + ); + } + Some(report) + } + + /// Open the reader pool toward its ceiling, once, then release every + /// connection back to the pool idle. + /// + /// Why: the boot ping leaves only the warm floor + /// ([`Db::reader_min_connections`]). A pod that meets a reconnect burst + /// with that floor dials the rest inside [`Db::READER_ACQUIRE_TIMEOUT`], + /// overruns it, and serves the read from the writer. Warming moves those + /// dials off the request path. sqlx's idle reaper closes the surplus + /// after `idle_timeout`, back down to the floor, so no reaping logic + /// lives here. + /// + /// Connections are held until the pass ends (an acquire from a pool + /// with an idle connection reuses it instead of dialing) and dropped + /// rather than `close_on_drop`ped, so they return idle. Bounded: a + /// single pass of bounded waves of [`Db::READER_WARM_CONCURRENCY`] + /// dials (see [`Db::warm_toward`]), each acquire bounded by the pool's + /// own acquire timeout ([`Db::READER_ACQUIRE_TIMEOUT`]). sqlx counts the + /// dial inside that timeout, so a dial slower than the request budget is + /// dropped and counts as a failed acquire, exactly as it would on the + /// request path. A wave that opens nothing (the reader is down, + /// saturated, or dialing slower than the budget) ends the pass. There is + /// no backoff and no second pass. + /// + /// Uses plain `acquire`, not the instrumented reader acquire: warm + /// misses must not inflate the `buzz_db_reader_*` acquire-timeout + /// signal that the fallback alerts watch. The pool gauges + /// (`buzz_db_read_pool_*`) show the result. + /// + /// Holding connections briefly lowers the capacity left for routed + /// reads: until the pass ends it holds every reader connection, + /// including the floor. The window is a few dial times, usually before + /// the pod takes traffic. Nothing orders it before serving, though: + /// boot-probe retries ([`Db::READER_BOOT_PROBE_BACKOFF`]) can push it + /// past the listener bind, so it can briefly overlap traffic. A routed + /// read that misses in it falls back to the writer, as it would on any + /// exhausted pool. + async fn warm_read_pool(read_pool: &PgPool) -> ReaderWarmReport { + let target = read_pool.options().get_max_connections(); + let (held, failed) = + Self::warm_toward(target, || async { read_pool.acquire().await.ok() }).await; + let report = ReaderWarmReport { + target, + held: held.len() as u32, + failed, + }; + // Dropping returns each connection to the pool idle (after the + // reader release check); it does not close it. + drop(held); + report + } + + /// The warm pass's loop, apart from the pool: runs `acquire` in waves of + /// at most [`Db::READER_WARM_CONCURRENCY`] until `target` connections are + /// held, and returns them with the number of failed acquires (`None`). + /// + /// Each wave tops up the remaining shortfall, so an acquire that missed + /// its deadline in one wave is covered by the next. Bounded three ways: + /// at most twice the waves a failure-free pass needs, so a reader that + /// admits only some dials cannot keep the pass running; a wave that + /// holds nothing new ends it; and no wave dials more than the shortfall. + /// There is no sleep or backoff between waves. + async fn warm_toward(target: u32, mut acquire: F) -> (Vec, u32) + where + F: FnMut() -> Fut, + Fut: std::future::Future>, + { + let mut held = Vec::new(); + let mut failed = 0_u32; + let max_waves = target.div_ceil(Self::READER_WARM_CONCURRENCY) * 2; + for _ in 0..max_waves { + let wave = Self::reader_warm_wave_size(target, held.len() as u32); + if wave == 0 { + break; + } + let held_before = held.len(); + for result in futures_util::future::join_all((0..wave).map(|_| acquire())).await { + match result { + Some(conn) => held.push(conn), + None => failed += 1, + } + } + if held.len() == held_before { + break; + } + } + (held, failed) } /// Backoff before each boot-probe retry after an acquire that overran @@ -1165,10 +1354,11 @@ impl Db { Duration::from_secs(2), ]; + /// Returns whether the reader answered. async fn read_pool_boot_ping_once( read_pool: PgPool, aurora_identity: std::sync::Arc>, - ) { + ) -> bool { let mut backoff = Self::READER_BOOT_PROBE_BACKOFF.into_iter(); let mut conn = loop { let error = match observability::acquire_reader_with_legacy_metrics( @@ -1186,7 +1376,7 @@ impl Db { tracing::warn!( "read replica unreachable at boot; serving all-writer until it recovers: {e}" ); - return; + return false; } } }; @@ -1205,6 +1395,7 @@ impl Db { // in the background under its own 300s deadline, outside the 150ms // request budget, releasing each connection idle as it lands. conn.close_on_drop(); + true } #[cfg(test)] @@ -1221,14 +1412,16 @@ impl Db { /// that need push must use [`Db::new`] with `push_enabled` instead. pub fn from_pool(pool: PgPool) -> Self { Self { + media_authorization_slots: media_authorization_slots(&pool), push_enqueue: None, max_connections: pool.options().get_max_connections(), read_max_connections: pool.options().get_max_connections(), + history_reads: history_reads::gate_for_read_pool(pool.options().get_max_connections()), pool, read_pool: None, fence: std::sync::Arc::new(replica_fence::ReplicaFence::new()), replica_read_max_age: None, - usage_metrics_replica_max_age: None, + fence_probe_interval: replica_fence::DEFAULT_PROBE_INTERVAL, reader_aurora_identity: std::sync::Arc::new(std::sync::OnceLock::new()), } } @@ -1242,14 +1435,18 @@ impl Db { /// [`Db::fence`]). pub fn from_pools(pool: PgPool, read_pool: PgPool) -> Self { Self { + media_authorization_slots: media_authorization_slots(&pool), push_enqueue: None, max_connections: pool.options().get_max_connections(), read_max_connections: read_pool.options().get_max_connections(), pool, + history_reads: history_reads::gate_for_read_pool( + read_pool.options().get_max_connections(), + ), read_pool: Some(read_pool), fence: std::sync::Arc::new(replica_fence::ReplicaFence::new()), replica_read_max_age: None, - usage_metrics_replica_max_age: Some(replica_fence::FENCE_STALENESS), + fence_probe_interval: replica_fence::DEFAULT_PROBE_INTERVAL, reader_aurora_identity: std::sync::Arc::new(std::sync::OnceLock::new()), } } @@ -1286,9 +1483,12 @@ impl Db { return Ok(false); } self.verify_replica_fence_at_boot().await?; + // The probe gets its own connection so serving-pool saturation + // cannot delay the beat (see `replica_fence::connect_probe_pool`). tokio::spawn(replica_fence::run_probe( - self.pool.clone(), + replica_fence::connect_probe_pool(&self.pool), std::sync::Arc::clone(&self.fence), + self.fence_probe_interval, )); Ok(true) } @@ -1322,6 +1522,13 @@ impl Db { self.read_pool.is_some() } + /// The cap on concurrent subscription-history reads (see + /// [`history_reads`]). Its ceiling is the share of the reader pool that + /// leaves room for authorization reads; operators may lower it at runtime. + pub fn history_read_gate(&self) -> &crate::concurrency_gate::ConcurrencyGate { + &self.history_reads + } + /// Open a reader request transaction and complete the connection-local /// half of the fence proof: `BEGIN ISOLATION LEVEL REPEATABLE READ, READ /// ONLY`, then observe the heartbeat token/epoch as the transaction's @@ -1355,7 +1562,7 @@ impl Db { // `read_pool` separately would spend a second budget whenever the // capability is uncached — i.e. after a failed boot ping, which is // precisely the reader-unavailable case the bound must hold for. - let conn = + let mut conn = match observability::acquire_reader_with_legacy_metrics(read_pool, operation).await { Ok(conn) => conn, Err(sqlx::Error::PoolTimedOut) => { @@ -1367,12 +1574,6 @@ impl Db { return Err("reader_validation_error"); } }; - let mut conn = conn; - if operation.bounded_release() { - // Must precede the first post-acquire await: a caller deadline - // can drop this checkout at any of them. - conn.close_on_drop(); - } // The proof is the reader's first wire round trip (no pre-acquire // ping, see `connect_read_pool`), so it carries the liveness bound: // a half-open socket to a vanished reader would otherwise hang the @@ -1480,6 +1681,32 @@ impl Db { } } + /// Count one routed read the replica could have served that the writer + /// served instead (`buzz_db_reader_spill_total{path, reason}`). + /// + /// A subset of `buzz_db_route_decision{decision="writer"}` that leaves + /// out configuration (`disabled`) and splits its ambiguous `stale` + /// reason by cause. Reasons: + /// - `heartbeat_stale`: the newest heartbeat is older than the + /// bounded-read budget (`BUZZ_REPLICA_READ_MAX_AGE_MS`) — the probe + /// is late, not the replica; + /// - `heartbeat_missing`: no live heartbeat proof at all (the probe has + /// not committed one, or none in [`replica_fence::FENCE_STALENESS`]); + /// - `fence_wall_behind`: the read's upper bound is newer than the + /// newest fence wall; + /// - `replica_lag`: the serving session proved only an older entry than + /// the read needs; + /// - `reader_acquire_timeout`, `reader_proof_timeout`, + /// `reader_token_behind`, `reader_validation_error`: the reader + /// session could not be checked out or could not prove the fence. + /// + /// History reads rejected on a saturated reader are not spills; they + /// stay `buzz_db_route_decision{decision="rejected"}`. + fn record_spill(path: &'static str, reason: &'static str) { + metrics::counter!("buzz_db_reader_spill_total", "path" => path, "reason" => reason) + .increment(1); + } + /// Record one route decision (Rev 2 observability): which path, where it /// went, and why. pub(crate) fn record_route(path: &'static str, decision: &'static str, reason: &'static str) { @@ -1700,73 +1927,60 @@ impl Db { Ok(result) } - /// Route a usage-telemetry query only to a proved, sufficiently fresh - /// reader. Unlike serving reads, an unavailable reader is recorded as - /// skipped and never represented as or executed on the writer. - pub(crate) async fn route_usage_read( - &self, - path: &'static str, - ) -> Option<(sqlx::Transaction<'static, sqlx::Postgres>, &'static str)> { - let skip = |reason| { - Self::record_route(path, "skipped", reason); - None - }; - let Some(read_pool) = &self.read_pool else { - return skip("disabled"); - }; - let Some(budget) = self.usage_metrics_replica_max_age else { - return skip("disabled"); - }; - let Some(newest) = self.fence.newest() else { - return skip("uninitialized"); - }; - if newest.committed_at.elapsed() > budget { - return skip("stale"); - } - match self - .proved_reader(read_pool, observability::ReaderOperation::Maintenance) - .await - { - Ok((tx, entry)) if entry.committed_at.elapsed() <= budget => Some((tx, "fresh")), - Ok((_tx, _entry)) => skip("stale"), - Err(reason) => skip(reason), - } - } - /// Shared route decision for one read: evaluate the predicate against a /// proved reader session and record the decision. Fail closed to the - /// writer everywhere. + /// writer, with one exception for subscription-history reads. + /// + /// History reads are the heavy, high-volume routed reads. They hold a + /// [`history_reads`] permit for as long as their reader transaction, so + /// they never fill the reader pool, and they are never moved to the + /// writer merely because the reader is busy: a history read that waits + /// out its permit ([`history_reads::PERMIT_WAIT`]) or + /// its reader acquire ([`Db::READER_ACQUIRE_TIMEOUT`]) on a saturated + /// reader pool ([`Db::reader_saturated`]) is rejected with + /// [`sqlx::Error::PoolTimedOut`], which the relay answers with its + /// retryable `CLOSED`. Spilling that load onto the writer starved the + /// authentication, tenant and moderation reads only the writer serves. + /// A reader that is wrong rather than busy (unreachable, validation + /// failure, proof timeout, stale token) still falls back to the writer, + /// as do prechecks that never reach the reader. Recorded as + /// `decision="rejected"` with `reason="history_read_cap"` or + /// `"reader_acquire_timeout"`. pub(crate) async fn route_read( &self, path: &'static str, predicate: RoutePredicate, operation: observability::ReaderOperation, - ) -> RouteDecision { + ) -> Result { let Some(read_pool) = &self.read_pool else { Self::record_route(path, "writer", "disabled"); - return RouteDecision::Writer; + return Ok(RouteDecision::Writer); }; // Cheap prechecks on the shared ring before spending a reader // checkout; the connection-local observation still has to prove it. let Some(newest) = self.fence.newest() else { Self::record_route(path, "writer", "uninitialized"); - return RouteDecision::Writer; + Self::record_spill(path, "heartbeat_missing"); + return Ok(RouteDecision::Writer); }; // Precheck helpers against the newest shared entry: if the newest - // cannot satisfy an arm, no proved (older-or-equal) entry can. - let bounded_precheck = - |budget: &Option| -> std::result::Result<(), &'static str> { - match budget { - Some(budget) if newest.committed_at.elapsed() <= *budget => Ok(()), - Some(_) => Err("stale"), - None => Err("disabled"), - } - }; - let covered_precheck = |upper: &DateTime| -> std::result::Result<(), &'static str> { + // cannot satisfy an arm, no proved (older-or-equal) entry can. Each + // failure carries its `buzz_db_route_decision` reason and, when the + // read is a spill rather than a configuration choice, its + // `buzz_db_reader_spill_total` reason. + type Precheck = std::result::Result<(), (&'static str, Option<&'static str>)>; + let bounded_precheck = |budget: &Option| -> Precheck { + match budget { + Some(budget) if newest.committed_at.elapsed() <= *budget => Ok(()), + Some(_) => Err(("stale", Some("heartbeat_stale"))), + None => Err(("disabled", None)), + } + }; + let covered_precheck = |upper: &DateTime| -> Precheck { if *upper <= newest.fence_wall { Ok(()) } else { - Err("stale") + Err(("stale", Some("fence_wall_behind"))) } }; let precheck = match &predicate { @@ -1774,15 +1988,31 @@ impl Db { RoutePredicate::Covered { upper, .. } => covered_precheck(upper), // No upper bound: the caller post-verifies served rows. RoutePredicate::CoveredPostVerified { .. } => Ok(()), - // Covered first (no budget dependence), else bounded. + // Covered first (no budget dependence), else bounded. With the + // bounded arm disabled the read still spilled for its wall. RoutePredicate::BoundedOrCovered { upper, .. } => { - covered_precheck(upper).or_else(|_| bounded_precheck(&self.replica_read_max_age)) + covered_precheck(upper).or_else(|(_, covered_spill)| { + bounded_precheck(&self.replica_read_max_age) + .map_err(|(reason, spill)| (reason, spill.or(covered_spill))) + }) } }; - if let Err(reason) = precheck { + if let Err((reason, spill)) = precheck { Self::record_route(path, "writer", reason); - return RouteDecision::Writer; + if let Some(spill) = spill { + Self::record_spill(path, spill); + } + return Ok(RouteDecision::Writer); } + let history = operation == observability::ReaderOperation::SubscriptionHistory; + let permit = if history { + let Some(permit) = self.history_reads.admit(history_reads::PERMIT_WAIT).await else { + return Err(Self::reject_history_read(path, "history_read_cap")); + }; + Some(permit) + } else { + None + }; match self.proved_reader(read_pool, operation).await { Ok((tx, entry)) => { // Re-evaluate against the entry the session actually proved @@ -1808,21 +2038,165 @@ impl Db { } }; match verdict { - Some(reason) => RouteDecision::Replica(tx, entry, reason), + Some(reason) => Ok(RouteDecision::Replica( + history_reads::ReaderTx::new(tx, permit), + entry, + reason, + )), None => { // The session proves an older entry than the // predicate needs (replication lag) — fail closed. Self::record_route(path, "writer", "stale"); - RouteDecision::Writer + Self::record_spill(path, "replica_lag"); + Ok(RouteDecision::Writer) } } } + Err(reason @ "reader_acquire_timeout") + if history && Self::reader_saturated(read_pool) => + { + Err(Self::reject_history_read(path, reason)) + } Err(reason) => { Self::record_route(path, "writer", reason); - RouteDecision::Writer + Self::record_spill(path, reason); + Ok(RouteDecision::Writer) + } + } + } + + /// Whether a reader acquire timeout means the reader is busy rather than + /// unreachable: every connection the pool may hold exists and none is + /// idle. `PoolTimedOut` alone cannot tell them apart, because sqlx keeps + /// retrying a refused or failing dial until the acquire budget runs out. + /// A reader that refuses or drops dials leaves the pool below its ceiling, + /// so its history reads still fall back to the writer. A reader that + /// accepts no TCP at all can fill the ceiling with in-flight dials and + /// read as busy; those reads are rejected as retryable, the same outcome + /// as a full gate. + fn reader_saturated(read_pool: &PgPool) -> bool { + read_pool.size() >= read_pool.options().get_max_connections() && read_pool.num_idle() == 0 + } + + /// Record a rejected history read (see [`Db::route_read`]) and build its + /// retryable error. + fn reject_history_read(path: &'static str, reason: &'static str) -> DbError { + Self::record_route(path, "rejected", reason); + DbError::Sqlx(sqlx::Error::PoolTimedOut) + } +} + +#[cfg(test)] +mod reader_warm_tests { + use super::{Db, ReaderWarmReport}; + use std::sync::{Arc, OnceLock}; + + /// A lazy reader pool whose server accepts TCP and immediately closes + /// it, so every dial fails fast without Postgres. + async fn dead_reader_pool(max_connections: u32) -> sqlx::PgPool { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind loopback listener"); + let port = listener.local_addr().expect("listener address").port(); + tokio::spawn(async move { + while let Ok((socket, _)) = listener.accept().await { + drop(socket); } + }); + let url = format!("postgres://u@127.0.0.1:{port}/db?sslmode=disable"); + let options: sqlx::postgres::PgConnectOptions = url.parse().expect("parse url"); + Db::read_pool_options(max_connections).connect_lazy_with(options) + } + + /// Table test for the wave sizing: the remaining shortfall, capped at the + /// concurrency bound, never underflowing once the target is met. + #[test] + fn warm_wave_size_is_the_shortfall_capped_at_the_concurrency_bound() { + let c = Db::READER_WARM_CONCURRENCY; + for (target, held, expected) in [ + (25, 0, c), + (25, 20, c), + (25, 22, 3), + (25, 24, 1), + (25, 25, 0), + (25, 30, 0), + (1, 0, 1), + (0, 0, 0), + ] { + assert_eq!( + Db::reader_warm_wave_size(target, held), + expected, + "target={target} held={held}" + ); } } + + /// A fake acquire that succeeds when `ok(call_index)` says so, counting + /// every call. + fn counting_acquire( + calls: &std::sync::atomic::AtomicU32, + ok: impl Fn(u32) -> bool, + ) -> impl std::future::Future> { + let n = calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + std::future::ready(ok(n).then_some(n)) + } + + /// With every dial succeeding the pass opens exactly the target, no more. + #[tokio::test] + async fn warm_toward_opens_exactly_the_target() { + let calls = std::sync::atomic::AtomicU32::new(0); + let (held, failed) = Db::warm_toward(25, || counting_acquire(&calls, |_| true)).await; + assert_eq!((held.len(), failed), (25, 0)); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 25); + } + + /// A reader that admits one dial per wave cannot keep the pass running: + /// attempts stop at twice the waves a clean pass needs (target 25, wave + /// 5: 10 waves of 5), well short of the shortfall-driven 25 waves. + #[tokio::test] + async fn warm_toward_is_bounded_when_dials_keep_missing() { + let calls = std::sync::atomic::AtomicU32::new(0); + let w = Db::READER_WARM_CONCURRENCY; + let (held, failed) = Db::warm_toward(25, || counting_acquire(&calls, |n| n % w == 0)).await; + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 50); + assert_eq!((held.len(), failed), (10, 40)); + } + + /// A wave that misses some dials is topped up by the next, so a slow + /// first wave does not leave the pool short. + #[tokio::test] + async fn warm_toward_tops_up_a_partially_failed_wave() { + let calls = std::sync::atomic::AtomicU32::new(0); + let (held, failed) = Db::warm_toward(10, || counting_acquire(&calls, |n| n != 1)).await; + assert_eq!((held.len(), failed), (10, 1)); + } + + /// A reader that refuses every dial ends the pass after one wave: warming + /// is a single bounded attempt, not a loop that hammers a dead reader + /// `target` times. + #[tokio::test] + async fn warm_pass_stops_after_one_wave_that_opens_nothing() { + let pool = dead_reader_pool(25).await; + let report = Db::warm_read_pool(&pool).await; + assert_eq!( + report, + ReaderWarmReport { + target: 25, + held: 0, + failed: Db::READER_WARM_CONCURRENCY, + } + ); + } + + /// An unreachable reader at boot is not warmed: the ping's failure ends + /// the task before any warm dial, and nothing panics or errors. + #[tokio::test] + async fn unreachable_reader_skips_the_warm_pass() { + let pool = dead_reader_pool(25).await; + let report = + Db::read_pool_boot_ping_then_warm(pool.clone(), Arc::new(OnceLock::new())).await; + assert_eq!(report, None); + } } #[cfg(test)] @@ -1879,3 +2253,9 @@ mod pool_role_tests { #[cfg(test)] #[path = "tests.rs"] mod postgres_tests; + +fn media_authorization_slots(pool: &PgPool) -> std::sync::Arc { + std::sync::Arc::new(tokio::sync::Semaphore::new( + (pool.options().get_max_connections() as usize / 4).clamp(1, 8), + )) +} diff --git a/crates/buzz-db/src/runtime/observability.rs b/crates/buzz-db/src/runtime/observability.rs index 6117eb78357..f8598d5606a 100644 --- a/crates/buzz-db/src/runtime/observability.rs +++ b/crates/buzz-db/src/runtime/observability.rs @@ -2,6 +2,9 @@ //! //! Label values come only from the closed enums in this module. Callers must //! never derive labels from tenant data, events, SQL text, or query identifiers. +//! The one exception is the advisory-lock `kind` label: the event kind of the +//! locked coordinate, bounded by the kind registry +//! (`buzz_core::kind::registered_kind_label`). use std::future::Future; use std::sync::Mutex; @@ -28,7 +31,6 @@ enum PoolOperation { ReaderSubscriptionHistory, WriterEventWrite, WriterMaintenance, - ReaderMaintenance, } /// Writer-pool operations. Reader-only combinations cannot be constructed. @@ -77,17 +79,14 @@ pub(crate) enum ReaderOperation { Bootstrap, Authorization, SubscriptionHistory, - /// Leader-only background reads such as fleet usage telemetry. - Maintenance, } impl ReaderOperation { #[cfg(test)] - const ALL: [Self; 4] = [ + const ALL: [Self; 3] = [ Self::Bootstrap, Self::Authorization, Self::SubscriptionHistory, - Self::Maintenance, ]; const fn pair(self) -> PoolOperation { @@ -95,26 +94,12 @@ impl ReaderOperation { Self::Bootstrap => PoolOperation::ReaderBootstrap, Self::Authorization => PoolOperation::ReaderAuthorization, Self::SubscriptionHistory => PoolOperation::ReaderSubscriptionHistory, - Self::Maintenance => PoolOperation::ReaderMaintenance, } } - - /// Whether a dropped checkout must close the connection under SQLx's - /// bounded `close_on_drop` instead of returning it to the pool. - /// - /// Maintenance reads run under relay-side deadlines that drop them - /// mid-query when a reader goes dark, and the reader pool is shared with - /// serving reads. The pool's release check is bounded, but SQLx's own - /// release ping after it is not, so a returned connection whose reader - /// goes silent in that window still strands its slot. Close-on-drop - /// bounds the whole release. Serving reads keep pooled reuse. - pub(crate) const fn bounded_release(self) -> bool { - matches!(self, Self::Maintenance) - } } impl PoolOperation { - pub(crate) const ALL: [Self; 12] = [ + pub(crate) const ALL: [Self; 11] = [ Self::WriterBootstrap, Self::ReaderBootstrap, Self::WriterReadiness, @@ -126,15 +111,13 @@ impl PoolOperation { Self::ReaderSubscriptionHistory, Self::WriterEventWrite, Self::WriterMaintenance, - Self::ReaderMaintenance, ]; pub(crate) const fn pool_role(self) -> &'static str { match self { - Self::ReaderBootstrap - | Self::ReaderAuthorization - | Self::ReaderSubscriptionHistory - | Self::ReaderMaintenance => DbPoolRole::Reader.as_str(), + Self::ReaderBootstrap | Self::ReaderAuthorization | Self::ReaderSubscriptionHistory => { + DbPoolRole::Reader.as_str() + } _ => DbPoolRole::Writer.as_str(), } } @@ -150,7 +133,7 @@ impl PoolOperation { "subscription_history" } Self::WriterEventWrite => "event_write", - Self::WriterMaintenance | Self::ReaderMaintenance => "maintenance", + Self::WriterMaintenance => "maintenance", } } @@ -159,7 +142,7 @@ impl PoolOperation { } } -pub(crate) const POOL_ACQUIRE_VALID_PAIRS: [(&str, &str); 12] = [ +pub(crate) const POOL_ACQUIRE_VALID_PAIRS: [(&str, &str); 11] = [ (DbPoolRole::Writer.as_str(), "bootstrap"), (DbPoolRole::Reader.as_str(), "bootstrap"), (DbPoolRole::Writer.as_str(), "readiness"), @@ -171,10 +154,9 @@ pub(crate) const POOL_ACQUIRE_VALID_PAIRS: [(&str, &str); 12] = [ (DbPoolRole::Reader.as_str(), "subscription_history"), (DbPoolRole::Writer.as_str(), "event_write"), (DbPoolRole::Writer.as_str(), "maintenance"), - (DbPoolRole::Reader.as_str(), "maintenance"), ]; -/// Twelve valid pairs × (12 histogram series + 1 start counter + 4 outcome counters + 1 gauge). +/// Eleven valid pairs × (12 histogram series + 1 start counter + 4 outcome counters + 1 gauge). pub(crate) const POOL_ACQUIRE_RAW_SERIES_PER_POD: usize = POOL_ACQUIRE_VALID_PAIRS.len() * 18; #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -313,17 +295,21 @@ fn record_pool_acquire( ) { // Preserve the original observed population for existing dashboards. // Newly instrumented raw-pool seams must not create a deployment-time - // discontinuity in these compatibility families. + // discontinuity in these compatibility families. They carry `operation` + // so a breakdown by it attributes every sample instead of reporting it + // as unlabelled; summing over `operation` gives the original series. if emit_legacy && outcome != Outcome::Cancelled { metrics::histogram!( "buzz_db_pool_acquire_wait_seconds", "pool_role" => pair.pool_role(), + "operation" => pair.operation(), "outcome" => outcome.as_str(), ) .record(elapsed.as_secs_f64()); metrics::counter!( "buzz_db_pool_acquisitions_total", "pool_role" => pair.pool_role(), + "operation" => pair.operation(), "outcome" => outcome.as_str(), ) .increment(1); @@ -556,7 +542,47 @@ pub(crate) async fn begin_transaction( Ok((transaction, TransactionTimer::start(operation))) } +/// `kind` label of an advisory lock that no event kind keys. +const UNKEYED_LOCK_KIND: &str = "none"; + +/// Observe an advisory-lock wait whose key has no event kind; it records +/// `kind="none"`. Locks keyed by an event coordinate, including every +/// replacement lock, use [`observe_event_lock`]. pub(crate) async fn observe_advisory_lock(lock_type: LockType, future: F) -> sqlx::Result +where + F: Future>, +{ + debug_assert_ne!( + lock_type, + LockType::Replacement, + "replacement locks carry an event kind; use observe_event_lock" + ); + observe_lock(lock_type, UNKEYED_LOCK_KIND.into(), future).await +} + +/// Observe an advisory-lock wait on a coordinate of event `kind`. The `kind` +/// label is the registered kind, or `other` for an unregistered one. +pub(crate) async fn observe_event_lock( + lock_type: LockType, + kind: i32, + future: F, +) -> sqlx::Result +where + F: Future>, +{ + observe_lock( + lock_type, + buzz_core::kind::registered_kind_label(kind).into(), + future, + ) + .await +} + +async fn observe_lock( + lock_type: LockType, + kind: metrics::SharedString, + future: F, +) -> sqlx::Result where F: Future>, { @@ -569,12 +595,14 @@ where metrics::histogram!( "buzz_db_advisory_lock_wait_seconds", "lock_type" => lock_type.as_str(), + "kind" => kind.clone(), "outcome" => outcome.as_str(), ) .record(started.elapsed().as_secs_f64()); metrics::counter!( "buzz_db_advisory_lock_acquisitions_total", "lock_type" => lock_type.as_str(), + "kind" => kind, "outcome" => outcome.as_str(), ) .increment(1); @@ -623,9 +651,9 @@ impl Drop for TransactionTimer { mod tests { use super::{ acquire_reader_with_legacy_metrics, acquire_writer, acquire_writer_with_legacy_metrics, - begin_transaction, observe_advisory_lock, record_pool_acquire, refresh_pool_waiters, - LockType, Outcome, PoolAcquireAttempt, PoolOperation, ReaderOperation, - TransactionOperation, TransactionTimer, WriterOperation, + begin_transaction, observe_advisory_lock, observe_event_lock, record_pool_acquire, + refresh_pool_waiters, LockType, Outcome, PoolAcquireAttempt, PoolOperation, + ReaderOperation, TransactionOperation, TransactionTimer, WriterOperation, }; use metrics_util::debugging::{DebugValue, DebuggingRecorder}; use std::collections::{BTreeMap, BTreeSet}; @@ -657,10 +685,9 @@ mod tests { PoolOperation::ReaderBootstrap, PoolOperation::ReaderAuthorization, PoolOperation::ReaderSubscriptionHistory, - PoolOperation::ReaderMaintenance, ] ); - assert_eq!(super::POOL_ACQUIRE_RAW_SERIES_PER_POD, 216); + assert_eq!(super::POOL_ACQUIRE_RAW_SERIES_PER_POD, 198); assert_eq!( LockType::ALL.map(LockType::as_str), [ @@ -754,9 +781,18 @@ mod tests { Duration::from_millis(34), true, ); - let lock_ok: sqlx::Result<()> = - observe_advisory_lock(LockType::Replacement, async { Ok(()) }).await; + let lock_ok: sqlx::Result<()> = observe_event_lock( + LockType::Replacement, + buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32, + async { Ok(()) }, + ) + .await; assert!(lock_ok.is_ok()); + let unregistered_ok: sqlx::Result<()> = + observe_event_lock(LockType::Replacement, 30999, async { Ok(()) }).await; + assert!(unregistered_ok.is_ok()); + // The fallback label lives in buzz-core; this file never names it. + let unregistered_kind = buzz_core::kind::registered_kind_label(30999); let lock_error: sqlx::Result<()> = observe_advisory_lock(LockType::Membership, async { Err(sqlx::Error::PoolClosed) }) .await; @@ -786,41 +822,82 @@ mod tests { }) .collect::>(); + for name in [ + "buzz_db_pool_acquire_wait_seconds", + "buzz_db_pool_acquisitions_total", + ] { + let labels = [ + ("operation", "subscription_history"), + ("outcome", "timeout"), + ("pool_role", "reader"), + ] + .into_iter() + .map(|(key, value)| (key.to_owned(), value.to_owned())) + .collect::>(); + assert!( + keys.contains(&(name.to_owned(), labels)), + "legacy family {name} must carry the operation label; got {keys:?}" + ); + } for expected in [ ( - "buzz_db_pool_acquire_wait_seconds", - [("outcome", "timeout"), ("pool_role", "reader")], + "buzz_db_advisory_lock_wait_seconds", + &[ + ("lock_type", "replacement"), + ("kind", "13534"), + ("outcome", "success"), + ][..], ), ( - "buzz_db_pool_acquisitions_total", - [("outcome", "timeout"), ("pool_role", "reader")], + "buzz_db_advisory_lock_wait_seconds", + &[ + ("lock_type", "replacement"), + ("kind", unregistered_kind.as_str()), + ("outcome", "success"), + ], ), ( "buzz_db_advisory_lock_wait_seconds", - [("lock_type", "replacement"), ("outcome", "success")], + &[ + ("lock_type", "membership"), + ("kind", "none"), + ("outcome", "error"), + ], ), ( - "buzz_db_advisory_lock_wait_seconds", - [("lock_type", "membership"), ("outcome", "error")], + "buzz_db_advisory_lock_acquisitions_total", + &[ + ("lock_type", "replacement"), + ("kind", "13534"), + ("outcome", "success"), + ], ), ( "buzz_db_advisory_lock_acquisitions_total", - [("lock_type", "replacement"), ("outcome", "success")], + &[ + ("lock_type", "replacement"), + ("kind", unregistered_kind.as_str()), + ("outcome", "success"), + ], ), ( "buzz_db_advisory_lock_acquisitions_total", - [("lock_type", "membership"), ("outcome", "error")], + &[ + ("lock_type", "membership"), + ("kind", "none"), + ("outcome", "error"), + ], ), ( "buzz_db_transaction_duration_seconds", - [ + &[ ("operation", "replace_parameterized_event"), ("outcome", "success"), ], ), ( "buzz_db_transaction_duration_seconds", - [ + &[ ("operation", "accept_push_lease_event"), ("outcome", "error"), ], @@ -828,8 +905,8 @@ mod tests { ] { let expected_labels = expected .1 - .into_iter() - .map(|(key, value)| (key.to_owned(), value.to_owned())) + .iter() + .map(|&(key, value)| (key.to_owned(), value.to_owned())) .collect::>(); assert!( keys.contains(&(expected.0.to_owned(), expected_labels)), @@ -841,15 +918,8 @@ mod tests { "buzz_db_pool_acquisitions_total", ] { assert!( - !keys.contains(&( - name.to_owned(), - [ - ("outcome".to_owned(), "success".to_owned()), - ("pool_role".to_owned(), "writer".to_owned()), - ] - .into_iter() - .collect(), - )), + !keys.iter().any(|(key, labels)| key == name + && labels.get("pool_role").map(String::as_str) == Some("writer")), "newly instrumented seams must not expand legacy metric population" ); } @@ -1566,7 +1636,6 @@ mod tests { let _ = writer_db .with_inactive_community_fence(test_scope, |_| ()) .await; - let _ = writer_db.usage_community_count().await; let _ = writer_db.reap_expired_ephemeral_channels().await; let deletion_store = writer_db.deletion_store(); let _ = deletion_store.reap_expired_serving_write_leases(1).await; @@ -1575,7 +1644,6 @@ mod tests { let _ = routed_db .query_events_routed("pool_operation_matrix_reader", &query) .await; - let _ = routed_db.usage_fleet_stock_snapshot().await; routed_db.refresh_pool_waiter_metrics(); let snapshot = snapshotter.snapshot().into_vec(); @@ -1779,8 +1847,9 @@ mod tests { let _guard = metrics::set_default_local_recorder(&recorder); let mut success_tx = pool.begin().await.expect("begin success transaction"); - observe_advisory_lock( + observe_event_lock( LockType::Replacement, + buzz_core::kind::KIND_NIP29_GROUP_MEMBERS as i32, sqlx::query("SELECT pg_advisory_xact_lock($1)") .bind(0x62757a7a6f627331_i64) .execute(&mut *success_tx), @@ -1908,6 +1977,16 @@ mod tests { ); } + /// A replacement lock must carry its kind. Mutation: drop the guard in + /// `observe_advisory_lock` → RED. + #[cfg(debug_assertions)] + #[tokio::test] + #[should_panic(expected = "replacement locks carry an event kind")] + async fn kindless_observer_rejects_replacement_locks() { + let _: sqlx::Result<()> = + observe_advisory_lock(LockType::Replacement, async { Ok(()) }).await; + } + mod postgres_tests { #[tokio::test(flavor = "current_thread")] #[ignore = "requires Postgres"] diff --git a/crates/buzz-db/src/runtime/push_enqueue.rs b/crates/buzz-db/src/runtime/push_enqueue.rs index 3cbfd7cc802..24db8eba487 100644 --- a/crates/buzz-db/src/runtime/push_enqueue.rs +++ b/crates/buzz-db/src/runtime/push_enqueue.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use std::time::Duration; use buzz_core::CommunityId; +use chrono::{DateTime, Utc}; use sqlx::{postgres::PgPoolOptions, PgPool}; use tokio::sync::{mpsc, Mutex}; use tokio::task::JoinHandle; @@ -12,6 +13,17 @@ use tokio_util::sync::CancellationToken; pub(crate) const CAPACITY: usize = 256; const ENQUEUE_TIMEOUT: Duration = Duration::from_secs(2); +// Bind the signed event timestamp, never receipt time: only its monthly partition +// can contain the admitted row. Durable queue records intentionally stay ID-only. +const ENQUEUE_SQL: &str = "INSERT INTO push_match_queue (community_id, event_id) \ + SELECT $1, $2 FROM events e \ + WHERE e.community_id = $1 AND e.id = $2 AND e.created_at = $3 AND e.deleted_at IS NULL \ + AND EXISTS (SELECT 1 FROM push_leases l \ + WHERE l.community_id = $1 AND l.active AND l.endpoint_enabled \ + AND l.updated_at <= e.received_at \ + AND l.expires_at > EXTRACT(EPOCH FROM now())::bigint) \ + ON CONFLICT DO NOTHING"; + #[derive(Clone, Debug)] pub(crate) struct PushEnqueue { sender: mpsc::Sender, @@ -23,6 +35,7 @@ pub(crate) struct PushEnqueue { struct Job { community: CommunityId, event_id: Vec, + created_at: DateTime, #[cfg(test)] barrier: Option>, } @@ -96,7 +109,12 @@ impl PushEnqueue { } } - pub(crate) fn submit(&self, community: CommunityId, event_id: Vec) { + pub(crate) fn submit( + &self, + community: CommunityId, + event_id: Vec, + created_at: DateTime, + ) { if self.cancel.is_cancelled() { record_drop("shutdown"); return; @@ -104,6 +122,7 @@ impl PushEnqueue { if let Err(error) = self.sender.try_send(Job { community, event_id, + created_at, #[cfg(test)] barrier: None, }) { @@ -121,6 +140,7 @@ impl PushEnqueue { .send(Job { community: CommunityId::from_uuid(uuid::Uuid::nil()), event_id: Vec::new(), + created_at: DateTime::UNIX_EPOCH, barrier: Some(sender), }) .await @@ -157,6 +177,7 @@ pub(crate) async fn enqueue_with_gate_barrier( pool: &PgPool, community: CommunityId, event_id: Vec, + created_at: DateTime, barrier: GateBarrier, ) -> crate::Result<()> { enqueue( @@ -164,6 +185,7 @@ pub(crate) async fn enqueue_with_gate_barrier( &Job { community, event_id, + created_at, barrier: None, }, Some(barrier), @@ -202,24 +224,30 @@ async fn enqueue( // Compare recorded receipt/update times without imposing commit ordering. // Registration overlapping message arrival may send or suppress a wake. // This bounded job never scans historical messages on lease activation. - sqlx::query( - "INSERT INTO push_match_queue (community_id, event_id) \ - SELECT $1, $2 FROM events e \ - WHERE e.community_id = $1 AND e.id = $2 AND e.deleted_at IS NULL \ - AND EXISTS (SELECT 1 FROM push_leases l \ - WHERE l.community_id = $1 AND l.active AND l.endpoint_enabled \ - AND l.updated_at <= e.received_at \ - AND l.expires_at > EXTRACT(EPOCH FROM now())::bigint) \ - ON CONFLICT DO NOTHING", - ) - .bind(job.community.as_uuid()) - .bind(&job.event_id) - .execute(&mut *tx) - .await?; + insert_queue_row(&mut tx, job).await?; tx.commit().await?; Ok(()) } +async fn insert_queue_row( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + job: &Job, +) -> crate::Result<()> { + // Not a cached prepared statement: this worker connection is long-lived, so + // after five runs Postgres could switch a cached statement to a generic + // plan. A generic plan prunes `events` partitions only at executor startup, + // after locking every partition and its indexes; a custom plan prunes at + // plan time and locks only the signed timestamp's month. + sqlx::query(ENQUEUE_SQL) + .persistent(false) + .bind(job.community.as_uuid()) + .bind(&job.event_id) + .bind(job.created_at) + .execute(&mut **tx) + .await?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -234,12 +262,12 @@ mod tests { }; let community = CommunityId::from_uuid(uuid::Uuid::new_v4()); for _ in 0..CAPACITY + 1 { - producer.submit(community, vec![1; 32]); + producer.submit(community, vec![1; 32], DateTime::UNIX_EPOCH); } assert_eq!(receiver.len(), CAPACITY); receiver.try_recv().unwrap(); producer.cancel(); - producer.submit(community, vec![2; 32]); + producer.submit(community, vec![2; 32], DateTime::UNIX_EPOCH); assert_eq!(receiver.len(), CAPACITY - 1); producer.join().await; } @@ -283,11 +311,13 @@ mod tests { let active = Job { community: communities[0], event_id: vec![0_u8; 32], + created_at: DateTime::from_timestamp(1, 0).unwrap(), barrier: None, }; let quiescing = Job { community: communities[1], event_id: vec![1_u8; 32], + created_at: DateTime::from_timestamp(1, 0).unwrap(), barrier: None, }; let err = enqueue(&db.pool, &quiescing, None) @@ -310,3 +340,7 @@ mod tests { } } } + +#[cfg(test)] +#[path = "push_enqueue/postgres_tests.rs"] +mod postgres_tests; diff --git a/crates/buzz-db/src/runtime/push_enqueue/postgres_tests.rs b/crates/buzz-db/src/runtime/push_enqueue/postgres_tests.rs new file mode 100644 index 00000000000..17155fa63b6 --- /dev/null +++ b/crates/buzz-db/src/runtime/push_enqueue/postgres_tests.rs @@ -0,0 +1,291 @@ +//! End-to-end signed timestamp propagation and production enqueue SQL pruning. + +use super::*; +use crate::{event, Db, DbConfig}; +use nostr::{Event, EventBuilder, Keys, Kind, Timestamp}; +use serde_json::Value; +use sqlx::AssertSqlSafe; + +async fn fixture() -> (Db, CommunityId) { + let db = Db::new(&DbConfig { + database_url: crate::test_support::database_url(), + push_enabled: true, + ..DbConfig::default() + }) + .await + .expect("connect isolated database"); + let community = CommunityId::from_uuid(uuid::Uuid::new_v4()); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(format!("push-timestamp-{community}.example")) + .execute(db.pool()) + .await + .expect("create community"); + sqlx::query( + "INSERT INTO push_leases (community_id, author, installation_id, \ + source_event_id, source_created_at, generation, active, endpoint_hash, \ + endpoint_grant, max_class, subscriptions, expires_at, updated_at) \ + VALUES ($1, $2, 'timestamp-test', $3, 1, 1, true, $4, 'grant', \ + 'default', '[]', EXTRACT(EPOCH FROM now())::bigint + 3600, \ + now() - interval '1 hour')", + ) + .bind(community.as_uuid()) + .bind(vec![1_u8; 32]) + .bind(vec![2_u8; 32]) + .bind(vec![3_u8; 32]) + .execute(db.pool()) + .await + .expect("activate lease before event receipt"); + (db, community) +} + +fn historical_event(keys: &Keys, kind: u16, date: &str) -> Event { + let timestamp = DateTime::parse_from_rfc3339(date).expect("fixed test date"); + EventBuilder::new(Kind::Custom(kind), date) + .custom_created_at(Timestamp::from(timestamp.timestamp() as u64)) + .sign_with_keys(keys) + .expect("sign historical event") +} + +fn signed_timestamp(event: &Event) -> DateTime { + DateTime::from_timestamp(event.created_at.as_secs() as i64, 0).expect("signed timestamp") +} + +async fn queued_ids(db: &Db, community: CommunityId) -> Vec> { + db.push_enqueue + .as_ref() + .expect("push enabled") + .flush() + .await; + sqlx::query_scalar( + "SELECT event_id FROM push_match_queue WHERE community_id = $1 ORDER BY event_id", + ) + .bind(community.as_uuid()) + .fetch_all(db.pool()) + .await + .expect("read completed enqueue jobs") +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn historical_timestamps_follow_each_staged_event_and_both_insert_seams() { + let (db, community) = fixture().await; + let keys = Keys::generate(); + // Deliberately not timestamp ordered: a transaction-wide timestamp or a + // swapped association must lose at least one wake. Receipt time is today. + let mut events = Vec::new(); + let mut tx = db.begin_event_write_transaction(community).await.unwrap(); + for (kind, date) in [ + (9, "2026-04-20T23:59:59Z"), + (40002, "2025-09-01T00:00:00Z"), + (45001, "2026-02-01T00:00:00Z"), + (45003, "2026-01-31T23:59:59Z"), + ] { + let event = historical_event(&keys, kind, date); + assert!( + event::insert_event_in_transaction(&mut tx, &event, None) + .await + .unwrap() + .1 + ); + events.push(event); + } + assert!(queued_ids(&db, community).await.is_empty(), "commit only"); + tx.commit().await.unwrap(); + + let threaded = historical_event(&keys, 9, "2026-03-01T00:00:00Z"); + assert!( + db.insert_event_with_thread_metadata(community, &threaded, None, None) + .await + .unwrap() + .1 + ); + events.push(threaded); + let mut expected: Vec<_> = events + .iter() + .map(|event| event.id.as_bytes().to_vec()) + .collect(); + expected.sort(); + assert_eq!(queued_ids(&db, community).await, expected); + + // Remove completed jobs so ON CONFLICT cannot hide an erroneous enqueue + // for a duplicate/no-op insert on either production insert seam. + sqlx::query("DELETE FROM push_match_queue WHERE community_id = $1") + .bind(community.as_uuid()) + .execute(db.pool()) + .await + .unwrap(); + assert!( + !db.insert_event(community, &events[0], None) + .await + .unwrap() + .1 + ); + assert!( + !db.insert_event_with_thread_metadata(community, &events[4], None, None) + .await + .unwrap() + .1 + ); + assert!(queued_ids(&db, community).await.is_empty()); + + let rolled_back = historical_event(&keys, 9, "2026-05-01T00:00:00Z"); + let mut tx = db.begin_event_write_transaction(community).await.unwrap(); + assert!( + event::insert_event_in_transaction(&mut tx, &rolled_back, None) + .await + .unwrap() + .1 + ); + tx.rollback().await.unwrap(); + assert!(queued_ids(&db, community).await.is_empty()); + let dropped = historical_event(&keys, 9, "2026-06-01T00:00:00Z"); + let mut tx = db.begin_event_write_transaction(community).await.unwrap(); + event::insert_event_in_transaction(&mut tx, &dropped, None) + .await + .unwrap(); + drop(tx); + assert!(queued_ids(&db, community).await.is_empty()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn enqueue_requires_exact_signed_timestamp_not_receipt_or_neighbor_month() { + let (db, community) = fixture().await; + let event = historical_event(&Keys::generate(), 9, "2026-02-01T00:00:00Z"); + // Store without the producer; exercise the real worker transaction below. + event::insert_event(db.pool(), community, &event, None) + .await + .unwrap(); + let mut job = Job { + community, + event_id: event.id.as_bytes().to_vec(), + created_at: signed_timestamp(&event) - chrono::Duration::seconds(1), + barrier: None, + }; + enqueue(db.pool(), &job, None).await.unwrap(); + assert!(queued_ids(&db, community).await.is_empty()); + job.created_at = Utc::now(); + enqueue(db.pool(), &job, None).await.unwrap(); + assert!(queued_ids(&db, community).await.is_empty()); + job.created_at = signed_timestamp(&event); + enqueue(db.pool(), &job, None).await.unwrap(); + assert_eq!(queued_ids(&db, community).await, vec![job.event_id]); +} + +fn executed_event_relations(plan: &Value, relations: &mut Vec) { + match plan { + Value::Object(node) => { + // Generic plans name Append children e_1, e_2, ... rather than + // e. Inspect base relations, not aliases or a particular plan shape. + if node + .get("Actual Loops") + .and_then(Value::as_u64) + .unwrap_or(0) + > 0 + { + if let Some(relation) = node.get("Relation Name").and_then(Value::as_str) { + if relation.starts_with("events_") { + relations.push(relation.to_owned()); + } + } + } + for child in node.values() { + executed_event_relations(child, relations); + } + } + Value::Array(nodes) => { + for child in nodes { + executed_event_relations(child, relations); + } + } + _ => {} + } +} + +/// The custom plan the production statement receives executes one partition. +/// Executed nodes say nothing about locks: a generic plan also executes one +/// partition after locking all of them, so lock coverage is asserted below. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn production_enqueue_sql_executes_one_month_in_custom_plan() { + let (db, community) = fixture().await; + let event = historical_event(&Keys::generate(), 9, "2026-02-01T00:00:00Z"); + event::insert_event(db.pool(), community, &event, None) + .await + .unwrap(); + let mut tx = db.pool().begin().await.unwrap(); + sqlx::query("SELECT set_config('plan_cache_mode', 'force_custom_plan', true)") + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query(AssertSqlSafe(format!( + "PREPARE push_pruning (uuid, bytea, timestamptz) AS {ENQUEUE_SQL}" + ))) + .execute(&mut *tx) + .await + .unwrap(); + // Only generated UUID/hex and a fixed signed date enter this test SQL. + // EXPLAIN the exact INSERT used by enqueue, not a lookalike SELECT. + let plan: Value = sqlx::query_scalar(AssertSqlSafe(format!( + "EXPLAIN (ANALYZE, FORMAT JSON) EXECUTE push_pruning \ + ('{community}', '\\x{}'::bytea, '{}')", + hex::encode(event.id.as_bytes()), + signed_timestamp(&event).to_rfc3339(), + ))) + .fetch_one(&mut *tx) + .await + .unwrap(); + let mut relations = Vec::new(); + executed_event_relations(&plan, &mut relations); + assert_eq!(relations, ["events_p2026_02"], "{plan}"); + tx.rollback().await.unwrap(); +} + +/// The production statement must lock one `events` partition. Locks, not +/// executed plan nodes, are what a long-lived push worker would contend on: a +/// generic plan executes one partition only after locking all of them. The +/// statement must therefore never be a cached prepared statement, which +/// Postgres may move to a generic plan after five executions. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn production_enqueue_statement_locks_only_the_signed_month_partition() { + let (db, community) = fixture().await; + let event = historical_event(&Keys::generate(), 9, "2026-02-01T00:00:00Z"); + event::insert_event(db.pool(), community, &event, None) + .await + .unwrap(); + let job = Job { + community, + event_id: event.id.as_bytes().to_vec(), + created_at: signed_timestamp(&event), + barrier: None, + }; + let mut tx = db.pool().begin().await.unwrap(); + // Past the five-execution custom-plan window of a cached statement. + for _ in 0..7 { + insert_queue_row(&mut tx, &job).await.unwrap(); + } + let cached: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_prepared_statements \ + WHERE statement LIKE 'INSERT INTO push_match_queue%'", + ) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(cached, 0, "enqueue SQL must not be a cached statement"); + // Locks on a partition or any of its indexes, attributed to the partition. + let locked: Vec = sqlx::query_scalar( + "SELECT DISTINCT t.relname::text FROM pg_locks l \ + JOIN pg_class c ON c.oid = l.relation \ + LEFT JOIN pg_index i ON i.indexrelid = c.oid \ + JOIN pg_class t ON t.oid = COALESCE(i.indrelid, c.oid) \ + WHERE l.locktype = 'relation' AND l.pid = pg_backend_pid() \ + AND t.relname LIKE 'events\\_p%' ORDER BY 1", + ) + .fetch_all(&mut *tx) + .await + .unwrap(); + assert_eq!(locked, ["events_p2026_02"]); + tx.rollback().await.unwrap(); +} diff --git a/crates/buzz-db/src/runtime/replica_fence.rs b/crates/buzz-db/src/runtime/replica_fence.rs index 520ff9e8698..40bb6aa7b77 100644 --- a/crates/buzz-db/src/runtime/replica_fence.rs +++ b/crates/buzz-db/src/runtime/replica_fence.rs @@ -3,12 +3,12 @@ //! A read replica may serve a cursor page only when every row the page could //! contain is provably present on the replica. The proof rests on two parts: //! -//! 1. **Commit-time floor** (migration 0021): a deferred constraint trigger -//! aborts, at COMMIT, any transaction inserting a channel-bearing `events` -//! row with `created_at` more than `floor` seconds before commit time -//! (`clock_timestamp()`, evaluated inside commit processing). Enforcement -//! is armed per session via the `buzz.created_at_floor` GUC, which the -//! relay's writer pool sets on every connection. +//! 1. **Insert-time floor**: supported channel-event writers check `created_at` +//! against database `clock_timestamp()` on their admitted transaction for +//! each new row. Duplicate INSERTs need no floor check. This is the primary +//! guard. Migration 0021's deferred trigger and the writer-pool +//! `buzz.created_at_floor` GUC remain the mixed-version backstop until phase 2; +//! they also reject rows that age below the floor before COMMIT. //! 2. **Ordered heartbeat handshake** (this module): on one pinned writer //! connection, one transaction first takes the exclusive replica-floor //! advisory lock (draining compliant shared-lock channel writers), then @@ -25,7 +25,7 @@ //! commit, so the replica session has replayed it; //! (b) open at the activity scan — represented by `xact_start`, so it is //! bounded by the `oldest_xact_start` term; -//! (c) started after the activity scan — its deferred floor guard runs +//! (c) started after the activity scan — its insert-time app guard runs //! after `S`, so it cannot commit a row with //! `created_at < S - floor`. //! There is no fourth bucket. Each committed token `M` therefore proves a @@ -48,26 +48,32 @@ //! `RETURNING token` or an epoch change (restore/re-seed) clears the retained //! ring, so no stale entry can masquerade as fresh coverage. //! -//! Everything fails **closed**: probe errors, masked `pg_stat_activity` -//! visibility, an unreadable heartbeat row on the reader session, an epoch -//! mismatch, or an observed token below every retained entry all route the -//! request back to the writer — degraded capacity, never holes. +//! Everything fails **closed**: an unreadable heartbeat row on the reader +//! session, an epoch mismatch, or an observed token below every retained +//! entry all route the request back to the writer — degraded capacity, never +//! holes. A failed probe (a writer error or masked `pg_stat_activity` +//! visibility) proves nothing new, so it records no entry; the entries +//! already retained stay valid, because a proof never decays. If the probe +//! keeps failing, the newest entry ages past [`FENCE_STALENESS`] and the +//! fence closes. //! -//! Operational bypasses (sessions without the GUC, `session_replication_role -//! = replica` restores) are outside the proof by design and require holding -//! the fence closed for their duration; see `migrations/0021`. +//! Raw SQL without the armed GUC and `session_replication_role = replica` +//! restores bypass the supported app writers. These operational bypasses are +//! outside the proof and require holding the fence closed; see `migrations/0021`. use std::collections::VecDeque; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use chrono::{DateTime, Utc}; -use sqlx::{PgConnection, PgPool, Row}; +use sqlx::pool::PoolConnection; +use sqlx::postgres::PgPoolOptions; +use sqlx::{PgConnection, PgPool, Postgres, Row}; use uuid::Uuid; use buzz_datastore_tracing::datastore_span; -/// Seconds of `created_at` history the commit-time floor guard tolerates. +/// Seconds of `created_at` history the app and mixed-version trigger tolerate. /// /// Must exceed the relay's ingest envelope (±900 s) by enough slack that a /// legitimately accepted event still commits within the floor even under @@ -75,6 +81,38 @@ use buzz_datastore_tracing::datastore_span; /// and the fence subtracts it; the two uses must never diverge. pub const CREATED_AT_FLOOR_SECS: i64 = 960; +/// Enforce the channel-event floor on the admitted INSERT connection. +/// +/// One SELECT keeps the five existing INSERT shapes intact. Every writer +/// checks after its INSERT, only when it inserted a row, before follow-ups, so +/// replaying a stored id (even a soft-deleted one) stays a duplicate. +/// Replacements roll back the supersede with it (savepoint or caller). +/// The caller must propagate failure and roll back the write transaction. Its +/// database clock is sampled after BEGIN: transactions open at the probe scan +/// are bounded by xact_start; transactions starting later sample after S. No +/// commit hook, candidate tracking or ordering against TTL refresh is needed. +/// NULL-channel rows never enter covered channel windows and need no query. +pub(crate) async fn guard_event_created_at_floor( + tx: &mut crate::AdmittedTx, + created_at: DateTime, + channel_id: Option, +) -> crate::Result<()> { + if channel_id.is_none() { + return Ok(()); + } + let below_floor: bool = sqlx::query_scalar( + "SELECT $1::timestamptz < clock_timestamp() - make_interval(secs => $2::double precision)", + ) + .bind(created_at) + .bind(CREATED_AT_FLOOR_SECS as f64) + .fetch_one(tx.conn()) + .await?; + if below_floor { + return Err(crate::DbError::CreatedAtFloorRejected); + } + Ok(()) +} + /// Deployment-global advisory-lock key ordering compliant channel-event write /// transactions against the writer probe handshake. /// @@ -91,14 +129,52 @@ pub const REPLICA_FLOOR_LOCK_KEY: i64 = 0x62757a7a666c6f72; /// between machines. pub const FENCE_CLOCK_MARGIN_SECS: i64 = 5; -/// How often the probe samples the writer and commits a heartbeat token. +/// Default interval at which the probe samples the writer and commits a +/// heartbeat token (env `BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS`). /// -/// 500ms keeps the cadence at least 2x under the smallest sensible bounded -/// budget (`BUZZ_REPLICA_READ_MAX_AGE_MS`, deploy plan 1000ms) so -/// eligibility doesn't flap between beats. Cost is one single-row UPDATE -/// tuple of WAL per beat per pod — ~20 beats/s fleet-wide, <0.1% of the -/// writer. -pub const PROBE_INTERVAL: Duration = Duration::from_millis(500); +/// Every beat takes the deployment-wide exclusive floor lock, and channel +/// writes queue behind it while it is held, so beating faster costs more +/// lock drains per pod, not just WAL. Tolerating a slow beat is the read +/// budget's job (see [`min_read_budget`]), not the interval's. +pub const DEFAULT_PROBE_INTERVAL: Duration = Duration::from_millis(500); + +/// Shortest accepted probe interval. Bounded by the retained ring, which +/// must hold more history than [`FENCE_STALENESS`] (see the assertion at +/// [`RING_CAPACITY`]), and by the writer cost of beating faster. +pub const MIN_PROBE_INTERVAL: Duration = Duration::from_millis(300); + +/// Longest accepted probe interval: a probe slower than this leaves only a +/// few beats inside [`FENCE_STALENESS`] and needs a multi-second read +/// budget to route at all. +pub const MAX_PROBE_INTERVAL: Duration = Duration::from_secs(10); + +/// Map a configured probe interval in milliseconds to the effective one: +/// `0` selects [`DEFAULT_PROBE_INTERVAL`]; other values are clamped to +/// [`MIN_PROBE_INTERVAL`]..=[`MAX_PROBE_INTERVAL`]. +pub fn probe_interval_from_ms(ms: u64) -> Duration { + if ms == 0 { + return DEFAULT_PROBE_INTERVAL; + } + Duration::from_millis(ms).clamp(MIN_PROBE_INTERVAL, MAX_PROBE_INTERVAL) +} + +/// Commit and scheduling latency a bounded-read budget should absorb on +/// top of one lock-timed-out beat. +const READ_BUDGET_LATENCY_MARGIN: Duration = Duration::from_millis(200); + +/// Smallest bounded-read budget (`BUZZ_REPLICA_READ_MAX_AGE_MS`) that +/// survives one beat failing on [`PROBE_LOCK_TIMEOUT`] at `probe_interval`: +/// the newest entry is one interval old when that beat starts, ages by the +/// lock wait, and the next beat (fired at once, since missed ticks are +/// delayed rather than skipped) commits after +/// [`READ_BUDGET_LATENCY_MARGIN`]. 1700ms at the default interval. A +/// smaller budget still works, but bounded reads spill to the writer +/// whenever a beat waits out the floor lock; the relay warns at startup. +pub const fn min_read_budget(probe_interval: Duration) -> Duration { + probe_interval + .saturating_add(PROBE_LOCK_TIMEOUT) + .saturating_add(READ_BUDGET_LATENCY_MARGIN) +} /// A fence whose newest entry is older than this is stale: the probe has /// stopped committing tokens and routing eligibility closes until a new @@ -110,8 +186,43 @@ pub const PROBE_INTERVAL: Duration = Duration::from_millis(500); /// just stops spending reader checkouts once the probe is evidently dead. pub const FENCE_STALENESS: Duration = Duration::from_secs(30); +/// `application_name` of the probe's dedicated connection, so it is +/// identifiable in `pg_stat_activity` and database-side wait reports. +pub const PROBE_APPLICATION_NAME: &str = "buzz-replica-fence-probe"; + +/// Bound on waiting for the probe's connection. The probe loop is the +/// pool's only, strictly sequential user, so this only ever covers a +/// (re)dial — never queueing behind serving traffic. +const PROBE_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(2); + +/// Session `lock_timeout` on the probe connection. +/// +/// While the probe waits for the exclusive floor lock, new shared +/// requesters (channel-event writes) queue behind it, so a long wait +/// stalls channel writes deployment-wide. A beat that gives up costs +/// nothing — retained proofs stand — so fail fast instead of inheriting +/// the serving writer's longer lock budget. +/// +/// Every pod's probe takes the same exclusive lock and the same heartbeat +/// row lock, so probes also queue behind each other. Each holds them for a +/// few milliseconds, so this budget assumes well under a hundred relay +/// processes per writer. +const PROBE_LOCK_TIMEOUT: Duration = Duration::from_secs(1); + +/// Session `statement_timeout` and `idle_in_transaction_session_timeout` +/// on the probe connection. Every probe statement is a sub-millisecond +/// point operation; the idle bound reaps a stalled client that still +/// holds the exclusive floor lock. +const PROBE_STATEMENT_TIMEOUT: Duration = Duration::from_secs(2); + +/// Client-side bound on one whole probe, covering stalls no server-side +/// timeout observes (for example a dead TCP peer). Comfortably above the +/// acquire timeout plus one lock wait plus the remaining statements. +const PROBE_DEADLINE: Duration = Duration::from_secs(5); + /// How many `(token, fence_wall)` entries the fence retains. At one probe -/// per [`PROBE_INTERVAL`] (500ms) this is ~60 seconds of history — a reader +/// per [`DEFAULT_PROBE_INTERVAL`] (500ms) this is ~60 seconds of history, +/// and at least 36 seconds at [`MIN_PROBE_INTERVAL`] — a reader /// session lagging further than that behind the newest token fails closed /// (routes to the writer) rather than proving from thin air. Aurora reader /// lag is typically tens of milliseconds; a reader minutes behind is a @@ -124,7 +235,8 @@ const RING_CAPACITY: usize = 120; // for capacity rather than lag. Compile-checked so a future cadence or // capacity tweak can't silently shrink the window below the gate. const _: () = assert!( - RING_CAPACITY as u64 * PROBE_INTERVAL.as_millis() as u64 > FENCE_STALENESS.as_millis() as u64, + RING_CAPACITY as u64 * MIN_PROBE_INTERVAL.as_millis() as u64 + > FENCE_STALENESS.as_millis() as u64, "fence ring must retain more history than the staleness gate" ); @@ -204,8 +316,9 @@ impl ReplicaFence { Self::default() } - /// Close the fence: drop all retained proofs; reads route to the writer. - pub fn close(&self) { + /// Test hook: drop all retained proofs, so reads route to the writer. + #[cfg(test)] + pub(crate) fn close(&self) { let mut inner = self.inner.lock().expect("fence lock poisoned"); inner.ring.clear(); } @@ -276,8 +389,13 @@ impl ReplicaFence { /// Age of the newest retained entry, ungated (observability: how long /// since the probe last committed a token). pub fn heartbeat_age(&self) -> Option { + self.last_committed_at().map(|at| at.elapsed()) + } + + /// Commit instant of the newest retained entry, ungated. + fn last_committed_at(&self) -> Option { let inner = self.inner.lock().expect("fence lock poisoned"); - inner.ring.back().map(|entry| entry.committed_at.elapsed()) + inner.ring.back().map(|entry| entry.committed_at) } /// The newest fence wall, or `None` when closed or stale. @@ -538,8 +656,8 @@ struct WriterSample { committed_at: Instant, } -/// Errors that close the fence. All variants are logged and treated -/// identically: fail closed. +/// Errors that fail one probe. All variants are logged and treated +/// identically: the probe records no entry, and the retained entries stand. #[derive(Debug, thiserror::Error)] pub enum ProbeError { /// A probe query against the writer failed. @@ -558,6 +676,146 @@ pub enum ProbeError { /// The single heartbeat row (migration 0026) is missing on the writer. #[error("replica_heartbeat row missing on the writer — migration 0026 not applied?")] HeartbeatRowMissing, + /// The whole probe overran [`PROBE_DEADLINE`] without any server-side + /// timeout firing (for example a stalled connection). + #[error("replica fence probe exceeded its {0:?} deadline")] + Deadline(Duration), +} + +impl ProbeError { + /// Stable, low-cardinality failure class for spans and logs. + pub fn kind(&self) -> &'static str { + match self { + Self::Writer(sqlx::Error::PoolTimedOut) => "acquire_timeout", + Self::Writer(sqlx::Error::PoolClosed) => "pool_closed", + Self::Writer(sqlx::Error::Database(e)) => match e.code().as_deref() { + // lock_not_available: the probe's `lock_timeout` fired. + Some("55P03") => "lock_timeout", + // query_canceled: the probe's `statement_timeout` fired. + Some("57014") => "statement_timeout", + _ => "database", + }, + Self::Writer(sqlx::Error::Io(_)) => "io", + Self::Writer(_) => "writer", + Self::MaskedActivity { .. } => "masked_activity", + Self::HeartbeatRowMissing => "heartbeat_row_missing", + Self::Deadline(_) => "deadline", + } + } +} + +/// Connect the probe's dedicated one-connection pool. +/// +/// The probe must not borrow the serving writer pool: under load its beat +/// then queues behind request traffic for up to that pool's acquire +/// timeout, every pod's newest token ages past the bounded-read budget at +/// once, and reads spill onto the writer that is already saturated. A pool +/// of its own keeps the beat independent of serving load, the way the push +/// producer's pool keeps push work off it. It costs one extra writer +/// connection per relay process. +/// +/// It reuses the writer's credentials and connection lifetime, so it +/// follows writer failover the same way. It does not run the writer pool's +/// `after_connect` policy: the probe never writes `events`, so it needs no +/// floor-guard arming, and it installs its own tighter timeouts (see +/// [`PROBE_LOCK_TIMEOUT`], [`PROBE_STATEMENT_TIMEOUT`]). The pool is lazy, +/// so a writer outage cannot make startup depend on it. +pub fn connect_probe_pool(writer: &PgPool) -> PgPool { + PgPoolOptions::new() + .max_connections(1) + .min_connections(1) + .acquire_timeout(PROBE_ACQUIRE_TIMEOUT) + .max_lifetime(writer.options().get_max_lifetime()) + .after_connect(|conn, _meta| { + Box::pin(async move { + sqlx::query( + "SELECT set_config('lock_timeout', $1, false), \ + set_config('statement_timeout', $2, false), \ + set_config('idle_in_transaction_session_timeout', $2, false)", + ) + .bind(millis(PROBE_LOCK_TIMEOUT).to_string()) + .bind(millis(PROBE_STATEMENT_TIMEOUT).to_string()) + .execute(&mut *conn) + .await?; + Ok(()) + }) + }) + .connect_lazy_with( + (*writer.connect_options()) + .clone() + .application_name(PROBE_APPLICATION_NAME), + ) +} + +/// Wall time of each probe phase, recorded on the probe span and in the +/// failure log. Phases a failed probe never reached stay zero. +#[derive(Debug, Default, Clone, Copy)] +struct ProbeTimings { + /// Waiting for the probe connection (a dial, at most). + acquire: Duration, + /// `BEGIN` plus waiting for the exclusive floor lock. + lock: Duration, + /// Sampling `S` and scanning `pg_stat_activity`. + scan: Duration, + /// The heartbeat `UPDATE ... RETURNING`. + heartbeat: Duration, + /// `COMMIT`. + commit: Duration, +} + +/// What one probe observed about itself, beyond its result. +#[derive(Debug, Default, Clone, Copy)] +struct ProbeTrace { + timings: ProbeTimings, + /// Time between the previously retained beat and this one's commit; + /// `None` before the first beat or when this probe failed. + beat_gap: Option, +} + +fn millis(elapsed: Duration) -> u64 { + u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX) +} + +/// Await `phase`, storing its wall time in `slot` whatever its outcome. +/// +/// The time is stored on drop, so a phase cut off by [`PROBE_DEADLINE`] +/// still reports how long it had been running — the stalled phase is the +/// one the failure log most needs to name. +async fn timed(slot: &mut Duration, phase: impl std::future::Future) -> T { + struct Stamp<'a> { + slot: &'a mut Duration, + started: Instant, + } + impl Drop for Stamp<'_> { + fn drop(&mut self) { + *self.slot = self.started.elapsed(); + } + } + let _stamp = Stamp { + slot, + started: Instant::now(), + }; + phase.await +} + +/// Check out the probe connection. Its own span (and the +/// `buzz_db_operation_duration_seconds` series the span macro records) +/// makes the probe's connection wait directly visible. +#[datastore_span(name = "replica_fence_probe_acquire", system = "postgresql")] +async fn acquire_probe_connection(pool: &PgPool) -> Result, sqlx::Error> { + pool.acquire().await +} + +/// Take the exclusive replica-floor lock, draining compliant shared-lock +/// channel writers. Spanned separately: this is the probe's only wait on +/// other database sessions. +#[datastore_span(name = "replica_fence_probe_lock", system = "postgresql")] +async fn take_floor_lock(conn: &mut PgConnection) -> Result<(), sqlx::Error> { + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(REPLICA_FLOOR_LOCK_KEY) + .execute(conn) + .await?; + Ok(()) } /// Take one ordered writer sample: under the exclusive replica-floor lock, @@ -566,75 +824,82 @@ pub enum ProbeError { /// The statements are separately awaited on one pinned writer transaction; /// a single SELECT would not guarantee evaluation order across the /// subexpressions, reopening the race this ordering exists to close. -async fn sample_writer(writer: &PgPool) -> Result { - let connection = crate::observability::acquire_writer( - writer, - crate::observability::WriterOperation::Maintenance, - ) +async fn sample_writer( + writer: &PgPool, + timings: &mut ProbeTimings, +) -> Result { + let connection = timed(&mut timings.acquire, acquire_probe_connection(writer)).await?; + + let mut tx = timed(&mut timings.lock, async { + let mut tx = sqlx::Transaction::begin(connection, None).await?; + take_floor_lock(&mut tx).await?; + Ok::<_, sqlx::Error>(tx) + }) .await?; - let mut tx = sqlx::Transaction::begin(connection, None).await?; - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(REPLICA_FLOOR_LOCK_KEY) - .execute(&mut *tx) - .await?; + let (sampled_at, oldest_xact_start) = timed(&mut timings.scan, async { + // 1. S first. + let sampled_at: DateTime = sqlx::query_scalar("SELECT clock_timestamp()") + .fetch_one(&mut *tx) + .await?; - // 1. S first. - let sampled_at: DateTime = sqlx::query_scalar("SELECT clock_timestamp()") + // 2. Activity scan. Classification (fail closed on anything unknown): + // - `backend_type IS NULL` → masked. CRITICAL: an unprivileged view + // masks `backend_type` itself along with `state`/`xact_start` + // (verified on PG 16/17), so filtering on + // `backend_type = 'client backend'` would silently EXCLUDE masked + // rows and fail open. Masked rows must be detected before any + // backend-type filter; + // - client backend with `state IS NULL`, or a transactional/unknown + // state with NULL `xact_start` → masked → error; + // - client backend, `state = 'idle'`, NULL `xact_start` + // → no transaction → safely ignore; + // - any row with non-NULL `xact_start` (any backend type) + // → include in the minimum. Background + // workers cannot insert events rows, but counting them is the + // conservative direction (a long autovacuum merely holds the fence + // back), and it keeps the classification simple. + // Scope is every other backend regardless of role or application + // name: an admin psql transaction writes under the same trigger and + // must be representable in the oldest-xact term. + // + // Prepared transactions (2PC) are a bucket of their own: while + // prepared they have left `pg_stat_activity` but can still commit + // after the token. Their deferred floor guard already ran at PREPARE, + // so `pg_prepared_xacts.prepared` bounds their rows exactly like + // `xact_start`; fold it into the same minimum. Only the retained + // deferred trigger provides that PREPARE-time check: the insert-time + // app guard runs earlier, and no app writer issues PREPARE TRANSACTION. + // Dropping the trigger must keep this case covered. + let row = sqlx::query( + r#" + SELECT + least( + (SELECT min(xact_start) + FROM pg_stat_activity + WHERE pid <> pg_backend_pid()), + (SELECT min(prepared) FROM pg_prepared_xacts) + ) AS oldest_xact_start, + (SELECT count(*) + FROM pg_stat_activity + WHERE pid <> pg_backend_pid() + AND (backend_type IS NULL + OR (backend_type = 'client backend' + AND (state IS NULL + OR (state <> 'idle' AND xact_start IS NULL)))) + ) AS masked + "#, + ) .fetch_one(&mut *tx) .await?; - - // 2. Activity scan. Classification (fail closed on anything unknown): - // - `backend_type IS NULL` → masked. CRITICAL: an unprivileged view - // masks `backend_type` itself along with `state`/`xact_start` - // (verified on PG 16/17), so filtering on - // `backend_type = 'client backend'` would silently EXCLUDE masked - // rows and fail open. Masked rows must be detected before any - // backend-type filter; - // - client backend with `state IS NULL`, or a transactional/unknown - // state with NULL `xact_start` → masked → error; - // - client backend, `state = 'idle'`, NULL `xact_start` - // → no transaction → safely ignore; - // - any row with non-NULL `xact_start` (any backend type) - // → include in the minimum. Background - // workers cannot insert events rows, but counting them is the - // conservative direction (a long autovacuum merely holds the fence - // back), and it keeps the classification simple. - // Scope is every other backend regardless of role or application - // name: an admin psql transaction writes under the same trigger and - // must be representable in the oldest-xact term. - // - // Prepared transactions (2PC) are a bucket of their own: while - // prepared they have left `pg_stat_activity` but can still commit - // after the token. Their deferred floor guard already ran at PREPARE, - // so `pg_prepared_xacts.prepared` bounds their rows exactly like - // `xact_start`; fold it into the same minimum. - let row = sqlx::query( - r#" - SELECT - least( - (SELECT min(xact_start) - FROM pg_stat_activity - WHERE pid <> pg_backend_pid()), - (SELECT min(prepared) FROM pg_prepared_xacts) - ) AS oldest_xact_start, - (SELECT count(*) - FROM pg_stat_activity - WHERE pid <> pg_backend_pid() - AND (backend_type IS NULL - OR (backend_type = 'client backend' - AND (state IS NULL - OR (state <> 'idle' AND xact_start IS NULL)))) - ) AS masked - "#, - ) - .fetch_one(&mut *tx) + let masked: i64 = row.get("masked"); + if masked > 0 { + return Err(ProbeError::MaskedActivity { masked }); + } + let oldest_xact_start: Option> = row.get("oldest_xact_start"); + Ok((sampled_at, oldest_xact_start)) + }) .await?; - let masked: i64 = row.get("masked"); - if masked > 0 { - return Err(ProbeError::MaskedActivity { masked }); - } - let oldest_xact_start: Option> = row.get("oldest_xact_start"); // 3. Token commit LAST, on the same pinned connection. The single-row // UPDATE serializes concurrent pods' probes, so RETURNING token is @@ -642,10 +907,13 @@ async fn sample_writer(writer: &PgPool) -> Result { // round trip so `elapsed()` over-estimates the observation's age — // the conservative direction for the head-freshness bound. let committed_at = Instant::now(); - let row = sqlx::query( - "UPDATE replica_heartbeat SET token = token + 1 WHERE id = 1 RETURNING token, epoch", + let row = timed( + &mut timings.heartbeat, + sqlx::query( + "UPDATE replica_heartbeat SET token = token + 1 WHERE id = 1 RETURNING token, epoch", + ) + .fetch_optional(&mut *tx), ) - .fetch_optional(&mut *tx) .await? .ok_or(ProbeError::HeartbeatRowMissing)?; @@ -656,7 +924,7 @@ async fn sample_writer(writer: &PgPool) -> Result { epoch: row.get("epoch"), committed_at, }; - tx.commit().await?; + timed(&mut timings.commit, tx.commit()).await?; Ok(sample) } @@ -680,8 +948,75 @@ fn fence_wall(sample_s: DateTime, oldest_xact_start: Option>) /// writer and records the rotated token, so a reader still serving the /// pre-rewind timeline (whose old, higher token would otherwise satisfy /// `token >= M`) fails the epoch check instead of proving stale coverage. +/// +/// `writer` is the probe's own pool in production ([`connect_probe_pool`]). pub async fn probe_once(writer: &PgPool, fence: &ReplicaFence) -> Result { - let sample = sample_writer(writer).await?; + probe_traced(writer, fence, &mut ProbeTrace::default()).await +} + +/// [`probe_once`] under one span carrying every phase's wall time, the gap +/// since the previous beat, and the failure class, bounded by +/// [`PROBE_DEADLINE`]. +#[datastore_span( + name = "replica_fence_probe", + system = "postgresql", + fields( + acquire_ms = ::tracing::field::Empty, + lock_ms = ::tracing::field::Empty, + scan_ms = ::tracing::field::Empty, + heartbeat_ms = ::tracing::field::Empty, + commit_ms = ::tracing::field::Empty, + beat_gap_ms = ::tracing::field::Empty, + token = ::tracing::field::Empty, + error_kind = ::tracing::field::Empty, + ) +)] +async fn probe_traced( + writer: &PgPool, + fence: &ReplicaFence, + trace: &mut ProbeTrace, +) -> Result { + let previous = fence.last_committed_at(); + let result = match tokio::time::timeout( + PROBE_DEADLINE, + probe_untraced(writer, fence, &mut trace.timings), + ) + .await + { + Ok(result) => result, + Err(_) => Err(ProbeError::Deadline(PROBE_DEADLINE)), + }; + if let Ok(entry) = &result { + trace.beat_gap = previous.map(|at| entry.committed_at.saturating_duration_since(at)); + } + + let span = tracing::Span::current(); + let timings = trace.timings; + span.record("acquire_ms", millis(timings.acquire)); + span.record("lock_ms", millis(timings.lock)); + span.record("scan_ms", millis(timings.scan)); + span.record("heartbeat_ms", millis(timings.heartbeat)); + span.record("commit_ms", millis(timings.commit)); + match &result { + Ok(entry) => { + span.record("token", entry.token); + if let Some(gap) = trace.beat_gap { + span.record("beat_gap_ms", millis(gap)); + } + } + Err(error) => { + span.record("error_kind", error.kind()); + } + } + result +} + +async fn probe_untraced( + writer: &PgPool, + fence: &ReplicaFence, + timings: &mut ProbeTimings, +) -> Result { + let sample = sample_writer(writer, timings).await?; let wall = fence_wall(sample.sampled_at, sample.oldest_xact_start); match fence.record(sample.token, sample.epoch, sample.committed_at, wall) { RecordOutcome::Recorded => Ok(TokenEntry { @@ -698,11 +1033,7 @@ pub async fn probe_once(writer: &PgPool, fence: &ReplicaFence) -> Result) { - let mut interval = tokio::time::interval(PROBE_INTERVAL); +/// Background probe loop: commit a heartbeat token every `probe_interval` +/// (see [`probe_interval_from_ms`]). Runs for the life of the process. +/// `writer` is the probe's own pool ([`connect_probe_pool`]), never the +/// serving writer pool. +pub async fn run_probe(writer: PgPool, fence: Arc, probe_interval: Duration) { + let mut interval = tokio::time::interval(probe_interval); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut state = ProbeLoopState::default(); loop { interval.tick().await; - match probe_once(&writer, &fence).await { - Ok(_) => {} - Err(e) => { - fence.close(); - tracing::warn!(error = %e, "replica fence probe failed; fence closed"); - } + probe_tick(&writer, &fence, &mut state).await; + } +} + +/// How often a run of failed, slow or late beats is logged. Every beat is +/// still on its span; the log only marks the +/// episode, so a degraded writer cannot turn the probe cadence into a log +/// flood. +const PROBE_LOG_INTERVAL: Duration = Duration::from_secs(10); + +/// Admits at most one log line per [`PROBE_LOG_INTERVAL`], counting the +/// rest. +#[derive(Debug, Default)] +struct LogThrottle { + last: Option, + suppressed: u64, +} + +impl LogThrottle { + /// `Some(suppressed since the last admitted line)` when a line may be + /// logged now. + fn admit(&mut self, now: Instant) -> Option { + if self + .last + .is_some_and(|at| now.duration_since(at) < PROBE_LOG_INTERVAL) + { + self.suppressed += 1; + return None; } + self.last = Some(now); + Some(std::mem::take(&mut self.suppressed)) + } +} + +/// Log state carried across probe ticks. +#[derive(Debug, Default)] +struct ProbeLoopState { + /// Failed probes since the last success. + consecutive_failures: u64, + /// Failure lines; reset on recovery so a new run's first failure + /// always logs. + failure_log: LogThrottle, +} + +/// One probe-loop tick. A failure is logged and keeps the retained entries: +/// they were proved by earlier handshakes and stay valid, so one failed +/// probe must not route every read to the writer. Only staleness +/// ([`FENCE_STALENESS`]) closes a fence whose probe keeps failing. +async fn probe_tick(writer: &PgPool, fence: &ReplicaFence, state: &mut ProbeLoopState) { + let mut trace = ProbeTrace::default(); + let result = probe_traced(writer, fence, &mut trace).await; + let timings = trace.timings; + match result { + Err(e) => { + state.consecutive_failures += 1; + let Some(suppressed) = state.failure_log.admit(Instant::now()) else { + return; + }; + tracing::warn!( + error = %e, + error_kind = e.kind(), + consecutive_failures = state.consecutive_failures, + suppressed, + heartbeat_age_ms = fence.heartbeat_age().map(millis), + acquire_ms = millis(timings.acquire), + lock_ms = millis(timings.lock), + scan_ms = millis(timings.scan), + heartbeat_ms = millis(timings.heartbeat), + commit_ms = millis(timings.commit), + "replica fence probe failed; retained proofs stand" + ); + } + Ok(entry) if state.consecutive_failures > 0 => { + tracing::info!( + token = entry.token, + failed_probes = state.consecutive_failures, + beat_gap_ms = trace.beat_gap.map(millis), + "replica fence probe recovered" + ); + state.consecutive_failures = 0; + state.failure_log = LogThrottle::default(); + } + Ok(_) => {} } } #[cfg(test)] mod postgres_tests { use super::*; + use crate::test_support::{ScratchDb, ScratchRole}; /// A private scratch database with migrations applied: the probe tests /// mutate the singleton heartbeat row (rewind/rotate), which must never - /// race the shared dev database or each other. - async fn scratch_db() -> (PgPool, PgPool, String) { - let admin = PgPool::connect(&crate::test_support::database_url()) - .await - .expect("connect admin"); - let name = format!("fence_probe_{}", uuid::Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(&admin) - .await - .expect("create scratch db"); - let base = crate::test_support::database_url(); - let idx = base.rfind('/').expect("db url has a path segment"); - let pool = PgPool::connect(&format!("{}/{}", &base[..idx], name)) - .await - .expect("connect scratch db"); - crate::migration::run_migrations(&pool) - .await - .expect("migrate scratch db"); - (admin, pool, name) - } - - async fn drop_scratch_db(admin: &PgPool, pool: PgPool, name: &str) { - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(admin) - .await; + /// race the shared dev database or each other. Dropping the guard drops + /// the database. + async fn scratch_db() -> (PgPool, ScratchDb) { + ScratchDb::migrated(&crate::test_support::database_url(), "fence_probe").await } #[test] @@ -893,6 +1280,79 @@ mod postgres_tests { assert!(fence.heartbeat_age().expect("entry retained") > FENCE_STALENESS); } + /// A failed probe proves nothing new but must keep what earlier probes + /// proved: the retained entry still answers `newest()` and `resolve()`. + /// Closing here routed every read to the writer until the next success. + #[tokio::test] + async fn failed_probe_keeps_retained_proofs() { + let fence = ReplicaFence::new(); + let epoch = Uuid::new_v4(); + let wall = Utc::now(); + fence.record(7, epoch, Instant::now(), wall); + + let writer = sqlx::postgres::PgPoolOptions::new() + .connect_lazy(&crate::test_support::database_url()) + .expect("construct lazy writer pool"); + writer.close().await; + probe_once(&writer, &fence) + .await + .expect_err("a closed writer pool fails the probe"); + + probe_tick(&writer, &fence, &mut ProbeLoopState::default()).await; + + let newest = fence + .newest() + .expect("retained proof survives a failed probe"); + assert_eq!((newest.token, newest.fence_wall), (7, wall)); + assert!(matches!( + fence.resolve(7, epoch), + ResolveOutcome::Proved(entry) if entry.token == 7 + )); + + // The retained entry is also what catches an epoch-keeping restore + // across the outage: a rewound token is a regression, not a fresh + // start. An emptied ring here would accept it under the old epoch. + assert_eq!( + fence.record(5, epoch, Instant::now(), wall), + RecordOutcome::TokenRegression + ); + } + + /// An unset interval selects the default, a set one is clamped to the + /// accepted range, and the budget floor covers one lock-timed-out beat. + #[test] + fn probe_interval_defaults_and_clamps() { + assert_eq!(probe_interval_from_ms(0), DEFAULT_PROBE_INTERVAL); + assert_eq!(probe_interval_from_ms(400), Duration::from_millis(400)); + assert_eq!(probe_interval_from_ms(1), MIN_PROBE_INTERVAL); + assert_eq!(probe_interval_from_ms(u64::MAX), MAX_PROBE_INTERVAL); + assert_eq!( + min_read_budget(DEFAULT_PROBE_INTERVAL), + Duration::from_millis(1700) + ); + assert_eq!( + min_read_budget(Duration::from_millis(400)), + Duration::from_millis(1600) + ); + } + + /// The probe's log throttle admits one line per interval and reports + /// how many it held back. + #[test] + fn probe_log_throttle_admits_one_line_per_interval() { + let mut throttle = LogThrottle::default(); + let start = Instant::now(); + assert_eq!(throttle.admit(start), Some(0), "first line always logs"); + assert_eq!(throttle.admit(start + Duration::from_secs(1)), None); + assert_eq!(throttle.admit(start + Duration::from_secs(2)), None); + assert_eq!( + throttle.admit(start + PROBE_LOG_INTERVAL), + Some(2), + "next line reports what was suppressed" + ); + assert_eq!(throttle.admit(start + PROBE_LOG_INTERVAL), None); + } + /// Resolve picks the greatest retained entry <= the observed token — /// a lagged reader proves from an older wall, never from thin air. #[test] @@ -1014,7 +1474,9 @@ mod postgres_tests { .expect("connect idle"); let _idle_conn = idle_pool.acquire().await.expect("idle conn"); - let before = sample_writer(&pool).await.expect("sample without tx"); + let before = sample_writer(&pool, &mut ProbeTimings::default()) + .await + .expect("sample without tx"); // Now hold a transaction open on a second connection. let tx_pool = PgPool::connect(&crate::test_support::database_url()) @@ -1026,7 +1488,9 @@ mod postgres_tests { .await .expect("touch tx"); - let during = sample_writer(&pool).await.expect("sample with open tx"); + let during = sample_writer(&pool, &mut ProbeTimings::default()) + .await + .expect("sample with open tx"); let oldest = during .oldest_xact_start .expect("open transaction must appear in the oldest-xact term"); @@ -1046,12 +1510,73 @@ mod postgres_tests { tx.rollback().await.expect("rollback"); } + /// The probe pool installs its own lock budget: while a shared floor + /// lock outlives it, the probe fails fast with `lock_timeout` rather + /// than holding an exclusive request (which queues every new channel + /// write behind it) for the serving writer's longer budget. Retained + /// proofs are untouched and the next beat succeeds once the lock clears. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn cluster_global_probe_pool_bounds_the_floor_lock_wait() { + let (pool, _scratch) = scratch_db().await; + let probe_pool = connect_probe_pool(&pool); + let fence = ReplicaFence::new(); + let first = probe_once(&probe_pool, &fence) + .await + .expect("probe through its own pool"); + let (statement, idle): (String, String) = sqlx::query_as( + "SELECT current_setting('statement_timeout'), \ + current_setting('idle_in_transaction_session_timeout')", + ) + .fetch_one(&probe_pool) + .await + .expect("read probe session timeouts"); + // PROBE_STATEMENT_TIMEOUT, as Postgres renders it. + assert_eq!( + (statement.as_str(), idle.as_str()), + ("2s", "2s"), + "probe session must bound statements and idle transactions" + ); + + let mut blocker = pool.begin().await.expect("begin shared-lock blocker"); + sqlx::query("SELECT pg_advisory_xact_lock_shared($1)") + .bind(REPLICA_FLOOR_LOCK_KEY) + .execute(&mut *blocker) + .await + .expect("hold shared floor lock"); + + let started = Instant::now(); + let err = probe_once(&probe_pool, &fence) + .await + .expect_err("a held shared floor lock must time the probe out"); + let waited = started.elapsed(); + assert_eq!(err.kind(), "lock_timeout", "unexpected error: {err:?}"); + assert!( + waited >= PROBE_LOCK_TIMEOUT && waited < PROBE_LOCK_TIMEOUT + Duration::from_secs(1), + "probe waited {waited:?}, expected about {PROBE_LOCK_TIMEOUT:?}" + ); + assert_eq!( + fence.newest().map(|entry| entry.token), + Some(first.token), + "a timed-out beat keeps the retained proof" + ); + + blocker + .rollback() + .await + .expect("release shared-lock blocker"); + let next = probe_once(&probe_pool, &fence) + .await + .expect("probe recovers once the lock clears"); + assert!(next.token > first.token); + } + /// The sample must not capture `S` while a compliant shared writer lock is /// still held. It must block until release, then sample. #[tokio::test] #[ignore = "requires Postgres"] - async fn sample_writer_waits_for_shared_floor_lock_before_sampling_time() { - let (admin, pool, name) = scratch_db().await; + async fn cluster_global_sample_writer_waits_for_shared_floor_lock_before_sampling_time() { + let (pool, _scratch) = scratch_db().await; let mut blocker = pool.begin().await.expect("begin shared-lock blocker"); sqlx::query("SELECT pg_advisory_xact_lock_shared($1)") @@ -1061,7 +1586,10 @@ mod postgres_tests { .expect("hold shared floor lock"); let sample_pool = pool.clone(); - let mut sampling = tokio::spawn(async move { sample_writer(&sample_pool).await }); + let mut sampling = + tokio::spawn( + async move { sample_writer(&sample_pool, &mut ProbeTimings::default()).await }, + ); assert!( tokio::time::timeout(Duration::from_millis(100), &mut sampling) .await @@ -1090,8 +1618,6 @@ mod postgres_tests { sample.sampled_at, marker_before_release ); - - drop_scratch_db(&admin, pool, &name).await; } /// An unprivileged probe role sees NULL `state`/`xact_start` for other @@ -1101,10 +1627,6 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn cluster_global_sample_writer_fails_closed_when_activity_is_masked() { - let admin = PgPool::connect(&crate::test_support::database_url()) - .await - .expect("connect"); - // Hold a transaction open as the privileged user: this is the row // the unprivileged probe must notice it cannot classify. let tx_pool = PgPool::connect(&crate::test_support::database_url()) @@ -1118,23 +1640,26 @@ mod postgres_tests { // An unprivileged login role (no pg_monitor): pg_stat_activity masks // other sessions' state columns for it. - let role = format!("fence_probe_{}", uuid::Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!( - "CREATE ROLE {role} LOGIN PASSWORD 'fence_probe_test'" // sadscan:disable np.postgres.1 - ))) - .execute(&admin) - .await - .expect("create unprivileged role"); + let role = ScratchRole::create( + &crate::test_support::database_url(), + "fence_probe", + "LOGIN PASSWORD 'fence_probe_test'", // sadscan:disable np.postgres.1 + ) + .await; let base = crate::test_support::database_url(); let unpriv_url = { let rest = base.strip_prefix("postgres://").expect("pg url"); let at = rest.rfind('@').expect("credentials in url"); - format!("postgres://{role}:fence_probe_test@{}", &rest[at + 1..]) + format!( + "postgres://{}:fence_probe_test@{}", + role.name(), + &rest[at + 1..] + ) }; let unpriv = PgPool::connect(&unpriv_url).await.expect("connect unpriv"); - let err = sample_writer(&unpriv) + let err = sample_writer(&unpriv, &mut ProbeTimings::default()) .await .expect_err("masked pg_stat_activity must fail closed"); assert!( @@ -1144,10 +1669,6 @@ mod postgres_tests { tx.rollback().await.expect("rollback"); unpriv.close().await; - sqlx::query(sqlx::AssertSqlSafe(format!("DROP ROLE {role}"))) - .execute(&admin) - .await - .expect("drop role"); } /// The Aurora PostgreSQL identity function name is exact — the @@ -1191,7 +1712,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn cluster_global_probe_commits_tokens_and_sessions_prove_coverage() { - let (admin, pool, name) = scratch_db().await; + let (pool, _scratch) = scratch_db().await; let fence = ReplicaFence::new(); let first = probe_once(&pool, &fence).await.expect("first probe"); @@ -1236,7 +1757,6 @@ mod postgres_tests { ); drop(conn); - drop_scratch_db(&admin, pool, &name).await; } /// A same-epoch token rewind on the writer (restore adversary) must not @@ -1246,10 +1766,13 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn cluster_global_probe_rotates_epoch_on_same_epoch_token_regression() { - let (admin, pool, name) = scratch_db().await; + let (pool, _scratch) = scratch_db().await; + // Through the production one-connection pool: rotation re-acquires + // after the sample has released its connection. + let probe_pool = connect_probe_pool(&pool); let fence = ReplicaFence::new(); - let before = probe_once(&pool, &fence).await.expect("probe"); + let before = probe_once(&probe_pool, &fence).await.expect("probe"); let mut conn = pool.acquire().await.expect("conn"); let old_epoch = observe_heartbeat(&mut conn, false) .await @@ -1263,7 +1786,9 @@ mod postgres_tests { .await .expect("rewind token"); - let after = probe_once(&pool, &fence).await.expect("recovery probe"); + let after = probe_once(&probe_pool, &fence) + .await + .expect("recovery probe"); // The pre-rewind observation must no longer prove anything. assert_eq!( fence.resolve(before.token, old_epoch), @@ -1286,6 +1811,5 @@ mod postgres_tests { ); drop(conn); - drop_scratch_db(&admin, pool, &name).await; } } diff --git a/crates/buzz-db/src/runtime/tests.rs b/crates/buzz-db/src/runtime/tests.rs index c9e1c6dc36a..f7763466737 100644 --- a/crates/buzz-db/src/runtime/tests.rs +++ b/crates/buzz-db/src/runtime/tests.rs @@ -1,8 +1,10 @@ use super::*; +use crate::test_support::ScratchDb; use crate::{relay_members, thread}; use buzz_core::CommunityId; use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter}; use sqlx::{Connection, PgPool}; +use std::time::Instant; use uuid::Uuid; const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 -- local test-only credentials @@ -168,6 +170,7 @@ async fn event_write_transaction_preserves_legacy_acquisition_metrics() { ( "buzz_db_pool_acquisitions_total".to_owned(), [ + ("operation".to_owned(), "event_write".to_owned()), ("outcome".to_owned(), "error".to_owned()), ("pool_role".to_owned(), "writer".to_owned()), ] @@ -360,11 +363,34 @@ async fn readiness_check_cancellation_balances_waiter_and_inflight_connection() querying_db .readiness_check_sql( tokio::time::Instant::now() + std::time::Duration::from_secs(5), - "SELECT pg_sleep(5)", + "SELECT pg_sleep(1)", ) .await }); - tokio::time::sleep(std::time::Duration::from_millis(25)).await; + // Abort only once the server is running the query. sqlx's release ping + // waits for it to finish, so the connection returns about 1 s later, + // well inside the 5 s recovery bound below. + let observer = PgPool::connect(&database_url) + .await + .expect("connect activity observer"); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let running: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_stat_activity \ + WHERE datname = current_database() AND state = 'active' \ + AND query = 'SELECT pg_sleep(1)')", + ) + .fetch_one(&observer) + .await + .expect("inspect readiness query"); + if running { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + }) + .await + .expect("readiness query reached the server"); querying.abort(); assert!(querying .await @@ -746,59 +772,14 @@ async fn admin_url() -> String { std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.into()) } -/// Create a fresh scratch database on the same server and optionally run migrations. -async fn create_scratch_db_through( - admin: &PgPool, - prefix: &str, - target: Option, -) -> (PgPool, String) { - let name = format!("{}_{}", prefix, Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(admin) - .await - .expect("create scratch db"); - let base = admin_url().await; - // Swap the database path segment of the admin URL for the scratch name. - let scratch_url = { - let idx = base.rfind('/').expect("db url has a path segment"); - format!("{}/{}", &base[..idx], name) - }; - let pool = PgPool::connect(&scratch_url) - .await - .expect("connect scratch db"); - match target { - Some(target) => migration::run_migrations_through(&pool, target) - .await - .expect("migrate scratch db through target"), - None => migration::run_migrations(&pool) - .await - .expect("migrate scratch db"), - } - (pool, name) -} - -/// Create a fresh scratch database on the same server and run all migrations. -/// Returns (pool, db_name); callers should `drop_scratch_db` when done. -async fn create_scratch_db(admin: &PgPool, prefix: &str) -> (PgPool, String) { - create_scratch_db_through(admin, prefix, None).await -} - -async fn drop_scratch_db(admin: &PgPool, pool: PgPool, name: &str) { - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(admin) - .await; -} - #[tokio::test] #[ignore = "requires Postgres"] async fn push_gateway_profile_migration_converges_brownfield_authority() { let admin = PgPool::connect(&admin_url().await) .await .expect("connect admin database"); - let (pool, name) = create_scratch_db_through(&admin, "push_profile", Some(42)).await; + let (pool, _scratch) = + ScratchDb::migrated_through(&admin_url().await, "push_profile", 42).await; let installation_id = Uuid::new_v4(); let now = chrono::Utc::now(); @@ -880,7 +861,6 @@ async fn push_gateway_profile_migration_converges_brownfield_authority() { .await; assert!(sandbox.is_err(), "legacy sandbox profile must be rejected"); - drop_scratch_db(&admin, pool, &name).await; admin.close().await; } @@ -933,27 +913,27 @@ fn signed_event_at(keys: &nostr::Keys, content: &str, secs: u64) -> nostr::Event .expect("sign event") } +// Routing tests intentionally model stored history and divergent replicas. +// Raw fixture SQL keeps them independent of serving-time floor admission. async fn insert_top_level(pool: &PgPool, community: Uuid, channel: Uuid, ev: &nostr::Event) { - let ts = chrono::DateTime::from_timestamp(ev.created_at.as_secs() as i64, 0).expect("valid ts"); - event::insert_event_with_thread_metadata( + crate::test_support::insert_historical_event( pool, CommunityId::from_uuid(community), ev, - Some(channel), - Some(event::ThreadMetadataParams { - event_id: ev.id.as_bytes(), - event_created_at: ts, - channel_id: channel, - parent_event_id: None, - parent_event_created_at: None, - root_event_id: None, - root_event_created_at: None, - depth: 0, - broadcast: true, - }), + channel, + ) + .await; + sqlx::query( + "INSERT INTO thread_metadata (community_id,event_id,event_created_at,channel_id,depth,broadcast) \ + VALUES ($1,$2,to_timestamp($3),$4,0,true)", ) + .bind(community) + .bind(ev.id.as_bytes().as_slice()) + .bind(ev.created_at.as_secs() as f64) + .bind(channel) + .execute(pool) .await - .expect("insert top-level event"); + .expect("seed top-level metadata"); } async fn insert_thread_reply( @@ -963,29 +943,37 @@ async fn insert_thread_reply( root: &nostr::Event, reply: &nostr::Event, ) { - let reply_ts = - chrono::DateTime::from_timestamp(reply.created_at.as_secs() as i64, 0).expect("valid ts"); - let root_ts = - chrono::DateTime::from_timestamp(root.created_at.as_secs() as i64, 0).expect("valid ts"); - event::insert_event_with_thread_metadata( + crate::test_support::insert_historical_event( pool, CommunityId::from_uuid(community), reply, - Some(channel), - Some(event::ThreadMetadataParams { - event_id: reply.id.as_bytes(), - event_created_at: reply_ts, - channel_id: channel, - parent_event_id: Some(root.id.as_bytes()), - parent_event_created_at: Some(root_ts), - root_event_id: Some(root.id.as_bytes()), - root_event_created_at: Some(root_ts), - depth: 1, - broadcast: false, - }), + channel, ) + .await; + sqlx::query( + "INSERT INTO thread_metadata \ + (community_id,event_id,event_created_at,channel_id,parent_event_id,parent_event_created_at, \ + root_event_id,root_event_created_at,depth,broadcast) \ + VALUES ($1,$2,to_timestamp($3),$4,$5,to_timestamp($6),$5,to_timestamp($6),1,false)", + ) + .bind(community) + .bind(reply.id.as_bytes().as_slice()) + .bind(reply.created_at.as_secs() as f64) + .bind(channel) + .bind(root.id.as_bytes().as_slice()) + .bind(root.created_at.as_secs() as f64) + .execute(pool) .await - .expect("insert reply"); + .expect("seed reply metadata"); + sqlx::query( + "UPDATE thread_metadata SET reply_count=reply_count+1,descendant_count=descendant_count+1, \ + last_reply_at=now() WHERE community_id=$1 AND event_id=$2", + ) + .bind(community) + .bind(root.id.as_bytes().as_slice()) + .execute(pool) + .await + .expect("seed root counters"); } /// Composite thread cursor: 8-byte BE seconds + raw event id. @@ -1008,6 +996,121 @@ async fn read_falls_back_to_writer_when_no_replica_configured() { assert!(db.read_pool_stats().is_none()); } +/// A match-nothing read is answered before any pool acquire, on every query +/// entry point, and an invalid query that would also match nothing still +/// returns its validation error. Replica routing is on and the fence is open, +/// so a routed read that reached `route_read` would try the reader first. Both +/// pools point at a closed port, and the `limit: 1` control proves that a real +/// page does try to acquire, from the reader and then the writer. +#[tokio::test] +async fn match_nothing_reads_take_no_connection() { + use metrics_util::debugging::DebuggingRecorder; + + let dead_pool = || { + sqlx::postgres::PgPoolOptions::new() + .acquire_timeout(std::time::Duration::from_millis(200)) + .connect_lazy("postgres://unused@127.0.0.1:1/unused") // sadscan:disable np.postgres.1 + .expect("lazy pool") + }; + let mut db = Db::from_pools(dead_pool(), dead_pool()); + db.set_replica_read_max_age_for_tests(Some(std::time::Duration::from_secs(3600))); + db.fence().force_open_for_tests(chrono::Utc::now()); + let community = CommunityId::from_uuid(Uuid::new_v4()); + let page = |limit| { + let mut q = EventQuery::for_community(community); + q.limit = Some(limit); + q + }; + let with = |edit: fn(&mut EventQuery)| { + let mut q = page(10); + edit(&mut q); + q + }; + let empty_pages = [ + ("limit 0", page(0)), + ("max_limit 0", with(|q| q.max_limit = Some(0))), + ("empty kinds", with(|q| q.kinds = Some(vec![]))), + ("empty authors", with(|q| q.authors = Some(vec![]))), + ("empty ids", with(|q| q.ids = Some(vec![]))), + ("empty #e", with(|q| q.e_tags = Some(vec![]))), + ("empty #a", with(|q| q.a_tags = Some(vec![]))), + ]; + // Validation runs before the match-nothing check, so the error wins. + let invalid = [ + ( + "before_id without until", + with(|q| { + q.limit = Some(0); + q.before_id = Some(vec![0; 32]); + }), + ), + ( + "global_only with channel_id", + with(|q| { + q.kinds = Some(vec![]); + q.global_only = true; + q.channel_id = Some(Uuid::nil()); + }), + ), + ]; + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + let acquiring_roles = || { + snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, _, _, _)| key.key().name() == "buzz_db_pool_acquire_attempts_total") + .filter_map(|(key, _, _, _)| { + key.key() + .labels() + .find(|label| label.key() == "pool_role") + .map(|label| label.value().to_owned()) + }) + .collect::>() + }; + + for (case, q) in &empty_pages { + let results = [ + db.query_events(q).await, + db.query_events_routed("test", q).await, + db.query_events_routed_bounded("test", q).await, + ]; + for (entry, result) in ["writer", "routed", "routed bounded"].iter().zip(results) { + let events = result.unwrap_or_else(|e| panic!("{case} via {entry}: {e}")); + assert!(events.is_empty(), "{case} via {entry} must match nothing"); + } + } + for (case, q) in &invalid { + let results = [ + db.query_events(q).await, + db.query_events_routed("test", q).await, + db.query_events_routed_bounded("test", q).await, + ]; + for (entry, result) in ["writer", "routed", "routed bounded"].iter().zip(results) { + assert!( + matches!(result, Err(DbError::InvalidData(_))), + "{case} via {entry} must fail validation, got {result:?}" + ); + } + } + assert!( + acquiring_roles().is_empty(), + "a match-nothing read must not try to acquire: {:?}", + acquiring_roles() + ); + + db.query_events_routed("test", &page(1)) + .await + .expect_err("a real page needs the (unreachable) pools"); + assert_eq!( + acquiring_roles(), + ["reader", "writer"].map(str::to_owned).into(), + "the control must have tried the reader, then the writer" + ); +} + #[test] fn read_budget_zero_disables_and_large_values_clamp_to_staleness() { assert_eq!(read_budget_from_ms(0), None, "0 = bounded routing off"); @@ -1192,11 +1295,8 @@ fn reader_min_connections_is_a_fifth_of_max_with_a_floor_of_one() { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_window_routes_head_to_writer_and_cursor_pages_to_replica() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "routing_w").await; - let (replica, rname) = create_scratch_db(&admin, "routing_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "routing_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "routing_r").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -1265,9 +1365,6 @@ async fn channel_window_routes_head_to_writer_and_cursor_pages_to_replica() { ], "cursor page must be served by the replica" ); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// Fail-closed on a mid-request replica failure (Dawn, review of @@ -1279,11 +1376,8 @@ async fn channel_window_routes_head_to_writer_and_cursor_pages_to_replica() { #[tokio::test] #[ignore = "requires Postgres"] async fn replica_window_failure_falls_back_to_writer() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "fb_w").await; - let (replica, rname) = create_scratch_db(&admin, "fb_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "fb_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "fb_r").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -1348,9 +1442,6 @@ async fn replica_window_failure_falls_back_to_writer() { vec!["m2", "m1"], "fallback page must be the writer's answer (no replica marker)" ); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// [`replica_window_failure_falls_back_to_writer`] for the thread-replies @@ -1359,11 +1450,8 @@ async fn replica_window_failure_falls_back_to_writer() { #[tokio::test] #[ignore = "requires Postgres"] async fn replica_thread_failure_falls_back_to_writer() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "fbt_w").await; - let (replica, rname) = create_scratch_db(&admin, "fbt_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "fbt_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "fbt_r").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -1421,9 +1509,6 @@ async fn replica_thread_failure_falls_back_to_writer() { page[0].stored_event.event.content, "r3", "fallback page must be the writer's answer" ); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// Mid-request degradation of the held session (Dawn, review of @@ -1438,8 +1523,8 @@ async fn read_session_degrades_to_writer_when_replica_connection_dies() { let admin = PgPool::connect(&admin_url().await) .await .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "deg_w").await; - let (replica, rname) = create_scratch_db(&admin, "deg_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "deg_w").await; + let (replica, replica_db) = ScratchDb::migrated(&admin_url().await, "deg_r").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -1482,7 +1567,7 @@ async fn read_session_degrades_to_writer_when_replica_connection_dies() { "SELECT pg_terminate_backend(pid) FROM pg_stat_activity \ WHERE datname = $1 AND pid <> pg_backend_pid()", ) - .bind(&rname) + .bind(replica_db.name()) .execute(&admin) .await .expect("terminate replica backends"); @@ -1504,8 +1589,146 @@ async fn read_session_degrades_to_writer_when_replica_connection_dies() { ); drop(session); - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; +} + +/// The history-read permit lives exactly as long as the reader transaction +/// it admitted, including a [`ReadSession`] held for follow-up queries; a +/// history read that cannot get a permit within the bounded wait is +/// rejected as retryable and never moves to the writer. +#[tokio::test(flavor = "current_thread")] +#[ignore = "requires Postgres"] +async fn history_permit_follows_the_read_session_and_a_full_gate_rejects() { + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "cap_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "cap_r").await; + + let author = nostr::Keys::generate(); + let community = Uuid::new_v4(); + let channel = Uuid::new_v4(); + seed_community_channel(&writer, community, channel, &author).await; + seed_community_channel(&replica, community, channel, &author).await; + let base = 1_700_000_000u64; + for pool in [&writer, &replica] { + for (content, at) in [("m1", base), ("m2", base + 10)] { + insert_top_level( + pool, + community, + channel, + &signed_event_at(&author, content, at), + ) + .await; + } + } + + let db = Db::from_pools(writer.clone(), replica.clone()); + db.fence().force_open_for_tests(chrono::Utc::now()); + let cid = CommunityId::from_uuid(community); + let cap = db.history_reads.available(); + assert_eq!( + cap, + super::history_reads::cap(db.read_max_connections) as usize + ); + + let head = db + .get_channel_window(cid, channel, 1, None, None) + .await + .expect("head window"); + let cursor = head.next_cursor.expect("has_more implies next_cursor"); + let (_window, session) = db + .get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .await + .expect("routed cursor window"); + assert!(session.is_replica(), "fixture must route to the replica"); + assert_eq!( + db.history_reads.available(), + cap - 1, + "the held session must keep its permit" + ); + + // Fill the gate: every remaining permit is held elsewhere. + let mut others = Vec::new(); + for _ in 1..cap { + others.push( + db.history_reads + .admit(super::history_reads::PERMIT_WAIT) + .await + .expect("free permit"), + ); + } + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let started = Instant::now(); + let rejected = { + let _guard = metrics::set_default_local_recorder(&recorder); + db.get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .await + } + .err() + .expect("a full gate must reject the history read"); + assert!( + matches!(rejected, DbError::Sqlx(sqlx::Error::PoolTimedOut)), + "the rejection must be the retryable pool timeout; got {rejected:?}" + ); + assert!( + started.elapsed() >= super::history_reads::PERMIT_WAIT, + "the read must wait out the bounded permit wait before rejecting" + ); + let decisions: Vec<(String, String)> = snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, ..)| key.key().name() == "buzz_db_route_decision") + .map(|(key, ..)| { + let label = |name: &str| { + key.key() + .labels() + .find(|l| l.key() == name) + .map(|l| l.value().to_owned()) + .unwrap_or_default() + }; + (label("decision"), label("reason")) + }) + .collect(); + assert_eq!( + decisions, + vec![("rejected".to_owned(), "history_read_cap".to_owned())], + "a capped history read is rejected once and never served by the writer" + ); + + // Dropping the session releases its permit, and the next read routes. + drop(session); + assert_eq!(db.history_reads.available(), 1); + let (_window, session) = db + .get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .await + .expect("a released permit admits the next read"); + assert!(session.is_replica()); + drop(session); + drop(others); + assert_eq!(db.history_reads.available(), cap); + + // An operator lowering the cap at runtime holds new reads to the new + // limit while one is in flight, and raising it readmits them. + let (_window, held) = db + .get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .await + .expect("routed cursor window"); + assert_eq!(db.history_read_gate().set_limit(1), 1); + let rejected = db + .get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .await + .err() + .expect("a lowered cap must reject the next history read"); + assert!( + matches!(rejected, DbError::Sqlx(sqlx::Error::PoolTimedOut)), + "a lowered cap sheds as retryable; got {rejected:?}" + ); + assert_eq!(db.history_read_gate().set_limit(cap), cap); + let (_window, second) = db + .get_channel_window_with_session(cid, channel, 10, Some(cursor), None) + .await + .expect("a raised cap admits the next read"); + drop((held, second)); + assert_eq!(db.history_reads.available(), cap); } /// Snapshot continuity (Wren, review of 17ea2ff6a): the routed request @@ -1519,11 +1742,8 @@ async fn read_session_degrades_to_writer_when_replica_connection_dies() { #[tokio::test] #[ignore = "requires Postgres"] async fn routed_request_holds_one_snapshot_across_page_and_aux() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "snap_w").await; - let (replica, rname) = create_scratch_db(&admin, "snap_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "snap_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "snap_r").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -1601,8 +1821,6 @@ async fn routed_request_holds_one_snapshot_across_page_and_aux() { ); drop(session); - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// Head gate (Predicate A): with the budget unset, a head fetch reads @@ -1613,11 +1831,8 @@ async fn routed_request_holds_one_snapshot_across_page_and_aux() { #[tokio::test] #[ignore = "requires Postgres"] async fn head_fetch_routes_by_configured_budget() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "head_w").await; - let (replica, rname) = create_scratch_db(&admin, "head_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "head_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "head_r").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -1684,9 +1899,6 @@ async fn head_fetch_routes_by_configured_budget() { vec!["fresh-writer-only".to_string(), "shared".to_string()], "an over-budget entry must fail the head gate closed" ); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// End-to-end deploy-default proof for the NEW routed seams: with the @@ -1698,11 +1910,8 @@ async fn head_fetch_routes_by_configured_budget() { #[tokio::test] #[ignore = "requires Postgres"] async fn query_events_routed_defaults_dark_and_routes_covered_when_enabled() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "qer_w").await; - let (replica, rname) = create_scratch_db(&admin, "qer_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "qer_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "qer_r").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -1762,9 +1971,6 @@ async fn query_events_routed_defaults_dark_and_routes_covered_when_enabled() { "budget set + covered-eligible must route to the replica" ); assert!(!contents(&rows).contains("writer-only")); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// COUNT is bounded-only (rev 5 deletion-visibility rule): a @@ -1775,11 +1981,8 @@ async fn query_events_routed_defaults_dark_and_routes_covered_when_enabled() { #[tokio::test] #[ignore = "requires Postgres"] async fn count_events_routed_is_bounded_only() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "cnt_w").await; - let (replica, rname) = create_scratch_db(&admin, "cnt_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "cnt_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "cnt_r").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -1841,9 +2044,6 @@ async fn count_events_routed_is_bounded_only() { "an over-budget entry must fail the count closed to the writer, \ even when the covered arm would admit the shape" ); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// Routed relay-membership check: budget unset ⇒ writer; budget set + @@ -1852,11 +2052,8 @@ async fn count_events_routed_is_bounded_only() { #[tokio::test] #[ignore = "requires Postgres"] async fn is_relay_member_is_bounded_routed_and_fails_closed() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "mem_w").await; - let (replica, rname) = create_scratch_db(&admin, "mem_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "mem_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "mem_r").await; let community = Uuid::new_v4(); for pool in [&writer, &replica] { @@ -1929,9 +2126,65 @@ async fn is_relay_member_is_bounded_routed_and_fails_closed() { .expect("entry too old"), "an over-budget entry must fail closed to the writer" ); +} + +/// The per-AUTH pending default-channel read is bounded-routed like +/// membership; the roster writers' read stays on the writer. A different +/// token on each pool proves which pool answered. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn pending_default_channel_join_routed_reads_the_bounded_replica() { + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "pend_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "pend_r").await; + + let community = Uuid::new_v4(); + let pubkey = "cc".repeat(32); + let (writer_token, replica_token) = (Uuid::new_v4(), Uuid::new_v4()); + for (pool, token) in [(&writer, writer_token), (&replica, replica_token)] { + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("pending-routing-{}.example", community.simple())) + .execute(pool) + .await + .expect("insert community"); + sqlx::query( + "INSERT INTO relay_members (community_id, pubkey, role, auto_join_pending) \ + VALUES ($1, $2, 'member', $3)", + ) + .bind(community) + .bind(&pubkey) + .bind(token) + .execute(pool) + .await + .expect("seed pending work"); + } + let cid = CommunityId::from_uuid(community); + let token = |pending: Option| { + pending.expect("pending work").token + }; + + let mut db = Db::from_pools(writer.clone(), replica.clone()); + db.fence().force_open_for_tests(chrono::Utc::now()); + + // Budget unset ⇒ writer. + let pending = db.pending_default_channel_join_routed(cid, &pubkey).await; + assert_eq!(token(pending.expect("gate off")), writer_token); - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; + // Budget set + fresh entry ⇒ replica; the writer-only read ignores it. + db.set_replica_read_max_age_for_tests(Some(std::time::Duration::from_secs(5))); + let pending = db.pending_default_channel_join_routed(cid, &pubkey).await; + assert_eq!(token(pending.expect("gate on")), replica_token); + let pending = db.pending_default_channel_join(cid, &pubkey).await; + assert_eq!(token(pending.expect("writer read")), writer_token); + + // Entry older than the budget ⇒ fail closed to the writer. + db.fence().close(); + db.fence().force_open_for_tests_at( + chrono::Utc::now(), + std::time::Instant::now() - std::time::Duration::from_secs(10), + ); + let pending = db.pending_default_channel_join_routed(cid, &pubkey).await; + assert_eq!(token(pending.expect("entry too old")), writer_token); } /// Community separation across every routed seam, verified on @@ -1950,8 +2203,10 @@ async fn is_relay_member_is_bounded_routed_and_fails_closed() { /// the replica (not the writer) served the read. Every assertion /// requests A and demands B's rows never appear, including B's /// `replica-only` row, which is the one a leaky predicate would surface. -/// The routed fallback must cost ONE reader acquire budget, even when the -/// Aurora capability cache is cold. +/// A saturated reader must cost a routed read ONE reader acquire budget, +/// even when the Aurora capability cache is cold. A history read is then +/// rejected as retryable instead of moving to the writer; an authorization +/// read still falls back to the writer. /// /// Regression test for a stacked-budget bug found at `9fa3c9c0b`: the /// capability probe used to `acquire()` from the pool itself and return @@ -1976,17 +2231,10 @@ async fn is_relay_member_is_bounded_routed_and_fails_closed() { /// already covers. #[tokio::test(flavor = "current_thread")] #[ignore = "requires Postgres"] -async fn routed_fallback_spends_one_acquire_budget_when_aurora_cache_is_cold() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed, wname) = create_scratch_db(&admin, "one_budget").await; +async fn saturated_reader_spends_one_acquire_budget_and_rejects_history_reads() { + let (seed, scratch) = ScratchDb::migrated(&admin_url().await, "one_budget").await; seed.close().await; - let base = admin_url().await; - let scratch_url = { - let idx = base.rfind('/').expect("db url has a path segment"); - format!("{}/{}", &base[..idx], wname) - }; + let scratch_url = scratch.url().to_owned(); // `Db::new` so the writer arms the floor guard and the reader is the // real lazy `connect_read_pool` pool (warm floor of 1, 150ms @@ -2048,20 +2296,41 @@ async fn routed_fallback_spends_one_acquire_budget_when_aurora_cache_is_cold() { // local recorder is installed and the label assertions would vacuously // see an empty snapshot. let start = std::time::Instant::now(); - let count = { + let rejected = { let _guard = metrics::set_default_local_recorder(&recorder); db.count_events_routed("one_budget_probe", &query).await } - .expect("writer fallback still answers the read"); + .expect_err("a history read must not spill onto the writer"); let elapsed = start.elapsed(); - assert_eq!(count, 0, "writer answered on an empty scratch database"); + assert!( + matches!(rejected, DbError::Sqlx(sqlx::Error::PoolTimedOut)), + "the rejection must be the retryable pool timeout; got {rejected:?}" + ); assert!( elapsed < Duration::from_millis(250), - "routed fallback must spend ONE {}ms acquire budget, not two; took {}ms", + "routed read must spend ONE {}ms acquire budget, not two; took {}ms", Db::READER_ACQUIRE_TIMEOUT.as_millis(), elapsed.as_millis() ); + assert_eq!( + db.history_reads.available(), + 1, + "a rejected history read must release its permit" + ); + + // An authorization read on the same saturated reader keeps the writer + // fallback: only history reads are rejected. + let is_member = { + let _guard = metrics::set_default_local_recorder(&recorder); + db.is_relay_member( + CommunityId::from_uuid(Uuid::new_v4()), + &nostr::Keys::generate().public_key().to_hex(), + ) + .await + } + .expect("authorization read falls back to the writer"); + assert!(!is_member, "writer answered on an empty scratch database"); let reasons: std::collections::HashMap<(String, String), u64> = snapshotter .snapshot() @@ -2084,10 +2353,15 @@ async fn routed_fallback_spends_one_acquire_budget_when_aurora_cache_is_cold() { }) .collect(); + assert_eq!( + reasons.get(&("rejected".to_owned(), "reader_acquire_timeout".to_owned())), + Some(&1), + "the history read must be rejected as reader_acquire_timeout; got {reasons:?}" + ); assert_eq!( reasons.get(&("writer".to_owned(), "reader_acquire_timeout".to_owned())), Some(&1), - "saturated reader must fall back as writer/reader_acquire_timeout; got {reasons:?}" + "only the authorization read may fall back to the writer; got {reasons:?}" ); // `reader_validation_error` would mean we misclassified a timeout as a // broken reader, and `pool_busy` is the retired name — neither may @@ -2100,17 +2374,13 @@ async fn routed_fallback_spends_one_acquire_budget_when_aurora_cache_is_cold() { ); drop(held); - drop_scratch_db(&admin, db.pool.clone(), &wname).await; } #[tokio::test] #[ignore = "requires Postgres"] async fn routed_reads_are_confined_to_the_requested_community() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "sep_w").await; - let (replica, rname) = create_scratch_db(&admin, "sep_r").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "sep_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "sep_r").await; let author = nostr::Keys::generate(); let (comm_a, chan_a) = (Uuid::new_v4(), Uuid::new_v4()); @@ -2263,17 +2533,15 @@ async fn routed_reads_are_confined_to_the_requested_community() { // 4. By-ID hydration — ids carry no channel pin, and B's ids are // requested alongside A's. Only A's may hydrate. - let ids: Vec<&[u8]> = vec![ - a_shared.id.as_bytes(), - a_replica_only.id.as_bytes(), - b_shared.id.as_bytes(), - b_replica_only.id.as_bytes(), - ]; + let hits: Vec<([u8; 32], i64)> = [&a_shared, &a_replica_only, &b_shared, &b_replica_only] + .iter() + .map(|e| (e.id.to_bytes(), e.created_at.as_secs() as i64)) + .collect(); let rows = db - .get_events_by_ids_routed("sep_by_ids", cid_a, &ids) + .get_events_by_ids_at_routed("sep_by_ids", cid_a, &hits) .await .expect("routed by-ids"); - assert_a_only(&rows, "a-replica-only", "get_events_by_ids_routed"); + assert_a_only(&rows, "a-replica-only", "get_events_by_ids_at_routed"); // 5-7. All three feed builders, each given BOTH channels as // accessible — so only the community predicate can exclude B. @@ -2299,9 +2567,6 @@ async fn routed_reads_are_confined_to_the_requested_community() { .await .expect("routed activity"); assert_a_only(&rows, "a-replica-only", "query_feed_activity_routed"); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// D4: a LAZY reader pool (connect_lazy, never yet @@ -2311,20 +2576,13 @@ async fn routed_reads_are_confined_to_the_requested_community() { #[tokio::test] #[ignore = "requires Postgres"] async fn lazy_reader_pool_still_spawns_fence_probe() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed, wname) = create_scratch_db(&admin, "lazy_w").await; + let (seed, scratch) = ScratchDb::migrated(&admin_url().await, "lazy_w").await; seed.close().await; - let writer_url = { - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - format!("{}/{}", &base[..idx], wname) - }; + let writer_url = scratch.url().to_owned(); // `Db::new` (not `from_pools`) so the WRITER pool arms the // `buzz.created_at_floor` GUC — `spawn_fence_probe` verifies the - // floor guard on a writer connection, and `create_scratch_db`'s + // floor guard on a writer connection, and `ScratchDb::migrated`'s // plain `PgPool::connect` never arms it. The reader is still the // lazy `connect_read_pool` pool this test is about. let db = Db::new(&DbConfig { @@ -2341,8 +2599,66 @@ async fn lazy_reader_pool_still_spawns_fence_probe() { .await .expect("floor-guard verification must pass on the migrated writer"); assert!(spawned, "a configured (lazy) reader must spawn the probe"); +} - drop_scratch_db(&admin, db.pool.clone(), &wname).await; +/// The fence probe must keep beating while every serving writer connection +/// is checked out. On the serving pool its beat queued behind request +/// traffic, so under load every pod's newest token aged past the +/// bounded-read budget and reads spilled onto the saturated writer. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn fence_probe_beats_while_serving_writer_pool_is_exhausted() { + let (seed, scratch) = ScratchDb::migrated(&admin_url().await, "fence_own_pool").await; + seed.close().await; + + let url = scratch.url().to_owned(); + let db = Db::new(&DbConfig { + database_url: url.clone(), + read_database_url: Some(url), + max_connections: 1, + min_connections: 0, + acquire_timeout_secs: 1, + ..DbConfig::default() + }) + .await + .expect("connect armed Db with one serving writer connection"); + assert!( + db.spawn_fence_probe().await.expect("verification passes"), + "a configured reader must spawn the probe" + ); + + // Hold the serving writer pool's only connection for the whole test. + let mut held = db.pool.acquire().await.expect("hold serving connection"); + let baseline = db.fence().newest().map(|entry| entry.token); + + // Two beats strictly after the hold: one in flight when the hold began + // cannot satisfy this on its own. + let mut beats = 0; + let mut last = baseline; + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while beats < 2 { + assert!( + std::time::Instant::now() < deadline, + "probe stopped beating while the serving writer pool was exhausted" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + let newest = db.fence().newest().map(|entry| entry.token); + if newest > last { + beats += 1; + last = newest; + } + } + + // The beats come from the probe's own, identifiable session. + let probe_sessions: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_stat_activity \ + WHERE datname = current_database() AND application_name = $1", + ) + .bind(replica_fence::PROBE_APPLICATION_NAME) + .fetch_one(&mut *held) + .await + .expect("count probe sessions"); + assert_eq!(probe_sessions, 1, "the probe holds exactly one connection"); } /// Thread replies: head fetch reads the writer; a FULL cursor page is @@ -2352,11 +2668,8 @@ async fn lazy_reader_pool_still_spawns_fence_probe() { #[tokio::test] #[ignore = "requires Postgres"] async fn thread_replies_cursor_pages_route_to_replica_with_writer_terminal_verification() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "routing_tw").await; - let (replica, rname) = create_scratch_db(&admin, "routing_tr").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "routing_tw").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "routing_tr").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -2447,9 +2760,6 @@ async fn thread_replies_cursor_pages_route_to_replica_with_writer_terminal_verif .map(|r| r.stored_event.event.content.as_str()) .collect(); assert_eq!(contents, vec!["r3"], "unset replica falls back to writer"); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// Channel DESC scrollback, out-of-order commit adversary: the replica is @@ -2461,11 +2771,8 @@ async fn thread_replies_cursor_pages_route_to_replica_with_writer_terminal_verif #[tokio::test] #[ignore = "requires Postgres"] async fn channel_cursor_above_fence_stays_on_writer_preventing_middle_hole() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "fence_cw").await; - let (replica, rname) = create_scratch_db(&admin, "fence_cr").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "fence_cw").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "fence_cr").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -2540,9 +2847,6 @@ async fn channel_cursor_above_fence_stays_on_writer_preventing_middle_hole() { vec!["m1".to_string()], "fixture models the inversion: an over-open fence would skip m2" ); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// Thread ASC pagination, out-of-order commit adversary: the replica @@ -2554,11 +2858,8 @@ async fn channel_cursor_above_fence_stays_on_writer_preventing_middle_hole() { #[tokio::test] #[ignore = "requires Postgres"] async fn thread_full_replica_page_above_fence_is_reverified_on_writer() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, "fence_tw").await; - let (replica, rname) = create_scratch_db(&admin, "fence_tr").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "fence_tw").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url().await, "fence_tr").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -2627,9 +2928,6 @@ async fn thread_full_replica_page_above_fence_is_reverified_on_writer() { vec!["r4"], "fixture models the inversion: an over-open fence would skip r3" ); - - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } /// Commit-time floor guard (migration 0021), exact held-transaction @@ -2641,10 +2939,7 @@ async fn thread_full_replica_page_above_fence_is_reverified_on_writer() { #[tokio::test] #[ignore = "requires Postgres"] async fn created_at_floor_guard_aborts_old_channel_rows_at_commit() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (pool, name) = create_scratch_db(&admin, "floor_guard").await; + let (pool, _scratch) = ScratchDb::migrated(&admin_url().await, "floor_guard").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -2722,8 +3017,6 @@ async fn created_at_floor_guard_aborts_old_channel_rows_at_commit() { // (and must hold the fence closed, per the migration header). let old_backfill = signed_event_at(&author, "old-backfill", now_secs - floor - 60); insert_top_level(&pool, community, channel, &old_backfill).await; - - drop_scratch_db(&admin, pool, &name).await; } #[test] @@ -2906,18 +3199,17 @@ async fn writer_pool_rejects_non_read_committed_database_default() { let admin = PgPool::connect(&admin_url().await) .await .expect("connect admin"); - let (seed_pool, name) = create_scratch_db(&admin, "writer_isolation").await; + let (seed_pool, scratch) = ScratchDb::migrated(&admin_url().await, "writer_isolation").await; sqlx::query(sqlx::AssertSqlSafe(format!( - "ALTER DATABASE {name} SET default_transaction_isolation = 'repeatable read'" + "ALTER DATABASE {} SET default_transaction_isolation = 'repeatable read'", + scratch.name() ))) .execute(&admin) .await .expect("set unsafe database default"); seed_pool.close().await; - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); + let scratch_url = scratch.url().to_owned(); let error = Db::new(&DbConfig { database_url: scratch_url, max_connections: 1, @@ -2952,13 +3244,6 @@ async fn writer_pool_rejects_non_read_committed_database_default() { 0, "an isolation-rejected connection must never reach ready" ); - - sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE {name} WITH (FORCE)" - ))) - .execute(&admin) - .await - .expect("drop isolation test database"); } #[tokio::test(flavor = "current_thread")] @@ -3102,6 +3387,22 @@ fn writer_statement_timeout_is_always_bounded() { assert_eq!(MAX_STATEMENT_TIMEOUT_MS, 300_000); } +/// Poll until the reader pool holds exactly `target` connections, all idle. +/// Returned and floor-maintenance connections land asynchronously, from +/// tasks sqlx spawns on drop. +async fn await_idle_floor(read_pool: &PgPool, target: u32) { + let deadline = Instant::now() + Duration::from_secs(10); + while read_pool.size() != target || read_pool.num_idle() != target as usize { + assert!( + Instant::now() < deadline, + "reader pool never settled at {target} idle; size={} idle={}", + read_pool.size(), + read_pool.num_idle() + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + /// Through the production constructors, every writer session carries the /// clamped statement timeout and every replica session the 20 s read /// deadline. Mutation oracles: dropping the clamp leaves `0`/`10min` on the @@ -3131,7 +3432,11 @@ async fn session_statement_timeouts_bound_writer_and_reader_sessions() { .await .expect("writer timeout"); assert_eq!(writer, writer_expected, "writer, configured {configured}"); + // Warm the reader the way the relay boots it: the routed-read acquire + // budget is 150 ms, and a cold dial on a busy server can exceed it. let reader_pool = db.read_pool.clone().expect("reader configured"); + db.read_pool_boot_ping_for_tests().await; + await_idle_floor(&reader_pool, 1).await; let reader: String = sqlx::query_scalar("SHOW statement_timeout") .fetch_one(&reader_pool) .await @@ -3147,15 +3452,10 @@ async fn session_statement_timeouts_bound_writer_and_reader_sessions() { #[tokio::test] #[ignore = "requires Postgres"] async fn session_timeouts_install_through_db_new_and_bound_lock_waits() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed_pool, name) = create_scratch_db(&admin, "session_timeouts").await; + let (seed_pool, scratch) = ScratchDb::migrated(&admin_url().await, "session_timeouts").await; seed_pool.close().await; - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); + let scratch_url = scratch.url().to_owned(); let db = Db::new(&DbConfig { database_url: scratch_url.clone(), max_connections: 2, @@ -3228,7 +3528,6 @@ async fn session_timeouts_install_through_db_new_and_bound_lock_waits() { let _ = sqlx::query("ROLLBACK").execute(&mut *holder).await; drop(holder); - drop_scratch_db(&admin, db.pool.clone(), &name).await; } /// The armed writer pool (`Db::new`) must enforce the floor end-to-end @@ -3237,10 +3536,7 @@ async fn session_timeouts_install_through_db_new_and_bound_lock_waits() { #[tokio::test] #[ignore = "requires Postgres"] async fn armed_pool_rejects_old_channel_inserts_through_public_api() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed_pool, name) = create_scratch_db(&admin, "floor_pool").await; + let (seed_pool, scratch) = ScratchDb::migrated(&admin_url().await, "floor_pool").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -3248,9 +3544,7 @@ async fn armed_pool_rejects_old_channel_inserts_through_public_api() { seed_community_channel(&seed_pool, community, channel, &author).await; // Connect a Db the production way: after_connect arms the guard. - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); + let scratch_url = scratch.url().to_owned(); let db = Db::new(&DbConfig { database_url: scratch_url, max_connections: 2, @@ -3326,8 +3620,7 @@ async fn armed_pool_rejects_old_channel_inserts_through_public_api() { .await .expect("fresh insert passes the armed guard"); - drop_scratch_db(&admin, seed_pool, &name).await; - // db pool still holds connections to the dropped DB; close it. + // Close before the `scratch` guard force-drops the database on return. db.pool.close().await; } @@ -3350,14 +3643,10 @@ async fn begin_replica_floor_locked_writer(db: &Db) -> sqlx::Transaction<'static #[tokio::test] #[ignore = "requires Postgres"] async fn replica_floor_writer_transaction_holds_shared_lock() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed_pool, name) = create_scratch_db(&admin, "floor_writer_foundation").await; + let (_seed_pool, scratch) = + ScratchDb::migrated(&admin_url().await, "floor_writer_foundation").await; - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); + let scratch_url = scratch.url().to_owned(); let db = Db::new(&DbConfig { database_url: scratch_url, max_connections: 3, @@ -3400,20 +3689,15 @@ async fn replica_floor_writer_transaction_holds_shared_lock() { .expect("rollback exclusive contender"); writer.rollback().await.expect("rollback writer tx"); db.pool.close().await; - drop_scratch_db(&admin, seed_pool, &name).await; } #[tokio::test] #[ignore = "requires Postgres"] -async fn replica_floor_probe_waits_for_shared_writer_and_records_after_release() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed_pool, name) = create_scratch_db(&admin, "floor_probe_foundation").await; +async fn cluster_global_replica_floor_probe_waits_for_shared_writer_and_records_after_release() { + let (_seed_pool, scratch) = + ScratchDb::migrated(&admin_url().await, "floor_probe_foundation").await; - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); + let scratch_url = scratch.url().to_owned(); let db = Db::new(&DbConfig { database_url: scratch_url, max_connections: 2, @@ -3463,7 +3747,6 @@ async fn replica_floor_probe_waits_for_shared_writer_and_records_after_release() ); db.pool.close().await; - drop_scratch_db(&admin, seed_pool, &name).await; } /// `spawn_fence_probe` must verify the floor guard before letting the @@ -3474,18 +3757,13 @@ async fn replica_floor_probe_waits_for_shared_writer_and_records_after_release() #[tokio::test] #[ignore = "requires Postgres"] async fn fence_probe_refuses_to_start_without_verified_floor_guard() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed_pool, wname) = create_scratch_db(&admin, "fence_gate_w").await; - let (replica_pool, rname) = create_scratch_db(&admin, "fence_gate_r").await; + let (seed_pool, writer_db) = ScratchDb::migrated(&admin_url().await, "fence_gate_w").await; + let (replica_pool, replica_db) = ScratchDb::migrated(&admin_url().await, "fence_gate_r").await; seed_pool.close().await; replica_pool.close().await; - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let writer_url = format!("{}/{}", &base[..idx], wname); - let replica_url = format!("{}/{}", &base[..idx], rname); + let writer_url = writer_db.url().to_owned(); + let replica_url = replica_db.url().to_owned(); // Healthy schema: verification passes, probe starts. A SEPARATE Db // instance, because its background probe legitimately opens its own @@ -3555,25 +3833,6 @@ async fn fence_probe_refuses_to_start_without_verified_floor_guard() { db.fence().verified_through().is_none(), "fence must remain closed when verification refuses the probe" ); - - db_healthy.pool.close().await; - if let Some(rp) = &db_healthy.read_pool { - rp.close().await; - } - db.pool.close().await; - if let Some(rp) = &db.read_pool { - rp.close().await; - } - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {wname} WITH (FORCE)" - ))) - .execute(&admin) - .await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {rname} WITH (FORCE)" - ))) - .execute(&admin) - .await; } /// The `UPDATE OF` arm of the floor guard (Perci's second structural @@ -3583,10 +3842,7 @@ async fn fence_probe_refuses_to_start_without_verified_floor_guard() { #[tokio::test] #[ignore = "requires Postgres"] async fn floor_guard_blocks_updates_that_move_rows_below_the_fence() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (pool, name) = create_scratch_db(&admin, "floor_upd").await; + let (pool, _scratch) = ScratchDb::migrated(&admin_url().await, "floor_upd").await; let author = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -3657,8 +3913,6 @@ async fn floor_guard_blocks_updates_that_move_rows_below_the_fence() { matches!(&err, sqlx::Error::Database(e) if e.code().as_deref() == Some("23514")), "unexpected error: {err}" ); - - drop_scratch_db(&admin, pool, &name).await; } // ---- Statement-deadline cancellation vs. replica fallback ---------------- @@ -3672,15 +3926,17 @@ async fn floor_guard_blocks_updates_that_move_rows_below_the_fence() { /// Writer and replica scratch DBs holding one root plus an `e`-tagged reply /// that mentions `mentioned` — the writer copy says "writer-reply" so a /// writer re-run is observable. Returns the reply-targeted query shape. +/// Dropping the fixture drops both databases. struct EtagFixture { admin: PgPool, writer: PgPool, - wname: String, + _writer_db: ScratchDb, replica: PgPool, - rname: String, + replica_db: ScratchDb, cid: CommunityId, channel: Uuid, root_hex: String, + root_seconds: i64, mentioned_hex: String, } @@ -3688,8 +3944,9 @@ async fn e_tag_fixture(prefix: &str) -> EtagFixture { let admin = PgPool::connect(&admin_url().await) .await .expect("connect admin"); - let (writer, wname) = create_scratch_db(&admin, &format!("{prefix}_w")).await; - let (replica, rname) = create_scratch_db(&admin, &format!("{prefix}_r")).await; + let (writer, writer_db) = ScratchDb::migrated(&admin_url().await, &format!("{prefix}_w")).await; + let (replica, replica_db) = + ScratchDb::migrated(&admin_url().await, &format!("{prefix}_r")).await; let author = nostr::Keys::generate(); let mentioned = nostr::Keys::generate(); let community = Uuid::new_v4(); @@ -3720,12 +3977,13 @@ async fn e_tag_fixture(prefix: &str) -> EtagFixture { EtagFixture { admin, writer, - wname, + _writer_db: writer_db, replica, - rname, + replica_db, cid: CommunityId::from_uuid(community), channel, root_hex: root.id.to_hex(), + root_seconds: base as i64, mentioned_hex: mentioned.public_key().to_hex(), } } @@ -3741,19 +3999,14 @@ impl EtagFixture { /// `ALTER DATABASE` settings made on the replica), with the fence open /// and a bounded budget so unpinned reads route to the replica. async fn routed_db(&self) -> Db { - let base = admin_url().await; - let url = format!("{}/{}", &base[..base.rfind('/').expect("path")], self.rname); - let reader = PgPool::connect(&url).await.expect("connect reader"); + let reader = PgPool::connect(self.replica_db.url()) + .await + .expect("connect reader"); let mut db = Db::from_pools(self.writer.clone(), reader); db.fence().force_open_for_tests(chrono::Utc::now()); db.set_replica_read_max_age_for_tests(Some(std::time::Duration::from_secs(5))); db } - - async fn drop(self) { - drop_scratch_db(&self.admin, self.replica, &self.rname).await; - drop_scratch_db(&self.admin, self.writer, &self.wname).await; - } } fn contents(rows: &[StoredEvent]) -> Vec<&str> { @@ -3769,7 +4022,7 @@ async fn replica_statement_cancel_propagates_without_writer_rerun() { // heartbeat proof still succeeds, then the routed read is cancelled. sqlx::query(sqlx::AssertSqlSafe(format!( "ALTER DATABASE {} SET statement_timeout = '300ms'", - fx.rname + fx.replica_db.name() ))) .execute(&fx.admin) .await @@ -3806,12 +4059,15 @@ async fn replica_statement_cancel_propagates_without_writer_rerun() { db.count_events_routed("t_cxl", &q).await.map(drop), "count_events_routed", ); - let root_id = hex::decode(&fx.root_hex).expect("hex"); + let root_id: [u8; 32] = hex::decode(&fx.root_hex) + .expect("hex") + .try_into() + .expect("32-byte id"); cancelled( - db.get_events_by_ids_routed("t_cxl", fx.cid, &[root_id.as_slice()]) + db.get_events_by_ids_at_routed("t_cxl", fx.cid, &[(root_id, fx.root_seconds)]) .await .map(drop), - "get_events_by_ids_routed", + "get_events_by_ids_at_routed", ); // The routed reads with their own SQL (feed, thread, channel window, // relay membership) fall back to the writer on replica failure, but not @@ -3857,7 +4113,6 @@ async fn replica_statement_cancel_propagates_without_writer_rerun() { locker.rollback().await.expect("unlock"); drop(db); - fx.drop().await; } /// [`replica_statement_cancel_propagates_without_writer_rerun`] for the @@ -3877,7 +4132,7 @@ async fn read_session_statement_cancel_propagates_without_writer_rerun() { .expect("begin reader tx"); let mut session = ReadSession { inner: ReadSessionInner::Replica { - tx: reader_tx, + tx: super::history_reads::ReaderTx::new(reader_tx, None), writer: fx.writer.clone(), }, }; @@ -3892,7 +4147,7 @@ async fn read_session_statement_cancel_propagates_without_writer_rerun() { unreachable!() }; sqlx::query("SET LOCAL statement_timeout = '50ms'") - .execute(&mut **tx) + .execute(&mut ***tx) .await .expect("cap session"); let mut locker = fx.replica.begin().await.expect("begin locker"); @@ -3913,7 +4168,6 @@ async fn read_session_statement_cancel_propagates_without_writer_rerun() { locker.rollback().await.expect("unlock"); drop(session); drop(db); - fx.drop().await; } /// Cancels (57014) the backend on `db_name` parked behind a lock. The thread @@ -3974,7 +4228,7 @@ async fn thread_window_statement_cancel_propagates_without_writer_rerun() { let mut budget = ScanBudget::default(); let (window, ()) = tokio::join!( db.get_thread_window_with_session(fx.cid, &request, &mut budget), - cancel_lock_waiter(&fx.admin, &fx.rname), + cancel_lock_waiter(&fx.admin, fx.replica_db.name()), ); match window { Err(e) => assert!(e.is_statement_cancelled(), "window: want 57014, got {e}"), @@ -3992,7 +4246,7 @@ async fn thread_window_statement_cancel_propagates_without_writer_rerun() { .expect("begin reader tx"); let mut session = ReadSession { inner: ReadSessionInner::Replica { - tx: reader_tx, + tx: super::history_reads::ReaderTx::new(reader_tx, None), writer: fx.writer.clone(), }, }; @@ -4000,7 +4254,7 @@ async fn thread_window_statement_cancel_propagates_without_writer_rerun() { unreachable!() }; sqlx::query("SET LOCAL statement_timeout = '50ms'") - .execute(&mut **tx) + .execute(&mut ***tx) .await .expect("cap session"); let targets = [fx.root_hex.clone()]; @@ -4027,7 +4281,6 @@ async fn thread_window_statement_cancel_propagates_without_writer_rerun() { locker.rollback().await.expect("unlock"); drop(session); drop(db); - fx.drop().await; } #[tokio::test] @@ -4067,7 +4320,6 @@ async fn replica_non_cancel_failure_still_falls_back_to_writer() { ); drop(db); - fx.drop().await; } /// The `#p`-joined SELECT (fenced, `e.` column prefix) and the COUNT `ANY` @@ -4112,16 +4364,23 @@ async fn e_tag_any_runs_with_real_binds_on_p_join_and_count() { .expect("miss count"), 0 ); - - fx.drop().await; } #[path = "tests/thread_window_postgres_tests.rs"] mod thread_window_postgres_tests; +#[path = "tests/listed_channel_name_postgres_tests.rs"] +mod listed_channel_name_postgres_tests; + #[path = "tests/reader_pool_postgres_tests.rs"] mod reader_pool_postgres_tests; +#[path = "tests/writer_pool_postgres_tests.rs"] +mod writer_pool_postgres_tests; + +#[path = "tests/event_hydration_postgres_tests.rs"] +mod event_hydration_postgres_tests; + /// `insert_event_with_serving_write_guard` indexes mentions in the event's own /// transaction, and an indexing failure stays best-effort: the savepoint rolls /// back only the mention rows, never the event. @@ -4277,3 +4536,6 @@ async fn serving_write_guard_insert_indexes_mentions_in_event_transaction() { .await .expect("release serving-write lease")); } + +#[path = "tests/pool_release_postgres_tests.rs"] +mod pool_release_postgres_tests; diff --git a/crates/buzz-db/src/runtime/tests/event_hydration_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/event_hydration_postgres_tests.rs new file mode 100644 index 00000000000..048aadafc6d --- /dev/null +++ b/crates/buzz-db/src/runtime/tests/event_hydration_postgres_tests.rs @@ -0,0 +1,99 @@ +//! Routing behavior for the timestamp-aware production hydration seam. +use super::*; + +fn key(event: &nostr::Event) -> ([u8; 32], i64) { + (event.id.to_bytes(), event.created_at.as_secs() as i64) +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn hydration_bounded_route_fence_and_replica_error_fallback() { + let admin_url = crate::test_support::database_url(); + let (writer, _writer_db) = ScratchDb::migrated(&admin_url, "hyd_w").await; + let (replica, _replica_db) = ScratchDb::migrated(&admin_url, "hyd_r").await; + let keys = nostr::Keys::generate(); + let cid = Uuid::new_v4(); + let foreign = Uuid::new_v4(); + let channel = Uuid::new_v4(); + let foreign_channel = Uuid::new_v4(); + let writer_only = signed_event_at(&keys, "writer-only", 1_768_435_200); + let replica_only = signed_event_at(&keys, "replica-only", 1_773_532_800); + let foreign_only = signed_event_at(&keys, "foreign-only", 1_773_532_800); + for pool in [&writer, &replica] { + seed_community_channel(pool, cid, channel, &keys).await; + seed_community_channel(pool, foreign, foreign_channel, &keys).await; + } + insert_top_level(&writer, cid, channel, &writer_only).await; + insert_top_level(&replica, cid, channel, &replica_only).await; + insert_top_level(&replica, foreign, foreign_channel, &foreign_only).await; + let community = CommunityId::from_uuid(cid); + let hits = [key(&writer_only), key(&replica_only), key(&foreign_only)]; + let mut db = Db::from_pools(writer.clone(), replica.clone()); + db.fence().force_open_for_tests(chrono::Utc::now()); + // Open content fence alone cannot route an unpinned by-key read. + let found = db + .get_events_by_ids_at_routed("req_search_hydrate", community, &hits) + .await + .unwrap(); + assert_eq!(contents(&found), ["writer-only"]); + db.set_replica_read_max_age_for_tests(Some(Duration::from_secs(30))); + let found = db + .get_events_by_ids_at_routed("req_search_hydrate", community, &hits) + .await + .unwrap(); + assert_eq!( + contents(&found), + ["replica-only"], + "bounded proof must use the replica, scoped to the community" + ); + // The heartbeat remains readable; only the proved data query fails. + sqlx::query("DROP TABLE events CASCADE") + .execute(&replica) + .await + .unwrap(); + let found = db + .get_events_by_ids_at_routed("req_search_hydrate", community, &hits) + .await + .unwrap(); + assert_eq!( + contents(&found), + ["writer-only"], + "non-cancel errors must retry on the writer" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn hydration_replica_cancel_is_not_retried_on_writer() { + let fx = e_tag_fixture("hyd_cxl").await; + sqlx::query(sqlx::AssertSqlSafe(format!( + "ALTER DATABASE {} SET statement_timeout = '300ms'", + fx.replica_db.name() + ))) + .execute(&fx.admin) + .await + .unwrap(); + let db = fx.routed_db().await; + let query = EventQuery::for_community(fx.cid); + let rows = event::query_events(&fx.replica, &query).await.unwrap(); + let hits: Vec<_> = rows.iter().map(|row| key(&row.event)).collect(); + let healthy = db + .get_events_by_ids_at_routed("req_search_hydrate", fx.cid, &hits) + .await + .unwrap(); + assert!(contents(&healthy).contains(&"replica-reply")); + let mut locker = fx.replica.begin().await.unwrap(); + sqlx::query("LOCK TABLE events IN ACCESS EXCLUSIVE MODE") + .execute(&mut *locker) + .await + .unwrap(); + let error = db + .get_events_by_ids_at_routed("req_search_hydrate", fx.cid, &hits) + .await + .unwrap_err(); + assert!( + error.is_statement_cancelled(), + "must surface replica cancellation: {error}" + ); + locker.rollback().await.unwrap(); +} diff --git a/crates/buzz-db/src/runtime/tests/listed_channel_name_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/listed_channel_name_postgres_tests.rs new file mode 100644 index 00000000000..096eee36f5f --- /dev/null +++ b/crates/buzz-db/src/runtime/tests/listed_channel_name_postgres_tests.rs @@ -0,0 +1,654 @@ +//! scripts/maintenance/plan_duplicate_listed_channel_renames.sql lists the +//! renames that leave no two listed channels in a community with one name, +//! ignoring case. It keeps the name on the oldest unarchived channel and picks +//! a new name that no other listed channel has. +//! +//! Migration 0083 then adds the unique index. It refuses to run over +//! duplicates that were not renamed. Otherwise it builds the index itself on a +//! populated table under its lock budget, accepts a valid concurrent prebuild +//! without replacing it, and rejects an invalid one. + +use super::*; + +/// The last migration before 0083. Duplicates can exist, and the plan has +/// work to do, only before the index does. +const BEFORE_INDEX: i64 = 82; + +const PLAN_SQL: &str = + include_str!("../../../../../scripts/maintenance/plan_duplicate_listed_channel_renames.sql"); + +struct Seed { + community: Uuid, + host: String, + created_by: Vec, +} + +impl Seed { + async fn new(pool: &PgPool) -> Self { + let community = Uuid::new_v4(); + let host = format!("listed-name-{}.example", community.simple()); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(&host) + .execute(pool) + .await + .expect("insert community"); + Self { + community, + host, + created_by: nostr::Keys::generate().public_key().to_bytes().to_vec(), + } + } + + /// Inserts an open stream `age` seconds old with plain SQL, as a relay + /// without the name rule did. + async fn open(&self, pool: &PgPool, id: Uuid, name: &str, age: i64) { + sqlx::query( + "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by, \ + created_at) \ + VALUES ($1, $2, $3, 'stream', 'open', $4, now() - make_interval(secs => $5))", + ) + .bind(id) + .bind(self.community) + .bind(name) + .bind(&self.created_by) + .bind(age as f64) + .execute(pool) + .await + .expect("insert channel"); + } + + async fn names(&self, pool: &PgPool) -> Vec<(Uuid, String)> { + sqlx::query_as("SELECT id, name FROM channels WHERE community_id = $1 ORDER BY id") + .bind(self.community) + .fetch_all(pool) + .await + .expect("read channel names") + } +} + +fn renamed(id: Uuid, name: &str) -> (Uuid, String) { + (id, format!("{name}-{}", &id.to_string()[..8])) +} + +/// The plan for `host`: (channel, current name, new name), as the rename +/// script reads it. +async fn rename_plan(pool: &PgPool, host: &str) -> Vec<(Uuid, String, String)> { + rename_plan_with_starters(pool, host, &[]).await +} + +/// The plan for `host` when the clients' starter channels have `starter_ids`. +async fn rename_plan_with_starters( + pool: &PgPool, + host: &str, + starter_ids: &[Uuid], +) -> Vec<(Uuid, String, String)> { + let (_, query) = PLAN_SQL.split_once("\nWITH").expect("plan query"); + sqlx::query_as(sqlx::AssertSqlSafe(format!( + "WITH{}", + query + .trim_end() + .trim_end_matches(';') + .replace(":'host'", "$1") + .replace(":'starter_ids'::uuid[]", "$2::uuid[]") + ))) + .bind(host) + .bind(starter_ids) + .fetch_all(pool) + .await + .expect("run the rename plan") +} + +/// Applies the plan the way the relay applies each rename the script sends, +/// and returns how many channels it renamed. +async fn rename_duplicates(pool: &PgPool, host: &str) -> usize { + let plan = rename_plan(pool, host).await; + for (channel, _, new_name) in &plan { + sqlx::query("UPDATE channels SET name = $2 WHERE id = $1") + .bind(channel) + .bind(new_name) + .execute(pool) + .await + .expect("rename channel"); + } + plan.len() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn plan_keeps_each_listed_name_on_its_oldest_unarchived_channel() { + let (pool, _scratch) = + ScratchDb::migrated_through(&admin_url().await, "listed_name_plan", BEFORE_INDEX).await; + let seed = Seed::new(&pool).await; + let [kept, archived, newer, private, deleted] = [(); 5].map(|_| Uuid::new_v4()); + seed.open(&pool, kept, "square-ios", 30).await; + seed.open(&pool, archived, "Square-iOS", 60).await; + seed.open(&pool, newer, "SQUARE-IOS", 10).await; + seed.open(&pool, private, "square-ios", 5).await; + seed.open(&pool, deleted, "square-ios", 90).await; + sqlx::query( + "UPDATE channels SET \ + archived_at = CASE WHEN id = $2 THEN now() END, \ + visibility = CASE WHEN id = $3 THEN 'private'::channel_visibility ELSE visibility END, \ + deleted_at = CASE WHEN id = $4 THEN now() END \ + WHERE community_id = $1", + ) + .bind(seed.community) + .bind(archived) + .bind(private) + .bind(deleted) + .execute(&pool) + .await + .unwrap(); + // Another community's channel with the same name is not a duplicate. + let other = Seed::new(&pool).await; + other.open(&pool, Uuid::new_v4(), "square-ios", 0).await; + // A community that is not active is left alone. + let inactive = Seed::new(&pool).await; + inactive.open(&pool, Uuid::new_v4(), "payments", 20).await; + inactive.open(&pool, Uuid::new_v4(), "payments", 10).await; + crate::test_support::quiesce_community_for_tests( + &pool, + buzz_core::CommunityId::from_uuid(inactive.community), + ) + .await; + + let mut expected = vec![ + ( + archived, + "Square-iOS".to_owned(), + renamed(archived, "Square-iOS").1, + ), + ( + newer, + "SQUARE-IOS".to_owned(), + renamed(newer, "SQUARE-IOS").1, + ), + ]; + expected.sort(); + assert_eq!(rename_plan(&pool, &seed.host).await, expected); + assert!(rename_plan(&pool, &other.host).await.is_empty()); + assert!(rename_plan(&pool, &inactive.host).await.is_empty()); + + assert_eq!(rename_duplicates(&pool, &seed.host).await, 2); + assert!( + rename_plan(&pool, &seed.host).await.is_empty(), + "nothing is left to rename" + ); + let mut names = vec![ + (kept, "square-ios".to_owned()), + renamed(archived, "Square-iOS"), + renamed(newer, "SQUARE-IOS"), + (private, "square-ios".to_owned()), + (deleted, "square-ios".to_owned()), + ]; + names.sort(); + assert_eq!(seed.names(&pool).await, names); +} + +/// Released desktop and mobile apps create `general` and `welcome-everyone` +/// when no open, unarchived stream has the name, and the relay refuses that +/// create while an archived channel holds it. The plan renames every holder of +/// a starter name when all of them are archived, and no other archived name, +/// unless a channel row has that name's starter id. +/// Mutation: drop the `all_archived` or `NOT IN starters` condition in the +/// plan, the `at_starter_id` sort key, or the slug binding in `starters` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn plan_frees_a_starter_name_that_only_archived_channels_hold() { + let (pool, _scratch) = + ScratchDb::migrated_through(&admin_url().await, "listed_name_plan_starter", BEFORE_INDEX) + .await; + let seed = Seed::new(&pool).await; + let [general, welcome_old, welcome_new, random] = [(); 4].map(|_| Uuid::new_v4()); + seed.open(&pool, general, "General", 30).await; + seed.open(&pool, welcome_old, "welcome-everyone", 60).await; + seed.open(&pool, welcome_new, "welcome-everyone", 10).await; + seed.open(&pool, random, "random", 20).await; + // A live `general` keeps its name; its archived namesake is a plain duplicate. + let live = Seed::new(&pool).await; + let [live_general, archived_general] = [(); 2].map(|_| Uuid::new_v4()); + live.open(&pool, live_general, "general", 10).await; + live.open(&pool, archived_general, "general", 60).await; + sqlx::query("UPDATE channels SET archived_at = now() WHERE id = ANY($1)") + .bind(vec![ + general, + welcome_old, + welcome_new, + random, + archived_general, + ]) + .execute(&pool) + .await + .unwrap(); + + let mut expected = vec![ + (general, "General".to_owned(), renamed(general, "General").1), + ( + welcome_old, + "welcome-everyone".to_owned(), + renamed(welcome_old, "welcome-everyone").1, + ), + ( + welcome_new, + "welcome-everyone".to_owned(), + renamed(welcome_new, "welcome-everyone").1, + ), + ]; + expected.sort(); + assert_eq!(rename_plan(&pool, &seed.host).await, expected); + assert_eq!( + rename_plan(&pool, &live.host).await, + vec![( + archived_general, + "general".to_owned(), + renamed(archived_general, "general").1 + )] + ); + + assert_eq!(rename_duplicates(&pool, &seed.host).await, 3); + assert!( + rename_plan(&pool, &seed.host).await.is_empty(), + "nothing is left to rename" + ); + let mut names = vec![ + renamed(general, "General"), + renamed(welcome_old, "welcome-everyone"), + renamed(welcome_new, "welcome-everyone"), + (random, "random".to_owned()), + ]; + names.sort(); + assert_eq!(seed.names(&pool).await, names); + + // An archived `general` at the clients' starter id keeps the name, even + // when an older archived namesake exists: the relay refuses a create at + // that id whatever the name. Only the namesake is renamed. + let fixed = Seed::new(&pool).await; + let [starter, older] = [(); 2].map(|_| Uuid::new_v4()); + fixed.open(&pool, starter, "general", 10).await; + fixed.open(&pool, older, "general", 60).await; + sqlx::query("UPDATE channels SET archived_at = now() WHERE id = ANY($1)") + .bind(vec![starter, older]) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + rename_plan_with_starters(&pool, &fixed.host, &[starter, Uuid::new_v4()]).await, + vec![(older, "general".to_owned(), renamed(older, "general").1)] + ); + + // Any row at a starter's id blocks the create there, whatever its name or + // visibility, so the starter rule renames nothing for that name. Each id + // binds only its own name: `welcome-everyone` is still freed. + let moved = Seed::new(&pool).await; + let [general_id, archived_general, archived_welcome] = [(); 3].map(|_| Uuid::new_v4()); + moved.open(&pool, general_id, "general", 90).await; + moved.open(&pool, archived_general, "general", 30).await; + moved + .open(&pool, archived_welcome, "welcome-everyone", 30) + .await; + sqlx::query("UPDATE channels SET name = 'general-old', visibility = 'private' WHERE id = $1") + .bind(general_id) + .execute(&pool) + .await + .unwrap(); + sqlx::query("UPDATE channels SET archived_at = now() WHERE id = ANY($1)") + .bind(vec![archived_general, archived_welcome]) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + rename_plan_with_starters(&pool, &moved.host, &[general_id, Uuid::new_v4()]).await, + vec![( + archived_welcome, + "welcome-everyone".to_owned(), + renamed(archived_welcome, "welcome-everyone").1 + )] + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn plan_picks_a_free_name_when_the_short_one_is_taken() { + let (pool, _scratch) = + ScratchDb::migrated_through(&admin_url().await, "listed_name_plan_taken", BEFORE_INDEX) + .await; + let seed = Seed::new(&pool).await; + // The longest name the column holds, so the new name must truncate it. + let long = "a".repeat(255); + let duplicate = Uuid::parse_str("20000000-0000-4000-8000-000000000000").unwrap(); + let (kept, squatter) = (Uuid::new_v4(), Uuid::new_v4()); + seed.open(&pool, kept, &long, 30).await; + seed.open(&pool, duplicate, &long, 10).await; + // Another listed channel already has the short new name, in another case. + let short = format!("{}-20000000", "A".repeat(246)); + seed.open(&pool, squatter, &short, 60).await; + + let new_name = format!("{}-{duplicate}", "a".repeat(218)); + assert_eq!( + rename_plan(&pool, &seed.host).await, + vec![(duplicate, long.clone(), new_name.clone())] + ); + assert!(new_name.chars().count() <= 255); +} + +/// Runs the real script for `host` against database `db`, with `cli_body` as +/// the stand-in CLI. Returns the script's output and each CLI call's +/// arguments. +#[cfg(unix)] +async fn run_rename_script( + host: &str, + db: &str, + cli_body: &str, +) -> (std::process::Output, Vec>>) { + let dir = std::env::temp_dir().join(format!("listed-name-script-{}", Uuid::new_v4().simple())); + std::fs::create_dir(&dir).unwrap(); + let (cli, log) = (dir.join("buzz"), dir.join("calls")); + std::fs::write( + &cli, + format!( + "#!/usr/bin/env bash\nset -euo pipefail\nprintf '%s\\0' \"$@\" '' >>\"$STUB_LOG\"\n{cli_body}" + ), + ) + .unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let base = admin_url().await; + let database_url = format!("{}/{}", &base[..base.rfind('/').unwrap()], db); + let mut path = std::env::var("PATH").unwrap_or_default(); + if let Ok(bin) = std::env::var("PG_BIN_DIR") { + path = format!("{bin}:{path}"); + } + let output = std::process::Command::new(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../scripts/maintenance/rename_duplicate_listed_channel_names.sh" + )) + .arg(host) + .env("PATH", path) + .env("DATABASE_URL", &database_url) + .env("BUZZ_PRIVATE_KEY", "unused") + .env("BUZZ_CLI", &cli) + .env("STUB_LOG", &log) + .output() + .expect("run the rename script"); + + // Each call ends with an empty field, so "\0\0" splits the calls. + let calls = std::fs::read(&log).unwrap_or_default(); + let calls = calls + .split(|b| *b == 0) + .collect::>() + .split(|field| field.is_empty()) + .filter(|call| !call.is_empty()) + .map(|call| call.iter().map(|field| field.to_vec()).collect()) + .collect(); + std::fs::remove_dir_all(&dir).unwrap(); + (output, calls) +} + +/// The real script, with a stand-in CLI that logs each call and applies the +/// rename. A name may hold any character but NUL, so a name holding control +/// characters must still yield exactly one rename, of its own channel. Like +/// clap, the stand-in takes a value that starts with "-" only as `--name=`. +#[cfg(unix)] +#[tokio::test] +#[ignore = "requires Postgres"] +async fn script_renames_each_planned_channel_once_whatever_its_name() { + let (pool, scratch) = + ScratchDb::migrated_through(&admin_url().await, "listed_name_script", BEFORE_INDEX).await; + let seed = Seed::new(&pool).await; + let [kept, duplicate, other] = [(); 3].map(|_| Uuid::new_v4()); + let tricky = format!("-ops\x1e{other}\x1fowned\x1f\n\t\"$(x)"); + seed.open(&pool, kept, &tricky, 30).await; + seed.open(&pool, duplicate, &tricky, 10).await; + seed.open(&pool, other, "other", 20).await; + + let (output, calls) = run_rename_script( + &seed.host, + scratch.name(), + "[[ $3 == --channel=* && $4 == --name=* ]] || exit 2\n\ + psql \"$DATABASE_URL\" -X -q -v ON_ERROR_STOP=1 -v id=\"${3#*=}\" -v name=\"${4#*=}\" <<'SQL'\n\ + UPDATE channels SET name = :'name' WHERE id = :'id';\nSQL\n", + ) + .await; + assert!( + output.status.success(), + "script failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let new_name = renamed(duplicate, &tricky).1; + let expected: Vec>> = vec![vec![ + b"channels".to_vec(), + b"update".to_vec(), + format!("--channel={duplicate}").into_bytes(), + format!("--name={new_name}").into_bytes(), + ]]; + assert_eq!(calls, expected, "one call, for the duplicate only"); + let mut names = vec![ + (kept, tricky.clone()), + (duplicate, new_name.clone()), + (other, "other".to_owned()), + ]; + names.sort(); + assert_eq!(seed.names(&pool).await, names); +} + +/// An auth refusal (CLI exit code 3, for example 403 relay_membership_required) +/// stops the script at the first rename, with a message that names the +/// membership precondition. +/// Mutation: drop the exit-code-3 branch in the script → RED. +#[cfg(unix)] +#[tokio::test] +#[ignore = "requires Postgres"] +async fn script_stops_at_the_first_auth_refusal() { + let (pool, scratch) = + ScratchDb::migrated_through(&admin_url().await, "listed_name_script_auth", BEFORE_INDEX) + .await; + let seed = Seed::new(&pool).await; + for (group, age) in [("first", 30), ("first", 10), ("second", 30), ("second", 10)] { + seed.open(&pool, Uuid::new_v4(), group, age).await; + } + + let (output, calls) = run_rename_script(&seed.host, scratch.name(), "exit 3\n").await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stderr}"); + assert_eq!(calls.len(), 1, "it stops after the first refusal"); + assert!(stderr.contains("a member of"), "{stderr}"); +} + +/// The relay serves only an active, unarchived community, so the script stops +/// before any rename for an archived community, one being deleted, or a host +/// no community has, and says why. +/// Mutation: drop the community check in the script → RED. +#[cfg(unix)] +#[tokio::test] +#[ignore = "requires Postgres"] +async fn script_stops_for_a_community_the_relay_does_not_serve() { + let (pool, scratch) = + ScratchDb::migrated_through(&admin_url().await, "listed_name_script_state", BEFORE_INDEX) + .await; + let archived = Seed::new(&pool).await; + let deleting = Seed::new(&pool).await; + for seed in [&archived, &deleting] { + seed.open(&pool, Uuid::new_v4(), "ops", 30).await; + seed.open(&pool, Uuid::new_v4(), "ops", 10).await; + } + sqlx::query("UPDATE communities SET archived_at = now() WHERE id = $1") + .bind(archived.community) + .execute(&pool) + .await + .unwrap(); + crate::test_support::quiesce_community_for_tests( + &pool, + buzz_core::CommunityId::from_uuid(deleting.community), + ) + .await; + + for (host, message) in [ + (archived.host.as_str(), "Unarchive it"), + (deleting.host.as_str(), "being deleted"), + ("missing.example", "no community has host"), + ] { + let (output, calls) = run_rename_script(host, scratch.name(), "exit 0\n").await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{host}: {stderr}"); + assert!(calls.is_empty(), "{host}: no rename"); + assert!(stderr.contains(message), "{host}: {stderr}"); + } +} + +async fn ledger_version(pool: &PgPool) -> i64 { + sqlx::query_scalar("SELECT max(version) FROM _sqlx_migrations") + .fetch_one(pool) + .await + .expect("read migration ledger") +} + +async fn listed_name_migration_recorded(pool: &PgPool) -> bool { + sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM _sqlx_migrations WHERE version = $1 AND success)", + ) + .bind(BEFORE_INDEX + 1) + .fetch_one(pool) + .await + .expect("read listed-name migration ledger entry") +} + +async fn index_oid(pool: &PgPool) -> Option { + sqlx::query_scalar("SELECT to_regclass('public.idx_channels_listed_name')::oid::bigint") + .fetch_one(pool) + .await + .expect("look up index") +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_listed_name_index_needs_the_renames_then_builds_inline() { + let (pool, _scratch) = + ScratchDb::migrated_through(&admin_url().await, "listed_name_index", BEFORE_INDEX).await; + let seed = Seed::new(&pool).await; + let (kept, newer) = (Uuid::new_v4(), Uuid::new_v4()); + seed.open(&pool, kept, "square-ios", 30).await; + seed.open(&pool, newer, "Square-iOS", 10).await; + let before = seed.names(&pool).await; + + let error = migration::run_migrations_through(&pool, BEFORE_INDEX + 1) + .await + .unwrap_err(); + assert!( + error.to_string().contains("duplicate names remain"), + "must name the duplicate rows, not merely fail: {error}" + ); + assert_eq!(ledger_version(&pool).await, BEFORE_INDEX); + assert_eq!(index_oid(&pool).await, None); + assert_eq!(seed.names(&pool).await, before, "no data changes"); + + assert_eq!(rename_duplicates(&pool, &seed.host).await, 1); + assert!(rename_plan(&pool, &seed.host).await.is_empty()); + + // A channel writer that holds its lock past the 1s lock budget makes the + // inline build fail closed: nothing is recorded and startup can retry. + let mut writer = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE channels IN ROW EXCLUSIVE MODE") + .execute(&mut *writer) + .await + .unwrap(); + let error = migration::run_migrations_through(&pool, BEFORE_INDEX + 1) + .await + .unwrap_err(); + assert!( + error.to_string().contains("lock timeout"), + "the build must not queue behind a writer: {error}" + ); + writer.rollback().await.unwrap(); + assert_eq!(ledger_version(&pool).await, BEFORE_INDEX); + assert_eq!(index_oid(&pool).await, None); + + // With no writer in the way, the populated table migrates with no + // operator step: the migration builds the index itself. + migration::run_migrations_through(&pool, BEFORE_INDEX + 1) + .await + .expect("migrate a populated table after the renames"); + assert!(listed_name_migration_recorded(&pool).await); + let mut expected = vec![ + (kept, "square-ios".to_owned()), + renamed(newer, "Square-iOS"), + ]; + expected.sort(); + assert_eq!(seed.names(&pool).await, expected); + + // The database now refuses what an older relay could still write. + let duplicate = sqlx::query( + "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) \ + VALUES ($1, $2, 'SQUARE-IOS', 'forum', 'open', $3)", + ) + .bind(Uuid::new_v4()) + .bind(seed.community) + .bind(&seed.created_by) + .execute(&pool) + .await + .unwrap_err(); + assert_eq!( + duplicate + .as_database_error() + .and_then(|e| e.constraint()) + .map(str::to_owned), + Some("idx_channels_listed_name".to_owned()) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_listed_name_index_validates_a_prebuild() { + let (pool, _scratch) = + ScratchDb::migrated_through(&admin_url().await, "listed_name_prebuild", BEFORE_INDEX).await; + for remnant in [ + // A different predicate: archived channels left out. + "CREATE UNIQUE INDEX idx_channels_listed_name ON channels (community_id, lower(name)) \ + WHERE visibility = 'open' AND NOT unlisted AND archived_at IS NULL", + // A failed concurrent build. Simulated only in this disposable + // superuser database. + "CREATE UNIQUE INDEX idx_channels_listed_name ON channels (community_id, lower(name)) \ + WHERE visibility = 'open' AND NOT unlisted \ + AND channel_type IN ('stream', 'forum') AND deleted_at IS NULL; \ + UPDATE pg_index SET indisvalid = false \ + WHERE indexrelid = 'idx_channels_listed_name'::regclass", + ] { + sqlx::raw_sql(sqlx::AssertSqlSafe(remnant)) + .execute(&pool) + .await + .unwrap(); + let error = migration::run_migrations_through(&pool, BEFORE_INDEX + 1) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("is invalid or has a different definition"), + "must reject the catalog shape: {error}" + ); + assert_eq!(ledger_version(&pool).await, BEFORE_INDEX); + sqlx::query("DROP INDEX CONCURRENTLY idx_channels_listed_name") + .execute(&pool) + .await + .unwrap(); + } + + crate::test_support::prebuild_listed_channel_name_index(&pool).await; + let oid = index_oid(&pool).await; + // A channel writer holds its lock through the migration. Over a prebuild, + // 0083 must not request the ShareLock a CREATE INDEX takes, even with + // IF NOT EXISTS: that waits behind writers and queues new ones. + let mut writer = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE channels IN ROW EXCLUSIVE MODE") + .execute(&mut *writer) + .await + .unwrap(); + migration::run_migrations_through(&pool, BEFORE_INDEX + 1) + .await + .expect("accept the prebuild without waiting for channel writers"); + writer.rollback().await.unwrap(); + assert!(listed_name_migration_recorded(&pool).await); + assert_eq!(index_oid(&pool).await, oid, "the prebuild is not replaced"); +} diff --git a/crates/buzz-db/src/runtime/tests/pool_release_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/pool_release_postgres_tests.rs new file mode 100644 index 00000000000..070d33b8481 --- /dev/null +++ b/crates/buzz-db/src/runtime/tests/pool_release_postgres_tests.rs @@ -0,0 +1,219 @@ +//! Pool capacity must recover when old database sockets silently stop answering. +use super::*; +use crate::test_support::PausingProxy; +use sqlx::{pool::PoolConnection, ConnectOptions, Postgres}; + +/// Production pool budgets are sized for a warm relay pod, not for a test +/// lane whose first wave dials cold through [`PausingProxy`] while every other +/// worker clones its database. `connect_writer_pool` and `connect_with` dial +/// eagerly under `acquire_timeout`, so the budget must cover a loaded first +/// connection (the lane budget #9273 chose), not only a steady-state checkout. +const TEST_LANE_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(30); + +async fn writer_pool(max: u32, min: u32) -> (PgPool, PausingProxy, ScratchDb) { + let scratch = ScratchDb::create(&crate::test_support::database_url(), "release").await; + let options: sqlx::postgres::PgConnectOptions = scratch.url().parse().unwrap(); + let proxy = PausingProxy::spawn(options.get_host().to_owned(), options.get_port()).await; + let proxied = options + .host("127.0.0.1") + .port(proxy.port) + .to_url_lossy() + .to_string(); + let pool = Db::connect_writer_pool(&DbConfig { + database_url: proxied, + max_connections: max, + min_connections: min, + acquire_timeout_secs: TEST_LANE_ACQUIRE_TIMEOUT.as_secs(), + ..DbConfig::default() + }) + .await + .expect("production writer pool"); + (pool, proxy, scratch) +} + +async fn hold(pool: &PgPool, count: usize) -> Vec> { + let mut held = Vec::new(); + for _ in 0..count { + let mut conn = pool.acquire().await.expect("checkout"); + sqlx::query("SELECT 1").execute(&mut *conn).await.unwrap(); + held.push(conn); + } + held +} + +async fn await_capacity(pool: &PgPool, size: u32) { + let started = std::time::Instant::now(); + let result = tokio::time::timeout(Duration::from_secs(10), async { + loop { + if pool.size() == size && pool.num_idle() == size as usize { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + eprintln!( + "release recovery: elapsed={:?} size={} idle={} target={size}", + started.elapsed(), + pool.size(), + pool.num_idle() + ); + result.expect("released connections must stop consuming pool capacity"); +} + +async fn fresh_query(pool: &PgPool) { + let value: i32 = tokio::time::timeout( + Duration::from_secs(5), + sqlx::query_scalar("SELECT 1").fetch_one(pool), + ) + .await + .expect("fresh query deadline") + .expect("fresh connection works while old sessions remain stalled"); + assert_eq!(value, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn dropped_writer_connections_reclaim_saturated_pool() { + let (pool, proxy, _scratch) = writer_pool(3, 0).await; + let held = hold(&pool, 3).await; + proxy.stall_established(); + drop(held); + proxy.wait_for_held_sessions(3).await; + await_capacity(&pool, 0).await; + drop(hold(&pool, 3).await); + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn aborted_writer_queries_reclaim_saturated_pool() { + let (pool, proxy, _scratch) = writer_pool(3, 0).await; + let held = hold(&pool, 3).await; + proxy.stall_established(); + let tasks: Vec<_> = held + .into_iter() + .map(|mut conn| { + tokio::spawn(async move { sqlx::query("SELECT 1").execute(&mut *conn).await }) + }) + .collect(); + proxy.wait_for_held_sessions(3).await; + for task in &tasks { + task.abort(); + } + for task in tasks { + assert!(task.await.expect_err("query task aborted").is_cancelled()); + } + await_capacity(&pool, 0).await; + fresh_query(&pool).await; + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn aborted_writer_begin_reclaims_slot_and_allows_committed_write() { + let (pool, proxy, scratch) = writer_pool(1, 0).await; + let observer = scratch.connect().await; + sqlx::query("CREATE TABLE release_probe (n int)") + .execute(&observer) + .await + .unwrap(); + let mut conn = pool.acquire().await.unwrap(); + proxy.stall_established(); + let task = tokio::spawn(async move { + let _tx = conn.begin().await.unwrap(); + }); + proxy.wait_for_held_sessions(1).await; + task.abort(); + assert!(task.await.expect_err("BEGIN task aborted").is_cancelled()); + await_capacity(&pool, 0).await; + sqlx::query("INSERT INTO release_probe VALUES (1)") + .execute(&pool) + .await + .unwrap(); + let committed: i32 = sqlx::query_scalar("SELECT n FROM release_probe") + .fetch_one(&observer) + .await + .expect("independent session sees commit"); + assert_eq!(committed, 1); + pool.close().await; + observer.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn transient_return_stall_reuses_healthy_writer_connection() { + let (pool, proxy, _scratch) = writer_pool(1, 0).await; + let mut conn = pool.acquire().await.unwrap(); + let before: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *conn) + .await + .unwrap(); + proxy.set_paused(true); + drop(conn); + proxy.wait_for_held_sessions(1).await; + proxy.resume_all(); + await_capacity(&pool, 1).await; + let after: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + before, after, + "a resumed return must reuse the healthy session" + ); + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn silent_return_replenishes_writer_minimum() { + let (pool, proxy, _scratch) = writer_pool(1, 1).await; + let held = hold(&pool, 1).await; + let sessions = proxy.sessions(); + proxy.stall_established(); + drop(held); + proxy.wait_for_held_sessions(1).await; + await_capacity(&pool, 1).await; + assert!( + proxy.sessions() > sessions, + "minimum must use a new physical session" + ); + fresh_query(&pool).await; + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn silence_after_release_hook_does_not_strand_sqlx_ping() { + let scratch = ScratchDb::create(&crate::test_support::database_url(), "release_hook").await; + let options: sqlx::postgres::PgConnectOptions = scratch.url().parse().unwrap(); + let proxy = std::sync::Arc::new( + PausingProxy::spawn(options.get_host().to_owned(), options.get_port()).await, + ); + let hook_proxy = proxy.clone(); + let first = std::sync::atomic::AtomicBool::new(true); + let pool = Db::read_pool_options(1) + .min_connections(0) + .acquire_timeout(TEST_LANE_ACQUIRE_TIMEOUT) + .after_release(move |conn, _| { + let proxy = hook_proxy.clone(); + let stall = first.swap(false, std::sync::atomic::Ordering::SeqCst); + Box::pin(async move { + let result = Db::reader_release_check(conn).await; + assert!(matches!(result, Ok(true)), "release hook must succeed"); + if stall { + proxy.stall_established(); + } + result + }) + }) + .connect_with(options.host("127.0.0.1").port(proxy.port)) + .await + .unwrap(); + drop(pool.acquire().await.unwrap()); + proxy.wait_for_held_sessions(1).await; + await_capacity(&pool, 0).await; + fresh_query(&pool).await; + pool.close().await; +} diff --git a/crates/buzz-db/src/runtime/tests/reader_pool_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/reader_pool_postgres_tests.rs index a2549715e08..5b970a92eea 100644 --- a/crates/buzz-db/src/runtime/tests/reader_pool_postgres_tests.rs +++ b/crates/buzz-db/src/runtime/tests/reader_pool_postgres_tests.rs @@ -3,24 +3,15 @@ //! reader). use super::*; -use std::time::Instant; /// A `Db` whose writer and lazy reader both point at one scratch database, /// with the fence open so routed reads attempt the reader. -async fn same_db_reader(prefix: &str, read_max: u32) -> (PgPool, Db, String, String) { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed, wname) = create_scratch_db(&admin, prefix).await; +async fn same_db_reader(prefix: &str, read_max: u32) -> (Db, ScratchDb) { + let (seed, scratch) = ScratchDb::migrated(&admin_url().await, prefix).await; seed.close().await; - let scratch_url = { - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - format!("{}/{}", &base[..idx], wname) - }; let mut db = Db::new(&DbConfig { - database_url: scratch_url.clone(), - read_database_url: Some(scratch_url.clone()), + database_url: scratch.url().to_owned(), + read_database_url: Some(scratch.url().to_owned()), max_connections: 4, read_max_connections: Some(read_max), ..DbConfig::default() @@ -29,23 +20,7 @@ async fn same_db_reader(prefix: &str, read_max: u32) -> (PgPool, Db, String, Str .expect("connect Db with lazy reader"); db.fence().force_open_for_tests(chrono::Utc::now()); db.set_replica_read_max_age_for_tests(Some(Duration::from_secs(30))); - (admin, db, wname, scratch_url) -} - -/// Poll until the reader pool holds exactly `target` connections, all idle. -/// Returned and floor-maintenance connections land asynchronously, from -/// tasks sqlx spawns on drop. -async fn await_idle_floor(read_pool: &PgPool, target: u32) { - let deadline = Instant::now() + Duration::from_secs(10); - while read_pool.size() != target || read_pool.num_idle() != target as usize { - assert!( - Instant::now() < deadline, - "reader pool never settled at {target} idle; size={} idle={}", - read_pool.size(), - read_pool.num_idle() - ); - tokio::time::sleep(Duration::from_millis(10)).await; - } + (db, scratch) } /// Counters keyed by `(name, decision, reason)` labels, drained: each @@ -102,7 +77,7 @@ fn release_closes(snapshotter: &Snapshotter) -> std::collections::HashMap continue, + connection => break connection, + } + } + }) + .await + .expect("second reader connects within 5s") + .expect("second warm connection"); drop((first, second)); } await_idle_floor(&read_pool, 2).await; @@ -388,9 +479,13 @@ async fn stalled_reader_sessions_release_their_slots_for_new_connections() { .sum::() }; loop { - db.count_events_routed("stalled_reader_probe", &query) - .await - .expect("routed read answers"); + // While both slots sit in the release check the reader pool is + // saturated, so a history read is rejected as retryable rather than + // moved to the writer; the caller retries, as a client would. + match db.count_events_routed("stalled_reader_probe", &query).await { + Ok(_) | Err(crate::error::DbError::Sqlx(sqlx::Error::PoolTimedOut)) => {} + Err(e) => panic!("routed read answers or is rejected as retryable: {e:?}"), + } for (key, n) in drain_counters(&snapshotter) { *totals.entry(key).or_default() += n; } @@ -420,5 +515,92 @@ async fn stalled_reader_sessions_release_their_slots_for_new_connections() { ); drop(_guard); read_pool.close().await; - drop_scratch_db(&admin, writer, &wname).await; +} + +/// Reads that spill to the writer are counted by cause, so a late fence +/// heartbeat is distinguishable from a busy or lagging reader, while the +/// legacy `buzz_db_route_decision` reasons stay as they were. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn reader_spills_are_counted_by_cause() { + let (mut db, _scratch) = same_db_reader("spill_cause", 2).await; + db.set_replica_read_max_age_for_tests(Some(Duration::from_secs(1))); + let query = EventQuery::for_community(CommunityId::from_uuid(Uuid::new_v4())); + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + + // Counters drained since the last step: (route decisions, spills). + let step = || { + let mut routes = std::collections::HashMap::new(); + let mut spills = std::collections::HashMap::new(); + for ((name, decision, reason), n) in drain_counters(&snapshotter) { + // Drained counters linger at zero. + if n == 0 { + continue; + } + match name.as_str() { + "buzz_db_route_decision" => { + routes.insert((decision, reason), n); + } + "buzz_db_reader_spill_total" => { + spills.insert(reason, n); + } + _ => {} + } + } + (routes, spills) + }; + let writer = |reason: &str| ("writer".to_owned(), reason.to_owned()); + + // A fresh heartbeat: the replica serves the read, nothing spills. + db.fence().force_open_for_tests(chrono::Utc::now()); + db.count_events_routed("spill_cause", &query) + .await + .expect("replica read"); + let (_, spills) = step(); + assert!( + spills.is_empty(), + "a served read is not a spill: {spills:?}" + ); + + // Older than the 1s budget but inside the staleness gate: the probe is + // late, the replica is fine. + db.fence() + .force_open_for_tests_at(chrono::Utc::now(), Instant::now() - Duration::from_secs(2)); + db.count_events_routed("spill_cause", &query) + .await + .expect("writer answers a late-heartbeat read"); + let (routes, spills) = step(); + assert_eq!(routes.get(&writer("stale")), Some(&1), "{routes:?}"); + assert_eq!( + spills, + [("heartbeat_stale".to_owned(), 1)].into(), + "a late heartbeat must be its own spill reason" + ); + + // Past the staleness gate: no live heartbeat proof at all. + db.fence().force_open_for_tests_at( + chrono::Utc::now(), + Instant::now() - replica_fence::FENCE_STALENESS - Duration::from_secs(1), + ); + db.count_events_routed("spill_cause", &query) + .await + .expect("writer answers a missing-heartbeat read"); + let (routes, spills) = step(); + assert_eq!(routes.get(&writer("uninitialized")), Some(&1), "{routes:?}"); + assert_eq!(spills, [("heartbeat_missing".to_owned(), 1)].into()); + + // A disabled bounded arm is configuration, not a spill. + db.set_replica_read_max_age_for_tests(None); + db.fence().force_open_for_tests(chrono::Utc::now()); + db.count_events_routed("spill_cause", &query) + .await + .expect("writer answers with routing disabled"); + let (routes, spills) = step(); + assert_eq!(routes.get(&writer("disabled")), Some(&1), "{routes:?}"); + assert!( + spills.is_empty(), + "disabled routing is not a spill: {spills:?}" + ); } diff --git a/crates/buzz-db/src/runtime/tests/schema_fence_bootstrap_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/schema_fence_bootstrap_postgres_tests.rs new file mode 100644 index 00000000000..67eb9a9a990 --- /dev/null +++ b/crates/buzz-db/src/runtime/tests/schema_fence_bootstrap_postgres_tests.rs @@ -0,0 +1,39 @@ +use sqlx::PgPool; + +/// A fresh bootstrap keeps the declared backstops but never discovers new +/// community tables and silently attaches a trigger to them. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_bootstrap_keeps_only_explicit_legacy_fences() { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + sqlx::raw_sql("CREATE TABLE new_tenant_probe (community_id UUID NOT NULL)") + .execute(&pool) + .await + .unwrap(); + // Only checked-in schema files contribute SQL to this test bootstrap. + sqlx::raw_sql(sqlx::AssertSqlSafe( + crate::test_support::desired_state_schema_sql(), + )) + .execute(&pool) + .await + .unwrap(); + + for (table, expected) in [ + ("new_tenant_probe", false), + ("events", true), + ("users", true), + ] { + let fenced: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_trigger \ + WHERE tgrelid = $1::regclass \ + AND tgfoid = 'enforce_community_write_fence()'::regprocedure)", + ) + .bind(table) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(fenced, expected, "unexpected fence on {table}"); + } +} diff --git a/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs index 48846b42cdf..93e61bde7a6 100644 --- a/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs +++ b/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs @@ -14,8 +14,8 @@ fn request(channel: Uuid, root: &nostr::Event, upper: u64) -> Request { #[ignore = "requires Postgres"] async fn thread_window_upper_fence_terminal_snapshot_and_fallback() { let admin = PgPool::connect(&admin_url().await).await.unwrap(); - let (writer, wname) = create_scratch_db(&admin, "tw_writer").await; - let (replica, rname) = create_scratch_db(&admin, "tw_replica").await; + let (writer, _writer_db) = ScratchDb::migrated(&admin_url().await, "tw_writer").await; + let (replica, replica_db) = ScratchDb::migrated(&admin_url().await, "tw_replica").await; let keys = nostr::Keys::generate(); let cid = Uuid::new_v4(); let channel = Uuid::new_v4(); @@ -87,9 +87,7 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() { .sign_with_keys(&keys) .unwrap(); for pool in [&writer, &replica] { - event::insert_event(pool, community, &edit, Some(channel)) - .await - .unwrap(); + crate::test_support::insert_historical_event(pool, community, &edit, channel).await; event::insert_event(pool, community, &deletion, None) .await .unwrap(); @@ -127,7 +125,7 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() { ); drop(fresh); sqlx::query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=$1 AND pid<>pg_backend_pid()") - .bind(&rname).execute(&admin).await.unwrap(); + .bind(replica_db.name()).execute(&admin).await.unwrap(); let degraded = session .thread_window_aux(&query, &mut budget) .await @@ -149,15 +147,12 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() { assert_eq!(page.rows.len(), 2); assert!(!page.has_more); drop(session); - drop_scratch_db(&admin, replica, &rname).await; - drop_scratch_db(&admin, writer, &wname).await; } #[tokio::test] #[ignore = "requires Postgres"] async fn migration_schema_thread_window_prebuild_validation_and_old_ledger() { - let admin = PgPool::connect(&admin_url().await).await.unwrap(); - let (pool, name) = create_scratch_db_through(&admin, "tw_prebuild", Some(48)).await; + let (pool, _scratch) = ScratchDb::migrated_through(&admin_url().await, "tw_prebuild", 48).await; for setup in [ "CREATE INDEX idx_thread_metadata_window ON thread_metadata (community_id,root_event_id,event_created_at ASC,event_id ASC)", // Simulate an invalid concurrent-build remnant only in this disposable superuser DB. @@ -205,14 +200,13 @@ async fn migration_schema_thread_window_prebuild_validation_and_old_ledger() { old.run(&pool).await, Err(sqlx::migrate::MigrateError::VersionMissing(49)) )); - drop_scratch_db(&admin, pool, &name).await; } #[tokio::test] #[ignore = "requires Postgres"] async fn migration_schema_thread_window_prebuild_does_not_queue_behind_writer() { - let admin = PgPool::connect(&admin_url().await).await.unwrap(); - let (pool, name) = create_scratch_db_through(&admin, "tw_prebuild_writer", Some(48)).await; + let (pool, _scratch) = + ScratchDb::migrated_through(&admin_url().await, "tw_prebuild_writer", 48).await; let community = Uuid::new_v4(); let channel = Uuid::new_v4(); // Plain SQL: the schema stops at 0048, so the current channel store's @@ -316,7 +310,6 @@ async fn migration_schema_thread_window_prebuild_does_not_queue_behind_writer() .unwrap(); drop(witness); writer.rollback().await.unwrap(); - drop_scratch_db(&admin, pool, &name).await; assert!( result.is_ok(), diff --git a/crates/buzz-db/src/runtime/tests/writer_pool_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/writer_pool_postgres_tests.rs new file mode 100644 index 00000000000..4e42455854d --- /dev/null +++ b/crates/buzz-db/src/runtime/tests/writer_pool_postgres_tests.rs @@ -0,0 +1,94 @@ +//! Writer-pool connection hygiene against a real Postgres. + +use super::*; + +/// A `BEGIN` cancelled before Postgres answers must not hand its pooled +/// connection to the next borrower still inside that transaction. +/// +/// sqlx 0.9.0 counted a transaction only once `BEGIN` was acknowledged, so a +/// begin dropped in flight queued no `ROLLBACK` and the release ping consumed +/// the late reply (fixed upstream in transact-rs/sqlx#4394). The writer pool +/// has no release check, so the next borrower's autocommit statements ran +/// inside the leftover transaction: `25001` on its next `BEGIN`, `25P02` on +/// every statement once one of them failed, and its writes were left +/// uncommitted. Covers the event read's custom `BEGIN ... READ ONLY` +/// ([`crate::event::fetch_with_read_deadline`]) and a plain `begin()`. +#[tokio::test(flavor = "current_thread")] +#[ignore = "requires Postgres"] +async fn begin_cancelled_in_flight_leaves_no_writer_transaction_open() { + let (seed, _scratch) = ScratchDb::migrated(&admin_url().await, "begin_cxl").await; + let options = seed.connect_options(); + let proxy = + crate::test_support::PausingProxy::spawn(options.get_host().to_owned(), options.get_port()) + .await; + // One connection, so every checkout is the one the cancelled begin used; + // like the writer pool, no release check. + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect_lazy_with((*options).clone().host("127.0.0.1").port(proxy.port)); + sqlx::query("CREATE TABLE begin_cancel_probe (n int NOT NULL)") + .execute(&pool) + .await + .expect("create probe table"); + + for (n, form) in [(1, "event read BEGIN ... READ ONLY"), (2, "plain begin()")] { + let mut conn = pool.acquire().await.expect("checkout before cancel"); + proxy.set_paused(true); + let budget = Duration::from_millis(200); + let cancelled = if n == 1 { + tokio::time::timeout( + budget, + crate::event::fetch_with_read_deadline( + &mut conn, + sqlx::query("SELECT 1"), + crate::event::ReadDeadline::PerRead, + ), + ) + .await + .is_err() + } else { + tokio::time::timeout(budget, conn.begin()).await.is_err() + }; + assert!( + cancelled, + "{form}: the paused proxy must hold BEGIN in flight" + ); + drop(conn); + proxy.set_paused(false); + + let mut next = pool.acquire().await.expect("checkout after cancel"); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *next) + .await + .expect("next borrower's backend pid"); + // A leftover `READ ONLY` transaction fails this write; a read-write one + // leaves it uncommitted (checked below). + if let Err(e) = sqlx::query("INSERT INTO begin_cancel_probe (n) VALUES ($1)") + .bind(n) + .execute(&mut *next) + .await + { + panic!("{form}: the next borrower's autocommit write failed: {e}"); + } + let state: Option = + sqlx::query_scalar("SELECT state FROM pg_stat_activity WHERE pid = $1") + .bind(pid) + .fetch_one(&seed) + .await + .expect("read the next borrower's backend state"); + assert_eq!( + state.as_deref(), + Some("idle"), + "{form}: the next borrower runs inside the cancelled BEGIN's transaction" + ); + } + + // Read from a connection outside the proxied pool: an autocommit write + // that ran inside a leftover transaction is not committed. + let committed: Vec = sqlx::query_scalar("SELECT n FROM begin_cancel_probe ORDER BY n") + .fetch_all(&seed) + .await + .expect("read probe rows"); + assert_eq!(committed, vec![1, 2], "every autocommit write must commit"); + pool.close().await; +} diff --git a/crates/buzz-db/src/store/admission_postgres_tests.rs b/crates/buzz-db/src/store/admission_postgres_tests.rs index c5b23f41e6a..8cef51834e6 100644 --- a/crates/buzz-db/src/store/admission_postgres_tests.rs +++ b/crates/buzz-db/src/store/admission_postgres_tests.rs @@ -318,9 +318,16 @@ async fn workflow_writers_require_application_admission() { .expect_err("workflow create must reject"), ); assert_fenced( - super::workflow::create_workflow_run(&db.pool, *community, Uuid::new_v4(), None, None) - .await - .expect_err("workflow run create must reject"), + super::workflow::create_workflow_run( + &db.pool, + *community, + Uuid::new_v4(), + None, + None, + &super::workflow::RunCause::Schedule, + ) + .await + .expect_err("workflow run create must reject"), ); assert_fenced( super::workflow::claim_scheduled_workflow_fire( diff --git a/crates/buzz-db/src/store/artifact.rs b/crates/buzz-db/src/store/artifact.rs index a8a49ac602b..6f9f46eb174 100644 --- a/crates/buzz-db/src/store/artifact.rs +++ b/crates/buzz-db/src/store/artifact.rs @@ -185,14 +185,15 @@ impl Db { } } sqlx::query( - "INSERT INTO artifact_revisions (community_id,event_id,artifact_id) VALUES ($1,$2,$3)", + "INSERT INTO artifact_revisions (community_id,event_id,artifact_id,source_channel_id,modified_at) VALUES ($1,$2,$3,$4,clock_timestamp())", ) .bind(community.as_uuid()) .bind(event.id.as_bytes().as_slice()) .bind(env.id) + .bind(if env.op == ArtifactOp::Move { source } else { None }) .execute(tx.conn()) .await?; - sqlx::query("INSERT INTO artifact_heads (community_id,artifact_id,event_id,channel_id,artifact_type,root,deleted) VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT (community_id,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,channel_id=EXCLUDED.channel_id,root=EXCLUDED.root,deleted=EXCLUDED.deleted") + sqlx::query("INSERT INTO artifact_heads (community_id,artifact_id,event_id,channel_id,artifact_type,root,deleted,modified_at) VALUES ($1,$2,$3,$4,$5,$6,$7,clock_timestamp()) ON CONFLICT (community_id,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,channel_id=EXCLUDED.channel_id,root=EXCLUDED.root,deleted=EXCLUDED.deleted,modified_at=clock_timestamp()") .bind(community.as_uuid()).bind(env.id).bind(event.id.as_bytes().as_slice()).bind(env.home).bind(&env.artifact_type).bind(&env.root).bind(env.op == ArtifactOp::Delete).execute(tx.conn()).await?; let (stored, _) = crate::event::insert_event_in_transaction(&mut tx, event, Some(env.home)).await?; diff --git a/crates/buzz-db/src/store/artifact_postgres_tests.rs b/crates/buzz-db/src/store/artifact_postgres_tests.rs index 97534792e76..f858deeb182 100644 --- a/crates/buzz-db/src/store/artifact_postgres_tests.rs +++ b/crates/buzz-db/src/store/artifact_postgres_tests.rs @@ -362,7 +362,7 @@ async fn unlisted_channel_artifacts_are_read_by_name_for_non_members() { #[ignore = "requires Postgres"] async fn artifacts_of_a_later_channel_type_are_read_only_by_name() { use super::legacy_channel_types_postgres_tests::{scratch_db_with_future_type, FUTURE_TYPE}; - let (db, admin, name) = scratch_db_with_future_type().await; + let (db, _scratch) = scratch_db_with_future_type().await; let f = Fixture::on(db).await; let later = Uuid::new_v4(); sqlx::query("INSERT INTO channels(community_id,id,name,visibility,channel_type,created_by) VALUES($1,$2,$3,'open',$4::channel_type,$5)") @@ -407,13 +407,6 @@ async fn artifacts_of_a_later_channel_type_are_read_only_by_name() { ); assert_eq!(f.count(&f.owner, named).await, per_channel as i64); } - - f.db.pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(&admin) - .await; } #[tokio::test] @@ -698,3 +691,135 @@ async fn head_outside_authorized_channel_matches_missing_head() { ArtifactOutcome::Accepted(_) )); } + +/// Sync's complete-set read: keyset pages by `d` share one snapshot, so a +/// change committed after it opens is in no page. Mutation: drop the +/// `REPEATABLE READ` statement → the late create appears in a later page → +/// RED. Mutation: drop the `a.artifact_id>` keyset bound → pages repeat → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_snapshot_pages_are_one_cut_and_head_includes_deletions() { + let f = Fixture::new().await; + let mut ids: Vec = (0..5).map(|_| Uuid::new_v4()).collect(); + ids.sort(); + let mut heads = vec![]; + for d in &ids { + let create = f.revision(*d, "create", f.a, None, &f.owner, vec![]); + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Accepted(_) + )); + heads.push(create); + } + // A deleted artifact leaves the set but stays visible to the head view. + let deleted = f.revision(ids[4], "delete", f.a, Some(&heads[4]), &f.owner, vec![]); + assert!(matches!( + f.accept(&deleted, None).await, + ArtifactOutcome::Accepted(_) + )); + let reader = f.owner.public_key(); + let mut snapshot = + f.db.open_artifact_snapshot(f.community, reader.as_bytes(), &[f.a]) + .await + .unwrap() + .unwrap(); + let first = snapshot.next_page(&[], 2).await.unwrap(); + // Committed after the snapshot opened, and its `d` sorts after the first + // page, so only a fresh snapshot per page would return it. + let late = loop { + let d = Uuid::new_v4(); + if d > ids[1] { + break d; + } + }; + let late_create = f.revision(late, "create", f.a, None, &f.owner, vec![]); + assert!(matches!( + f.accept(&late_create, None).await, + ArtifactOutcome::Accepted(_) + )); + let mut seen: Vec<_> = first.iter().map(|e| e.event.id).collect(); + loop { + let page = snapshot.next_page(&[], 2).await.unwrap(); + if page.is_empty() { + break; + } + seen.extend(page.iter().map(|e| e.event.id)); + } + snapshot.finish().await.unwrap(); + assert_eq!(seen, heads[..4].iter().map(|e| e.id).collect::>()); + + // Predicates apply inside the snapshot. + let mut filtered = + f.db.open_artifact_snapshot(f.community, reader.as_bytes(), &[f.a]) + .await + .unwrap() + .unwrap(); + let none = filtered + .next_page(&[("type".into(), vec!["other".into()])], 10) + .await + .unwrap(); + assert!(none.is_empty()); + + // A private channel the reader cannot read refuses the whole sync. + assert!(matches!( + f.db.open_artifact_snapshot(f.community, f.peer.public_key().as_bytes(), &[f.a, f.b]) + .await + .unwrap(), + Err(super::artifact_query::SnapshotDenied::Restricted) + )); + // So does a channel that does not exist. + assert!(matches!( + f.db.open_artifact_snapshot(f.community, reader.as_bytes(), &[Uuid::new_v4()]) + .await + .unwrap(), + Err(super::artifact_query::SnapshotDenied::Restricted) + )); + + let (head, is_deletion) = + f.db.artifact_head(f.community, reader.as_bytes(), ids[4], &[]) + .await + .unwrap() + .unwrap(); + assert_eq!(head.event.id, deleted.id); + assert!(is_deletion); + let (head, is_deletion) = + f.db.artifact_head(f.community, reader.as_bytes(), ids[0], &[]) + .await + .unwrap() + .unwrap(); + assert_eq!(head.event.id, heads[0].id); + assert!(!is_deletion); + let (view, _) = f + .query( + &f.owner, + serde_json::json!({"artifact":"head","#d":[ids[4], ids[0]]}), + false, + ) + .await; + let mut view: Vec<_> = view.iter().map(|e| e.event.id).collect(); + view.sort(); + let mut expected = vec![deleted.id, heads[0].id]; + expected.sort(); + assert_eq!(view, expected); + assert_eq!( + f.count( + &f.owner, + serde_json::json!({"artifact":"current","#d":[ids[4]]}) + ) + .await, + 0 + ); + // A reader who cannot read the head's channel learns nothing. + let private = Uuid::new_v4(); + let create = f.revision(private, "create", f.b, None, &f.owner, vec![]); + assert!(matches!( + f.accept(&create, None).await, + ArtifactOutcome::Accepted(_) + )); + assert!(f + .db + .artifact_head(f.community, f.peer.public_key().as_bytes(), private, &[]) + .await + .unwrap() + .is_none()); +} diff --git a/crates/buzz-db/src/store/artifact_query.rs b/crates/buzz-db/src/store/artifact_query.rs index f359726d925..9a5cee1bc4f 100644 --- a/crates/buzz-db/src/store/artifact_query.rs +++ b/crates/buzz-db/src/store/artifact_query.rs @@ -4,11 +4,191 @@ use buzz_core::{ artifact::{ArtifactQuery, ArtifactView}, CommunityId, StoredEvent, }; -use sqlx::QueryBuilder; +use sqlx::{pool::PoolConnection, Postgres, QueryBuilder, Transaction}; +use uuid::Uuid; + +const EVENT_COLUMNS: &str = + "SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id FROM events e "; + +/// Own the visibility and tag rules for artifact queries and current-ID +/// reads: the `query.view` join, then `push_scope` with the channels `#h` +/// names. +pub(super) fn predicates( + qb: &mut QueryBuilder, + community: CommunityId, + reader: &[u8], + query: &ArtifactQuery, +) { + match query.view { + ArtifactView::Current => { + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND NOT a.deleted "); + } + ArtifactView::Head => { + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id "); + } + ArtifactView::History => {} + } + push_scope( + qb, + community, + reader, + &query.tags, + named_channels(&query.tags), + ); + if query.view != ArtifactView::History { + for (_, values) in query.tags.iter().filter(|(name, _)| name == "d") { + qb.push(" AND a.artifact_id=ANY(") + .push_bind( + values + .iter() + .filter_map(|id| id.parse::().ok()) + .collect::>(), + ) + .push(")"); + } + } +} + +/// Append the reader's permission scope and the exact tag predicates. A +/// system channel, or an unlisted open channel the reader is not a member +/// of, is readable only when `named_channels` names it (NIP-CL). This is the +/// one copy of the current-state access rule. +fn push_scope( + qb: &mut QueryBuilder, + community: CommunityId, + reader: &[u8], + tags: &[(String, Vec)], + named_channels: Vec, +) { + // The explicit kind lets the community/kind index exclude chat before + // the join, even for an unfiltered current-state page. + qb.push("WHERE e.community_id=").push_bind(community.as_uuid()).push(" AND e.kind=45010 AND e.deleted_at IS NULL AND EXISTS (SELECT 1 FROM channels c WHERE c.community_id=e.community_id AND c.id=e.channel_id AND c.deleted_at IS NULL AND (") + .push(crate::store::channel::legacy_channel_type_sql("c.channel_type")) + .push(" OR c.id=ANY(") + .push_bind(named_channels.clone()) + .push(")) AND ((c.visibility='open' AND (NOT c.unlisted OR c.id=ANY(") + .push_bind(named_channels) + .push("))) OR EXISTS (SELECT 1 FROM channel_members m WHERE m.community_id=c.community_id AND m.channel_id=c.id AND m.pubkey=") + .push_bind(reader.to_vec()).push(" AND m.removed_at IS NULL)))"); + tag_predicates(qb, tags); +} + +/// Apply exact artifact tag predicates after access is resolved. +fn tag_predicates(qb: &mut QueryBuilder, tags: &[(String, Vec)]) { + for (name, values) in tags { + // GIN-usable necessary prefilter; retain the positional recheck + // because JSON array containment alone also matches swapped values. + qb.push(" AND ("); + for (index, value) in values.iter().enumerate() { + if index != 0 { + qb.push(" OR "); + } + qb.push("e.tags @> ") + .push_bind(serde_json::json!([[name, value]])); + } + qb.push(")"); + qb.push(" AND EXISTS (SELECT 1 FROM jsonb_array_elements(e.tags) tag WHERE tag->>0=") + .push_bind(name) + .push(" AND tag->>1=ANY(") + .push_bind(values) + .push("))"); + } +} + +/// Channel UUIDs named by `#h`; malformed values name no channel. +fn named_channels(tags: &[(String, Vec)]) -> Vec { + tags.iter() + .filter(|(name, _)| name == "h") + .flat_map(|(_, values)| values.iter().filter_map(|value| value.parse().ok())) + .collect() +} + +fn rows_to_events(rows: Vec) -> Result> { + let mut events = vec![]; + for row in rows { + if let Some(event) = crate::event::row_to_stored_event(row)? { + events.push(event); + } + } + Ok(events) +} + +/// Read-only: a plain writer-pool connection, labeled as the history read it +/// is, so it neither takes community admission nor counts as an event write. +/// The writer is always at least as fresh as every accepted change. +async fn read_connection(db: &Db) -> Result> { + crate::observability::acquire_writer( + &db.pool, + crate::observability::WriterOperation::SubscriptionHistory, + ) + .await + .map_err(Into::into) +} + +/// Why a sync snapshot did not open. +#[derive(Debug, PartialEq, Eq)] +pub enum SnapshotDenied { + /// The reader cannot read a named channel, or it does not exist. + Restricted, +} + +/// One read-only `REPEATABLE READ` snapshot of a sync's current heads, read +/// in keyset pages ordered by artifact identity. Every page sees the same +/// database snapshot, so the pages together are one consistent cut. +pub struct ArtifactSnapshot { + tx: Transaction<'static, Postgres>, + community: CommunityId, + reader: Vec, + channels: Vec, + after: Option, + done: bool, +} + +impl ArtifactSnapshot { + /// Read the next page of at most `page` heads that match `tags`, ordered + /// by `d`. Returns an empty page once the set is exhausted. + pub async fn next_page( + &mut self, + tags: &[(String, Vec)], + page: i64, + ) -> Result> { + if self.done { + return Ok(vec![]); + } + let mut qb = QueryBuilder::::new( + "SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id,a.artifact_id FROM events e ", + ); + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND NOT a.deleted "); + push_scope( + &mut qb, + self.community, + &self.reader, + tags, + self.channels.clone(), + ); + if let Some(after) = self.after { + qb.push(" AND a.artifact_id>").push_bind(after); + } + qb.push(" ORDER BY a.artifact_id LIMIT ").push_bind(page); + let rows = qb.build().fetch_all(&mut *self.tx).await?; + self.done = (rows.len() as i64) < page; + if let Some(last) = rows.last() { + self.after = Some(sqlx::Row::try_get(last, "artifact_id")?); + } + rows_to_events(rows) + } + + /// End the snapshot. Dropping it rolls the read-only transaction back. + pub async fn finish(self) -> Result<()> { + self.tx.commit().await?; + Ok(()) + } +} impl Db { - /// Execute a bounded query against current artifacts or revision history. - /// Permission is resolved in the query snapshot. + /// Execute a bounded query against current artifacts, current heads + /// including deletions, or revision history. Permission is resolved in + /// the query snapshot. pub async fn query_artifacts( &self, community: CommunityId, @@ -16,63 +196,17 @@ impl Db { query: &ArtifactQuery, count: bool, ) -> Result<(Vec, i64)> { - // Read-only: a plain writer-pool snapshot transaction, labeled as the - // history read it is, so it neither takes community admission nor - // counts as an event write. - let connection = crate::observability::acquire_writer( - &self.pool, - crate::observability::WriterOperation::SubscriptionHistory, - ) - .await?; + let connection = read_connection(self).await?; let mut tx = sqlx::Transaction::begin(connection, None).await?; sqlx::query("SET LOCAL statement_timeout='2s'") .execute(&mut *tx) .await?; - let mut qb = QueryBuilder::::new(if count { + let mut qb = QueryBuilder::::new(if count { "SELECT count(*) AS count FROM events e " } else { - "SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id FROM events e " + EVENT_COLUMNS }); - if query.view == ArtifactView::Current { - qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND NOT a.deleted "); - } - // A system channel, or an unlisted open channel the reader is not a - // member of, is read only by a query whose `#h` names it (NIP-CL); - // malformed `#h` values name no channel. - let named_channels: Vec = query - .tags - .iter() - .filter(|(name, _)| name == "h") - .flat_map(|(_, values)| values.iter().filter_map(|value| value.parse().ok())) - .collect(); - // The explicit kind lets the community/kind index exclude chat before - // the join, even for an unfiltered current-state page. - qb.push("WHERE e.community_id=").push_bind(community.as_uuid()).push(" AND e.kind=45010 AND e.deleted_at IS NULL AND EXISTS (SELECT 1 FROM channels c WHERE c.community_id=e.community_id AND c.id=e.channel_id AND c.deleted_at IS NULL AND (") - .push(crate::store::channel::legacy_channel_type_sql("c.channel_type")) - .push(" OR c.id=ANY(") - .push_bind(named_channels.clone()) - .push(")) AND ((c.visibility='open' AND (NOT c.unlisted OR c.id=ANY(") - .push_bind(named_channels) - .push("))) OR EXISTS (SELECT 1 FROM channel_members m WHERE m.community_id=c.community_id AND m.channel_id=c.id AND m.pubkey=") - .push_bind(reader.to_vec()).push(" AND m.removed_at IS NULL)))"); - for (name, values) in &query.tags { - // GIN-usable necessary prefilter; retain the positional recheck - // because JSON array containment alone also matches swapped values. - qb.push(" AND ("); - for (index, value) in values.iter().enumerate() { - if index != 0 { - qb.push(" OR "); - } - qb.push("e.tags @> ") - .push_bind(serde_json::json!([[name, value]])); - } - qb.push(")"); - qb.push(" AND EXISTS (SELECT 1 FROM jsonb_array_elements(e.tags) tag WHERE tag->>0=") - .push_bind(name) - .push(" AND tag->>1=ANY(") - .push_bind(values) - .push("))"); - } + predicates(&mut qb, community, reader, query); if count { let n: i64 = qb.build_query_scalar().fetch_one(&mut *tx).await?; tx.commit().await?; @@ -82,14 +216,74 @@ impl Db { .push_bind(query.limit) .push(" OFFSET ") .push_bind(query.offset); - let rows = qb.build().fetch_all(&mut *tx).await?; - let mut events = vec![]; - for row in rows { - if let Some(event) = crate::event::row_to_stored_event(row)? { - events.push(event); - } - } + let events = rows_to_events(qb.build().fetch_all(&mut *tx).await?)?; tx.commit().await?; Ok((events, 0)) } + + /// The current head of one artifact, including a deletion, when the + /// reader can read the head's channel, with whether it is a deletion. + /// `named_channels` are the system channels the caller's request names. + pub async fn artifact_head( + &self, + community: CommunityId, + reader: &[u8], + artifact: Uuid, + named_channels: &[Uuid], + ) -> Result> { + let mut connection = read_connection(self).await?; + let mut qb = QueryBuilder::::new( + "SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id,a.deleted FROM events e ", + ); + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND a.artifact_id=") + .push_bind(artifact) + .push(" "); + push_scope(&mut qb, community, reader, &[], named_channels.to_vec()); + let Some(row) = qb.build().fetch_optional(&mut *connection).await? else { + return Ok(None); + }; + let deleted: bool = sqlx::Row::try_get(&row, "deleted")?; + Ok(rows_to_events(vec![row])? + .into_iter() + .next() + .map(|head| (head, deleted))) + } + + /// Open a sync snapshot over `channels`, after confirming in the same + /// snapshot that the reader can read every one of them. + /// `statement_timeout` bounds each page read. + pub async fn open_artifact_snapshot( + &self, + community: CommunityId, + reader: &[u8], + channels: &[Uuid], + ) -> Result> { + let connection = read_connection(self).await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + .execute(&mut *tx) + .await?; + sqlx::query("SET LOCAL statement_timeout='2s'") + .execute(&mut *tx) + .await?; + let readable: i64 = sqlx::query_scalar( + "SELECT count(*) FROM channels c WHERE c.community_id=$1 AND c.id=ANY($2) AND c.deleted_at IS NULL AND (c.visibility='open' OR EXISTS (SELECT 1 FROM channel_members m WHERE m.community_id=c.community_id AND m.channel_id=c.id AND m.pubkey=$3 AND m.removed_at IS NULL))", + ) + .bind(community.as_uuid()) + .bind(channels) + .bind(reader) + .fetch_one(&mut *tx) + .await?; + if readable != channels.len() as i64 { + return Ok(Err(SnapshotDenied::Restricted)); + } + Ok(Ok(ArtifactSnapshot { + tx, + community, + reader: reader.to_vec(), + channels: channels.to_vec(), + after: None, + done: false, + })) + } } diff --git a/crates/buzz-db/src/store/artifact_sync.rs b/crates/buzz-db/src/store/artifact_sync.rs new file mode 100644 index 00000000000..4da01728fd0 --- /dev/null +++ b/crates/buzz-db/src/store/artifact_sync.rs @@ -0,0 +1,205 @@ +//! Indexed artifact changes. Each page reads current authority on the writer. +use crate::{Db, DbError, Result}; +use buzz_core::{artifact::ArtifactQuery, CommunityId, StoredEvent}; +use chrono::{DateTime, Utc}; +use futures_util::TryStreamExt; +use serde::{Deserialize, Serialize}; +use sqlx::{QueryBuilder, Row}; +use uuid::Uuid; + +/// Maximum changes or requested identities in one page. +pub const PAGE_ROWS: usize = 100; + +/// A stable position within one timestamp window. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Position { + /// Database timestamp of the change. + pub at: DateTime, + /// Change source, which separates equal keys from different tables. + pub source: i32, + /// Stable identity within that source. + pub id: String, +} + +/// A changed identity that requires a current, permission-scoped read. +pub struct Candidate { + /// Position used after this candidate is processed. + pub position: Position, + /// Artifact to revalidate, absent for a removed membership. + pub artifact_id: Option, + /// Removed channel belonging to the authenticated reader's membership. + pub removed_channel: Option, +} + +impl Db { + /// Read server time and the community's access-policy recovery boundary. + pub async fn artifact_sync_boundary( + &self, + community: CommunityId, + ) -> Result<(DateTime, DateTime)> { + sqlx::query_as("SELECT clock_timestamp(),artifact_policy_modified_at FROM communities WHERE id=$1 AND deletion_state='active' AND deleted_at IS NULL") + .bind(community.as_uuid()).fetch_optional(&self.pool).await? + .ok_or_else(|| DbError::InvalidData("artifact sync community unavailable".into())) + } + + /// Find at most one page plus one look-ahead row, without a channel roster. + pub async fn artifact_sync_candidates( + &self, + community: CommunityId, + reader: &[u8], + since: Option>, + until: DateTime, + after: Option<&Position>, + query: &ArtifactQuery, + ) -> Result> { + let connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::SubscriptionHistory, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + sqlx::query("SET LOCAL statement_timeout='2s'") + .execute(&mut *tx) + .await?; + let types = query + .tags + .iter() + .filter(|(n, _)| n == "type") + .flat_map(|(_, v)| v.iter().cloned()) + .collect::>(); + let named = query + .tags + .iter() + .filter(|(n, _)| n == "h") + .flat_map(|(_, v)| v.iter().filter_map(|id| id.parse::().ok())) + .collect::>(); + let rows = sqlx::query(CANDIDATES) + .bind(community.as_uuid()) + .bind(reader) + .bind(since) + .bind(until) + .bind(after.map(|p| p.at)) + .bind(after.map(|p| p.source)) + .bind(after.map(|p| p.id.as_str())) + .bind(types) + .bind(named) + .bind((PAGE_ROWS + 1) as i64) + .bind(buzz_core::channel::LEGACY_CHANNEL_TYPES.to_vec()) + .bind(query.tags.iter().any(|(name, _)| name == "h")) + .fetch_all(&mut *tx) + .await?; + let candidates = rows + .into_iter() + .map(|r| { + Ok(Candidate { + position: Position { + at: r.try_get("at")?, + source: r.try_get("source")?, + id: r.try_get("id")?, + }, + artifact_id: r.try_get("artifact_id")?, + removed_channel: r.try_get("removed_channel")?, + }) + }) + .collect::>>()?; + tx.commit().await?; + Ok(candidates) + } + + /// Return current matching events for bounded known identities. + /// Omitted identities have the same unavailable meaning for every cause. + pub async fn artifact_sync_current( + &self, + community: CommunityId, + reader: &[u8], + query: &ArtifactQuery, + ids: &[Uuid], + ) -> Result> { + if ids.len() > PAGE_ROWS { + return Err(DbError::ArtifactSyncLimit); + } + if ids.is_empty() { + return Ok(vec![]); + } + let connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::SubscriptionHistory, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY") + .execute(&mut *tx) + .await?; + sqlx::query("SET LOCAL statement_timeout='2s'") + .execute(&mut *tx) + .await?; + let mut qb = QueryBuilder::new("SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id FROM events e "); + super::artifact_query::predicates(&mut qb, community, reader, query); + qb.push(" AND a.artifact_id=ANY(").push_bind(ids).push(")"); + qb.push(" AND EXISTS (SELECT 1 FROM channels c WHERE c.community_id=e.community_id AND c.id=e.channel_id AND c.ttl_seconds IS NULL)"); + qb.push(" LIMIT ").push_bind(PAGE_ROWS as i64); + let mut events = Vec::new(); + let mut bytes = 0; + { + let mut rows = qb.build().fetch(&mut *tx); + while let Some(row) = rows.try_next().await? { + if let Some(event) = crate::event::row_to_stored_event(row)? { + bytes += serde_json::to_vec(&event.event) + .map_err(|e| DbError::InvalidData(e.to_string()))? + .len() + + 512; + if bytes > 8_388_608 { + return Err(DbError::ArtifactSyncLimit); + } + events.push(event); + } + } + } + tx.commit().await?; + Ok(events) + } +} + +// Keep candidate access rules aligned with artifact_query::predicates, which owns +// current-state visibility. This query also reads retained move and membership rows. +const CANDIDATES: &str = r#" +WITH readable AS NOT MATERIALIZED ( + SELECT c.id FROM channels c + WHERE c.community_id=$1 AND c.deleted_at IS NULL AND c.ttl_seconds IS NULL + AND (NOT $12::boolean OR c.id=ANY($9)) + AND (c.channel_type::text=ANY($11) OR c.id=ANY($9)) + AND ((c.visibility='open' AND (NOT c.unlisted OR c.id=ANY($9))) OR EXISTS ( + SELECT 1 FROM channel_members m WHERE m.community_id=c.community_id + AND m.channel_id=c.id AND m.pubkey=$2 AND m.removed_at IS NULL)) +), changes AS ( + SELECT a.modified_at AS at,1 AS source,a.artifact_id::text AS id, + a.artifact_id,NULL::uuid AS removed_channel + FROM artifact_heads a + WHERE a.community_id=$1 AND a.modified_at >= COALESCE($3::timestamptz,'epoch'::timestamptz) + AND a.modified_at <= $4 AND a.channel_id IN (SELECT id FROM readable) + AND ($3::timestamptz IS NOT NULL OR NOT a.deleted) + AND (cardinality($8::text[])=0 OR a.artifact_type=ANY($8)) + UNION ALL + SELECT m.sync_modified_at,0,m.channel_id::text,NULL::uuid,m.channel_id + FROM channel_members m WHERE m.community_id=$1 AND m.pubkey=$2 + AND $3::timestamptz IS NOT NULL AND m.sync_modified_at >= $3 + AND m.sync_modified_at <= $4 AND m.removed_at IS NOT NULL + AND (NOT $12::boolean OR m.channel_id=ANY($9)) + AND NOT EXISTS (SELECT 1 FROM readable r WHERE r.id=m.channel_id) + UNION ALL + SELECT m.sync_modified_at,2,a.artifact_id::text,a.artifact_id,NULL::uuid + FROM channel_members m JOIN artifact_heads a + ON a.community_id=m.community_id AND a.channel_id=m.channel_id + WHERE m.community_id=$1 AND m.pubkey=$2 AND m.removed_at IS NULL + AND $3::timestamptz IS NOT NULL AND m.sync_modified_at >= $3 + AND m.sync_modified_at <= $4 AND a.channel_id IN (SELECT id FROM readable) + AND (cardinality($8::text[])=0 OR a.artifact_type=ANY($8)) + UNION ALL + SELECT DISTINCT r.modified_at,3,r.artifact_id::text,r.artifact_id,NULL::uuid + FROM artifact_revisions r WHERE r.community_id=$1 + AND r.source_channel_id IS NOT NULL AND r.source_channel_id IN (SELECT id FROM readable) + AND $3::timestamptz IS NOT NULL AND r.modified_at >= $3 AND r.modified_at <= $4 +) +SELECT * FROM changes WHERE $5::timestamptz IS NULL OR (at,source,id)>($5,$6,$7) +ORDER BY at,source,id LIMIT $10 +"#; diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index e577113ef9f..f20a4f4e988 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -27,9 +27,9 @@ pub use crate::channel_members::{ add_member, get_accessible_channel_ids, get_accessible_channels, get_bot_members, get_member_count, get_member_counts_bulk, get_member_role, get_members, get_members_bulk, get_users_bulk, is_member, list_large_channel_rosters_needing_reconciliation, - lock_member_snapshot, membership_pairs, remove_member, verify_channel_roster_fence_behavior, - verify_channel_roster_fence_catalog, AccessibleChannel, BotChannelEntry, BotMemberRecord, - ChannelIdentity, LargeChannelRoster, LockedMemberSnapshot, MemberRecord, UserRecord, + lock_member_snapshot, membership_pairs, remove_member, AccessibleChannel, BotChannelEntry, + BotMemberRecord, ChannelIdentity, LargeChannelRoster, LockedMemberSnapshot, MemberRecord, + UserRecord, }; /// A channel row as returned from the database. @@ -89,6 +89,10 @@ pub struct ChannelRecord { /// join an unlisted open channel by naming it, and private channels are /// never listed to non-members. pub unlisted: bool, + /// Whether the relay joins new community members into this channel. Only + /// effective while the channel is open and unarchived; see + /// [`group_metadata_tags`] and [`list_auto_join_channels`]. + pub auto_join: bool, } impl ChannelRecord { @@ -155,13 +159,15 @@ pub async fn create_channel( .bind(labels) .bind(unlisted) .execute(tx.conn()) - .await?; + .await + .map_err(|e| listed_name_taken(e, Some(name)))?; sqlx::query( r#" INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) VALUES ($1, $2, $3, 'owner', $4) ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET + sync_modified_at = CASE WHEN channel_members.removed_at IS NOT NULL THEN clock_timestamp() ELSE channel_members.sync_modified_at END, removed_at = NULL, removed_by = NULL, role = EXCLUDED.role @@ -182,7 +188,7 @@ pub async fn create_channel( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted + ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 "#, ) @@ -245,7 +251,7 @@ pub async fn create_channel_with_id( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted + ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 "#, ) @@ -313,11 +319,19 @@ pub(crate) async fn create_channel_with_event( tx.set_push_enqueue(push_enqueue); if !insert_channel_rows(&mut tx, channel_id, channel).await? { + let seconds = i64::try_from(event.created_at.as_secs()) + .map_err(|_| DbError::InvalidTimestamp(i64::MAX))?; + let created_at = DateTime::::from_timestamp(seconds, 0) + .ok_or(DbError::InvalidTimestamp(seconds))?; + // Not a cached prepared statement: a generic plan would lock every + // `events` partition (PG16 prunes only at executor startup). let resent = sqlx::query( - "SELECT 1 FROM events WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL LIMIT 1", + "SELECT 1 FROM events WHERE community_id = $1 AND id = $2 AND created_at = $3 AND deleted_at IS NULL LIMIT 1", ) + .persistent(false) .bind(community_id.as_uuid()) .bind(event.id.as_bytes().as_slice()) + .bind(created_at) .fetch_optional(tx.conn()) .await? .is_some(); @@ -391,7 +405,8 @@ async fn insert_channel_rows( .bind(labels) .bind(unlisted) .execute(tx.conn()) - .await? + .await + .map_err(|e| listed_name_taken(e, Some(name)))? .rows_affected(); let was_created = rows_affected > 0; @@ -403,6 +418,7 @@ async fn insert_channel_rows( INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) VALUES ($1, $2, $3, 'owner', $4) ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET + sync_modified_at = CASE WHEN channel_members.removed_at IS NOT NULL THEN clock_timestamp() ELSE channel_members.sync_modified_at END, removed_at = NULL, removed_by = NULL, role = EXCLUDED.role @@ -444,6 +460,34 @@ async fn insert_channel_rows( Ok(was_created) } +/// The unique index (migration 0083) that keeps two channels the channel +/// directory lists from sharing a name in a community, ignoring case. It +/// covers open, not unlisted streams and forums that are not deleted; an +/// archived channel keeps its name. Private channels, DMs and the other +/// types may repeat names: nobody browses them side by side, and refusing a +/// name that a private channel holds would tell anyone that the channel +/// exists. A write that claims a taken name waits for a concurrent writer of +/// that name to finish, then fails if it committed. +const LISTED_NAME_INDEX: &str = "idx_channels_listed_name"; + +/// SQL that is true for a channel the channel directory lists: the predicate +/// of [`LISTED_NAME_INDEX`]. An archived channel is still listed. +pub(crate) const LISTED_CHANNEL_SQL: &str = + "visibility = 'open' AND NOT unlisted AND channel_type IN ('stream', 'forum') \ + AND deleted_at IS NULL"; + +/// Reports a channel write that [`LISTED_NAME_INDEX`] refused as +/// [`DbError::ChannelNameTaken`] for `name`, the name the channel would have +/// had. +fn listed_name_taken(error: sqlx::Error, name: Option<&str>) -> DbError { + match (&error, name) { + (sqlx::Error::Database(db), Some(name)) if db.constraint() == Some(LISTED_NAME_INDEX) => { + DbError::ChannelNameTaken(name.to_owned()) + } + _ => error.into(), + } +} + /// SQL that is true when `column` holds a legacy channel type /// ([`buzz_core::channel::LEGACY_CHANNEL_TYPES`]): ` IN ('stream', …)`. /// @@ -480,6 +524,15 @@ async fn get_channel_with_operation( operation: crate::observability::WriterOperation, ) -> Result { let mut connection = crate::observability::acquire_writer(pool, operation).await?; + select_channel(&mut connection, community_id, channel_id).await +} + +/// Read a live channel on `conn`. +async fn select_channel( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + channel_id: Uuid, +) -> Result { let row = sqlx::query( r#" SELECT id, name, channel_type::text AS channel_type, visibility::text AS visibility, @@ -488,13 +541,13 @@ async fn get_channel_with_operation( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted + ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL "#, ) .bind(community_id.as_uuid()) .bind(channel_id) - .fetch_optional(&mut *connection) + .fetch_optional(conn) .await? .ok_or(DbError::ChannelNotFound(channel_id))?; @@ -577,7 +630,7 @@ async fn list_channels_with_operation( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted + ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND deleted_at IS NULL AND visibility::text = $2 ORDER BY created_at DESC @@ -597,7 +650,7 @@ async fn list_channels_with_operation( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted + ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC @@ -612,6 +665,83 @@ async fn list_channels_with_operation( rows.into_iter().map(row_to_channel_record).collect() } +/// Lists the channels whose `auto_join` is effective: set on a stream channel +/// that is open, unarchived and not deleted. Oldest first, so the first +/// default channel a member sees is the one that was flagged first. +/// +/// Every effective channel, not a page of them: kind:9002 accepts the flag on +/// any number of channels, and the kind:39000 `auto_join` tag promises the +/// relay joins new members there, so a cap here would silently break that +/// promise for the channels past it. The set is bounded by the community's +/// channels, each flagged by a relay owner or admin. +pub async fn list_auto_join_channels( + pool: &PgPool, + community_id: CommunityId, +) -> Result> { + let mut connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let rows = sqlx::query( + r#" + SELECT id, name, channel_type::text AS channel_type, visibility::text AS visibility, + description, canvas, + created_by, created_at, updated_at, archived_at, deleted_at, + nip29_group_id, topic_required, max_members, + topic, topic_set_by, topic_set_at, + purpose, purpose_set_by, purpose_set_at, + ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join + FROM channels + WHERE community_id = $1 AND auto_join AND channel_type = 'stream' + AND visibility = 'open' AND archived_at IS NULL AND deleted_at IS NULL + ORDER BY created_at ASC + "#, + ) + .bind(community_id.as_uuid()) + .fetch_all(&mut *connection) + .await?; + rows.into_iter().map(row_to_channel_record).collect() +} + +/// The effective `auto_join` channels (see [`list_auto_join_channels`]) where +/// `pubkey` has never had a membership row, active or removed; oldest first. +/// +/// A kind:9022 leave or a kind:9001 removal keeps the row with `removed_at` +/// set, so a channel the person left is not listed. Read without the +/// membership lock: [`crate::channel_members::put_first_member`] decides +/// again under it. +pub async fn list_never_joined_auto_join_channels( + pool: &PgPool, + community_id: CommunityId, + pubkey: &[u8], +) -> Result> { + let mut connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let ids = sqlx::query_scalar( + r#" + SELECT c.id + FROM channels c + WHERE c.community_id = $1 AND c.auto_join AND c.channel_type = 'stream' + AND c.visibility = 'open' AND c.archived_at IS NULL AND c.deleted_at IS NULL + AND NOT EXISTS ( + SELECT 1 FROM channel_members m + WHERE m.community_id = c.community_id AND m.channel_id = c.id + AND m.pubkey = $2 + ) + ORDER BY c.created_at ASC + "#, + ) + .bind(community_id.as_uuid()) + .bind(pubkey) + .fetch_all(&mut *connection) + .await?; + Ok(ids) +} + /// A channel archived by the ephemeral-channel reaper. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ReapedEphemeralChannel { @@ -667,14 +797,27 @@ pub(crate) fn row_to_channel_record(row: sqlx::postgres::PgRow) -> Result bool { + channel.channel_type == ChannelType::Dm.as_str() +} + +/// The roles a channel's relay-signed NIP-29 kind:39001 admins event lists. +/// The locked snapshot that feeds it reads only these members. +pub const GROUP_ADMIN_ROLES: [MemberRole; 2] = [MemberRole::Owner, MemberRole::Admin]; + /// The tags of a channel's relay-signed NIP-29 kind:39000 metadata event. /// /// This is the single builder for kind:39000: the relay's discovery emitter /// and the `buzz-admin` backfill both call it, so the published flags cannot -/// drift apart. `members` is used only for DM participant `p` tags. +/// drift apart. `members` is read only when [`group_metadata_uses_members`] +/// holds, for DM participant `p` tags. /// /// The NIP-29 access flags follow the channel's settings: /// - `private` (members-only read), or Buzz's explicit `public`; @@ -686,10 +829,14 @@ pub(crate) fn row_to_channel_record(row: sqlx::postgres::PgRow) -> Result Vec> { let tag = |parts: &[&str]| parts.iter().map(|p| (*p).to_owned()).collect::>(); let mut tags = vec![ @@ -720,7 +867,7 @@ pub fn group_metadata_tags(channel: &ChannelRecord, members: &[MemberRecord]) -> if channel.channel_type == ChannelType::System.as_str() && !open { tags.push(tag(&["hidden"])); } - if channel.channel_type == ChannelType::Dm.as_str() { + if group_metadata_uses_members(channel) { tags.push(tag(&["hidden"])); // Include participant pubkeys in kind:39000 for DMs so clients can // resolve display names without a separate kind:39002 fetch. @@ -746,6 +893,9 @@ pub fn group_metadata_tags(channel: &ChannelRecord, members: &[MemberRecord]) -> &channel.created_at.timestamp().to_string(), ])); tags.push(tag(&["join_role", join_role.as_str()])); + if channel.auto_join && open && channel.archived_at.is_none() { + tags.push(tag(&["auto_join"])); + } // Optional topic / purpose for richer client UX if let Some(topic) = channel.topic.as_deref().filter(|t| !t.is_empty()) { tags.push(tag(&["topic", topic])); @@ -767,6 +917,139 @@ pub fn group_metadata_tags(channel: &ChannelRecord, members: &[MemberRecord]) -> tags } +/// A channel and its active members, read behind the replacement lock of the +/// channel's relay-signed kind:39000 or kind:39001 event, with the +/// `created_at` of that event's live copy. +/// +/// The event built from this snapshot is stored by [`Self::replace`] before +/// the lock is released, so racing publishers store in the order they read, +/// each one second past the last: the live event never falls back to state +/// read before a newer publisher's. kind:39002 has the same fence in +/// [`LockedMemberSnapshot`]. +pub struct LockedGroupStateSnapshot { + /// The channel, read behind the lock. + pub channel: ChannelRecord, + /// The active members the kind's tags use, read behind the lock: every + /// member for a DM's kind:39000 (its `p` tags), owners and admins for + /// kind:39001, and none for any other kind:39000, whose tags do not + /// mention members. Reading only those keeps the lock short on large + /// channels. + pub members: Vec, + /// `created_at` of the coordinate's live event, if it has one. + pub latest_created_at: Option, + kind: i32, + relay_pubkey: Vec, + tx: crate::AdmittedTx, + /// Times lock, reads and replacement as one `replace_addressable_event` + /// transaction, which is where these writes were timed before. + timer: crate::observability::TransactionTimer, +} + +impl LockedGroupStateSnapshot { + /// Store `event`, built from this snapshot, as the coordinate's live + /// event, and release the lock. Returns `(event, false)`, storing + /// nothing, when an equal or newer event is already live. + pub async fn replace(self, event: &nostr::Event) -> Result<(StoredEvent, bool)> { + let Self { + channel, + kind, + relay_pubkey, + mut tx, + timer, + .. + } = self; + let channel_id = channel.id; + if buzz_core::kind::event_kind_i32(event) != kind + || event.pubkey.to_bytes().as_slice() != relay_pubkey.as_slice() + || crate::event::extract_d_tag(event) != Some(channel_id.to_string()) + { + return Err(DbError::InvalidData( + "group-state replacement does not match its locked coordinate".into(), + )); + } + timer + .observe(async { + let (stored, inserted) = crate::replaceable::replace_addressable_event_under_lock( + &mut tx, + event, + Some(channel_id), + ) + .await?; + if inserted { + tx.commit().await?; + } else { + tx.rollback().await?; + } + Ok((stored, inserted)) + }) + .await + } +} + +/// Take the replacement lock of `channel_id`'s relay-signed `kind` event +/// (39000 or 39001), then read the channel, the members that kind's tags +/// use and the live event's `created_at` behind it. See +/// [`LockedGroupStateSnapshot`]. Any other `kind` is refused. +pub async fn lock_group_state_snapshot( + pool: &PgPool, + community_id: CommunityId, + channel_id: Uuid, + kind: i32, + relay_pubkey: &[u8], +) -> Result { + if kind != 39000 && kind != 39001 { + return Err(DbError::InvalidData(format!( + "group-state snapshots cover kind:39000 and kind:39001, not kind:{kind}" + ))); + } + // The same writer population and transaction timer as + // `Db::replace_addressable_event`, which stored these events before. + let mut tx = crate::begin_community_event_write_transaction_with_legacy_metrics( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let timer = crate::observability::TransactionTimer::start( + crate::observability::TransactionOperation::ReplaceAddressableEvent, + ); + crate::replaceable::take_replacement_lock(&mut tx, kind, relay_pubkey, Some(channel_id)) + .await?; + let channel = select_channel(tx.conn(), community_id, channel_id).await?; + let members = if kind == 39001 { + crate::channel_members::select_active_members_in_roles( + tx.conn(), + community_id, + channel_id, + &GROUP_ADMIN_ROLES, + ) + .await? + } else if group_metadata_uses_members(&channel) { + crate::channel_members::select_active_members(tx.conn(), community_id, channel_id).await? + } else { + Vec::new() + }; + let latest_created_at: Option> = sqlx::query_scalar( + "SELECT created_at FROM events WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ + AND channel_id = $4 AND deleted_at IS NULL ORDER BY created_at DESC, id ASC LIMIT 1", + ) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(relay_pubkey) + .bind(channel_id) + .fetch_optional(tx.conn()) + .await?; + Ok(LockedGroupStateSnapshot { + channel, + members, + latest_created_at: latest_created_at.map(|created_at| created_at.timestamp() as u64), + kind, + relay_pubkey: relay_pubkey.to_vec(), + tx, + timer, + }) +} + /// Partial update for channel metadata. Every field is `None` to leave the /// column unchanged. #[derive(Default)] @@ -789,6 +1072,10 @@ pub struct ChannelUpdate { /// New unlisted flag, or `None` to leave unchanged. It decides listing, /// not admission, so it does not take the membership lock. pub unlisted: Option, + /// Whether the relay joins new community members into the channel, or + /// `None` to leave unchanged. `Some(true)` needs an open, unarchived + /// channel; `apply_channel_metadata_event` refuses it otherwise. + pub auto_join: Option, } impl ChannelUpdate { @@ -801,6 +1088,7 @@ impl ChannelUpdate { && self.labels.is_none() && self.join_role.is_none() && self.unlisted.is_none() + && self.auto_join.is_none() } /// True when the update changes a setting that decides admission: @@ -881,6 +1169,7 @@ pub(crate) struct ChannelSettingsWriter<'tx> { ttl: TtlLock, previous_visibility: String, archived: bool, + listed: bool, } impl ChannelSettingsWriter<'_> { @@ -895,6 +1184,12 @@ impl ChannelSettingsWriter<'_> { self.archived } + /// Whether the channel was listed ([`LISTED_CHANNEL_SQL`]) when the lock + /// was taken. The row lock keeps this current until the transaction ends. + pub(crate) fn listed(&self) -> bool { + self.listed + } + /// The locked transaction, for writes that are not channel settings /// (for example, storing the event that requested the change). pub(crate) fn tx(&mut self) -> &mut crate::AdmittedTx { @@ -932,9 +1227,11 @@ impl ChannelSettingsWriter<'_> { /// 3. the channel row, `FOR NO KEY UPDATE`. /// /// Roster publication holds the membership lock and then, at commit, takes -/// the TTL lock and updates the row. A huddle join takes the membership -/// lock, then the TTL lock, then the row. A writer that took these locks in -/// any other order could wait for one of them while it waits for this one. +/// the TTL lock and updates the row. A huddle join and a `put_members` +/// membership write take the membership lock, then the TTL lock, then the +/// row; the row lock is what orders them against an archive, which does not +/// take the membership lock. A writer that took these locks in any other +/// order could wait for one of them while it waits for this one. /// /// Returns `ChannelNotFound` when the channel is missing or deleted. pub(crate) async fn lock_channel_for_settings_write<'tx>( @@ -981,15 +1278,16 @@ async fn lock_channel_row( // `FOR NO KEY UPDATE`, like a huddle join: it orders this write against // every other settings write and a huddle join, but not against the // `KEY SHARE` lock that a membership INSERT takes for its foreign key. - let (previous_visibility, archived): (String, bool) = sqlx::query_as( - "SELECT visibility::text, archived_at IS NOT NULL FROM channels \ - WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL FOR NO KEY UPDATE", - ) - .bind(community_id.as_uuid()) - .bind(channel_id) - .fetch_optional(tx.conn()) - .await? - .ok_or(DbError::ChannelNotFound(channel_id))?; + let (previous_visibility, archived, listed): (String, bool, bool) = + sqlx::query_as(sqlx::AssertSqlSafe(format!( + "SELECT visibility::text, archived_at IS NOT NULL, {LISTED_CHANNEL_SQL} FROM channels \ + WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL FOR NO KEY UPDATE" + ))) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_optional(tx.conn()) + .await? + .ok_or(DbError::ChannelNotFound(channel_id))?; Ok(ChannelSettingsWriter { tx, channel_id, @@ -997,6 +1295,7 @@ async fn lock_channel_row( ttl, previous_visibility, archived, + listed, }) } @@ -1041,6 +1340,10 @@ async fn update_channel_on( set_parts.push(format!("unlisted = ${param_idx}")); param_idx += 1; } + if updates.auto_join.is_some() { + set_parts.push(format!("auto_join = ${param_idx}")); + param_idx += 1; + } if let Some(ref ttl) = updates.ttl_seconds { // Set ttl_seconds, then reset the deadline from now (or clear both). set_parts.push(format!("ttl_seconds = ${param_idx}")); @@ -1079,6 +1382,9 @@ async fn update_channel_on( if let Some(unlisted) = updates.unlisted { q = q.bind(unlisted); } + if let Some(auto_join) = updates.auto_join { + q = q.bind(auto_join); + } if let Some(ref ttl) = updates.ttl_seconds { q = q.bind(*ttl); } @@ -1088,10 +1394,35 @@ async fn update_channel_on( q = q.bind(community_id.as_uuid()); q = q.bind(channel_id); - let result = q.execute(tx.conn()).await?; + // The current name is what a visibility or unlisted change that + // [`LISTED_NAME_INDEX`] refuses would have listed. + let (policy_changed, current_name) = if updates.visibility.is_some() + || updates.ttl_seconds.is_some() + || updates.unlisted.is_some() + { + sqlx::query_as::<_,(bool, String)>("SELECT (($3::text IS NOT NULL AND visibility::text IS DISTINCT FROM $3) OR ($4 AND ttl_seconds IS DISTINCT FROM $5::int) OR ($6::bool IS NOT NULL AND unlisted IS DISTINCT FROM $6)), name FROM channels WHERE community_id=$1 AND id=$2") + .bind(community_id.as_uuid()).bind(channel_id).bind(updates.visibility.as_deref()) + .bind(updates.ttl_seconds.is_some()).bind(updates.ttl_seconds.flatten()).bind(updates.unlisted) + .fetch_one(tx.conn()).await + .map(|(changed, name)| (changed, Some(name)))? + } else { + (false, None) + }; + let result = q + .execute(tx.conn()) + .await + .map_err(|e| listed_name_taken(e, updates.name.as_deref().or(current_name.as_deref())))?; if result.rows_affected() == 0 { return Err(DbError::ChannelNotFound(channel_id)); } + if policy_changed { + sqlx::query( + "UPDATE communities SET artifact_policy_modified_at=clock_timestamp() WHERE id=$1", + ) + .bind(community_id.as_uuid()) + .execute(tx.conn()) + .await?; + } Ok(()) } @@ -1276,7 +1607,7 @@ async fn set_archived_on(w: &mut ChannelSettingsWriter<'_>, archive: bool) -> Re /// unchanged. #[derive(Default)] pub struct ChannelMetadataEdit { - /// Name, description, visibility, TTL and labels. + /// Name, description, visibility, TTL, labels, `join_role` and `auto_join`. pub columns: ChannelUpdate, /// New topic, recorded as set by the event's author. pub topic: Option, @@ -1284,6 +1615,14 @@ pub struct ChannelMetadataEdit { pub purpose: Option, /// `Some(true)` archives the channel; `Some(false)` restores it. pub archived: Option, + /// Set for a relay operator's name-only rename, whatever the operator's + /// channel role. It may rename an archived listed channel + /// ([`LISTED_CHANNEL_SQL`]), which stays archived. Checked under the row + /// lock. + pub operator_rename: bool, + /// Set when the actor is the channel's owner or admin. An operator rename + /// without it applies only to a listed channel. + pub channel_authority: bool, } /// The result of [`Db::apply_channel_metadata_event`]. @@ -1335,17 +1674,48 @@ pub(crate) async fn apply_channel_metadata_event( previous_visibility, }); } - // Decide the archive state here, after the duplicate check and under - // the row lock, not during validation. A resend that races the first - // commit then sees that commit as a duplicate (above), never as a - // channel already in the requested state. + // Decide the archive state and an operator's right to rename here, + // after the duplicate check and under the row lock, not during + // validation. A resend that races the first commit then sees that commit + // as a duplicate (above), never as a channel already in the requested + // state, and an owner who makes the channel private or unlisted + // meanwhile is seen. + if edit.operator_rename && !edit.channel_authority && !locked.listed() { + return Err(DbError::AccessDenied( + "a relay operator may rename only a listed channel".to_string(), + )); + } match (locked.archived(), edit.archived) { (true, Some(false)) | (false, None | Some(true)) => {} + (true, None) if edit.operator_rename && locked.listed() => {} (true, _) => return Err(DbError::AccessDenied("channel is archived".to_string())), (false, Some(false)) => { return Err(DbError::AccessDenied("channel is not archived".to_string())); } } + // `auto_join` only makes sense where a kind:9021 self-join would work: + // an open, unarchived channel. Decide it here, under the row lock and + // after the archive decision, on the state this event leaves behind, so + // one event may open a channel and flag it, and a concurrent archive + // cannot slip past a check made before the lock. Either value needs the + // event to leave the channel open: the relay role that authorizes + // `auto_join` needs no channel membership, so a `false` on a private + // channel would store and fan out an event, with its mentions and + // notice, in a channel its sender cannot read. One refusal for both + // values also keeps the response from telling them apart. + if let Some(auto_join) = edit.columns.auto_join { + let visibility = edit + .columns + .visibility + .as_deref() + .unwrap_or(locked.previous_visibility()); + let archived = edit.archived.unwrap_or(locked.archived()); + if visibility != ChannelVisibility::Open.as_str() || (auto_join && archived) { + return Err(DbError::AccessDenied( + "auto_join requires an open, unarchived channel".to_string(), + )); + } + } crate::insert_mentions_in_transaction(locked.tx(), event, Some(channel_id)).await?; let ChannelMetadataEdit { @@ -1353,6 +1723,8 @@ pub(crate) async fn apply_channel_metadata_event( topic, purpose, archived, + operator_rename: _, + channel_authority: _, } = edit; let actor = event.pubkey.to_bytes(); if !columns.is_empty() { @@ -1393,6 +1765,31 @@ pub async fn soft_delete_channel( community_id: CommunityId, channel_id: Uuid, ) -> Result { + Ok( + soft_delete_channel_capturing_members(pool, community_id, channel_id) + .await? + .is_some(), + ) +} + +/// A deleted channel's type and the members active when it was deleted. +#[derive(Debug, Clone)] +pub struct DeletedChannel { + /// The channel's type, e.g. `stream`. + pub channel_type: String, + /// The pubkeys of its active members, oldest first. + pub members: Vec>, +} + +/// [`soft_delete_channel`], also returning who was a member at the deletion's +/// serialization point: read under the same membership lock, so a join either +/// commits first and is included, or waits and is then refused. `None` when the +/// channel was already deleted or never existed. +pub async fn soft_delete_channel_capturing_members( + pool: &PgPool, + community_id: CommunityId, + channel_id: Uuid, +) -> Result> { let mut tx = crate::begin_community_write_transaction( pool, community_id, @@ -1401,12 +1798,31 @@ pub async fn soft_delete_channel( .await?; let mut writer = match lock_channel_for_delete(&mut tx, channel_id).await { Ok(writer) => writer, - Err(DbError::ChannelNotFound(_)) => return Ok(false), + Err(DbError::ChannelNotFound(_)) => return Ok(None), Err(error) => return Err(error), }; + let channel_type: String = sqlx::query_scalar( + "SELECT channel_type::text FROM channels WHERE community_id = $1 AND id = $2", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_one(writer.tx.conn()) + .await?; + let members: Vec> = sqlx::query_scalar( + "SELECT pubkey FROM channel_members \ + WHERE community_id = $1 AND channel_id = $2 AND removed_at IS NULL \ + ORDER BY joined_at ASC", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_all(writer.tx.conn()) + .await?; soft_delete_on(&mut writer).await?; tx.commit().await?; - Ok(true) + Ok(Some(DeletedChannel { + channel_type, + members, + })) } async fn soft_delete_on(w: &mut ChannelSettingsWriter<'_>) -> Result<()> { @@ -1422,6 +1838,10 @@ async fn soft_delete_on(w: &mut ChannelSettingsWriter<'_>) -> Result<()> { .bind(channel_id) .execute(w.tx.conn()) .await?; + sqlx::query("UPDATE communities SET artifact_policy_modified_at=clock_timestamp() WHERE id=$1") + .bind(community_id.as_uuid()) + .execute(w.tx.conn()) + .await?; Ok(()) } @@ -1665,6 +2085,19 @@ impl Db { .await } + /// Read a channel's kind:39000 or kind:39001 inputs behind that event's + /// replacement lock. See [`LockedGroupStateSnapshot`]. + #[datastore_span(name = "lock_group_state_snapshot", system = "postgresql")] + pub async fn lock_group_state_snapshot( + &self, + community_id: CommunityId, + channel_id: Uuid, + kind: i32, + relay_pubkey: &[u8], + ) -> Result { + lock_group_state_snapshot(&self.pool, community_id, channel_id, kind, relay_pubkey).await + } + /// Returns the canvas content for a channel, if any. #[datastore_span(name = "get_canvas", system = "postgresql")] pub async fn get_canvas( @@ -1696,6 +2129,28 @@ impl Db { list_channels(&self.pool, community_id, visibility).await } + /// Lists the channels the relay joins new community members into: + /// `auto_join` set, open, unarchived and not deleted; oldest first. + #[datastore_span(name = "list_auto_join_channels", system = "postgresql")] + pub async fn list_auto_join_channels( + &self, + community_id: CommunityId, + ) -> Result> { + list_auto_join_channels(&self.pool, community_id).await + } + + /// Lists the effective `auto_join` channels `pubkey` has never been a + /// member of, active or removed (see + /// [`list_never_joined_auto_join_channels`]). + #[datastore_span(name = "list_never_joined_auto_join_channels", system = "postgresql")] + pub async fn list_never_joined_auto_join_channels( + &self, + community_id: CommunityId, + pubkey: &[u8], + ) -> Result> { + list_never_joined_auto_join_channels(&self.pool, community_id, pubkey).await + } + /// Lists channels during startup reconciliation. #[datastore_span(name = "list_channels_for_bootstrap", system = "postgresql")] pub async fn list_channels_for_bootstrap( @@ -1773,6 +2228,16 @@ impl Db { soft_delete_channel(&self.pool, community_id, channel_id).await } + /// See [`soft_delete_channel_capturing_members`]. + #[datastore_span(name = "soft_delete_channel_capturing_members", system = "postgresql")] + pub async fn soft_delete_channel_capturing_members( + &self, + community_id: CommunityId, + channel_id: Uuid, + ) -> Result> { + soft_delete_channel_capturing_members(&self.pool, community_id, channel_id).await + } + /// Archive ephemeral channels whose TTL deadline has passed. #[datastore_span(name = "reap_expired_ephemeral_channels", system = "postgresql")] pub async fn reap_expired_ephemeral_channels(&self) -> Result> { @@ -1820,6 +2285,7 @@ mod group_metadata_tag_tests { labels: Vec::new(), join_role: join_role.into(), unlisted: false, + auto_join: false, } } @@ -1863,6 +2329,26 @@ mod group_metadata_tag_tests { assert!(tags.contains(&vec!["join_role".to_string(), "guest".to_string()])); } + /// The bare `auto_join` tag is effective-state: published only while the + /// column is set and the channel is open and unarchived. + #[test] + fn publishes_auto_join_only_while_effective() { + let has_tag = |channel: &ChannelRecord| { + group_metadata_tags(channel, &[]).contains(&vec!["auto_join".to_string()]) + }; + let mut flagged = channel("open", "member"); + assert!(!has_tag(&flagged), "unset"); + flagged.auto_join = true; + assert!(has_tag(&flagged), "open, unarchived"); + let mut archived = channel("open", "member"); + archived.auto_join = true; + archived.archived_at = Some(Utc::now()); + assert!(!has_tag(&archived), "archived"); + let mut private = channel("private", "member"); + private.auto_join = true; + assert!(!has_tag(&private), "private"); + } + /// The type `t` tag comes first among `t` tags, then the creator `P`, /// as on 39001 and 39002; kind:39000 also carries the creation time. #[test] @@ -2376,6 +2862,86 @@ mod postgres_tests { assert!(matches!(outcome, ChannelCreate::Created(_)), "{outcome:?}"); } + /// Holds an open create of the listed channel `race` on its own + /// transaction while a second create claims the same name beside it. + async fn second_listed_create_beside_open_create(commit_first: bool) -> Result { + let pool = setup_pool().await; + let community = CommunityId::from_uuid(make_test_community(&pool).await); + let creator = Keys::generate(); + let creator_bytes = creator.public_key().to_bytes().to_vec(); + let listed = |name: &'static str| NewChannel { + name, + visibility: ChannelVisibility::Open, + ..new_channel(&creator_bytes, &[]) + }; + + let mut first = crate::begin_community_write_transaction( + &pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .expect("begin first create"); + assert!( + insert_channel_rows(&mut first, Uuid::new_v4(), listed("race")) + .await + .expect("first create's rows") + ); + + let second_id = Uuid::new_v4(); + let second = tokio::spawn({ + let (creator, creator_bytes) = (creator.clone(), creator_bytes.clone()); + async move { + let pool = crate::test_support::named_pool("listed-name-race").await; + create_channel_with_event( + &pool, + None, + community, + second_id, + NewChannel { + name: "RACE", + visibility: ChannelVisibility::Open, + ..new_channel(&creator_bytes, &[]) + }, + &create_event(&creator, second_id), + ) + .await + } + }); + crate::test_support::wait_for_lock_wait(&pool, "listed-name-race").await; + assert!( + !second.is_finished(), + "the second create waits for the open create's name" + ); + + if commit_first { + first.commit().await.expect("commit first create"); + } else { + drop(first); + } + second.await.expect("second create task") + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn a_listed_create_beside_an_open_create_of_its_name_is_refused_once_committed() { + let outcome = second_listed_create_beside_open_create(true).await; + assert!( + matches!(&outcome, Err(DbError::ChannelNameTaken(name)) if name == "RACE"), + "{outcome:?}" + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn a_listed_create_beside_a_failed_create_of_its_name_succeeds() { + let outcome = second_listed_create_beside_open_create(false).await; + assert!( + matches!(outcome, Ok(ChannelCreate::Created(_))), + "{outcome:?}" + ); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn a_create_whose_event_fails_leaves_no_channel() { @@ -2459,6 +3025,84 @@ mod postgres_tests { assert_eq!(members.len(), 1, "only the first creator is a member"); } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn soft_delete_captures_members_at_its_serialization_point() { + let pool = setup_pool().await; + let community_id = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_id); + let owner = random_pubkey(); + let early = random_pubkey(); + let late = random_pubkey(); + let channel = create_test_channel( + &pool, + community_id, + "delete-captures-members", + ChannelType::Stream, + ChannelVisibility::Open, + None, + &owner, + None, + ) + .await + .expect("create channel"); + let channel_id = channel.id; + + // Queue a join, then the delete, behind a held membership lock: the + // join is serialized before the delete, so the delete must see it. + let snapshot = + crate::channel_members::lock_member_snapshot(&pool, community, channel_id, &[9u8; 32]) + .await + .expect("hold membership lock"); + let join_pool = crate::test_support::named_pool("join-before-delete").await; + let early_key = early.clone(); + let join = tokio::spawn(async move { + crate::channel_members::add_member( + &join_pool, + community, + channel_id, + &early_key, + MemberRole::Member, + None, + ) + .await + }); + crate::test_support::wait_for_lock_wait(&pool, "join-before-delete").await; + let delete_pool = crate::test_support::named_pool("delete-after-join").await; + let delete = tokio::spawn(async move { + soft_delete_channel_capturing_members(&delete_pool, community, channel_id).await + }); + crate::test_support::wait_for_lock_wait(&pool, "delete-after-join").await; + snapshot.release().await.expect("release membership lock"); + + join.await.expect("join task").expect("join before delete"); + let deleted = delete + .await + .expect("delete task") + .expect("delete") + .expect("channel was live"); + assert_eq!(deleted.channel_type, "stream"); + assert_eq!(deleted.members, vec![owner, early]); + + // A join after the delete is refused, so nobody is left un-notified. + assert!(crate::channel_members::add_member( + &pool, + community, + channel_id, + &late, + MemberRole::Member, + None, + ) + .await + .is_err()); + assert!( + soft_delete_channel_capturing_members(&pool, community, channel_id) + .await + .expect("second delete") + .is_none() + ); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn soft_delete_waits_for_membership_lock() { @@ -2506,4 +3150,270 @@ mod postgres_tests { "a second delete finds no live channel" ); } + + /// A group-state snapshot reads behind its coordinate's replacement lock. + /// One taken while another is held waits for it, then sees a channel + /// change committed while it waited and the held snapshot's stored + /// `created_at`. Mutation: read the channel or the live timestamp before + /// taking the lock → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn group_state_snapshot_reads_behind_the_replacement_lock() { + let pool = setup_pool().await; + let community_id = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_id); + let channel = create_test_channel( + &pool, + community_id, + "group-state-snapshot", + ChannelType::Stream, + ChannelVisibility::Open, + None, + &random_pubkey(), + None, + ) + .await + .expect("create channel"); + let relay = Keys::generate(); + let relay_pubkey = relay.public_key().to_bytes(); + + let held = lock_group_state_snapshot(&pool, community, channel.id, 39000, &relay_pubkey) + .await + .expect("hold snapshot"); + assert_eq!(held.latest_created_at, None); + let waiter_pool = crate::test_support::named_pool("group-state-snapshot").await; + let channel_id = channel.id; + let waiter = tokio::spawn(async move { + lock_group_state_snapshot(&waiter_pool, community, channel_id, 39000, &relay_pubkey) + .await + }); + crate::test_support::wait_for_lock_wait(&pool, "group-state-snapshot").await; + sqlx::query("UPDATE channels SET topic = 'changed while waiting' WHERE id = $1") + .bind(channel.id) + .execute(&pool) + .await + .expect("change the channel"); + + let held_at = 1_800_000_000; + let event = nostr::EventBuilder::new(nostr::Kind::Custom(39000), "") + .tags( + group_metadata_tags(&held.channel, &held.members) + .into_iter() + .map(|tag| nostr::Tag::parse(tag).expect("tag")), + ) + .custom_created_at(nostr::Timestamp::from(held_at)) + .sign_with_keys(&relay) + .expect("sign 39000"); + assert!(held.replace(&event).await.expect("store held snapshot").1); + + let next = waiter.await.expect("waiter task").expect("next snapshot"); + assert_eq!(next.channel.topic.as_deref(), Some("changed while waiting")); + assert_eq!(next.latest_created_at, Some(held_at)); + } + + /// A snapshot reads only the members its kind's tags use, and the tags + /// built from it are the ones the full roster would give: none of the + /// roster for a stream's kind:39000, owners and admins in roster order + /// for kind:39001, the whole roster for a DM's kind:39000. Any other + /// kind is refused. Mutation: read the roster for a stream's kind:39000, + /// or drop the role filter for kind:39001 → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn group_state_snapshot_reads_the_members_its_kind_publishes() { + let pool = setup_pool().await; + let community_id = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_id); + let relay_pubkey = Keys::generate().public_key().to_bytes(); + let roster = async |channel_id: Uuid| { + let mut conn = pool.acquire().await.expect("acquire"); + crate::channel_members::select_active_members(&mut conn, community, channel_id) + .await + .expect("roster") + }; + let who = |members: &[MemberRecord]| { + members + .iter() + .map(|m| (m.pubkey.clone(), m.role.clone())) + .collect::>() + }; + // `create_test_channel` seats the creator as owner; the rest join + // directly, past the join-role policy `add_member` applies. + let seat = async |channel_id: Uuid, role: &str| { + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey, role) \ + VALUES ($1, $2, $3, $4::member_role)", + ) + .bind(community_id) + .bind(channel_id) + .bind(random_pubkey()) + .bind(role) + .execute(&pool) + .await + .expect("seat member"); + }; + + let owner = random_pubkey(); + let stream = create_test_channel( + &pool, + community_id, + "group-state-members", + ChannelType::Stream, + ChannelVisibility::Open, + None, + &owner, + None, + ) + .await + .expect("create stream"); + for role in ["member", "admin", "guest"] { + seat(stream.id, role).await; + } + let all = roster(stream.id).await; + assert_eq!(all.len(), 4); + + let metadata = lock_group_state_snapshot(&pool, community, stream.id, 39000, &relay_pubkey) + .await + .expect("stream 39000 snapshot"); + assert!(metadata.members.is_empty(), "{:?}", who(&metadata.members)); + assert_eq!( + group_metadata_tags(&metadata.channel, &metadata.members), + group_metadata_tags(&metadata.channel, &all) + ); + drop(metadata); + + let admins = lock_group_state_snapshot(&pool, community, stream.id, 39001, &relay_pubkey) + .await + .expect("stream 39001 snapshot"); + let expected: Vec<_> = all + .iter() + .filter(|m| m.role == "owner" || m.role == "admin") + .cloned() + .collect(); + assert_eq!(expected.len(), 2); + assert_eq!(who(&admins.members), who(&expected)); + drop(admins); + + let dm = create_test_channel( + &pool, + community_id, + "group-state-members-dm", + ChannelType::Dm, + ChannelVisibility::Private, + None, + &owner, + None, + ) + .await + .expect("create dm"); + seat(dm.id, "member").await; + let dm_all = roster(dm.id).await; + assert_eq!(dm_all.len(), 2); + let dm_metadata = lock_group_state_snapshot(&pool, community, dm.id, 39000, &relay_pubkey) + .await + .expect("dm 39000 snapshot"); + assert_eq!(who(&dm_metadata.members), who(&dm_all)); + let tags = group_metadata_tags(&dm_metadata.channel, &dm_metadata.members); + assert_eq!(tags, group_metadata_tags(&dm_metadata.channel, &dm_all)); + assert_eq!(tags.iter().filter(|t| t[0] == "p").count(), 2); + drop(dm_metadata); + + let refused = lock_group_state_snapshot(&pool, community, dm.id, 39002, &relay_pubkey) + .await + .err() + .expect("kind:39002 is not a group-state snapshot"); + assert!(matches!(refused, DbError::InvalidData(_)), "{refused:?}"); + } + + /// A group-state write takes its replacement lock once: the snapshot + /// takes it and the replacement runs under it, so the lock metrics see + /// one acquisition per write, as they do for + /// `Db::replace_addressable_event`, each labelled with the written kind. + /// Mutation: take the lock again in `replace_addressable_event_under_lock`, + /// or drop the kind from `take_replacement_lock` → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn group_state_replacement_takes_its_lock_once() { + use metrics_util::debugging::{DebugValue, DebuggingRecorder}; + + let pool = setup_pool().await; + let community_id = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_id); + let channel = create_test_channel( + &pool, + community_id, + "group-state-lock-once", + ChannelType::Stream, + ChannelVisibility::Open, + None, + &random_pubkey(), + None, + ) + .await + .expect("create channel"); + let relay = Keys::generate(); + let relay_pubkey = relay.public_key().to_bytes(); + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + // A debugging snapshot drains what it reads, so each call returns the + // acquisitions since the previous one. + let replacement_acquisitions_since_last = |kind: &str| { + snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, _, _, _)| { + key.key().name() == "buzz_db_advisory_lock_acquisitions_total" + && key.key().labels().any(|label| { + label.key() == "lock_type" + && label.value() + == crate::observability::LockType::Replacement.as_str() + }) + && key + .key() + .labels() + .any(|label| label.key() == "kind" && label.value() == kind) + }) + .map(|(_, _, _, value)| match value { + DebugValue::Counter(count) => count, + other => panic!("acquisitions are a counter, got {other:?}"), + }) + .sum::() + }; + + let snapshot = + lock_group_state_snapshot(&pool, community, channel.id, 39000, &relay_pubkey) + .await + .expect("snapshot"); + let event = nostr::EventBuilder::new(nostr::Kind::Custom(39000), "") + .tags( + group_metadata_tags(&snapshot.channel, &snapshot.members) + .into_iter() + .map(|tag| nostr::Tag::parse(tag).expect("tag")), + ) + .sign_with_keys(&relay) + .expect("sign 39000"); + assert!(snapshot.replace(&event).await.expect("store").1); + assert_eq!( + replacement_acquisitions_since_last("39000"), + 1, + "one lock per group-state write" + ); + + let profile = nostr::EventBuilder::new(nostr::Kind::Custom(0), "{}") + .sign_with_keys(&relay) + .expect("sign kind:0"); + assert!( + Db::from_pool(pool.clone()) + .replace_addressable_event(community, &profile, None) + .await + .expect("store kind:0") + .1 + ); + assert_eq!( + replacement_acquisitions_since_last("0"), + 1, + "one lock per addressable replace" + ); + } } diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 0922be59487..0d0286c7841 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -9,12 +9,15 @@ use uuid::Uuid; use crate::channel::{row_to_channel_record, ChannelRecord}; use crate::error::{DbError, Result}; -use crate::{AdmittedTx, Db}; +use crate::{AdmittedTx, Db, ReadAt}; use buzz_core::CommunityId; use buzz_datastore_tracing::datastore_span; pub use buzz_core::channel::MemberRole; +/// `(pubkey, channel_id)` membership rows. +pub type PubkeyChannels = Vec<(Vec, Uuid)>; + /// A channel membership row as returned from the database. #[derive(Debug, Clone)] pub struct MemberRecord { @@ -41,20 +44,22 @@ pub struct MemberRecord { /// concurrent demotions (or a demotion racing a removal) to each observe two /// owners, each pass, and together leave zero — the exact governance loss the /// guards exist to prevent. An advisory key rather than `SELECT ... FOR UPDATE` -/// on the channel row: membership is its own contention domain and must not -/// serialize against unrelated channel metadata writers (`update_channel`, -/// `set_topic`, the TTL transition). Distinct key domain from +/// on the channel row, so a removal, which takes only this key, does not +/// serialize against the row's writers that leave admission alone +/// (`set_topic`, `set_canvas`, the TTL transition). Admissions also lock the +/// row, after this key (see [`lock_channel_for_member_put`]), because the row +/// is what orders an archive against them. Distinct key domain from /// `buzz_channel_ttl:`. const CHANNEL_MEMBERSHIP_LOCK_NAMESPACE: &str = "buzz_channel_membership:"; /// Verify that migration 0032's roster fence is active on the partitioned /// `events` parent and every attached partition. /// -/// New roster publishers depend on this database-side guard to serialize with -/// legacy publishers during a rolling deployment. If the migration has not -/// been applied, publishing with the new lock protocol would falsely appear -/// safe while an old pod could still overwrite it with stale membership. -pub async fn verify_channel_roster_fence_catalog<'e>( +/// Only tests use this. The relay no longer requires the trigger at startup or +/// after migrating: [`validate_channel_roster_snapshot`] enforces the same rule +/// in every roster writer, so the trigger can be dropped. +#[cfg(test)] +pub(crate) async fn verify_channel_roster_fence_catalog<'e>( executor: impl sqlx::PgExecutor<'e>, ) -> Result<()> { // tgtype bits: 1 = ROW, 2 = BEFORE, 4 = INSERT, 16 = UPDATE, 64 = INSTEAD. @@ -94,87 +99,6 @@ pub async fn verify_channel_roster_fence_catalog<'e>( Ok(()) } -/// Prove migration 0032's roster fence semantics through the live writer pool. -/// -/// The catalog check cannot detect a no-op or otherwise corrupted trigger -/// function. This rolled-back probe verifies that a canonical empty roster is -/// accepted while a stale roster member is rejected with `check_violation`. -pub async fn verify_channel_roster_fence_behavior(pool: &sqlx::PgPool) -> Result<()> { - let connection = crate::observability::acquire_writer( - pool, - crate::observability::WriterOperation::Bootstrap, - ) - .await?; - let mut tx = sqlx::Transaction::begin(connection, None).await?; - let community_id = Uuid::new_v4(); - let channel_id = Uuid::new_v4(); - sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") - .bind(community_id) - .bind(format!( - "roster-fence-verify-{}.invalid", - community_id.simple() - )) - .execute(&mut *tx) - .await?; - - let insert = |id: Vec, tags: serde_json::Value| { - sqlx::query( - "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) \ - VALUES ($1, $2, $3, NOW(), 39002, $4, '', $5, NOW(), $6, $7)", - ) - .bind(community_id) - .bind(id) - .bind(vec![0u8; 32]) - .bind(tags) - .bind(vec![0u8; 64]) - .bind(channel_id) - .bind(channel_id.to_string()) - }; - - insert( - vec![0u8; 32], - serde_json::json!([["d", channel_id.to_string()]]), - ) - .execute(&mut *tx) - .await - .map_err(|error| { - DbError::InvalidData(format!( - "channel roster fence rejected a canonical probe roster: {error}" - )) - })?; - - sqlx::query("SAVEPOINT roster_fence_probe") - .execute(&mut *tx) - .await?; - let stale = insert( - vec![1u8; 32], - serde_json::json!([ - ["d", channel_id.to_string()], - ["p", hex::encode([2u8; 32]), "", "member"] - ]), - ) - .execute(&mut *tx) - .await; - match stale { - Err(sqlx::Error::Database(error)) if error.code().as_deref() == Some("23514") => {} - Ok(_) => { - return Err(DbError::InvalidData( - "channel roster fence is inert: a stale probe roster was accepted".into(), - )); - } - Err(error) => { - return Err(DbError::InvalidData(format!( - "channel roster fence probe failed unexpectedly: {error}" - ))); - } - } - sqlx::query("ROLLBACK TO SAVEPOINT roster_fence_probe") - .execute(&mut *tx) - .await?; - tx.rollback().await?; - Ok(()) -} - /// Take the per-channel membership lock. MUST be the first statement in the /// transaction that then reads roles/owner counts and writes membership, so the /// whole check-then-write sequence is atomic against a concurrent one. @@ -337,6 +261,7 @@ impl ChannelMembershipLocks<'_> { INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) VALUES ($1, $2, $3, 'member'::member_role, $4) ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET + sync_modified_at = CASE WHEN channel_members.removed_at IS NOT NULL THEN clock_timestamp() ELSE channel_members.sync_modified_at END, removed_at = NULL, removed_by = NULL, role = EXCLUDED.role @@ -578,7 +503,15 @@ impl LockedMemberSnapshot { } let tags = serde_json::to_value(&event.tags)?; validate_channel_roster_snapshot(&mut self.tx, channel_id, &tags).await?; - sqlx::query("UPDATE events SET deleted_at = NOW() WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND channel_id = $4 AND deleted_at IS NULL") + crate::replica_fence::guard_event_created_at_floor( + &mut self.tx, + created_at, + Some(channel_id), + ) + .await?; + sqlx::query(superseded_with_mentions_sql!( + "UPDATE events SET deleted_at = NOW() WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND channel_id = $4 AND deleted_at IS NULL" + )) .bind(community_id.as_uuid()).bind(kind).bind(pubkey.as_slice()).bind(channel_id) .execute(self.tx.conn()).await?; let received_at = Utc::now(); @@ -596,6 +529,7 @@ impl LockedMemberSnapshot { crate::store::event_follow_up::after_admitted_insert( &mut self.tx, event.id.as_bytes().as_slice(), + created_at, kind, Some(channel_id), ) @@ -641,37 +575,23 @@ pub async fn lock_member_snapshot( // this key before INSERT; migration 0032 then takes the membership key in // the INSERT trigger. Taking both in that order avoids mixed-version // duplicate heads without introducing a lock-order inversion. + let members_kind = buzz_core::kind::KIND_NIP29_GROUP_MEMBERS as i32; let replacement_lock = crate::replaceable::event_replacement_lock_key( community_id, - 39002, + members_kind, relay_pubkey, Some(channel_id.as_bytes()), ); - crate::observability::observe_advisory_lock( + crate::observability::observe_event_lock( crate::observability::LockType::Replacement, + members_kind, sqlx::query("SELECT pg_advisory_xact_lock($1)") .bind(replacement_lock) .execute(tx.conn()), ) .await?; acquire_channel_membership_lock(tx.conn(), community_id, channel_id).await?; - let rows = sqlx::query( - r#" - SELECT cm.channel_id, cm.pubkey, cm.role::text AS role, cm.joined_at, cm.invited_by, cm.removed_at - FROM channel_members cm - JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL - WHERE cm.community_id = $1 AND cm.channel_id = $2 AND cm.removed_at IS NULL - ORDER BY cm.joined_at ASC - "#, - ) - .bind(community_id.as_uuid()) - .bind(channel_id) - .fetch_all(tx.conn()) - .await?; - let members = rows - .into_iter() - .map(row_to_member_record) - .collect::>>()?; + let members = select_active_members(tx.conn(), community_id, channel_id).await?; let identity = sqlx::query_as::<_, (String, Vec, Vec)>( "SELECT channel_type::text, labels, created_by FROM channels WHERE community_id = $1 AND id = $2", ) @@ -732,6 +652,11 @@ pub async fn add_member( /// neither a membership write nor a setting change can slip between the /// decision and the write. /// +/// An archived channel admits nobody new: a target who is not an active +/// member is refused with `AccessDenied` while `archived_at` is set. The +/// archive state is read under the channel row lock, which every archive +/// write needs too (see [`lock_channel_for_member_put`]). +/// /// There is no creator exception: channel creation installs the creator as /// owner in the same transaction, so a creator without an active row was /// removed and is admitted like anyone else. @@ -791,26 +716,226 @@ pub async fn put_members( targets: &[MemberPut<'_>], invited_by: Option<&[u8]>, ) -> Result>> { - let mut seen = std::collections::HashSet::with_capacity(targets.len()); - if let Some(dup) = targets.iter().find(|t| !seen.insert(t.pubkey)) { - return Err(DbError::InvalidData(format!( - "pubkey {} appears more than once", - hex::encode(dup.pubkey) - ))); - } + check_distinct_targets(targets)?; + let mut tx = crate::begin_community_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + + // First statements: serialize the whole decision / owner-count / upsert + // sequence against concurrent membership writes and archives of this + // channel. + lock_channel_for_member_put(&mut tx, channel_id).await?; + let results = put_members_on(&mut tx, channel_id, targets, invited_by).await?; + tx.commit().await?; + Ok(results) +} + +/// Self-join `pubkey` to `channel_id` as [`put_member`] with no actor and no +/// requested role (so the channel's `join_role` applies), but only if +/// `pubkey` has never had a membership row in the channel, active or removed. +/// Returns `None`, writing nothing, when such a row exists. +/// +/// The row is checked under the [`put_member`] locks, so a leave, a join or +/// another first join of the same person commits wholly before or after this +/// write: two sign-ins racing each other write once, and a leave that commits +/// first keeps the person out. A refusal (an archived or private channel) is +/// the [`put_member`] error. +pub async fn put_first_member( + pool: &PgPool, + community_id: CommunityId, + channel_id: Uuid, + pubkey: &[u8], +) -> Result> { + put_first_member_with_pending(pool, community_id, channel_id, pubkey, None).await +} +async fn put_first_member_with_pending( + pool: &PgPool, + community_id: CommunityId, + channel_id: Uuid, + pubkey: &[u8], + pending: Option, +) -> Result> { let mut tx = crate::begin_community_write_transaction( pool, community_id, crate::observability::WriterOperation::EventWrite, ) .await?; + let admitted_at = if let Some(pending) = pending { + // Fence removal/re-admission and completion against an older worker. + // Keep this lock through the channel write, on the same connection. + let current = sqlx::query_scalar::<_, DateTime>( + "SELECT created_at FROM relay_members \ + WHERE community_id = $1 AND pubkey = $2 AND auto_join_pending = $3 FOR SHARE", + ) + .bind(community_id.as_uuid()) + .bind(hex::encode(pubkey)) + .bind(pending) + .fetch_optional(tx.conn()) + .await?; + let Some(created_at) = current else { + tx.rollback().await?; + return Ok(None); + }; + Some(created_at) + } else { + None + }; + lock_channel_for_member_put(&mut tx, channel_id).await?; + let history: Option<(Option>,)> = sqlx::query_as( + "SELECT removed_at FROM channel_members \ + WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .bind(pubkey) + .fetch_optional(tx.conn()) + .await?; + if let Some((removed_at,)) = history { + // Ordinary first joins preserve all history. Recovery preserves a + // leave from this admission, but fresh roster admissions retain the + // original behavior of restoring earlier removed memberships. + if admitted_at.is_none() || removed_at.is_none() || removed_at >= admitted_at { + tx.rollback().await?; + return Ok(None); + } + } + let target = MemberPut { + pubkey, + requested: None, + }; + let put = put_members_on(&mut tx, channel_id, &[target], None) + .await? + .pop() + .ok_or_else(|| DbError::InvalidData("membership put returned no result".to_string()))?; + match put { + Ok(put) => { + tx.commit().await?; + Ok(Some(put.member)) + } + Err(refused) => { + tx.rollback().await?; + if pending.is_some() && matches!(refused, DbError::AccessDenied(_)) { + Ok(None) + } else { + Err(refused) + } + } + } +} + +/// The result of [`Db::put_members_with_event`]. +pub enum MemberPutEventWrite { + /// The event was stored and at least one person was written. One result + /// per target, in order, as from [`put_members`]. + Applied { + /// The stored kind:9000 event. + stored: buzz_core::StoredEvent, + /// One result per target. + results: Vec>, + }, + /// The event was already stored. Nothing changed: its membership changes + /// committed with it the first time. + Duplicate(buzz_core::StoredEvent), + /// Every person was refused, so nothing was stored. One error per target. + Refused(Vec), +} + +/// Store a kind:9000 `event` and apply its [`put_members`] writes in one +/// transaction. If any write fails, nothing is stored, so the client can +/// resend the same event and have it applied. +/// +/// The locks of [`put_members`] come first, so a second copy of the event +/// waits for the first and then finds it stored. +pub(crate) async fn put_members_with_event( + pool: &PgPool, + push_enqueue: Option, + community_id: CommunityId, + channel_id: Uuid, + event: &nostr::Event, + targets: &[MemberPut<'_>], + thread_meta: Option>, +) -> Result { + check_distinct_targets(targets)?; + let mut tx = crate::begin_community_event_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + tx.set_push_enqueue(push_enqueue); + lock_channel_for_member_put(&mut tx, channel_id).await?; + + // The same writes as `Db::insert_event_with_thread_metadata`. + let (stored, inserted) = crate::event::insert_event_with_thread_metadata_tx( + &mut tx, + event, + Some(channel_id), + thread_meta, + ) + .await?; + if !inserted { + tx.rollback().await?; + return Ok(MemberPutEventWrite::Duplicate(stored)); + } + crate::insert_mentions_in_transaction(&mut tx, event, Some(channel_id)).await?; + + let actor = event.pubkey.to_bytes(); + let results = put_members_on(&mut tx, channel_id, targets, Some(&actor)).await?; + if results.iter().all(Result::is_err) { + tx.rollback().await?; + return Ok(MemberPutEventWrite::Refused( + results.into_iter().filter_map(Result::err).collect(), + )); + } + tx.commit().await?; + Ok(MemberPutEventWrite::Applied { stored, results }) +} - // First statement: serialize the whole decision / owner-count / upsert - // sequence against concurrent membership writes on this channel. +/// Take the locks of a [`put_members`] write on `tx`, in the channel lock +/// order (see `channel::lock_channel_for_settings_write`): the membership +/// lock, the shared TTL lock, then the channel row `FOR NO KEY UPDATE`. +/// +/// The row lock is what orders the write against an archive. Every archive +/// and unarchive updates that row (`archive_channel`, a kind:9002 `archived` +/// tag, the TTL reaper's single UPDATE), and none of them takes the +/// membership lock. So an archive either commits before [`put_members_on`] +/// reads `archived_at`, or waits until this write commits. +async fn lock_channel_for_member_put(tx: &mut AdmittedTx, channel_id: Uuid) -> Result<()> { + let community_id = tx.community(); acquire_channel_membership_lock(tx.conn(), community_id, channel_id).await?; + lock_channel_ttl_shared_in_transaction(tx, channel_id).await?; + lock_channel_archived_at_in_transaction(tx, channel_id).await?; + Ok(()) +} +fn check_distinct_targets(targets: &[MemberPut<'_>]) -> Result<()> { + let mut seen = std::collections::HashSet::with_capacity(targets.len()); + match targets.iter().find(|t| !seen.insert(t.pubkey)) { + Some(dup) => Err(DbError::InvalidData(format!( + "pubkey {} appears more than once", + hex::encode(dup.pubkey) + ))), + None => Ok(()), + } +} + +/// The decisions and upsert of [`put_members`], on a transaction that holds +/// `channel_id`'s [`lock_channel_for_member_put`] locks. The caller owns the +/// commit. +async fn put_members_on( + tx: &mut AdmittedTx, + channel_id: Uuid, + targets: &[MemberPut<'_>], + invited_by: Option<&[u8]>, +) -> Result>> { + let community_id = tx.community(); let channel = get_channel_tx(tx.conn(), community_id, channel_id).await?; + let archived = channel.archived_at.is_some(); let private = channel.visibility == "private"; let join_role = buzz_core::channel::ChannelJoinRole::parse_fail_closed(&channel.join_role); @@ -848,6 +973,12 @@ pub async fn put_members( } let actor = invited_by.unwrap_or(target.pubkey); let current_role = roles.get(target.pubkey).cloned(); + if archived && current_role.is_none() { + decided.push(Err(DbError::AccessDenied( + "channel is archived".to_string(), + ))); + continue; + } let actor_role: Option = roles .get(actor) .map(|r| { @@ -927,6 +1058,7 @@ pub async fn put_members( SELECT $1, $2, t.pubkey, t.role::member_role, $5 FROM UNNEST($3::bytea[], $4::text[]) AS t(pubkey, role) ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET + sync_modified_at = CASE WHEN channel_members.removed_at IS NOT NULL THEN clock_timestamp() ELSE channel_members.sync_modified_at END, removed_at = NULL, removed_by = NULL, role = EXCLUDED.role @@ -945,7 +1077,6 @@ pub async fn put_members( written.insert(member.pubkey.clone(), member); } } - tx.commit().await?; Ok(targets .iter() @@ -1061,7 +1192,7 @@ pub async fn remove_member( let result = sqlx::query( r#" UPDATE channel_members - SET removed_at = NOW(), removed_by = $1 + SET removed_at = clock_timestamp(), sync_modified_at = clock_timestamp(), removed_by = $1 WHERE community_id = $2 AND channel_id = $3 AND pubkey = $4 AND removed_at IS NULL "#, ) @@ -1106,6 +1237,79 @@ pub async fn is_member( Ok(cnt > 0) } +/// Up to `limit` channel IDs for which [`is_member`] is true, with the read's connection +/// checkout time. Unlike discovery's [`get_member_channel_ids`], this includes +/// every channel type and does not grant open-channel access to non-members. +/// A result of `limit` rows may be incomplete; callers must not cache it as a full set. +pub async fn get_active_membership_ids_read_at( + pool: &PgPool, + community_id: CommunityId, + pubkey: &[u8], + limit: u32, +) -> Result>> { + let mut connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let read_at = std::time::Instant::now(); + let value = sqlx::query_scalar( + "SELECT cm.channel_id FROM channel_members cm \ + JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL \ + WHERE cm.community_id = $1 AND cm.pubkey = $2 AND cm.removed_at IS NULL LIMIT $3", + ) + .bind(community_id.as_uuid()) + .bind(pubkey) + .bind(i64::from(limit)) + .fetch_all(&mut *connection) + .await?; + Ok(ReadAt { value, read_at }) +} + +/// [`get_active_membership_ids_read_at`] for many pubkeys in one statement: +/// `(pubkey, channel_id)` rows, up to `limit` per pubkey. A pubkey with +/// `limit` rows may be incomplete; callers must not cache it as a full set. +pub async fn get_active_membership_ids_bulk_read_at( + pool: &PgPool, + community_id: CommunityId, + pubkeys: &[Vec], + limit: u32, +) -> Result> { + if pubkeys.is_empty() { + return Ok(ReadAt { + value: Vec::new(), + read_at: std::time::Instant::now(), + }); + } + let mut connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let read_at = std::time::Instant::now(); + // One bounded read per pubkey, as in the single-user query: each user's + // scan stops at `limit` rows. + let rows = sqlx::query( + "SELECT u.pubkey, m.channel_id FROM unnest($2::bytea[]) AS u(pubkey) \ + CROSS JOIN LATERAL ( \ + SELECT cm.channel_id FROM channel_members cm \ + JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL \ + WHERE cm.community_id = $1 AND cm.pubkey = u.pubkey AND cm.removed_at IS NULL \ + LIMIT $3 \ + ) m", + ) + .bind(community_id.as_uuid()) + .bind(pubkeys) + .bind(i64::from(limit)) + .fetch_all(&mut *connection) + .await?; + let value = rows + .into_iter() + .map(|row| Ok((row.try_get("pubkey")?, row.try_get("channel_id")?))) + .collect::>()?; + Ok(ReadAt { value, read_at }) +} + /// Verify that a member is still removed under the channel-membership lock, /// serializing with any concurrent [`add_member`] call on the same channel. /// @@ -1342,18 +1546,50 @@ async fn get_members_with_operation( operation: crate::observability::WriterOperation, ) -> Result> { let mut connection = crate::observability::acquire_writer(pool, operation).await?; + select_active_members(&mut connection, community_id, channel_id).await +} + +/// Read a live channel's active members on `conn`, oldest first. +pub(crate) async fn select_active_members( + conn: &mut PgConnection, + community_id: CommunityId, + channel_id: Uuid, +) -> Result> { + select_active_members_filtered(conn, community_id, channel_id, None).await +} + +/// The active members of `channel_id` whose role is one of `roles`, in the +/// order [`select_active_members`] returns them. +pub(crate) async fn select_active_members_in_roles( + conn: &mut PgConnection, + community_id: CommunityId, + channel_id: Uuid, + roles: &[MemberRole], +) -> Result> { + let roles: Vec<&str> = roles.iter().map(MemberRole::as_str).collect(); + select_active_members_filtered(conn, community_id, channel_id, Some(&roles)).await +} + +async fn select_active_members_filtered( + conn: &mut PgConnection, + community_id: CommunityId, + channel_id: Uuid, + roles: Option<&[&str]>, +) -> Result> { let rows = sqlx::query( r#" SELECT cm.channel_id, cm.pubkey, cm.role::text AS role, cm.joined_at, cm.invited_by, cm.removed_at FROM channel_members cm JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL WHERE cm.community_id = $1 AND cm.channel_id = $2 AND cm.removed_at IS NULL + AND ($3::text[] IS NULL OR cm.role::text = ANY($3)) ORDER BY cm.joined_at ASC "#, ) .bind(community_id.as_uuid()) .bind(channel_id) - .fetch_all(&mut *connection) + .bind(roles) + .fetch_all(conn) .await?; rows.into_iter().map(row_to_member_record).collect() } @@ -1410,6 +1646,19 @@ pub async fn get_accessible_channel_ids( pool: &PgPool, community_id: CommunityId, pubkey: &[u8], +) -> Result> { + let mut ids = get_member_channel_ids(pool, community_id, pubkey).await?; + let open = get_listed_open_channel_ids(pool, community_id).await?; + merge_channel_ids(&mut ids, &open); + Ok(ids) +} + +/// The member half of [`get_accessible_channel_ids`]: legacy-type channels +/// where the pubkey is an active member. +pub async fn get_member_channel_ids( + pool: &PgPool, + community_id: CommunityId, + pubkey: &[u8], ) -> Result> { let mut connection = crate::observability::acquire_writer( pool, @@ -1423,28 +1672,61 @@ pub async fn get_accessible_channel_ids( JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL WHERE cm.community_id = $1 AND cm.pubkey = $2 AND cm.removed_at IS NULL AND {member_types} - UNION - SELECT id AS channel_id + "#, + member_types = crate::store::channel::legacy_channel_type_sql("c.channel_type"), + ); + // Built only from the constant type list. + sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) + .bind(community_id.as_uuid()) + .bind(pubkey) + .fetch_all(&mut *connection) + .await + .map_err(Into::into) +} + +/// The open half of [`get_accessible_channel_ids`]: listed open channels of +/// legacy types. It is the same for every reader in the community. +pub async fn get_listed_open_channel_ids( + pool: &PgPool, + community_id: CommunityId, +) -> Result> { + Ok(get_listed_open_channel_ids_read_at(pool, community_id) + .await? + .value) +} + +/// [`get_listed_open_channel_ids`], with when its connection was checked out. +pub async fn get_listed_open_channel_ids_read_at( + pool: &PgPool, + community_id: CommunityId, +) -> Result>> { + let mut connection = crate::observability::acquire_writer( + pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let read_at = std::time::Instant::now(); + let sql = format!( + r#" + SELECT id FROM channels WHERE community_id = $1 AND visibility = 'open' AND NOT unlisted AND deleted_at IS NULL AND {open_types} "#, - member_types = crate::store::channel::legacy_channel_type_sql("c.channel_type"), open_types = crate::store::channel::legacy_channel_type_sql("channel_type"), ); // Built only from the constant type list. - let rows = sqlx::query(sqlx::AssertSqlSafe(sql)) + let value = sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) .bind(community_id.as_uuid()) - .bind(pubkey) .fetch_all(&mut *connection) .await?; + Ok(ReadAt { value, read_at }) +} - rows.into_iter() - .map(|r| { - let id: Uuid = r.try_get("channel_id")?; - Ok(id) - }) - .collect() +/// Appends the channels of `more` that `ids` lacks. +pub fn merge_channel_ids(ids: &mut Vec, more: &[Uuid]) { + let have: std::collections::HashSet = ids.iter().copied().collect(); + ids.extend(more.iter().filter(|id| !have.contains(id))); } /// A channel that [`get_readable_named_only_channels`] found readable. @@ -1700,7 +1982,7 @@ async fn get_channel_tx( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, - ttl_seconds, ttl_deadline, labels, join_role, unlisted + ttl_seconds, ttl_deadline, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL "#, ) @@ -1798,7 +2080,7 @@ pub async fn get_accessible_channels( c.nip29_group_id, c.topic_required, c.max_members, c.topic, c.topic_set_by, c.topic_set_at, c.purpose, c.purpose_set_by, c.purpose_set_at, - c.ttl_seconds, c.ttl_deadline, c.labels, c.join_role, c.unlisted, + c.ttl_seconds, c.ttl_deadline, c.labels, c.join_role, c.unlisted, c.auto_join, (cm.channel_id IS NOT NULL) AS is_member FROM channels c LEFT JOIN channel_members cm @@ -2047,20 +2329,6 @@ pub async fn get_member_role( } impl Db { - /// Verify the mixed-version channel-roster database fence end to end. - #[datastore_span(name = "verify_channel_roster_fence", system = "postgresql")] - pub async fn verify_channel_roster_fence(&self) -> Result<()> { - { - let mut connection = crate::observability::acquire_writer( - &self.pool, - crate::observability::WriterOperation::Bootstrap, - ) - .await?; - verify_channel_roster_fence_catalog(&mut *connection).await?; - } - verify_channel_roster_fence_behavior(&self.pool).await - } - /// Capture the active roster while holding the membership-writer lock. #[datastore_span(name = "lock_member_snapshot", system = "postgresql")] pub async fn lock_member_snapshot( @@ -2115,17 +2383,53 @@ impl Db { .await } - /// [`Db::put_member`] for several people in one transaction (see - /// [`put_members`]). - #[datastore_span(name = "put_members", system = "postgresql")] - pub async fn put_members( + /// Complete one pending default-channel join, preserving leaves since admission. + /// A stale token or a removed relay member writes nothing. + #[datastore_span(name = "put_pending_default_member", system = "postgresql")] + pub async fn put_pending_default_member( + &self, + community: CommunityId, + channel: Uuid, + pubkey: &[u8], + pending: Uuid, + ) -> Result> { + put_first_member_with_pending(&self.pool, community, channel, pubkey, Some(pending)).await + } + + /// Self-joins `pubkey` with the channel's `join_role` only if they have + /// never been a member of the channel (see [`put_first_member`]). + #[datastore_span(name = "put_first_member", system = "postgresql")] + pub async fn put_first_member( + &self, + community_id: CommunityId, + channel_id: Uuid, + pubkey: &[u8], + ) -> Result> { + put_first_member(&self.pool, community_id, channel_id, pubkey).await + } + + /// Stores a kind:9000 `event` and applies its [`put_members`] writes, + /// with the event's author as the actor, in one transaction (see + /// [`put_members_with_event`]). + #[datastore_span(name = "put_members_with_event", system = "postgresql")] + pub async fn put_members_with_event( &self, community_id: CommunityId, channel_id: Uuid, + event: &nostr::Event, targets: &[MemberPut<'_>], - invited_by: Option<&[u8]>, - ) -> Result>> { - put_members(&self.pool, community_id, channel_id, targets, invited_by).await + thread_meta: Option>, + ) -> Result { + put_members_with_event( + &self.pool, + self.push_enqueue.clone(), + community_id, + channel_id, + event, + targets, + thread_meta, + ) + .await } /// Removes a member from a channel. @@ -2248,6 +2552,61 @@ impl Db { get_accessible_channel_ids(&self.pool, community_id, pubkey).await } + /// Bounded active memberships across every channel type for authorization. + /// `limit` rows may be incomplete; request cap + 1 to detect oversized users. + #[datastore_span(name = "get_active_membership_ids", system = "postgresql")] + pub async fn get_active_membership_ids_read_at( + &self, + community_id: CommunityId, + pubkey: &[u8], + limit: u32, + ) -> Result>> { + get_active_membership_ids_read_at(&self.pool, community_id, pubkey, limit).await + } + + /// [`Self::get_active_membership_ids_read_at`] for many pubkeys in one + /// statement, as `(pubkey, channel_id)` rows, up to `limit` per pubkey. + #[datastore_span(name = "get_active_membership_ids_bulk", system = "postgresql")] + pub async fn get_active_membership_ids_bulk_read_at( + &self, + community_id: CommunityId, + pubkeys: &[Vec], + limit: u32, + ) -> Result> { + get_active_membership_ids_bulk_read_at(&self.pool, community_id, pubkeys, limit).await + } + + /// Channel IDs where a pubkey is an active member. See [`get_member_channel_ids`]. + #[datastore_span(name = "get_member_channel_ids", system = "postgresql")] + pub async fn get_member_channel_ids( + &self, + community_id: CommunityId, + pubkey: &[u8], + ) -> Result> { + get_member_channel_ids(&self.pool, community_id, pubkey).await + } + + /// A community's listed open channel IDs. See [`get_listed_open_channel_ids`]. + pub async fn get_listed_open_channel_ids( + &self, + community_id: CommunityId, + ) -> Result> { + Ok(self + .get_listed_open_channel_ids_read_at(community_id) + .await? + .value) + } + + /// [`Self::get_listed_open_channel_ids`], with when its connection was + /// checked out, for caches that bound staleness from the read. + #[datastore_span(name = "get_listed_open_channel_ids", system = "postgresql")] + pub async fn get_listed_open_channel_ids_read_at( + &self, + community_id: CommunityId, + ) -> Result>> { + get_listed_open_channel_ids_read_at(&self.pool, community_id).await + } + /// The channels of non-legacy types a pubkey can read (member, or open /// and listed or among `named`), and the unlisted open channels among /// `named`. See [`get_readable_named_only_channels`]. @@ -2385,6 +2744,7 @@ mod postgres_tests { use super::*; use crate::channel::{ChannelType, ChannelVisibility}; use crate::migration; + use crate::test_support::ScratchDb; use crate::user::{ensure_user, set_agent_owner}; use nostr::Keys; use sqlx::postgres::PgPoolOptions; @@ -2395,6 +2755,93 @@ mod postgres_tests { .expect("connect to test DB") } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn active_membership_snapshot_matches_point_checks_for_all_channel_types() { + let pool = setup_pool().await; + let a = CommunityId::from_uuid(make_test_community(&pool).await); + let b = CommunityId::from_uuid(make_test_community(&pool).await); + let user = random_pubkey(); + let other_user = random_pubkey(); + let mut channels = Vec::new(); + for (i, kind) in ["stream", "forum", "dm", "workflow", "system"] + .iter() + .enumerate() + { + for visibility in ["open", "private"] { + let channel = Uuid::new_v4(); + channels.push(channel); + for community in [a, b] { + sqlx::query("INSERT INTO channels (community_id, id, name, channel_type, visibility, created_by, archived_at) VALUES ($1, $2, $2::text, $3::channel_type, $4::channel_visibility, $5, NOW())") + .bind(community.as_uuid()).bind(channel).bind(kind).bind(visibility).bind(&user) + .execute(&pool).await.unwrap(); + // Same user and channel IDs in two communities, but different memberships. + if community == a || i == 0 { + sqlx::query("INSERT INTO channel_members (community_id, channel_id, pubkey, hidden_at) VALUES ($1, $2, $3, NOW())") + .bind(community.as_uuid()).bind(channel).bind(&user).execute(&pool).await.unwrap(); + } + } + } + } + sqlx::query("UPDATE channel_members SET removed_at = NOW() WHERE community_id = $1 AND channel_id = $2") + .bind(a.as_uuid()).bind(channels[0]).execute(&pool).await.unwrap(); + sqlx::query("UPDATE channels SET deleted_at = NOW() WHERE community_id = $1 AND id = $2") + .bind(a.as_uuid()) + .bind(channels[1]) + .execute(&pool) + .await + .unwrap(); + channels.push(Uuid::new_v4()); // Missing channel. + for community in [a, b] { + for pubkey in [&user, &other_user] { + let snapshot = get_active_membership_ids_read_at(&pool, community, pubkey, 100) + .await + .unwrap(); + for channel in &channels { + assert_eq!( + snapshot.value.contains(channel), + is_member(&pool, community, *channel, pubkey).await.unwrap(), + "snapshot differs for {community:?}/{channel}" + ); + } + if community == a && pubkey == &user { + assert_eq!( + snapshot.value.len(), + 8, + "archived and hidden memberships still count, removed/deleted ones do not" + ); + let listed = get_member_channel_ids(&pool, community, pubkey) + .await + .unwrap(); + assert!( + snapshot.value.len() > listed.len(), + "system memberships must not inherit discovery's filter" + ); + } + } + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn membership_snapshot_clock_starts_after_pool_wait() { + let pool = PgPoolOptions::new() + .max_connections(1) + .connect(&crate::test_support::database_url()) + .await + .unwrap(); + let community = CommunityId::from_uuid(make_test_community(&pool).await); + let user = random_pubkey(); + let held = pool.acquire().await.unwrap(); + let read = get_active_membership_ids_read_at(&pool, community, &user, 100); + tokio::pin!(read); + assert!(futures_util::poll!(&mut read).is_pending()); + tokio::time::sleep(std::time::Duration::from_millis(30)).await; + let released = std::time::Instant::now(); + drop(held); + assert!(read.await.unwrap().read_at >= released); + } + fn random_pubkey() -> Vec { Keys::generate().public_key().to_bytes().to_vec() } @@ -2445,21 +2892,128 @@ mod postgres_tests { .await .expect("insert test channel"); - sqlx::query( - r#" - INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) - VALUES ($1, $2, $3, 'owner', $4) - "#, - ) - .bind(community_id) - .bind(id) - .bind(created_by) - .bind(created_by) - .execute(pool) - .await - .expect("insert owner membership"); + sqlx::query( + r#" + INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) + VALUES ($1, $2, $3, 'owner', $4) + "#, + ) + .bind(community_id) + .bind(id) + .bind(created_by) + .bind(created_by) + .execute(pool) + .await + .expect("insert owner membership"); + + crate::channel::get_channel(pool, CommunityId::from_uuid(community_id), id).await + } + + /// A person who has never been in a flagged channel is listed for it and + /// joined once, with the channel's `join_role`; a second put finds the + /// row; after a leave the channel is neither listed nor joined again. An + /// unflagged channel is never listed. + /// + /// Two racing first joins write once. + /// + /// Mutations: drop the row check from `put_first_member` → the leave is + /// undone (RED); take the locks after the row check → racing joins both + /// write (RED); drop the `NOT EXISTS` from + /// `list_never_joined_auto_join_channels` → the left channel is still + /// listed (RED). + #[tokio::test] + #[ignore = "requires Postgres"] + async fn first_member_put_joins_once_and_never_undoes_a_leave() { + use crate::channel::{list_never_joined_auto_join_channels, update_channel, ChannelUpdate}; + let pool = setup_pool().await; + let community = CommunityId::from_uuid(make_test_community(&pool).await); + let (owner, person) = (random_pubkey(), random_pubkey()); + let mut channels = Vec::new(); + for name in ["general", "announcements", "random"] { + let channel = create_test_channel( + &pool, + *community.as_uuid(), + name, + ChannelType::Stream, + ChannelVisibility::Open, + None, + &owner, + None, + ) + .await + .expect("create channel"); + channels.push(channel.id); + } + let (general, announcements, unflagged) = (channels[0], channels[1], channels[2]); + for (channel, join_role) in [(general, None), (announcements, Some("guest"))] { + update_channel( + &pool, + community, + channel, + ChannelUpdate { + auto_join: Some(true), + join_role: join_role.map(str::to_string), + ..Default::default() + }, + ) + .await + .expect("flag channel"); + } + + let never_joined = || list_never_joined_auto_join_channels(&pool, community, &person); + assert_eq!( + never_joined().await.expect("list"), + [general, announcements] + ); - crate::channel::get_channel(pool, CommunityId::from_uuid(community_id), id).await + let put_first = |channel| put_first_member(&pool, community, channel, &person); + assert_eq!( + put_first(general).await.expect("first put").map(|m| m.role), + Some("member".to_string()) + ); + assert_eq!( + put_first(announcements) + .await + .expect("first put") + .map(|m| m.role), + Some("guest".to_string()), + "the channel's join_role applies" + ); + assert!(put_first(general).await.expect("second put").is_none()); + assert!(never_joined().await.expect("list").is_empty()); + + // Two first joins of the same person racing each other write once. + for _ in 0..5 { + let racer = random_pubkey(); + let (a, b) = tokio::join!( + put_first_member(&pool, community, general, &racer), + put_first_member(&pool, community, general, &racer), + ); + let written = [a.expect("racing put"), b.expect("racing put")] + .iter() + .filter(|put| put.is_some()) + .count(); + assert_eq!(written, 1, "racing first joins write once"); + } + + remove_member(&pool, community, general, &person, &person) + .await + .expect("leave"); + assert!(never_joined().await.expect("list").is_empty()); + assert!(put_first(general).await.expect("put after leave").is_none()); + assert_eq!( + get_member_role(&pool, community, general, &person) + .await + .expect("role"), + None, + "a leave stands" + ); + assert_eq!( + get_member_role(&pool, community, unflagged, &person) + .await + .expect("role"), + None + ); } #[tokio::test] @@ -3476,6 +4030,112 @@ mod postgres_tests { assert!(matches!(err, DbError::InvalidData(_)), "{err:?}"); } + /// `put_members_with_event` stores the event only with the writes it + /// carries: a stored event applies its people, a resend changes nothing, + /// and an event whose every person is refused under the lock is not + /// stored. Mutations: commit when everyone is refused → the refused event + /// is stored → RED; write people on a duplicate → the removed person is + /// back → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn put_members_with_event_stores_the_event_with_its_writes() { + let pool = setup_pool().await; + let community_id = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_id); + let (owner, outsider) = (Keys::generate(), Keys::generate()); + let (owner_pk, outsider_pk) = ( + owner.public_key().to_bytes().to_vec(), + outsider.public_key().to_bytes().to_vec(), + ); + let person = random_pubkey(); + for pk in [&owner_pk, &outsider_pk, &person] { + ensure_user(&pool, community, pk) + .await + .expect("ensure user"); + } + let channel = create_test_channel( + &pool, + community_id, + "put-members-event", + ChannelType::Stream, + ChannelVisibility::Private, + None, + &owner_pk, + None, + ) + .await + .expect("create channel"); + let event = |actor: &Keys| { + nostr::EventBuilder::new(nostr::Kind::Custom(9000), "") + .tags([ + nostr::Tag::parse(["h", &channel.id.to_string()]).unwrap(), + nostr::Tag::parse(["p", &hex::encode(&person)]).unwrap(), + ]) + .sign_with_keys(actor) + .expect("sign 9000") + }; + let targets = [MemberPut { + pubkey: &person, + requested: None, + }]; + let stored = |id: nostr::EventId| { + let pool = pool.clone(); + async move { + crate::event::get_event_by_id(&pool, community, id.as_bytes()) + .await + .expect("read event") + .is_some() + } + }; + + // A non-member may not add anyone to a private channel. + let refused = event(&outsider); + let write = + put_members_with_event(&pool, None, community, channel.id, &refused, &targets, None) + .await + .expect("refused write"); + assert!( + matches!(&write, MemberPutEventWrite::Refused(errors) + if matches!(errors.as_slice(), [DbError::AccessDenied(_)])), + "expected a refusal" + ); + assert!(!stored(refused.id).await, "a refused event is not stored"); + assert_eq!( + get_member_role(&pool, community, channel.id, &person) + .await + .expect("read role"), + None + ); + + let added = event(&owner); + let write = + put_members_with_event(&pool, None, community, channel.id, &added, &targets, None) + .await + .expect("applied write"); + let MemberPutEventWrite::Applied { results, .. } = write else { + panic!("expected the event to apply"); + }; + let put = results[0].as_ref().expect("person added"); + assert_eq!(put.prior_role, None); + assert!(stored(added.id).await); + + // A resend finds the event stored and leaves the roster alone. + remove_member(&pool, community, channel.id, &person, &owner_pk) + .await + .expect("remove person"); + let write = + put_members_with_event(&pool, None, community, channel.id, &added, &targets, None) + .await + .expect("duplicate write"); + assert!(matches!(write, MemberPutEventWrite::Duplicate(_))); + assert_eq!( + get_member_role(&pool, community, channel.id, &person) + .await + .expect("read role"), + None + ); + } + /// `put_member` enforces admission itself, so a caller that skips the /// relay validator still cannot join an announce channel above /// `join_role`, and a guest still cannot add anyone. No role tag keeps an @@ -3691,6 +4351,205 @@ mod postgres_tests { .expect("join_role change"); } + /// An archive and an admission are ordered by the channel row lock, and an + /// archived channel admits nobody new. A join that waits on an uncommitted + /// archive is refused once it commits, with no row, and re-adding a + /// removed member is refused too. A kind:9000 add that waits on an + /// uncommitted archive is refused the same way, and its event is not + /// stored. The other order: an archive waits for an admission that holds + /// the locks. + /// The archive here is the TTL reaper's single UPDATE, which takes no + /// advisory lock. The join and the kind:9000 add each wait on their own + /// archive, so neither queues behind the other's membership lock. + /// Mutations: drop the row lock from `lock_channel_for_member_put`, take + /// only the membership lock in `put_members_with_event`, or drop the + /// archived refusal from `put_members_on` → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn put_member_waits_for_a_concurrent_archive() { + let pool = setup_pool().await; + let community_id = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_id); + let owner_keys = Keys::generate(); + let owner = owner_keys.public_key().to_bytes().to_vec(); + let joiner = random_pubkey(); + let removed = random_pubkey(); + let invitee = random_pubkey(); + for pk in [&owner, &joiner, &removed, &invitee] { + ensure_user(&pool, community, pk) + .await + .expect("ensure user"); + } + let channel = create_test_channel( + &pool, + community_id, + "put-member-archive-race", + ChannelType::Stream, + ChannelVisibility::Open, + None, + &owner, + None, + ) + .await + .expect("create channel"); + put_member(&pool, community, channel.id, &removed, None, None) + .await + .expect("join before the archive"); + remove_member(&pool, community, channel.id, &removed, &removed) + .await + .expect("leave before the archive"); + + let mut archive = pool.begin().await.expect("begin archive"); + sqlx::query( + "UPDATE channels SET archived_at = NOW() \ + WHERE community_id = $1 AND id = $2 AND archived_at IS NULL", + ) + .bind(community_id) + .bind(channel.id) + .execute(&mut *archive) + .await + .expect("archive"); + + let join_pool = crate::test_support::named_pool("put-member-archive-race").await; + let join = tokio::spawn({ + let channel_id = channel.id; + let joiner = joiner.clone(); + async move { put_member(&join_pool, community, channel_id, &joiner, None, None).await } + }); + crate::test_support::wait_for_lock_wait(&pool, "put-member-archive-race").await; + assert!(!join.is_finished(), "the join must wait for the archive"); + archive.commit().await.expect("commit archive"); + + let err = join + .await + .expect("join task") + .expect_err("the join is decided on the archived channel"); + assert!( + matches!(&err, DbError::AccessDenied(reason) if reason == "channel is archived"), + "{err:?}" + ); + let readd = put_member(&pool, community, channel.id, &removed, None, Some(&owner)) + .await + .expect_err("an archived channel does not reactivate a removed member"); + assert!( + matches!(&readd, DbError::AccessDenied(reason) if reason == "channel is archived"), + "{readd:?}" + ); + + // A kind:9000 add stores its event in the same transaction as the + // write, so it takes the same locks: it waits on an uncommitted + // archive, then is refused and stores nothing. + crate::channel::unarchive_channel(&pool, community, channel.id) + .await + .expect("unarchive before the kind:9000 race"); + let mut archive = pool.begin().await.expect("begin second archive"); + sqlx::query( + "UPDATE channels SET archived_at = NOW() \ + WHERE community_id = $1 AND id = $2 AND archived_at IS NULL", + ) + .bind(community_id) + .bind(channel.id) + .execute(&mut *archive) + .await + .expect("archive again"); + let add = nostr::EventBuilder::new(nostr::Kind::Custom(9000), "") + .tags([ + nostr::Tag::parse(["h", &channel.id.to_string()]).unwrap(), + nostr::Tag::parse(["p", &hex::encode(&invitee)]).unwrap(), + ]) + .sign_with_keys(&owner_keys) + .expect("sign 9000"); + let add_pool = crate::test_support::named_pool("put-members-event-archive-race").await; + let add_write = tokio::spawn({ + let channel_id = channel.id; + let add = add.clone(); + let invitee = invitee.clone(); + async move { + let targets = [MemberPut { + pubkey: &invitee, + requested: None, + }]; + put_members_with_event(&add_pool, None, community, channel_id, &add, &targets, None) + .await + } + }); + crate::test_support::wait_for_lock_wait(&pool, "put-members-event-archive-race").await; + assert!( + !add_write.is_finished(), + "the kind:9000 add must wait for the archive" + ); + archive.commit().await.expect("commit second archive"); + let write = add_write + .await + .expect("kind:9000 task") + .expect("kind:9000 write"); + assert!( + matches!(&write, MemberPutEventWrite::Refused(errors) + if matches!(errors.as_slice(), + [DbError::AccessDenied(reason)] if reason == "channel is archived")), + "expected an archived refusal" + ); + assert!( + crate::event::get_event_by_id(&pool, community, add.id.as_bytes()) + .await + .expect("read event") + .is_none(), + "a refused kind:9000 is not stored" + ); + + let mut roles = Vec::new(); + for pk in [&owner, &joiner, &removed, &invitee] { + roles.push( + get_member_role(&pool, community, channel.id, pk) + .await + .expect("read role"), + ); + } + assert_eq!(roles, [Some("owner".to_string()), None, None, None]); + + // The other order: an archive waits for an admission that holds the + // locks, and the member it admitted stays a member. + crate::channel::unarchive_channel(&pool, community, channel.id) + .await + .expect("unarchive"); + let mut admission = crate::begin_community_write_transaction( + &pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .expect("begin admission"); + lock_channel_for_member_put(&mut admission, channel.id) + .await + .expect("lock for the admission"); + let targets = [MemberPut { + pubkey: &joiner, + requested: None, + }]; + let admitted = put_members_on(&mut admission, channel.id, &targets, None) + .await + .expect("admission"); + assert!(admitted[0].is_ok(), "{admitted:?}"); + let archive_pool = crate::test_support::named_pool("archive-vs-admission").await; + let archive = tokio::spawn({ + let channel_id = channel.id; + async move { crate::channel::archive_channel(&archive_pool, community, channel_id).await } + }); + crate::test_support::wait_for_lock_wait(&pool, "archive-vs-admission").await; + assert!( + !archive.is_finished(), + "an archive must wait for an admission in progress" + ); + admission.commit().await.expect("commit admission"); + archive.await.expect("archive task").expect("archive"); + assert_eq!( + get_member_role(&pool, community, channel.id, &joiner) + .await + .expect("read role"), + Some("member".to_string()) + ); + } + /// A `join_role` change on an ephemeral channel and a roster publication /// take the channel's locks in one order. The roster holds the membership /// lock and refreshes the channel's TTL (TTL lock, then row) at commit. A @@ -4655,8 +5514,8 @@ mod postgres_tests { let mut contender = pool.begin().await.expect("begin deletion contender"); let exclusive_taken: bool = - sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community.as_uuid()) + sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))") + .bind(crate::deletion::community_deletion_lock_key(community)) .fetch_one(&mut *contender) .await .expect("try exclusive community deletion lock"); @@ -4993,56 +5852,6 @@ mod postgres_tests { assert_eq!(restored.as_deref(), Some("owner")); } - async fn admin_url() -> String { - crate::test_support::database_url() - } - - /// Create a fresh scratch database on the same server and optionally run migrations. - async fn create_scratch_db_through( - admin: &PgPool, - prefix: &str, - target: Option, - ) -> (PgPool, String) { - let name = format!("{}_{}", prefix, Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(admin) - .await - .expect("create scratch db"); - let base = admin_url().await; - // Swap the database path segment of the admin URL for the scratch name. - let scratch_url = { - let idx = base.rfind('/').expect("db url has a path segment"); - format!("{}/{}", &base[..idx], name) - }; - let pool = PgPool::connect(&scratch_url) - .await - .expect("connect scratch db"); - match target { - Some(target) => migration::run_migrations_through(&pool, target) - .await - .expect("migrate scratch db through target"), - None => migration::run_migrations(&pool) - .await - .expect("migrate scratch db"), - } - (pool, name) - } - - /// Create a fresh scratch database on the same server and run all migrations. - /// Returns (pool, db_name); callers should `drop_scratch_db` when done. - async fn create_scratch_db(admin: &PgPool, prefix: &str) -> (PgPool, String) { - create_scratch_db_through(admin, prefix, None).await - } - - async fn drop_scratch_db(admin: &PgPool, pool: PgPool, name: &str) { - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(admin) - .await; - } - /// Insert identical community + channel rows into a database so the same /// (community, channel) ids resolve in both writer and replica. async fn seed_community_channel( @@ -5073,142 +5882,29 @@ mod postgres_tests { .expect("create channel"); } + /// The relay must run without the 0032 roster trigger: the app-side check + /// in every roster writer is the fence, and a later migration drops the + /// trigger. Migrating a database that has no trigger must succeed. + /// + /// Mutation: restore the catalog check after `MIGRATOR.run` in + /// `run_migrations_locked` → migrating fails → RED. #[tokio::test] #[ignore = "requires Postgres"] - async fn unmigrated_roster_fence_blocks_startup_until_0032_is_applied() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (pool, scratch_name) = - create_scratch_db_through(&admin, "roster_fence_unmigrated", Some(31)).await; - let db = Db::from_pool(pool.clone()); - - let error = db - .verify_channel_roster_fence() - .await - .expect_err("pre-0032 schema must block roster publishers"); - assert!( - error.to_string().contains("channel roster fence trigger"), - "startup gate must report the missing schema fence: {error}" - ); - let rows_before: i64 = sqlx::query_scalar("SELECT count(*) FROM events WHERE kind = 39002") - .fetch_one(&pool) - .await - .expect("count pre-migration rosters"); - assert_eq!( - rows_before, 0, - "failed startup gate must not publish a roster" - ); - - migration::run_migrations(&pool) - .await - .expect("apply migration 0032"); - db.verify_channel_roster_fence() - .await - .expect("0032 must open the startup gate"); - - drop_scratch_db(&admin, pool, &scratch_name).await; - } - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn channel_roster_fence_behavior_verification_detects_inert_function() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (pool, scratch_name) = create_scratch_db(&admin, "roster_fence_inert").await; - let db = Db::from_pool(pool.clone()); - + async fn migrations_run_without_the_roster_trigger() { + let (pool, _scratch) = + ScratchDb::migrated(&crate::test_support::database_url(), "roster_fence_absent").await; sqlx::raw_sql( - "CREATE OR REPLACE FUNCTION guard_channel_roster_snapshot() \ - RETURNS TRIGGER AS $$ BEGIN RETURN NEW; END; $$ LANGUAGE plpgsql;", - ) - .execute(&pool) - .await - .expect("replace roster fence with inert body"); - let error = db - .verify_channel_roster_fence() - .await - .expect_err("inert roster fence must fail closed"); - assert!( - error - .to_string() - .contains("stale probe roster was accepted"), - "behavior probe must identify inert semantics: {error}" - ); - - drop_scratch_db(&admin, pool, &scratch_name).await; - } - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn channel_roster_fence_catalog_verification_fails_closed() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (pool, scratch_name) = create_scratch_db(&admin, "roster_fence_catalog").await; - let db = Db::from_pool(pool.clone()); - - db.verify_channel_roster_fence() - .await - .expect("migrated roster fence must verify"); - - let child: String = sqlx::query_scalar( - "SELECT n.nspname || '.' || c.relname \ - FROM pg_inherits i JOIN pg_class c ON c.oid = i.inhrelid \ - JOIN pg_namespace n ON n.oid = c.relnamespace \ - WHERE i.inhparent = 'public.events'::regclass ORDER BY i.inhrelid LIMIT 1", + "DROP TRIGGER trg_events_guard_channel_roster_snapshot ON events; \ + DROP FUNCTION guard_channel_roster_snapshot();", ) - .fetch_one(&pool) - .await - .expect("load event partition"); - sqlx::query(sqlx::AssertSqlSafe(format!( - "ALTER TABLE {child} DISABLE TRIGGER trg_events_guard_channel_roster_snapshot" - ))) .execute(&pool) .await - .expect("disable partition roster trigger"); - let error = db - .verify_channel_roster_fence() - .await - .expect_err("disabled partition roster fence must fail closed"); - assert!( - error.to_string().contains(&child), - "verification must identify the unfenced partition: {error}" - ); - - drop_scratch_db(&admin, pool, &scratch_name).await; - } + .expect("drop the roster trigger"); + assert!(verify_channel_roster_fence_catalog(&pool).await.is_err()); - #[tokio::test] - #[ignore = "requires Postgres"] - async fn channel_roster_fence_verification_supports_size_one_pool() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (seed_pool, scratch_name) = create_scratch_db(&admin, "roster_fence_size_one").await; - seed_pool.close().await; - - let base_url = admin_url().await; - let path = base_url.rfind('/').expect("database URL path"); - let scratch_url = format!("{}/{}", &base_url[..path], scratch_name); - let pool = PgPoolOptions::new() - .max_connections(1) - .acquire_timeout(std::time::Duration::from_secs(1)) - .connect(&scratch_url) + migration::run_migrations(&pool) .await - .expect("connect size-one writer pool"); - let db = Db::from_pool(pool.clone()); - - tokio::time::timeout( - std::time::Duration::from_secs(2), - db.verify_channel_roster_fence(), - ) - .await - .expect("roster verification must not self-deadlock on its second checkout") - .expect("migrated roster fence verifies on a size-one pool"); - - drop_scratch_db(&admin, pool, &scratch_name).await; + .expect("migrating must not require the roster trigger"); } #[tokio::test] @@ -5216,22 +5912,11 @@ mod postgres_tests { async fn desired_schema_rejects_stale_legacy_roster_role() { use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let scratch_name = format!("schema_roster_role_{}", Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!( - "CREATE DATABASE {scratch_name}" - ))) - .execute(&admin) - .await - .expect("create desired-schema scratch db"); - let base_url = admin_url().await; - let slash = base_url.rfind('/').expect("database URL has path segment"); - let scratch_url = format!("{}/{}", &base_url[..slash], scratch_name); + let scratch = + ScratchDb::create(&crate::test_support::database_url(), "schema_roster_role").await; let pool = PgPoolOptions::new() .max_connections(1) - .connect(&scratch_url) + .connect(scratch.url()) .await .expect("connect desired-schema scratch db"); sqlx::raw_sql(sqlx::AssertSqlSafe( @@ -5357,7 +6042,5 @@ mod postgres_tests { .await .expect("count rejected stale roster"); assert_eq!(stale_rows, 0, "legacy stale insert must roll back"); - - drop_scratch_db(&admin, pool, &scratch_name).await; } } diff --git a/crates/buzz-db/src/store/channel_name_postgres_tests.rs b/crates/buzz-db/src/store/channel_name_postgres_tests.rs new file mode 100644 index 00000000000..bc387dc2a3c --- /dev/null +++ b/crates/buzz-db/src/store/channel_name_postgres_tests.rs @@ -0,0 +1,270 @@ +//! Two listed open channels in a community never share a name, ignoring +//! case. Every write that can make a channel claim a listed name goes through +//! the real store functions here: create, rename, private to open, and +//! unlisted to listed. An archived channel keeps its name; a deleted one +//! frees it. + +use crate::channel::ChannelUpdate; +use crate::error::DbError; +use crate::Db; +use buzz_core::channel::{ChannelType, ChannelVisibility}; +use buzz_core::CommunityId; +use nostr::Keys; +use sqlx::PgPool; +use uuid::Uuid; + +struct Fixture { + db: Db, + community: CommunityId, + owner: Keys, +} + +impl Fixture { + async fn new() -> Self { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect to test DB"); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + crate::migration::run_migrations(&pool) + .await + .expect("migrate test DB"); + } + Self { + community: insert_community(&pool).await, + db: Db::from_pool(pool), + owner: Keys::generate(), + } + } + + async fn create( + &self, + name: &str, + channel_type: ChannelType, + visibility: ChannelVisibility, + ) -> crate::error::Result { + self.create_in(self.community, name, channel_type, visibility) + .await + } + + async fn create_in( + &self, + community: CommunityId, + name: &str, + channel_type: ChannelType, + visibility: ChannelVisibility, + ) -> crate::error::Result { + self.db + .create_channel( + community, + name, + channel_type, + visibility, + None, + &self.owner.public_key().to_bytes(), + None, + ) + .await + .map(|channel| channel.id) + } + + async fn open(&self, name: &str) -> Uuid { + self.create(name, ChannelType::Stream, ChannelVisibility::Open) + .await + .expect("create open channel") + } + + async fn update(&self, channel: Uuid, update: ChannelUpdate) -> crate::error::Result<()> { + self.db + .update_channel(self.community, channel, update) + .await + .map(|_| ()) + } + + async fn listing_state(&self, channel: Uuid) -> (String, String, bool) { + let channel = self + .db + .get_channel(self.community, channel) + .await + .expect("reload channel"); + (channel.name, channel.visibility, channel.unlisted) + } +} + +async fn insert_community(pool: &PgPool) -> CommunityId { + let community = CommunityId::from_uuid(Uuid::new_v4()); + sqlx::query("INSERT INTO communities(id,host) VALUES($1,$2)") + .bind(community.as_uuid()) + .bind(format!("channel-name-{}.test", community.as_uuid())) + .execute(pool) + .await + .expect("insert community"); + community +} + +fn assert_taken(result: crate::error::Result, name: &str) { + match result { + Err(DbError::ChannelNameTaken(taken)) => assert_eq!(taken, name), + other => panic!("expected {name:?} to be taken, got {other:?}"), + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_listed_name_is_taken_only_for_listed_channels() { + let f = Fixture::new().await; + f.open("Square-iOS").await; + + // Another listed channel cannot take it, whatever its case or type, and + // the display prefix is not part of the name. + for (name, channel_type) in [ + ("square-ios", ChannelType::Stream), + ("SQUARE-IOS", ChannelType::Forum), + ("#square-ios ", ChannelType::Stream), + ] { + assert_taken( + f.create(name, channel_type, ChannelVisibility::Open).await, + buzz_core::channel::canonical_channel_name(name), + ); + } + + // Channels the directory does not list may repeat it. + for (channel_type, visibility) in [ + (ChannelType::Stream, ChannelVisibility::Private), + (ChannelType::Forum, ChannelVisibility::Private), + (ChannelType::Dm, ChannelVisibility::Private), + (ChannelType::Workflow, ChannelVisibility::Open), + (ChannelType::System, ChannelVisibility::Open), + ] { + f.create("square-ios", channel_type, visibility) + .await + .unwrap_or_else(|e| panic!("{channel_type:?}/{visibility:?}: {e}")); + } + + // Names are per community. + let other = insert_community(f.db.pool()).await; + f.create_in( + other, + "square-ios", + ChannelType::Stream, + ChannelVisibility::Open, + ) + .await + .expect("another community may use the name"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_change_that_would_list_a_taken_name_changes_nothing() { + let f = Fixture::new().await; + f.open("payments").await; + + let private = f + .create("payments", ChannelType::Stream, ChannelVisibility::Private) + .await + .expect("private channel"); + let unlisted = f.open("payments-unlisted").await; + f.update( + unlisted, + ChannelUpdate { + name: Some("payments".into()), + unlisted: Some(true), + ..Default::default() + }, + ) + .await + .expect("an unlisted channel may share the name"); + let other = f.open("payments-team").await; + + let cases = [ + ( + private, + ChannelUpdate { + visibility: Some("open".into()), + ..Default::default() + }, + ), + ( + unlisted, + ChannelUpdate { + unlisted: Some(false), + ..Default::default() + }, + ), + ( + other, + ChannelUpdate { + name: Some("PAYMENTS".into()), + description: Some("rolled back with the name".into()), + ..Default::default() + }, + ), + ]; + for (channel, update) in cases { + let before = f.listing_state(channel).await; + let description = + f.db.get_channel(f.community, channel) + .await + .expect("reload") + .description; + let attempted = update.name.clone().unwrap_or_else(|| before.0.clone()); + assert_taken(f.update(channel, update).await, &attempted); + assert_eq!(f.listing_state(channel).await, before); + assert_eq!( + f.db.get_channel(f.community, channel) + .await + .expect("reload") + .description, + description, + "the whole update rolls back" + ); + } + + // A rename to a free name, and the same name in another case, still work. + f.update( + other, + ChannelUpdate { + name: Some("payments-core".into()), + ..Default::default() + }, + ) + .await + .expect("rename to a free name"); + f.update( + other, + ChannelUpdate { + name: Some("Payments-Core".into()), + ..Default::default() + }, + ) + .await + .expect("a channel may change the case of its own name"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_archived_channel_keeps_its_name_until_it_is_deleted() { + let f = Fixture::new().await; + let archived = f.open("square-ios").await; + f.db.archive_channel(f.community, archived) + .await + .expect("archive"); + + assert_taken( + f.create("square-ios", ChannelType::Stream, ChannelVisibility::Open) + .await, + "square-ios", + ); + f.db.unarchive_channel(f.community, archived) + .await + .expect("unarchive never collides"); + f.db.archive_channel(f.community, archived) + .await + .expect("archive again"); + + assert!(f + .db + .soft_delete_channel(f.community, archived) + .await + .expect("delete")); + f.open("square-ios").await; +} diff --git a/crates/buzz-db/src/store/community.rs b/crates/buzz-db/src/store/community.rs index 1df5bea0218..1bd4e0bb6c5 100644 --- a/crates/buzz-db/src/store/community.rs +++ b/crates/buzz-db/src/store/community.rs @@ -6,7 +6,13 @@ use chrono::{DateTime, Utc}; use sqlx::Row; use uuid::Uuid; -use crate::{relay_members, Db, DbError, Result}; +use crate::{relay_members, Db, DbError, ReadAt, Result}; + +// Admission and policy must select the same serving row. A deletion request +// alone does not stop serving; begin_quiescing changes deletion_state. +pub(super) const SERVING_HOST_QUERY: &str = "SELECT id, host, requires_nip_fi, policy_generation + FROM communities WHERE lower(host) = lower($1) + AND archived_at IS NULL AND deleted_at IS NULL AND deletion_state = 'active'"; /// Community host-map row returned by [`Db::lookup_community_by_host`]. #[derive(Debug, Clone, PartialEq, Eq)] @@ -35,6 +41,10 @@ pub struct CreatedCommunityRecord { pub id: CommunityId, /// Normalized host stored for the community. pub host: String, + /// Whether this transaction inserted the community. + pub created: bool, + /// Stored policy read from the inserted or existing row. + pub requires_nip_fi: bool, } /// Result of atomically creating a community with its initial owner. @@ -110,57 +120,73 @@ impl Db { /// /// The caller owns host normalization and turns `None` into the fail-closed /// request/connection error. buzz-db only reads the durable host map. - #[datastore_span(name = "lookup_community_by_host", system = "postgresql")] pub async fn lookup_community_by_host( &self, normalized_host: &str, ) -> Result> { + Ok(self + .lookup_community_by_host_read_at(normalized_host) + .await? + .value) + } + + /// [`Self::lookup_community_by_host`], with when its connection was + /// checked out, for caches that bound staleness from the read. + #[datastore_span(name = "lookup_community_by_host", system = "postgresql")] + pub async fn lookup_community_by_host_read_at( + &self, + normalized_host: &str, + ) -> Result>> { let mut connection = crate::observability::acquire_writer( &self.pool, crate::observability::WriterOperation::TenantResolution, ) .await?; - let row = sqlx::query( - r#" - SELECT id, host - FROM communities - WHERE lower(host) = lower($1) - AND archived_at IS NULL - AND deleted_at IS NULL - AND deletion_state = 'active' - "#, - ) - .bind(normalized_host) - .fetch_optional(&mut *connection) - .await?; + let read_at = std::time::Instant::now(); + let row = sqlx::query(SERVING_HOST_QUERY) + .bind(normalized_host) + .fetch_optional(&mut *connection) + .await?; - row.map(|row| { - let id: Uuid = row.try_get("id")?; - let host: String = row.try_get("host")?; + let value = row + .map(|row| { + let id: Uuid = row.try_get("id")?; + let host: String = row.try_get("host")?; - Ok(CommunityRecord { - id: CommunityId::from_uuid(id), - host, + Ok::<_, DbError>(CommunityRecord { + id: CommunityId::from_uuid(id), + host, + }) }) - }) - .transpose() + .transpose()?; + Ok(ReadAt { value, read_at }) } /// Returns whether a community id still exists in the active lifecycle state. - #[datastore_span(name = "is_community_active", system = "postgresql")] pub async fn is_community_active(&self, community_id: CommunityId) -> Result { + Ok(self.is_community_active_read_at(community_id).await?.value) + } + + /// [`Self::is_community_active`], with when its connection was checked + /// out, for caches that bound staleness from the read. + #[datastore_span(name = "is_community_active", system = "postgresql")] + pub async fn is_community_active_read_at( + &self, + community_id: CommunityId, + ) -> Result> { let mut connection = crate::observability::acquire_writer( &self.pool, crate::observability::WriterOperation::Authorization, ) .await?; - let active = sqlx::query_scalar::<_, bool>( + let read_at = std::time::Instant::now(); + let value = sqlx::query_scalar::<_, bool>( "SELECT EXISTS(SELECT 1 FROM communities WHERE id = $1 AND archived_at IS NULL AND deleted_at IS NULL AND deletion_state = 'active')", ) .bind(community_id.as_uuid()) .fetch_one(&mut *connection) .await?; - Ok(active) + Ok(ReadAt { value, read_at }) } /// Runs `apply` while holding the community row lock only when the exact @@ -474,6 +500,50 @@ impl Db { Ok(()) } + /// Look up an existing host for legacy operator convergence without creating. + /// + /// Matches ensure's lifecycle rules, including archived rows. Returns None + /// for missing hosts and rejects tombstones. No row or issuer is inserted. + /// Release this short transaction before calling `provision_owner`, which + /// acquires its own lifecycle locks in the established order. + #[datastore_span(name = "existing_configured_community", system = "postgresql")] + pub async fn existing_configured_community( + &self, + normalized_host: &str, + ) -> Result> { + let connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + let row = sqlx::query( + "SELECT id, host, deletion_state, deleted_at FROM communities \ + WHERE lower(host) = lower($1) FOR NO KEY UPDATE", + ) + .bind(normalized_host) + .fetch_optional(&mut *tx) + .await?; + let record = row + .map(|row| { + let state: String = row.try_get("deletion_state")?; + let deleted_at: Option> = row.try_get("deleted_at")?; + if state != "active" || deleted_at.is_some() { + return Err(DbError::AccessDenied(format!( + "community host {normalized_host:?} is permanently tombstoned" + ))); + } + Ok(EnsuredCommunityRecord { + id: CommunityId::from_uuid(row.try_get("id")?), + host: row.try_get("host")?, + created: false, + }) + }) + .transpose()?; + tx.commit().await?; + Ok(record) + } + /// Ensure a configured community host exists and return its row. /// /// This is the startup/config seeding path for N=1 deployments. Migrations @@ -589,7 +659,9 @@ impl Db { /// Like [`Db::create_community_with_owner`], binding `nip_fi_issuers` to /// the new community in the same transaction. Identical retries return the - /// original record without touching its bindings. + /// original record without touching its bindings. Operator tenant creation + /// must use [`Db::create_community_with_owner_and_nip_fi_policy`] to apply + /// the configured creation requirement. #[datastore_span( name = "create_community_with_owner_and_nip_fi_issuers", system = "postgresql" @@ -600,6 +672,31 @@ impl Db { owner_pubkey: &str, nip_fi_issuers: &[String], relay_keypair: &nostr::Keys, + ) -> Result> { + self.create_community_with_owner_and_nip_fi_policy( + normalized_host, + owner_pubkey, + nip_fi_issuers, + false, + relay_keypair, + ) + .await + } + + /// Atomically create a community, owner, issuer bindings and initial NIP-FI + /// policy (generation 1 when required, otherwise 0). Identical retries keep + /// the original policy and bindings. Required creation needs issuers. + #[datastore_span( + name = "create_community_with_owner_and_nip_fi_policy", + system = "postgresql" + )] + pub async fn create_community_with_owner_and_nip_fi_policy( + &self, + normalized_host: &str, + owner_pubkey: &str, + nip_fi_issuers: &[String], + requires_nip_fi: bool, + relay_keypair: &nostr::Keys, ) -> Result> { use relay_members::MembershipWrite; let owner_pubkey = owner_pubkey.to_ascii_lowercase(); @@ -622,17 +719,21 @@ impl Db { let row = sqlx::query( r#" - INSERT INTO communities (host) - VALUES ($1) + INSERT INTO communities (host, requires_nip_fi, policy_generation) + VALUES ($1, $2, CASE WHEN $2 THEN 1 ELSE 0 END) ON CONFLICT (lower(host)) DO NOTHING - RETURNING id, host + RETURNING id, host, requires_nip_fi "#, ) .bind(normalized_host) + .bind(requires_nip_fi) .fetch_optional(&mut *tx) .await?; if let Some(row) = row { + if requires_nip_fi && nip_fi_issuers.is_empty() { + return Err(DbError::NipFiBindingRequired); + } let id: Uuid = row.try_get("id")?; let host: String = row.try_get("host")?; @@ -672,12 +773,14 @@ impl Db { let record = CreateCommunityWithOwnerResult::Created(CreatedCommunityRecord { id: CommunityId::from_uuid(id), host, + created: true, + requires_nip_fi: row.try_get("requires_nip_fi")?, }); relay_members::commit_membership_write(tx, record, true, relay_keypair).await } else { let existing = sqlx::query( r#" - SELECT c.id, c.host + SELECT c.id, c.host, c.requires_nip_fi FROM communities c JOIN relay_members rm ON rm.community_id = c.id WHERE lower(c.host) = lower($1) @@ -701,6 +804,8 @@ impl Db { let record = CreateCommunityWithOwnerResult::Created(CreatedCommunityRecord { id: CommunityId::from_uuid(existing.try_get("id")?), host: existing.try_get("host")?, + created: false, + requires_nip_fi: existing.try_get("requires_nip_fi")?, }); tx.commit().await?; Ok(MembershipWrite::unchanged(record)) @@ -1130,7 +1235,10 @@ mod postgres_tests { .expect("same-owner retry"); assert_eq!( retry, - CreateCommunityWithOwnerResult::Created(created.clone()), + CreateCommunityWithOwnerResult::Created(CreatedCommunityRecord { + created: false, + ..created.clone() + }), "retry returns the original row" ); @@ -1607,8 +1715,23 @@ mod postgres_tests { let first = first.expect("first concurrent create"); let second = second.expect("second concurrent create"); - assert!(matches!(first, CreateCommunityWithOwnerResult::Created(_))); - assert_eq!(first, second, "conflict loser re-reads the winning row"); + let ( + CreateCommunityWithOwnerResult::Created(first), + CreateCommunityWithOwnerResult::Created(second), + ) = (first, second) + else { + panic!("both concurrent callers must receive the stored community"); + }; + assert_eq!( + first.id, second.id, + "conflict loser re-reads the winning row" + ); + assert_eq!(first.host, second.host); + assert_eq!(first.requires_nip_fi, second.requires_nip_fi); + assert_ne!( + first.created, second.created, + "exactly one caller inserted the row" + ); } #[tokio::test] diff --git a/crates/buzz-db/src/store/community_auth.rs b/crates/buzz-db/src/store/community_auth.rs new file mode 100644 index 00000000000..21cee02ad2d --- /dev/null +++ b/crates/buzz-db/src/store/community_auth.rs @@ -0,0 +1,451 @@ +//! Community authentication policy management and durable operator receipts. +//! +//! Receipts are deployment-global and intentionally survive target deletion: +//! an operation UUID must never acquire a new meaning after a lost response. + +use buzz_core::CommunityId; +use buzz_datastore_tracing::datastore_span; +use serde::Serialize; +use sqlx::{FromRow, Row}; +use uuid::Uuid; + +use crate::{Db, Result}; + +/// Fleet protocol bound for a cached host's policy, measured before checkout. +/// Increasing this requires a coordinated acceptance-writer rollout first. +pub const POLICY_LEASE_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(1); +// Allow clock-rate drift between pods. Never shorten below the fleet lease bound. +const POLICY_LEASE_DRAIN: std::time::Duration = + POLICY_LEASE_MAX_AGE.saturating_add(std::time::Duration::from_millis(100)); +// Two-int advisory key space, separate from the existing bigint lock protocols. +const POLICY_LEASE_NAMESPACE: i32 = 0x4649504c; + +/// Canonical request tuple, with the authenticated operator added by the relay. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UpgradeRequest { + /// Caller-generated, deployment-global idempotency UUID. + pub operation_id: Uuid, + /// Immutable community identity. + pub community_id: Uuid, + /// Normalized expected community host. + pub expected_host: String, + /// Registered key of the authenticated invoking owner. + pub actor_pubkey: String, + /// Owner precondition, checked under the community row lock. + pub expected_owner_pubkey: String, + /// Exact issuer selected by trusted deployment configuration. + pub expected_issuer: String, + /// NIP-98 authenticated deployment operator; never taken from request JSON. + pub operator_pubkey: String, +} + +/// General policy intent; both preconditions are checked under the writer row lock. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PolicyRequest { + /// Canonical operation tuple. Disable uses an empty issuer. + pub tuple: UpgradeRequest, + /// Desired stored requirement. + pub requires_nip_fi: bool, + /// Last observed generation. + pub expected_policy_generation: i64, + /// Last observed stored requirement. + pub expected_requires_nip_fi: bool, +} + +/// Durable accepted intent and the current primary-database snapshot. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, FromRow)] +pub struct PolicyRecord { + /// Original operation tuple and accepted generation, never current authority. + #[serde(flatten)] + #[sqlx(flatten)] + pub acceptance: UpgradeRecord, + /// Null only for legacy, unfenced requests. + pub expected_policy_generation: Option, + /// Null only for legacy, unfenced requests. + pub expected_requires_nip_fi: Option, + /// Current target generation, absent after target deletion. + pub current_policy_generation: Option, + /// Current stored flag, absent after target deletion. + pub current_requires_nip_fi: Option, +} + +/// Refusal or an immutable acceptance with current status. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PolicyOutcome { + /// Durable acceptance or identical read-only replay. + Accepted(Box), + /// No mutation or receipt was committed. + Refused(&'static str), +} + +/// Durable acceptance tuple plus the current availability of its target. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, FromRow)] +pub struct UpgradeRecord { + /// Caller idempotency UUID. + pub operation_id: Uuid, + /// Target identity, preserved after deletion. + #[sqlx(rename = "target_community_id")] + pub community_id: Uuid, + /// Host at acceptance. + pub expected_host: String, + /// Invoking owner's registered key at acceptance. + pub actor_pubkey: String, + /// Owner precondition at acceptance. + pub expected_owner_pubkey: String, + /// Issuer precondition at acceptance; omitted for disable. + #[serde(skip_serializing_if = "String::is_empty")] + pub expected_issuer: String, + /// Operator authorized to recover this receipt. + pub operator_pubkey: String, + /// Immutable generation accepted for this operation. + pub policy_generation: i64, + /// Receipt proves acceptance; availability does not undo this fact. + pub requires_nip_fi: bool, + /// Current availability, with no certification of fleet-wide socket closure. + pub state: String, + /// Extensible activation obligations; unknown reasons must remain pending. + pub pending_reasons: Vec, +} + +impl UpgradeRecord { + fn matches(&self, request: &UpgradeRequest) -> bool { + self.operation_id == request.operation_id + && self.community_id == request.community_id + && self.expected_host == request.expected_host + && self.actor_pubkey == request.actor_pubkey + && self.expected_owner_pubkey == request.expected_owner_pubkey + && self.expected_issuer == request.expected_issuer + && self.operator_pubkey == request.operator_pubkey + } +} + +/// Authoritative policy for a community in the active lifecycle. +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRow)] +pub struct CommunityAuthPolicy { + /// Immutable identity from the same row as this policy. + #[sqlx(rename = "id")] + pub community_id: Uuid, + /// Durable stored requirement. Global enforce remains an additional floor. + pub requires_nip_fi: bool, + /// Zero before the first operation; increases with every accepted CAS intent. + pub policy_generation: i64, +} + +// One statement gives status a single primary-database snapshot. Missing trust, +// host/policy drift and terminal lifecycle never become a usable active result. +const RECEIPT: &str = "SELECT u.operation_id, u.target_community_id, u.expected_host, + u.actor_pubkey, u.expected_owner_pubkey, u.expected_issuer, u.operator_pubkey, + u.policy_generation, u.requested_requires_nip_fi AS requires_nip_fi, + u.expected_policy_generation, u.expected_requires_nip_fi, + c.policy_generation AS current_policy_generation, + c.requires_nip_fi AS current_requires_nip_fi, + CASE WHEN c.id IS NULL OR c.host <> u.expected_host + OR c.archived_at IS NOT NULL OR c.deleted_at IS NOT NULL + OR c.deletion_state <> 'active' + OR EXISTS (SELECT 1 FROM community_deletion_requests d + WHERE d.community_id = c.id AND d.stage <> 'aborted') THEN 'unavailable' + WHEN c.policy_generation <> u.policy_generation + OR c.requires_nip_fi <> u.requested_requires_nip_fi THEN 'superseded' + WHEN NOT u.requested_requires_nip_fi THEN 'applied' + WHEN EXISTS (SELECT 1 FROM community_nip_fi_issuers i + WHERE i.community_id = c.id AND i.issuer = u.expected_issuer) + THEN 'pending' ELSE 'unavailable' END AS state, + CASE WHEN u.requested_requires_nip_fi + THEN ARRAY['connection_closure_unverified']::text[] + ELSE ARRAY[]::text[] END AS pending_reasons + FROM community_auth_upgrades u + LEFT JOIN communities c ON c.id = u.target_community_id + WHERE u.operation_id = $1"; + +impl Db { + /// Read a cacheable serving policy under the host's shared lease lock. + /// + /// Callers must anchor expiry BEFORE invoking this method and refuse an + /// expired result. Acceptance excludes new leases and drains old ones before + /// committing. The lock and row read MUST be separate READ COMMITTED + /// statements: a snapshot from before lock acquisition is not a lease. + /// Contention refuses immediately; it never leaves a server-side lock wait. + pub async fn community_auth_policy_lease_for_host( + &self, + host: &str, + ) -> Result> { + let host = buzz_core::tenant::normalize_host(host); + let connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL READ COMMITTED") + .execute(&mut *tx) + .await?; + sqlx::query("SET LOCAL statement_timeout = '400ms'") + .execute(&mut *tx) + .await?; + let acquired: bool = + sqlx::query_scalar("SELECT pg_try_advisory_xact_lock_shared($1, hashtext($2))") + .bind(POLICY_LEASE_NAMESPACE) + .bind(&host) + .fetch_one(&mut *tx) + .await?; + if !acquired { + return Err(crate::DbError::AccessDenied( + "community policy transition".into(), + )); + } + let policy = sqlx::query_as(super::community::SERVING_HOST_QUERY) + .bind(&host) + .fetch_optional(&mut *tx) + .await?; + tx.commit().await?; + Ok(policy) + } + + /// Bind a serving host and its authentication policy from one writer row. + /// A lifecycle transition between earlier checks and this lookup cannot + /// supply a tenant with another snapshot's optional policy. + #[datastore_span(name = "community_auth_binding_for_host", system = "postgresql")] + pub async fn community_auth_binding_for_host( + &self, + host: &str, + ) -> Result> { + let mut connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::TenantResolution, + ) + .await?; + let row = sqlx::query(super::community::SERVING_HOST_QUERY) + .bind(host) + .fetch_optional(&mut *connection) + .await?; + row.map(|row| { + Ok(( + crate::CommunityRecord { + id: CommunityId::from_uuid(row.try_get("id")?), + host: row.try_get("host")?, + }, + CommunityAuthPolicy { + community_id: row.try_get("id")?, + requires_nip_fi: row.try_get("requires_nip_fi")?, + policy_generation: row.try_get("policy_generation")?, + }, + )) + }) + .transpose() + } + + /// Resolve active host policy in one writer read. No replica or cross-request cache. + #[datastore_span(name = "community_auth_policy_for_host", system = "postgresql")] + pub async fn community_auth_policy_for_host( + &self, + host: &str, + ) -> Result> { + let mut connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + Ok(sqlx::query_as(super::community::SERVING_HOST_QUERY) + .bind(host) + .fetch_optional(&mut *connection) + .await?) + } + + /// Read current active-community policy from the writer, never a replica. + #[datastore_span(name = "community_auth_policy", system = "postgresql")] + pub async fn community_auth_policy( + &self, + community: CommunityId, + ) -> Result> { + let mut connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + Ok(sqlx::query_as("SELECT id, requires_nip_fi, policy_generation FROM communities + WHERE id = $1 AND archived_at IS NULL AND deleted_at IS NULL AND deletion_state = 'active'") + .bind(community.as_uuid()).fetch_optional(&mut *connection).await?) + } + + /// Recover any policy receipt for its original authenticated operator. + pub async fn community_auth_policy_status( + &self, + operation: Uuid, + operator: &str, + ) -> Result> { + let mut connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let record: Option = sqlx::query_as(RECEIPT) + .bind(operation) + .fetch_optional(&mut *connection) + .await?; + Ok(record.filter(|record| record.acceptance.operator_pubkey == operator)) + } + + /// Apply a compare-and-set policy intent; identical committed replay is read-only. + pub async fn set_community_nip_fi_policy( + &self, + request: &PolicyRequest, + configured_trust: std::result::Result<(), &'static str>, + ) -> Result { + let desired = request.requires_nip_fi; + let expected_generation = request.expected_policy_generation; + let expected_state = request.expected_requires_nip_fi; + let request = &request.tuple; + let connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + sqlx::query("SET LOCAL lock_timeout = '5s'") + .execute(&mut *tx) + .await?; + // Lock UUID first across all targets, so cross-community UUID reuse + // cannot race the INSERT. Hash collisions merely serialize callers. + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 510))") + .bind(request.operation_id.to_string()) + .execute(&mut *tx) + .await?; + let existing: Option = sqlx::query_as(RECEIPT) + .bind(request.operation_id) + .fetch_optional(&mut *tx) + .await?; + if let Some(record) = existing { + return Ok( + if record.acceptance.matches(request) + && record.acceptance.requires_nip_fi == desired + && record.expected_policy_generation == Some(expected_generation) + && record.expected_requires_nip_fi == Some(expected_state) + { + PolicyOutcome::Accepted(Box::new(record)) + } else { + PolicyOutcome::Refused("idempotency_conflict") + }, + ); + } + if let Err(code) = configured_trust { + return Ok(PolicyOutcome::Refused(code)); + } + let community = CommunityId::from_uuid(request.community_id); + crate::deletion::lock_community_deletion_shared(&mut tx, community).await?; + // Same order and lock strength as ownership transfer; archive/delete + // also take this row lock. Read ownership only after acquiring it. + let row = sqlx::query( + "SELECT host, archived_at IS NULL AND deleted_at IS NULL + AND deletion_state = 'active' AS active, requires_nip_fi, policy_generation + FROM communities WHERE id = $1 FOR NO KEY UPDATE", + ) + .bind(request.community_id) + .fetch_optional(&mut *tx) + .await?; + let Some(row) = row else { + return Ok(PolicyOutcome::Refused("community_not_found")); + }; + if row.try_get::("host")? != request.expected_host { + return Ok(PolicyOutcome::Refused("host_conflict")); + } + let old_required: bool = row.try_get("requires_nip_fi")?; + let old_generation: i64 = row.try_get("policy_generation")?; + if expected_generation != old_generation || expected_state != old_required { + return Ok(PolicyOutcome::Refused("policy_conflict")); + } + if old_generation == i64::MAX { + return Ok(PolicyOutcome::Refused("policy_generation_exhausted")); + } + // Lock order: deletion-shared, community row, host lease. Fills take + // only the shared host lease and never a community row lock. Derive + // the key from the locked, validated row, not an earlier host snapshot. + let lease_host = buzz_core::tenant::normalize_host(&row.try_get::("host")?); + sqlx::query("SELECT pg_advisory_xact_lock($1, hashtext($2))") + .bind(POLICY_LEASE_NAMESPACE) + .bind(&lease_host) + .execute(&mut *tx) + .await?; + // Keep the row stable while ALL optional leases expire, including + // leases under former host keys. No remap (single or double) can + // refill another host's optional cache while this drain is running. + if desired && !old_required { + tokio::time::sleep(POLICY_LEASE_DRAIN).await; + } + let deletion_pending: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM + community_deletion_requests WHERE community_id = $1 AND stage <> 'aborted')", + ) + .bind(request.community_id) + .fetch_one(&mut *tx) + .await?; + if !row.try_get::("active")? || deletion_pending { + return Ok(PolicyOutcome::Refused("lifecycle_conflict")); + } + let owners: Vec = sqlx::query_scalar( + "SELECT pubkey FROM relay_members + WHERE community_id = $1 AND role = 'owner' ORDER BY pubkey FOR UPDATE", + ) + .bind(request.community_id) + .fetch_all(&mut *tx) + .await?; + if owners != [request.expected_owner_pubkey.clone()] + || request.actor_pubkey != request.expected_owner_pubkey + { + return Ok(PolicyOutcome::Refused("owner_conflict")); + } + if desired { + let issuer: Option = sqlx::query_scalar( + "SELECT issuer FROM community_nip_fi_issuers + WHERE community_id = $1 AND issuer = $2 FOR UPDATE", + ) + .bind(request.community_id) + .bind(&request.expected_issuer) + .fetch_optional(&mut *tx) + .await?; + if issuer.is_none() { + return Ok(PolicyOutcome::Refused("issuer_conflict")); + } + } + // Admission is also required for this communities-row mutation. + self.deletion_store() + .guard_transaction(&mut tx, community) + .await?; + let generation = old_generation + 1; + sqlx::query( + "UPDATE communities SET policy_generation = $2, requires_nip_fi = $3 WHERE id = $1", + ) + .bind(request.community_id) + .bind(generation) + .bind(desired) + .execute(&mut *tx) + .await?; + sqlx::query( + "INSERT INTO community_auth_upgrades + (operation_id, target_community_id, expected_host, actor_pubkey, expected_owner_pubkey, + expected_issuer, operator_pubkey, policy_generation, requested_requires_nip_fi, + expected_policy_generation, expected_requires_nip_fi) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)", + ) + .bind(request.operation_id) + .bind(request.community_id) + .bind(&request.expected_host) + .bind(&request.actor_pubkey) + .bind(&request.expected_owner_pubkey) + .bind(&request.expected_issuer) + .bind(&request.operator_pubkey) + .bind(generation) + .bind(desired) + .bind(expected_generation) + .bind(expected_state) + .execute(&mut *tx) + .await?; + let record = sqlx::query_as(RECEIPT) + .bind(request.operation_id) + .fetch_one(&mut *tx) + .await?; + tx.commit().await?; + Ok(PolicyOutcome::Accepted(Box::new(record))) + } +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/community_auth/postgres_tests.rs b/crates/buzz-db/src/store/community_auth/postgres_tests.rs new file mode 100644 index 00000000000..9f10184d4cc --- /dev/null +++ b/crates/buzz-db/src/store/community_auth/postgres_tests.rs @@ -0,0 +1,909 @@ +use super::*; +use crate::CreateCommunityWithOwnerResult; +use nostr::Keys; + +const ISSUER: &str = "https://identity.example/api/goose"; + +async fn fixture() -> (Db, UpgradeRequest, Keys) { + let db = Db::from_pool( + sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(), + ); + let keys = Keys::generate(); + let owner = Keys::generate().public_key().to_hex(); + let host = format!("auth-{}.example", Uuid::new_v4().simple()); + let write = db + .create_community_with_owner_and_nip_fi_issuers(&host, &owner, &[ISSUER.to_owned()], &keys) + .await + .unwrap(); + let CreateCommunityWithOwnerResult::Created(record) = write.outcome else { + panic!("create failed") + }; + let request = UpgradeRequest { + operation_id: Uuid::new_v4(), + community_id: *record.id.as_uuid(), + expected_host: host, + actor_pubkey: owner.clone(), + expected_owner_pubkey: owner, + expected_issuer: ISSUER.to_owned(), + operator_pubkey: keys.public_key().to_hex(), + }; + (db, request, keys) +} + +fn initial_enable(tuple: &UpgradeRequest) -> PolicyRequest { + PolicyRequest { + tuple: tuple.clone(), + requires_nip_fi: true, + expected_policy_generation: 0, + expected_requires_nip_fi: false, + } +} + +async fn accepted(db: &Db, request: &UpgradeRequest) -> UpgradeRecord { + let PolicyOutcome::Accepted(record) = db + .set_community_nip_fi_policy(&initial_enable(request), Ok(())) + .await + .unwrap() + else { + panic!("acceptance refused") + }; + record.acceptance +} + +async fn policy(db: &Db, request: &UpgradeRequest) -> CommunityAuthPolicy { + db.community_auth_policy(CommunityId::from_uuid(request.community_id)) + .await + .unwrap() + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn response_loss_recovery_and_payload_binding() { + let (db, request, _) = fixture().await; + assert!(!policy(&db, &request).await.requires_nip_fi); + let first = accepted(&db, &request).await; + assert_eq!(first.state, "pending"); + assert_eq!(first.policy_generation, 1); + // Discard the POST result and recover by original operator/UUID. + assert_eq!( + db.community_auth_policy_status(request.operation_id, &request.operator_pubkey) + .await + .unwrap() + .map(|record| record.acceptance), + Some(first.clone()) + ); + assert_eq!(accepted(&db, &request).await, first); + assert!(db + .community_auth_policy_status(request.operation_id, "another operator") + .await + .unwrap() + .map(|record| record.acceptance) + .is_none()); + for field in 0..6 { + let mut changed = request.clone(); + match field { + 0 => changed.community_id = Uuid::new_v4(), + 1 => changed.expected_host = "another.example".to_owned(), + 2 => changed.actor_pubkey = "b".repeat(64), + 3 => changed.expected_owner_pubkey = "c".repeat(64), + 4 => changed.expected_issuer = "https://another.example".to_owned(), + _ => changed.operator_pubkey = "d".repeat(64), + } + assert_eq!( + db.set_community_nip_fi_policy(&initial_enable(&changed), Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("idempotency_conflict") + ); + } + assert_eq!(policy(&db, &request).await.policy_generation, 1); + let community = CommunityId::from_uuid(request.community_id); + for allow_last in [true, false] { + assert_eq!( + db.unbind_nip_fi_issuer(community, ISSUER, allow_last) + .await + .unwrap(), + crate::NipFiUnbind::RequiredIssuer + ); + } + assert_eq!(accepted(&db, &request).await, first); + // Rotation can remove the accepted issuer only after a replacement is bound. + db.bind_nip_fi_issuers(community, &["https://replacement.example".to_owned()]) + .await + .unwrap(); + assert_eq!( + db.unbind_nip_fi_issuer(community, ISSUER, true) + .await + .unwrap(), + crate::NipFiUnbind::Removed + ); + assert_eq!(accepted(&db, &request).await.state, "unavailable"); + assert_eq!( + db.unbind_nip_fi_issuer(community, "https://replacement.example", true) + .await + .unwrap(), + crate::NipFiUnbind::RequiredIssuer + ); + assert!(policy(&db, &request).await.requires_nip_fi); + // Out-of-band trust loss requires an explicit repair, never a bulk rebind. + sqlx::query("DELETE FROM community_nip_fi_issuers WHERE community_id = $1") + .bind(request.community_id) + .execute(&db.pool) + .await + .unwrap(); + assert_eq!( + db.bind_nip_fi_issuers_to_active(&[community], &[ISSUER.to_owned()]) + .await + .unwrap(), + 0 + ); + assert_eq!(accepted(&db, &request).await.state, "unavailable"); + db.bind_nip_fi_issuers(community, &[ISSUER.to_owned()]) + .await + .unwrap(); + assert_eq!(accepted(&db, &request).await, first); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn concurrent_ids_and_duplicate_requests_converge() { + let (db, request, _) = fixture().await; + let first = initial_enable(&request); + let second = intent(&request, true, 0, false); + let (a, b) = tokio::join!( + db.set_community_nip_fi_policy(&first, Ok(())), + db.set_community_nip_fi_policy(&second, Ok(())) + ); + let (winner, loser) = match (a.unwrap(), b.unwrap()) { + (PolicyOutcome::Accepted(record), other) => (&first, (record, other)), + (other, PolicyOutcome::Accepted(record)) => (&second, (record, other)), + outcomes => panic!("no CAS winner: {outcomes:?}"), + }; + assert_eq!(loser.1, PolicyOutcome::Refused("policy_conflict")); + assert_eq!(apply(&db, winner).await, *loser.0); + let (replay_a, replay_b) = tokio::join!(apply(&db, winner), apply(&db, winner)); + assert_eq!(replay_a, replay_b); + assert_eq!(policy(&db, &request).await.policy_generation, 1); + let (_, mut other, _) = fixture().await; + other.operation_id = winner.tuple.operation_id; + assert_eq!( + db.set_community_nip_fi_policy(&initial_enable(&other), Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("idempotency_conflict") + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn failed_preconditions_leave_free_policy_and_no_receipt() { + let (db, request, _) = fixture().await; + for (mut changed, code) in [ + (request.clone(), "host_conflict"), + (request.clone(), "owner_conflict"), + (request.clone(), "issuer_conflict"), + (request.clone(), "community_not_found"), + ] { + match code { + "host_conflict" => changed.expected_host = "wrong.example".to_owned(), + "owner_conflict" => changed.actor_pubkey = "b".repeat(64), + "issuer_conflict" => changed.expected_issuer = "https://wrong.example".to_owned(), + _ => changed.community_id = Uuid::new_v4(), + } + assert_eq!( + db.set_community_nip_fi_policy(&initial_enable(&changed), Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused(code) + ); + } + assert_eq!( + db.set_community_nip_fi_policy(&initial_enable(&request), Err("authorization_unavailable")) + .await + .unwrap(), + PolicyOutcome::Refused("authorization_unavailable") + ); + db.unbind_nip_fi_issuer(CommunityId::from_uuid(request.community_id), ISSUER, true) + .await + .unwrap(); + assert_eq!( + db.set_community_nip_fi_policy(&initial_enable(&request), Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("issuer_conflict") + ); + assert_eq!( + policy(&db, &request).await, + CommunityAuthPolicy { + community_id: request.community_id, + requires_nip_fi: false, + policy_generation: 0 + } + ); + assert!(db + .community_auth_policy_status(request.operation_id, &request.operator_pubkey) + .await + .unwrap() + .map(|record| record.acceptance) + .is_none()); +} + +// Observe the actual PostgreSQL blocker and statement, rather than treating +// elapsed time or either possible race outcome as evidence of serialization. +async fn blocked_upgrade( + db: &Db, + request: &UpgradeRequest, + locker_pid: i32, + statement: &str, +) -> tokio::task::JoinHandle> { + use std::str::FromStr; + let application = format!("upgrade-lock-{}", request.operation_id.simple()); + let options = sqlx::postgres::PgConnectOptions::from_str(&crate::test_support::database_url()) + .unwrap() + .application_name(&application); + let upgrade_db = Db::from_pool( + sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(), + ); + let request = request.clone(); + let task = tokio::spawn(async move { + upgrade_db + .set_community_nip_fi_policy(&initial_enable(&request), Ok(())) + .await + }); + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + assert!( + !task.is_finished(), + "enable escaped before taking its precondition lock" + ); + let row: Option<(String, Vec)> = sqlx::query_as( + "SELECT query, pg_blocking_pids(pid) FROM pg_stat_activity + WHERE application_name = $1 AND wait_event_type = 'Lock'", + ) + .bind(&application) + .fetch_optional(&db.pool) + .await + .unwrap(); + if let Some((query, blockers)) = row { + if blockers.contains(&locker_pid) { + let query = query.split_whitespace().collect::>().join(" "); + assert!( + query.starts_with(statement), + "enable reached a later statement without the precondition lock: {query}" + ); + break; + } + } + tokio::task::yield_now().await; + } + }) + .await + .expect("observe the enable statement blocked by the held transaction"); + task +} + +async fn assert_refused_without_mutation( + db: &Db, + request: &UpgradeRequest, + task: tokio::task::JoinHandle>, + code: &'static str, +) { + assert_eq!(task.await.unwrap().unwrap(), PolicyOutcome::Refused(code)); + assert!(db + .community_auth_policy_status(request.operation_id, &request.operator_pubkey) + .await + .unwrap() + .map(|record| record.acceptance) + .is_none()); + let policy: (bool, i64) = + sqlx::query_as("SELECT requires_nip_fi, policy_generation FROM communities WHERE id = $1") + .bind(request.community_id) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(policy, (false, 0)); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn owner_lock_blocks_uncommitted_owner_change_then_refuses_enable() { + let (db, request, _) = fixture().await; + let mut locker = db.pool.begin().await.unwrap(); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *locker) + .await + .unwrap(); + sqlx::query("UPDATE relay_members SET role = 'member' WHERE community_id = $1 AND pubkey = $2") + .bind(request.community_id) + .bind(&request.expected_owner_pubkey) + .execute(&mut *locker) + .await + .unwrap(); + let task = blocked_upgrade(&db, &request, pid, "SELECT pubkey FROM relay_members").await; + locker.commit().await.unwrap(); + assert_refused_without_mutation(&db, &request, task, "owner_conflict").await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn community_lock_blocks_uncommitted_archive_then_refuses_enable() { + let (db, request, _) = fixture().await; + let mut locker = db.pool.begin().await.unwrap(); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *locker) + .await + .unwrap(); + sqlx::query("UPDATE communities SET archived_at = now() WHERE id = $1") + .bind(request.community_id) + .execute(&mut *locker) + .await + .unwrap(); + let task = blocked_upgrade(&db, &request, pid, "SELECT host, archived_at").await; + locker.commit().await.unwrap(); + assert_refused_without_mutation(&db, &request, task, "lifecycle_conflict").await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn issuer_lock_blocks_uncommitted_unbind_then_refuses_enable() { + let (db, request, _) = fixture().await; + let mut locker = db.pool.begin().await.unwrap(); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *locker) + .await + .unwrap(); + sqlx::query("DELETE FROM community_nip_fi_issuers WHERE community_id = $1 AND issuer = $2") + .bind(request.community_id) + .bind(ISSUER) + .execute(&mut *locker) + .await + .unwrap(); + let task = blocked_upgrade( + &db, + &request, + pid, + "SELECT issuer FROM community_nip_fi_issuers", + ) + .await; + locker.commit().await.unwrap(); + assert_refused_without_mutation(&db, &request, task, "issuer_conflict").await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn accepted_receipt_survives_transfer_without_granting_fresh_owner_authority() { + let (db, request, keys) = fixture().await; + let first = accepted(&db, &request).await; + let new_owner = Keys::generate().public_key().to_hex(); + let _ = db + .transfer_ownership( + CommunityId::from_uuid(request.community_id), + &new_owner, + &request.expected_owner_pubkey, + &keys, + ) + .await + .unwrap(); + assert_eq!(accepted(&db, &request).await, first); + let mut fresh = request.clone(); + fresh.operation_id = Uuid::new_v4(); + assert_eq!( + db.set_community_nip_fi_policy( + &PolicyRequest { + tuple: fresh.clone(), + requires_nip_fi: true, + expected_policy_generation: 1, + expected_requires_nip_fi: true + }, + Ok(()) + ) + .await + .unwrap(), + PolicyOutcome::Refused("owner_conflict") + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn authoritative_lookup_failure_is_error_not_fabricated_acceptance() { + let db = Db::from_pool( + sqlx::postgres::PgPoolOptions::new() + .acquire_timeout(std::time::Duration::from_millis(100)) + .connect_lazy("postgres://127.0.0.1:1/unavailable") + .unwrap(), + ); + let (_, request, _) = fixture().await; + assert!(db + .set_community_nip_fi_policy(&initial_enable(&request), Ok(())) + .await + .is_err()); + assert!(db + .community_auth_policy_status(request.operation_id, &request.operator_pubkey) + .await + .is_err()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn deletion_intent_refuses_enable_before_quiescing() { + let (db, request, _) = fixture().await; + db.deletion_store() + .submit( + Some(&request.expected_host), + "operator", + None, + Some(CommunityId::from_uuid(request.community_id)), + ) + .await + .unwrap(); + assert_eq!( + db.set_community_nip_fi_policy(&initial_enable(&request), Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("lifecycle_conflict") + ); + assert!(!policy(&db, &request).await.requires_nip_fi); + assert!(db + .community_auth_policy_status(request.operation_id, &request.operator_pubkey) + .await + .unwrap() + .map(|record| record.acceptance) + .is_none()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_expansion_preserves_existing_optional_rows_with_and_without_trust() { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + crate::migration::run_migrations_through(&pool, 81) + .await + .unwrap(); + let db = Db::from_pool(pool.clone()); + let free = db + .ensure_configured_community("free-before.example") + .await + .unwrap() + .id; + let bound = db + .ensure_configured_community_with_nip_fi_issuers( + "bound-before.example", + &[ISSUER.to_owned()], + ) + .await + .unwrap() + .id; + crate::migration::run_migrations(&pool).await.unwrap(); + for community in [free, bound] { + assert_eq!( + db.community_auth_policy(community).await.unwrap(), + Some(CommunityAuthPolicy { + community_id: *community.as_uuid(), + requires_nip_fi: false, + policy_generation: 0, + }) + ); + } + assert_eq!( + db.lookup_nip_fi_binding_by_host("bound-before.example") + .await + .unwrap() + .unwrap() + .issuers, + vec![ISSUER.to_owned()] + ); + let receipts: i64 = sqlx::query_scalar("SELECT count(*) FROM community_auth_upgrades") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(receipts, 0); + let global: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM _operator_global_tables WHERE table_name = 'community_auth_upgrades')") + .fetch_one(&pool).await.unwrap(); + assert!(global); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn supported_writer_maintains_generation_while_direct_sql_is_not_constrained() { + let (db, mut request, _) = fixture().await; + assert_eq!(policy(&db, &request).await.policy_generation, 0); + sqlx::query("UPDATE communities SET policy_generation = -1 WHERE id = $1") + .bind(request.community_id) + .execute(db.pool()) + .await + .unwrap(); + assert_eq!(policy(&db, &request).await.policy_generation, -1); + sqlx::query("UPDATE communities SET policy_generation = DEFAULT WHERE id = $1") + .bind(request.community_id) + .execute(db.pool()) + .await + .unwrap(); + assert_eq!(policy(&db, &request).await.policy_generation, 0); + let first = accepted(&db, &request).await; + assert_eq!(first.policy_generation, 1); + request.operation_id = Uuid::new_v4(); + assert_eq!( + apply( + &db, + &PolicyRequest { + tuple: request.clone(), + requires_nip_fi: true, + expected_policy_generation: 1, + expected_requires_nip_fi: true + } + ) + .await + .acceptance + .policy_generation, + 2 + ); + let invalid_receipt = sqlx::query( + "UPDATE community_auth_upgrades SET policy_generation = 0 WHERE operation_id = $1", + ) + .bind(request.operation_id) + .execute(db.pool()) + .await + .unwrap_err(); + assert_eq!( + invalid_receipt + .as_database_error() + .unwrap() + .code() + .as_deref(), + Some("23514") + ); + assert_eq!(policy(&db, &request).await.policy_generation, 2); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn host_policy_tracks_primary_requirement_and_serving_lifecycle() { + let (db, request, _) = fixture().await; + let host = &request.expected_host; + assert_eq!( + db.community_auth_policy_for_host(host).await.unwrap(), + Some(CommunityAuthPolicy { + community_id: request.community_id, + requires_nip_fi: false, + policy_generation: 0 + }) + ); + let upgraded = accepted(&db, &request).await; + assert_eq!( + db.community_auth_policy_for_host(host).await.unwrap(), + Some(CommunityAuthPolicy { + community_id: request.community_id, + requires_nip_fi: true, + policy_generation: upgraded.policy_generation + }) + ); + assert!(db + .community_auth_policy_for_host("unknown.example") + .await + .unwrap() + .is_none()); + sqlx::query("INSERT INTO community_deletion_requests (community_id, community_host, requested_by) VALUES ($1, $2, 'policy-test')") + .bind(request.community_id).bind(host).execute(db.pool()).await.unwrap(); + for stage in ["submitted", "inventoried", "approved"] { + sqlx::query("UPDATE community_deletion_requests SET stage = $2 WHERE community_id = $1") + .bind(request.community_id) + .bind(stage) + .execute(db.pool()) + .await + .unwrap(); + assert!(db.lookup_community_by_host(host).await.unwrap().is_some()); + assert!( + db.community_auth_policy_for_host(host) + .await + .unwrap() + .unwrap() + .requires_nip_fi, + "{stage}" + ); + } + sqlx::query("UPDATE communities SET archived_at = now() WHERE id = $1") + .bind(request.community_id) + .execute(db.pool()) + .await + .unwrap(); + assert!(db + .community_auth_policy_for_host(host) + .await + .unwrap() + .is_none()); +} + +fn intent(tuple: &UpgradeRequest, desired: bool, generation: i64, required: bool) -> PolicyRequest { + let mut tuple = tuple.clone(); + tuple.operation_id = Uuid::new_v4(); + if !desired { + tuple.expected_issuer.clear(); + } + PolicyRequest { + tuple, + requires_nip_fi: desired, + expected_policy_generation: generation, + expected_requires_nip_fi: required, + } +} + +async fn apply(db: &Db, request: &PolicyRequest) -> PolicyRecord { + let PolicyOutcome::Accepted(record) = db + .set_community_nip_fi_policy(request, Ok(())) + .await + .unwrap() + else { + panic!("policy refused") + }; + *record +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn policy_enable_disable_reenable_history_and_identity() { + let (db, tuple, _) = fixture().await; + let enable = intent(&tuple, true, 0, false); + let first = apply(&db, &enable).await; + assert_eq!(first.acceptance.policy_generation, 1); + assert_eq!(first.acceptance.state, "pending"); + let disable = intent(&tuple, false, 1, true); + let second = apply(&db, &disable).await; + assert_eq!(second.acceptance.policy_generation, 2); + assert_eq!(second.acceptance.state, "applied"); + let old = db + .community_auth_policy_status(enable.tuple.operation_id, &tuple.operator_pubkey) + .await + .unwrap() + .unwrap(); + assert_eq!(old.acceptance.state, "superseded"); + assert_eq!(old.current_policy_generation, Some(2)); + assert_eq!(old.current_requires_nip_fi, Some(false)); + // A committed retry is history even with the mutation gate disabled. + assert_eq!( + db.set_community_nip_fi_policy(&enable, Err("upgrades_disabled")) + .await + .unwrap(), + PolicyOutcome::Accepted(Box::new(old)) + ); + let reenable = intent(&tuple, true, 2, false); + let third = apply(&db, &reenable).await; + assert_eq!(third.acceptance.policy_generation, 3); + assert_eq!(third.current_requires_nip_fi, Some(true)); + for request in [&enable, &disable, &reenable] { + let record = db + .community_auth_policy_status(request.tuple.operation_id, &tuple.operator_pubkey) + .await + .unwrap() + .unwrap(); + assert_eq!(record.current_policy_generation, Some(3)); + assert_eq!( + record.acceptance.state, + if request == &reenable { + "pending" + } else { + "superseded" + } + ); + } + for change in 0..5 { + let mut changed = enable.clone(); + match change { + 0 => changed.requires_nip_fi = false, + 1 => changed.expected_policy_generation = 2, + 2 => changed.expected_requires_nip_fi = true, + 3 => changed.tuple.operator_pubkey = "f".repeat(64), + _ => changed.tuple.expected_issuer = "https://different.example".into(), + } + assert_eq!( + db.set_community_nip_fi_policy(&changed, Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("idempotency_conflict") + ); + } + assert_eq!(policy(&db, &tuple).await.policy_generation, 3); + // Reasserting required policy fences an earlier uncommitted disable too. + let stale_disable = intent(&tuple, false, 3, true); + let reassert = intent(&tuple, true, 3, true); + assert_eq!(apply(&db, &reassert).await.acceptance.policy_generation, 4); + assert_eq!( + db.set_community_nip_fi_policy(&stale_disable, Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("policy_conflict") + ); + assert!(policy(&db, &tuple).await.requires_nip_fi); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn policy_same_state_barrier_and_retained_legacy_receipt_identity() { + let (db, tuple, _) = fixture().await; + let stale = intent(&tuple, true, 0, false); + let barrier = intent(&tuple, false, 0, false); + let record = apply(&db, &barrier).await; + assert_eq!(record.acceptance.policy_generation, 1); + assert!(!record.acceptance.requires_nip_fi); + assert_eq!( + db.set_community_nip_fi_policy(&stale, Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("policy_conflict") + ); + let wrong_state = intent(&tuple, true, 1, true); + assert_eq!( + db.set_community_nip_fi_policy(&wrong_state, Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("policy_conflict") + ); + assert_eq!(apply(&db, &barrier).await, record); + let enable = intent(&tuple, true, 1, false); + apply(&db, &enable).await; + // Emulate an acceptance written before migration 0085, without restoring + // an unfenced writer just to create test data. Old INSERTs remain valid. + let legacy_id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO community_auth_upgrades + (operation_id,target_community_id,expected_host,actor_pubkey,expected_owner_pubkey, + expected_issuer,operator_pubkey,policy_generation) VALUES ($1,$2,$3,$4,$4,$5,$6,2)", + ) + .bind(legacy_id) + .bind(tuple.community_id) + .bind(&tuple.expected_host) + .bind(&tuple.actor_pubkey) + .bind(&tuple.expected_issuer) + .bind(&tuple.operator_pubkey) + .execute(db.pool()) + .await + .unwrap(); + let retained = db + .community_auth_policy_status(legacy_id, &tuple.operator_pubkey) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.expected_policy_generation, None); + assert_eq!(retained.expected_requires_nip_fi, None); + assert_eq!(retained.acceptance.state, "pending"); + let mut reuse = intent(&tuple, true, 2, true); + reuse.tuple.operation_id = legacy_id; + assert_eq!( + db.set_community_nip_fi_policy(&reuse, Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("idempotency_conflict") + ); + apply(&db, &intent(&tuple, false, 2, true)).await; + let retained = db + .community_auth_policy_status(legacy_id, &tuple.operator_pubkey) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.acceptance.state, "superseded"); + assert_eq!(retained.current_policy_generation, Some(3)); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn policy_disable_guards_and_issuer_removal_then_reenable() { + let (db, tuple, _) = fixture().await; + accepted(&db, &tuple).await; + let disable = intent(&tuple, false, 1, true); + for kind in 0..4 { + let mut changed = disable.clone(); + let code = match kind { + 0 => { + changed.tuple.actor_pubkey = "a".repeat(64); + "owner_conflict" + } + 1 => { + changed.tuple.expected_host = "wrong.example".into(); + "host_conflict" + } + 2 => { + changed.tuple.expected_owner_pubkey = "b".repeat(64); + "owner_conflict" + } + _ => { + changed.tuple.community_id = Uuid::new_v4(); + "community_not_found" + } + }; + assert_eq!( + db.set_community_nip_fi_policy(&changed, Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused(code) + ); + } + assert_eq!( + db.set_community_nip_fi_policy(&disable, Err("upgrades_disabled")) + .await + .unwrap(), + PolicyOutcome::Refused("upgrades_disabled") + ); + apply(&db, &disable).await; + let community = CommunityId::from_uuid(tuple.community_id); + assert_eq!( + db.unbind_nip_fi_issuer(community, ISSUER, true) + .await + .unwrap(), + crate::NipFiUnbind::Removed + ); + let enable = intent(&tuple, true, 2, false); + assert_eq!( + db.set_community_nip_fi_policy(&enable, Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("issuer_conflict") + ); + // Disable works without a trusted/bound issuer and still advances its barrier. + let next = apply(&db, &intent(&tuple, false, 2, false)).await; + assert_eq!(next.acceptance.policy_generation, 3); + sqlx::query("UPDATE communities SET archived_at = now() WHERE id = $1") + .bind(tuple.community_id) + .execute(&db.pool) + .await + .unwrap(); + assert_eq!( + db.set_community_nip_fi_policy(&intent(&tuple, false, 3, false), Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("lifecycle_conflict") + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn policy_disable_serializes_behind_enable_drain() { + use std::str::FromStr; + let (db, tuple, _) = fixture().await; + let application = format!("policy-drain-{}", Uuid::new_v4().simple()); + let options = sqlx::postgres::PgConnectOptions::from_str(&crate::test_support::database_url()) + .unwrap() + .application_name(&application); + let writer = Db::from_pool( + sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .unwrap(), + ); + let enable = intent(&tuple, true, 0, false); + let task = tokio::spawn(async move { apply(&writer, &enable).await }); + // The lease-lock statement followed by idle-in-transaction identifies the + // production drain while the writer still owns its community row lock. + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + assert!(!task.is_finished(), "missed the production lease drain"); + let draining: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE application_name = $1 AND state = 'idle in transaction' AND query LIKE 'SELECT pg_advisory_xact_lock($1,%')") + .bind(&application).fetch_one(&db.pool).await.unwrap(); + if draining { break; } + tokio::task::yield_now().await; + } + }).await.unwrap(); + let disable = intent(&tuple, false, 0, false); + assert_eq!( + db.set_community_nip_fi_policy(&disable, Ok(())) + .await + .unwrap(), + PolicyOutcome::Refused("policy_conflict") + ); + assert_eq!(task.await.unwrap().acceptance.policy_generation, 1); + assert!(policy(&db, &tuple).await.requires_nip_fi); + assert_eq!( + apply(&db, &intent(&tuple, false, 1, true)) + .await + .acceptance + .policy_generation, + 2 + ); +} diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 3ef4fdfb333..7d4899e9660 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -19,6 +19,8 @@ use uuid::Uuid; use crate::error::{DbError, Result}; use crate::Db; +mod lookup; + /// Default PostgreSQL lease duration for one claimed deletion request. pub const DEFAULT_LEASE_DURATION: Duration = Duration::from_secs(60); /// Durable name of the schema manifest's PostgreSQL component. @@ -42,6 +44,18 @@ pub const OWNER_DELETION_ACKNOWLEDGEMENT_VERSION: i32 = 1; /// against replicas still holding the old key during a rolling deploy. pub const SCHEMA_DESTRUCTION_LOCK_KEY: i64 = 0x62757a7a64656c31; +/// Name of one community's deletion advisory lock; lock it with +/// `hashtextextended($1, 0)`. +/// +/// Deletion takes the lock exclusively and community writers take it shared. +/// The bytes must equal the SQL function +/// `community_deletion_lock_key(uuid)` (`'buzz-community-deletion:' || +/// target::text`) for as long as any relay or database function still uses +/// it, or deletion and writers stop excluding each other. +pub fn community_deletion_lock_key(community: CommunityId) -> String { + format!("buzz-community-deletion:{}", community.as_uuid()) +} + /// Control-plane tables that survive the community data purge. pub const CONTROL_PLANE_TABLES: &[&str] = &[ "community_deletion_approvals", @@ -76,6 +90,7 @@ pub const RELAY_ADMIN_TABLES: &[(&str, &str)] = &[ /// approval and again before PostgreSQL purge. A new tenant table therefore /// blocks deletion until this manifest is intentionally updated. pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ + "nip_fi_profile_heads", "api_tokens", "archived_identities", "artifact_heads", @@ -90,6 +105,8 @@ pub const EXPECTED_SCOPED_TABLES: &[&str] = &[ "events", "git_repo_names", "join_policy_acceptances", + "media_uploaders", + "media_publications", "moderation_actions", "moderation_reports", "parameterized_event_watermarks", @@ -127,6 +144,7 @@ const EXCLUDED_SCOPED_TABLES: &[&str] = &[ /// Foreign-key-safe child-before-parent order for the PostgreSQL purge. pub const PURGE_SCOPED_TABLES: &[&str] = &[ + "nip_fi_profile_heads", "personal_read_frontiers", "personal_read_accounts", "workflow_approvals", @@ -134,6 +152,8 @@ pub const PURGE_SCOPED_TABLES: &[&str] = &[ "workflow_runs", "push_wake_outbox", "join_policy_acceptances", + "media_uploaders", + "media_publications", "moderation_reports", "subscriptions", "api_tokens", @@ -845,22 +865,58 @@ impl DeletionStore { /// Persist a request. Only active non-tombstone communities may be submitted. /// /// `requested_by` is recorded on a new row and is also the convergence key - /// when a `submitted` request already exists. Owner provenance pins an - /// owner-origin request's `requested_by` to its `owner_pubkey`, so taking - /// one over manually means passing that owner pubkey; the operator's own - /// pubkey conflicts with the existing request instead of converging. + /// when a `submitted` request already exists. With `expected_community`, + /// admission is create-only and pinned to that ID (and host, if supplied); + /// existing requests, including aborted ones, are left for the caller to read. + /// Owner provenance pins an owner-origin request's `requested_by` to its + /// `owner_pubkey`. Manual takeover must pass that owner pubkey; the operator's + /// own pubkey conflicts with the existing request instead of converging. pub async fn submit( &self, - community_host: &str, + community_host: Option<&str>, requested_by: &str, reason: Option<&str>, + expected_community: Option, ) -> Result { + if community_host.is_none() && expected_community.is_none() { + return Err(DbError::DeletionSafety( + "community host or ID is required".into(), + )); + } + let mut tx = self.pool.begin().await?; + // Keep resolution and admission together, including when a caller pins + // the immutable ID. NO KEY UPDATE permits the legacy request FK check. + let target: Option = sqlx::query_scalar( + "SELECT id FROM communities + WHERE ($1::text IS NULL OR lower(host) = lower($1)) + AND ($2::uuid IS NULL OR id = $2) + FOR NO KEY UPDATE", + ) + .bind(community_host) + .bind(expected_community.map(|id| *id.as_uuid())) + .fetch_optional(&mut *tx) + .await?; + if expected_community.is_some() { + // Parent workflows only create when absent. In particular, never + // replace an aborted child. The caller can read the existing row. + let exists: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM community_deletion_requests WHERE community_id = $1)", + ) + .bind(target) + .fetch_one(&mut *tx) + .await?; + if exists { + return Err(DbError::DeletionSafety( + "community deletion already requested".into(), + )); + } + } let row = sqlx::query( r#" WITH target AS ( SELECT id, host FROM communities - WHERE lower(host) = lower($1) + WHERE id = $1 AND deletion_state = 'active' AND deleted_at IS NULL ), inserted AS ( @@ -881,15 +937,21 @@ impl DeletionStore { LIMIT 1 "#, ) - .bind(community_host) + .bind(target) .bind(requested_by) .bind(reason) - .fetch_optional(&self.pool) + .fetch_optional(&mut *tx) .await?; + tx.commit().await?; + let target_label = community_host.map(str::to_owned).unwrap_or_else(|| { + expected_community + .map(|id| id.as_uuid().to_string()) + .unwrap_or_default() + }); match row { Some(row) => row_to_request(row), None => Err(DbError::DeletionSafety(format!( - "community {community_host:?} is missing, already requested, fenced, or tombstoned" + "community {target_label} is missing, already requested, fenced, or tombstoned" ))), } } @@ -1191,9 +1253,8 @@ impl DeletionStore { ))); } - let required_objects_present: bool = sqlx::query_scalar( - "SELECT to_regprocedure('community_deletion_lock_key(uuid)') IS NOT NULL \ - AND EXISTS (SELECT 1 FROM pg_trigger t \ + let tombstone_trigger_present: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_trigger t \ JOIN pg_class c ON c.oid = t.tgrelid \ JOIN pg_proc p ON p.oid = t.tgfoid \ WHERE c.relname = 'communities' \ @@ -1202,9 +1263,9 @@ impl DeletionStore { ) .fetch_one(&mut *conn) .await?; - if !required_objects_present { + if !tombstone_trigger_present { return Err(DbError::DeletionSafety( - "community deletion lock function or tombstone trigger is missing".to_string(), + "community tombstone trigger is missing".to_string(), )); } Ok(()) @@ -3320,8 +3381,8 @@ async fn lock_community_deletion( ) -> Result<()> { crate::observability::observe_advisory_lock( crate::observability::LockType::Deletion, - sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community.as_uuid()) + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(community_deletion_lock_key(community)) .execute(&mut **tx), ) .await?; @@ -3373,10 +3434,10 @@ pub(crate) async fn lock_community_deletion_shared( let (_, isolation): ((), String) = crate::observability::observe_advisory_lock( crate::observability::LockType::Deletion, sqlx::query_as( - "SELECT pg_advisory_xact_lock_shared(community_deletion_lock_key($1)), \ + "SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0)), \ current_setting('transaction_isolation')", ) - .bind(community.as_uuid()) + .bind(community_deletion_lock_key(community)) .fetch_one(&mut **tx), ) .await?; @@ -4393,6 +4454,7 @@ pub(crate) mod owner_provenance_contract { #[cfg(test)] mod postgres_tests { use super::*; + use crate::test_support::ScratchDb; use crate::{ relay_members::{ProvisionOwnerResult, TransferResult}, CreateCommunityWithOwnerResult, Db, DbConfig, UnarchiveCommunityResult, @@ -4400,6 +4462,116 @@ mod postgres_tests { use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; use std::str::FromStr; + #[tokio::test] + #[ignore = "requires Postgres"] + async fn user_fences_survive_community_and_profile_deletion() { + assert_user_fence_retention().await; + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn migration_schema_user_fences_survive_community_and_profile_deletion() { + assert_user_fence_retention().await; + } + + async fn assert_user_fence_retention() { + use crate::user_deletion_fences::{self as fences, FenceIdentity}; + let (db, store) = store().await; + let (request, inventory) = inventoried_request(&db, &store).await; + let entity = db + .user_deletion_store() + .submit("demo:fence-retention", "operator", None) + .await + .unwrap(); + let entities = db.entity_deletion_store(); + entities + .approve( + entity.id, + "approver", + entity.inventory_digest.as_deref().unwrap(), + ) + .await + .unwrap(); + let entity_lease = entities + .claim(entity.id, "fence-worker", Duration::from_secs(300)) + .await + .unwrap() + .unwrap(); + let human_key = nostr::Keys::generate().public_key(); + let agent_key = nostr::Keys::generate().public_key(); + let human = FenceIdentity::user(human_key); + let agent = FenceIdentity::agent(request.community_id, agent_key); + sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2)") + .bind(request.community_id.as_uuid()) + .bind(human_key.to_bytes().to_vec()) + .execute(&db.pool) + .await + .unwrap(); + let mut tx = db.pool.begin().await.unwrap(); + fences::lock_request(&mut tx, &entity_lease).await.unwrap(); + fences::lock_exclusive(&mut tx, &[human, agent]) + .await + .unwrap(); + let global = fences::insert(&mut tx, human, &entity_lease, None) + .await + .unwrap(); + let scoped = fences::insert(&mut tx, agent, &entity_lease, Some(human_key)) + .await + .unwrap(); + tx.commit().await.unwrap(); + sqlx::query("DELETE FROM users WHERE community_id = $1 AND pubkey = $2") + .bind(request.community_id.as_uuid()) + .bind(human_key.to_bytes().to_vec()) + .execute(&db.pool) + .await + .unwrap(); + let mut tx = db.pool.begin().await.unwrap(); + assert_eq!( + fences::find(&mut tx, human).await.unwrap(), + Some(global.clone()) + ); + tx.commit().await.unwrap(); + + store.approve(request.id, "approver", None).await.unwrap(); + let claim = store + .claim_specific(request.id, "executor", DEFAULT_LEASE_DURATION) + .await + .unwrap() + .unwrap(); + store.begin_quiescing(&claim.lease).await.unwrap(); + let generation = store.fence(&claim.lease).await.unwrap(); + let token = LeaseToken { + fence_generation: Some(generation), + ..claim.lease + }; + store + .freeze_destructive_storage_manifest(&token, &inventory.storage) + .await + .unwrap(); + store.mark_drained(&token).await.unwrap(); + store + .mark_bindings_removed(&token, serde_json::json!({"keys": 0})) + .await + .unwrap(); + store.purge_postgres(&token).await.unwrap(); + // This database-only fixture models the external cache adapter's + // completion before exercising PostgreSQL's logical-absence verifier. + store + .mark_cache_purged(&token, serde_json::json!({"test_cache": "empty"})) + .await + .unwrap(); + store + .verify_postgres_logically_deleted(&token) + .await + .unwrap(); + // Full row equality also proves that scoped restrictions were not + // widened to global ones by clearing scope_community_id. + let mut tx = db.pool.begin().await.unwrap(); + assert_eq!(fences::find(&mut tx, human).await.unwrap(), Some(global)); + assert_eq!(fences::find(&mut tx, agent).await.unwrap(), Some(scoped)); + tx.commit().await.unwrap(); + } + async fn store() -> (Db, DeletionStore) { let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") .or_else(|_| std::env::var("DATABASE_URL")) @@ -4434,6 +4606,12 @@ mod postgres_tests { .await .expect("migrate with fence objects present"); let store = db.deletion_store(); + let legacy_fenced_tables = store.live_fenced_tables().await.expect("legacy fences"); + // Include current tables without requiring new application-admitted + // tables to acquire legacy database fence triggers. + db.migrate() + .await + .expect("migrate current deletion catalog"); let community = db .ensure_configured_community("optional-fences.example") .await @@ -4483,11 +4661,12 @@ DROP FUNCTION enforce_community_write_fence(); DROP FUNCTION assert_community_write_allowed(UUID); DROP FUNCTION community_write_allowed(UUID); DROP FUNCTION community_write_fence_excluded_table(NAME); +DROP FUNCTION community_deletion_lock_key(UUID); "#) .execute(&db.pool) .await - .expect("retire only universal fence objects"); + .expect("retire universal fence objects and the lock-key function"); } store .validate_serving_catalog() @@ -4502,11 +4681,11 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); let inventory = store.inventory_schema(community).await.expect("inventory"); assert_eq!(inventory.scoped_tables.len(), EXPECTED_SCOPED_TABLES.len()); assert_eq!( - inventory.fenced_tables.len(), + inventory.fenced_tables.into_iter().collect::>(), if objects_present { - EXPECTED_SCOPED_TABLES.len() + legacy_fenced_tables.clone() } else { - 0 + BTreeSet::new() } ); let lease = store @@ -4522,6 +4701,14 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .release_serving_write_lease(&lease) .await .expect("release lease"); + db.bind_nip_fi_issuers_to_active(&[community], &["https://issuer.example".to_string()]) + .await + .expect("bulk bind takes the shared deletion locks"); + let mut deletion = db.pool.begin().await.expect("begin deletion"); + lock_community_deletion(&mut deletion, community) + .await + .expect("exclusive deletion lock"); + deletion.rollback().await.expect("release deletion lock"); for state in ["quiescing", "fenced", "tombstone"] { crate::test_support::set_deletion_state(&db.pool, *community.as_uuid(), state) .await; @@ -4555,6 +4742,27 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); } } + /// Mixed-version fleets lock through both the Rust key and the SQL + /// function until the function is dropped; they must name the same lock. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn community_deletion_lock_key_matches_the_sql_function() { + let (db, _) = store().await; + let mut communities = vec![Uuid::nil(), Uuid::max()]; + communities.extend((0..64).map(|_| Uuid::new_v4())); + for id in communities { + let community = CommunityId::from_uuid(id); + let (rust_lock, sql_lock): (i64, i64) = + sqlx::query_as("SELECT hashtextextended($1, 0), community_deletion_lock_key($2)") + .bind(community_deletion_lock_key(community)) + .bind(id) + .fetch_one(&db.pool) + .await + .expect("hash lock keys"); + assert_eq!(rust_lock, sql_lock, "lock key drifted for {id}"); + } + } + fn empty_prefix_manifest(prefix: String) -> PrefixManifest { PrefixManifest { prefix, @@ -4585,7 +4793,7 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .await .expect("create community"); let submitted = store - .submit(&host, "test-operator", Some("test deletion")) + .submit(Some(&host), "test-operator", Some("test deletion"), None) .await .expect("submit"); assert_eq!(submitted.community_id, community.id); @@ -4876,9 +5084,9 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); "SELECT count(*) FROM pg_locks \ WHERE locktype = 'advisory' AND objsubid = 1 AND NOT granted \ AND ((classid::bigint << 32) | objid::bigint) \ - = community_deletion_lock_key($1)", + = hashtextextended($1, 0)", ) - .bind(community.as_uuid()) + .bind(community_deletion_lock_key(community)) .fetch_one(&db.pool) .await .expect("inspect community lock queue"); @@ -5704,7 +5912,7 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .await .expect("create operator community"); let operator_request = store - .submit(&operator_host, "manual-operator", None) + .submit(Some(&operator_host), "manual-operator", None, None) .await .expect("submit manual request"); @@ -6732,8 +6940,8 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("claim") .expect("won claim"); let mut gate = db.pool.begin().await.expect("begin lock gate"); - sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(request.community_id.as_uuid()) + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(community_deletion_lock_key(request.community_id)) .execute(&mut *gate) .await .expect("hold community lock"); @@ -6843,8 +7051,8 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("won claim"); store.begin_quiescing(&claim.lease).await.expect("quiesce"); let mut gate = db.pool.begin().await.expect("begin lock gate"); - sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(request.community_id.as_uuid()) + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(community_deletion_lock_key(request.community_id)) .execute(&mut *gate) .await .expect("hold community lock"); @@ -6909,9 +7117,10 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); let replacement = store .submit( - &request.community_host, + Some(&request.community_host), "second-operator", Some("fresh review"), + None, ) .await .expect("submit replacement request"); @@ -7126,13 +7335,12 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("open writer transaction with community lock"); let mut shared_contender = db.pool.begin().await.expect("begin shared contender"); - let shared_taken: bool = sqlx::query_scalar( - "SELECT pg_try_advisory_xact_lock_shared(community_deletion_lock_key($1))", - ) - .bind(community.as_uuid()) - .fetch_one(&mut *shared_contender) - .await - .expect("try shared deletion lock"); + let shared_taken: bool = + sqlx::query_scalar("SELECT pg_try_advisory_xact_lock_shared(hashtextextended($1, 0))") + .bind(community_deletion_lock_key(community)) + .fetch_one(&mut *shared_contender) + .await + .expect("try shared deletion lock"); assert!( shared_taken, "compliant writer must allow another shared community deletion lock holder" @@ -7144,8 +7352,8 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); let mut deleter = db.pool.begin().await.expect("begin deletion contender"); let exclusive_taken: bool = - sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community.as_uuid()) + sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))") + .bind(community_deletion_lock_key(community)) .fetch_one(&mut *deleter) .await .expect("try deletion exclusive lock"); @@ -7439,25 +7647,19 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); /// A scratch database bootstrapped from the desired-state schema, for /// tests that alter shared objects (locks, session caps) and must not - /// disturb the shared test database. Returns the admin pool, the scratch - /// database name and its URL; drop with [`drop_scratch_database`]. - async fn scratch_desired_state_database(prefix: &str) -> (PgPool, String, String) { + /// disturb the shared test database. Returns the admin pool and the + /// scratch database guard, which drops the database. + async fn scratch_desired_state_database(prefix: &str) -> (PgPool, ScratchDb) { let base_url = std::env::var("BUZZ_TEST_DATABASE_URL") .or_else(|_| std::env::var("DATABASE_URL")) .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); let admin = PgPool::connect(&base_url) .await .expect("connect admin database"); - let probe_db = format!("{prefix}_{}", Uuid::new_v4().simple()); - sqlx::query(AssertSqlSafe(format!("CREATE DATABASE {probe_db}"))) - .execute(&admin) - .await - .expect("create probe database"); - let (base_prefix, _) = base_url.rsplit_once('/').expect("database url has a path"); - let probe_url = format!("{base_prefix}/{probe_db}"); + let probe_db = ScratchDb::create(&base_url, prefix).await; let schema_sql = crate::test_support::desired_state_schema_sql(); - let bootstrap = PgPool::connect(&probe_url) + let bootstrap = PgPool::connect(probe_db.url()) .await .expect("connect probe database"); sqlx::raw_sql(AssertSqlSafe(schema_sql)) @@ -7465,16 +7667,7 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .await .expect("apply desired-state schema"); bootstrap.close().await; - (admin, probe_db, probe_url) - } - - async fn drop_scratch_database(admin: &PgPool, probe_db: &str) { - sqlx::query(AssertSqlSafe(format!( - "DROP DATABASE {probe_db} WITH (FORCE)" - ))) - .execute(admin) - .await - .expect("drop probe database"); + (admin, probe_db) } /// Run `op` while another session holds `ACCESS EXCLUSIVE` on `events` @@ -7531,10 +7724,9 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); #[tokio::test] #[ignore = "requires Postgres"] async fn deletion_whole_tenant_stages_outlive_the_writer_statement_timeout() { - let (admin, probe_db, probe_url) = - scratch_desired_state_database("buzz_deletion_cap").await; + let (admin, probe_db) = scratch_desired_state_database("buzz_deletion_cap").await; let db = Db::new(&DbConfig { - database_url: probe_url, + database_url: probe_db.url().to_owned(), max_connections: 5, min_connections: 0, statement_timeout_ms: 500, @@ -7572,13 +7764,13 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .await .expect("create community"); let submitted = store - .submit(&host, "test-operator", Some("test deletion")) + .submit(Some(&host), "test-operator", Some("test deletion"), None) .await .expect("submit"); let schema = run_behind_events_lock_past_cap( &db, &admin, - &probe_db, + probe_db.name(), store.inventory_schema(community.id), ) .await @@ -7615,7 +7807,7 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .mark_bindings_removed(&token, serde_json::json!({"keys": 0})) .await .expect("bindings"); - run_behind_events_lock_past_cap(&db, &admin, &probe_db, store.purge_postgres(&token)) + run_behind_events_lock_past_cap(&db, &admin, probe_db.name(), store.purge_postgres(&token)) .await .expect("purge outlives the writer cap"); assert_eq!( @@ -7629,7 +7821,7 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); run_behind_events_lock_past_cap( &db, &admin, - &probe_db, + probe_db.name(), store.verify_postgres_logically_deleted(&token), ) .await @@ -7642,9 +7834,6 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("show restored"); assert_eq!(restored, "500ms", "the lift is transaction-local"); } - - db.pool.close().await; - drop_scratch_database(&admin, &probe_db).await; } #[tokio::test] @@ -7664,8 +7853,8 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("active community") .id; let mut fence_tx = db.pool.begin().await.expect("begin fence transaction"); - sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community.as_uuid()) + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(community_deletion_lock_key(community)) .execute(&mut *fence_tx) .await .expect("hold exclusive deletion lock"); @@ -7944,6 +8133,13 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .execute(&db.pool) .await .expect("insert guarded NIP-RS row"); + let media_hash = "a".repeat(64); + db.record_media_upload(request.community_id, &media_hash, &[7; 32]) + .await + .expect("upload proof"); + db.record_media_publications(request.community_id, vec![media_hash.clone()]) + .await + .expect("publication boundary"); store .approve(request.id, "approver", None) .await @@ -7954,6 +8150,14 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("claim") .expect("won claim"); store.begin_quiescing(&claim.lease).await.expect("quiesce"); + assert!(db + .record_media_upload(request.community_id, &media_hash, &[8; 32]) + .await + .is_err()); + assert!(db + .record_media_publications(request.community_id, vec!["b".repeat(64)]) + .await + .is_err()); let generation = store.fence(&claim.lease).await.expect("fence"); let token = LeaseToken { fence_generation: Some(generation), @@ -8009,6 +8213,8 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .await .expect("bindings"); let first = store.purge_postgres(&token).await.expect("purge postgres"); + assert_eq!(first["media_uploaders"], 1); + assert_eq!(first["media_publications"], 1); let expected_tables: BTreeSet<&str> = EXPECTED_SCOPED_TABLES .iter() .chain(RELAY_ADMIN_TABLES.iter().map(|(table, _)| table)) @@ -8099,6 +8305,7 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); #[ignore = "requires Postgres"] async fn manifest_key_chunks_bind_freeze_execution_and_cleanup() { let (db, store) = store().await; + crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; let (request, inventory) = inventoried_request(&db, &store).await; store .approve(request.id, "approver", None) @@ -8252,6 +8459,138 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); ); } + /// The whole-community purge is the only supported hard delete of channels, + /// personal-read accounts, and users. With every FK action retired, each + /// child must still be deleted explicitly (the quiesce barrier itself is + /// pinned by `begin_quiescing_waits_for_open_admitted_writer_note_update`). + #[tokio::test] + #[ignore = "requires Postgres"] + async fn purge_removes_fk_children_explicitly_without_fk_actions() { + let (db, store) = store().await; + crate::test_support::retire_foreign_key_delete_actions(&db.pool).await; + let (request, inventory) = inventoried_request(&db, &store).await; + let community = request.community_id; + let owner = vec![7_u8; 32]; + let agent = vec![8_u8; 32]; + let channel = Uuid::new_v4(); + let feedback_id = Uuid::new_v4(); + sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(&owner) + .execute(&db.pool) + .await + .expect("seed owner"); + sqlx::query( + "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) VALUES ($1, $2, $3)", + ) + .bind(community.as_uuid()) + .bind(&agent) + .bind(&owner) + .execute(&db.pool) + .await + .expect("seed agent owned by user"); + sqlx::query( + "INSERT INTO channels (community_id, id, name, created_by) VALUES ($1, $2, 'purge', $3)", + ) + .bind(community.as_uuid()) + .bind(channel) + .bind(&owner) + .execute(&db.pool) + .await + .expect("seed channel"); + sqlx::query("INSERT INTO personal_read_accounts (community_id, actor) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(&owner) + .execute(&db.pool) + .await + .expect("seed read account"); + sqlx::query( + "INSERT INTO product_feedback \ + (id, community_id, event_id, submitter_pubkey, body, event_created_at) \ + VALUES ($1, $2, $3, $4, 'feedback survives', now())", + ) + .bind(feedback_id) + .bind(community.as_uuid()) + .bind(vec![9_u8; 32]) + .bind(&owner) + .execute(&db.pool) + .await + .expect("seed operator feedback"); + + store + .approve(request.id, "approver", None) + .await + .expect("approve"); + let claim = store + .claim_specific(request.id, "executor", DEFAULT_LEASE_DURATION) + .await + .expect("claim") + .expect("won claim"); + let mut writer = db + .begin_event_write_transaction(community) + .await + .expect("admit child seed"); + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey) VALUES ($1, $2, $3)", + ) + .bind(community.as_uuid()) + .bind(channel) + .bind(&owner) + .execute(writer.conn()) + .await + .expect("seed channel member"); + sqlx::query( + "INSERT INTO personal_read_frontiers \ + (community_id, actor, channel_id, through_timestamp) VALUES ($1, $2, $3, now())", + ) + .bind(community.as_uuid()) + .bind(&owner) + .bind(channel) + .execute(writer.conn()) + .await + .expect("seed read frontier"); + writer.commit().await.expect("commit seeded children"); + store.begin_quiescing(&claim.lease).await.expect("quiesce"); + + let generation = store.fence(&claim.lease).await.expect("fence"); + let token = LeaseToken { + fence_generation: Some(generation), + ..claim.lease + }; + store + .freeze_destructive_storage_manifest(&token, &inventory.storage) + .await + .expect("freeze destructive storage"); + store.mark_drained(&token).await.expect("drain"); + store + .mark_bindings_removed(&token, serde_json::json!({"keys": 0})) + .await + .expect("bindings removed"); + let deleted = store + .purge_postgres(&token) + .await + .expect("purge without FK actions"); + for table in [ + "channel_members", + "personal_read_frontiers", + "personal_read_accounts", + "channels", + ] { + assert_eq!(deleted.get(table), Some(&1), "{table} explicitly removed"); + } + assert_eq!(deleted.get("users"), Some(&2), "owner and agent removed"); + let provenance: Option = + sqlx::query_scalar("SELECT community_id FROM product_feedback WHERE id = $1") + .bind(feedback_id) + .fetch_one(&db.pool) + .await + .expect("feedback remains"); + assert_eq!( + provenance, None, + "operator feedback loses tenant provenance" + ); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn destructive_stages_serialize_with_migrations_and_fail_closed_on_new_scoped_tables() { @@ -8263,17 +8602,9 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); let base_url = std::env::var("BUZZ_TEST_DATABASE_URL") .or_else(|_| std::env::var("DATABASE_URL")) .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); - let admin = PgPool::connect(&base_url) - .await - .expect("connect admin database"); - let probe_db = format!("buzz_lock_probe_{}", Uuid::new_v4().simple()); - sqlx::query(AssertSqlSafe(format!("CREATE DATABASE {probe_db}"))) - .execute(&admin) - .await - .expect("create probe database"); - let (base_prefix, _) = base_url.rsplit_once('/').expect("database url has a path"); + let probe_db = ScratchDb::create(&base_url, "buzz_lock_probe").await; let db = Db::new(&DbConfig { - database_url: format!("{base_prefix}/{probe_db}"), + database_url: probe_db.url().to_owned(), max_connections: 5, min_connections: 0, ..DbConfig::default() @@ -8423,14 +8754,6 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .mark_retention_pending(&token, serde_json::json!({"probe": "clean"})) .await .expect("terminal"); - - db.pool.close().await; - sqlx::query(AssertSqlSafe(format!( - "DROP DATABASE {probe_db} WITH (FORCE)" - ))) - .execute(&admin) - .await - .expect("drop probe database"); } /// Seed one report-backed and one direct staff action, each with an outbox @@ -8528,6 +8851,21 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .await .unwrap() .approvals; + // Upgrade receipts are operator recovery evidence, intentionally retained + // through purge so their UUID cannot be rebound to another community. + let upgrade_id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO community_auth_upgrades + (operation_id, target_community_id, expected_host, actor_pubkey, + expected_owner_pubkey, expected_issuer, operator_pubkey, policy_generation) + VALUES ($1,$2,$3,'owner','owner','https://issuer.example','operator',1)", + ) + .bind(upgrade_id) + .bind(community) + .bind(&request.community_host) + .execute(&db.pool) + .await + .unwrap(); let history_id: Uuid = sqlx::query_scalar( "INSERT INTO entity_deletion_stage_history (request_id, target_community_id, stage, is_current) @@ -8571,6 +8909,13 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("bindings"); let deleted = store.purge_postgres(&token).await.expect("purge postgres"); + let upgrade = db + .community_auth_policy_status(upgrade_id, "operator") + .await + .unwrap() + .expect("receipt survives purge"); + assert_eq!(upgrade.acceptance.community_id, community); + assert_eq!(upgrade.acceptance.state, "unavailable"); let retained: Uuid = sqlx::query_scalar( "SELECT target_community_id FROM entity_deletion_stage_history WHERE id = $1", ) @@ -8645,11 +8990,10 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); #[tokio::test] #[ignore = "requires Postgres"] async fn desired_state_schema_bootstrap_progresses_beyond_fencing() { - let (admin, probe_db, probe_url) = - scratch_desired_state_database("buzz_desired_state").await; + let (_, probe_db) = scratch_desired_state_database("buzz_desired_state").await; let db = Db::new(&DbConfig { - database_url: probe_url, + database_url: probe_db.url().to_owned(), max_connections: 5, min_connections: 0, ..DbConfig::default() @@ -8724,8 +9068,5 @@ DROP FUNCTION community_write_fence_excluded_table(NAME); .expect("terminal"); let terminal = store.get(request.id).await.expect("terminal request"); assert_eq!(terminal.stage, DeletionStage::RetentionPending); - - db.pool.close().await; - drop_scratch_database(&admin, &probe_db).await; } } diff --git a/crates/buzz-db/src/store/deletion/lookup.rs b/crates/buzz-db/src/store/deletion/lookup.rs new file mode 100644 index 00000000000..391877b841e --- /dev/null +++ b/crates/buzz-db/src/store/deletion/lookup.rs @@ -0,0 +1,21 @@ +//! Community-ID lookup for parent deletion workflows. + +use super::*; + +impl DeletionStore { + /// Find the current request, including terminal requests. If only aborted + /// requests exist, return the latest one; callers must not silently recreate it. + pub async fn find_for_community( + &self, + community: CommunityId, + ) -> Result> { + let row = sqlx::query( + "SELECT * FROM community_deletion_requests WHERE community_id = $1 + ORDER BY (stage = 'aborted'), created_at DESC, id DESC LIMIT 1", + ) + .bind(community.as_uuid()) + .fetch_optional(&self.pool) + .await?; + row.map(row_to_request).transpose() + } +} diff --git a/crates/buzz-db/src/store/dm.rs b/crates/buzz-db/src/store/dm.rs index 0c86e13f050..ebdbc45d271 100644 --- a/crates/buzz-db/src/store/dm.rs +++ b/crates/buzz-db/src/store/dm.rs @@ -76,7 +76,7 @@ pub async fn find_dm_by_participants( created_by, created_at, updated_at, archived_at, deleted_at, nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, - purpose, purpose_set_by, purpose_set_at, labels, join_role, unlisted + purpose, purpose_set_by, purpose_set_at, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND participant_hash = $2 @@ -142,7 +142,7 @@ pub async fn create_dm( created_by, created_at, updated_at, archived_at, deleted_at, nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, - purpose, purpose_set_by, purpose_set_at, labels, join_role, unlisted + purpose, purpose_set_by, purpose_set_at, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND participant_hash = $2 @@ -192,6 +192,7 @@ pub async fn create_dm( INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) VALUES ($1, $2, $3, 'member', $4) ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET + sync_modified_at = CASE WHEN channel_members.removed_at IS NOT NULL THEN clock_timestamp() ELSE channel_members.sync_modified_at END, removed_at = NULL, removed_by = NULL, role = EXCLUDED.role @@ -212,7 +213,7 @@ pub async fn create_dm( created_by, created_at, updated_at, archived_at, deleted_at, nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, - purpose, purpose_set_by, purpose_set_at, labels, join_role, unlisted + purpose, purpose_set_by, purpose_set_at, labels, join_role, unlisted, auto_join FROM channels WHERE community_id = $1 AND id = $2 "#, ) @@ -535,6 +536,7 @@ fn row_to_channel_record(row: sqlx::postgres::PgRow) -> Result { labels: row.try_get("labels")?, join_role: row.try_get("join_role")?, unlisted: row.try_get("unlisted")?, + auto_join: row.try_get("auto_join")?, }) } diff --git a/crates/buzz-db/src/store/entity_deletion/leases.rs b/crates/buzz-db/src/store/entity_deletion/leases.rs index 92fcc0b789a..add97324d96 100644 --- a/crates/buzz-db/src/store/entity_deletion/leases.rs +++ b/crates/buzz-db/src/store/entity_deletion/leases.rs @@ -101,23 +101,40 @@ impl EntityDeletionStore { })) } - /// Renew an unexpired lease. An expired or superseded worker cannot revive it. + /// Renew this lease. A superseded lease is never renewed; an expired lease + /// can be renewed only while nobody has reclaimed it. + /// + /// One autocommit statement: the worker drops this future whenever its + /// stage handler finishes first, so the renewal leaves no transaction + /// to roll back. pub async fn heartbeat(&self, lease: &EntityLease, duration: Duration) -> Result<()> { let millis = duration_millis(duration)?; - let mut tx = self.pool.begin().await?; - lock_owned(&mut tx, lease).await?; - sqlx::query( + // `lock_owned`'s predicate. After a row-lock wait, Postgres re-checks it + // only if the holder committed an update of this row, so a reclaim's new + // generation always wins. A holder that only locked the row (e.g. + // `save_stage_success`) or rolled back leaves the pre-wait expiry check + // in force, so a heartbeat that waits past expiry still renews. No one + // can reclaim in that window: `claim` skips locked rows. + let renewed = sqlx::query( "UPDATE entity_deletion_requests - SET lease_expires_at = clock_timestamp() + $2 * interval '1 millisecond', + SET lease_expires_at = clock_timestamp() + $4 * interval '1 millisecond', heartbeat_at = clock_timestamp() - WHERE id = $1", + WHERE id = $1 AND lease_owner = $2 AND lease_generation = $3 + AND status IN ('approved', 'running', 'retry_wait', 'completed') + AND lease_expires_at > clock_timestamp()", ) .bind(lease.request_id) + .bind(&lease.owner) + .bind(lease.generation) .bind(millis) - .execute(&mut *tx) - .await?; - tx.commit().await?; - Ok(()) + .execute(&self.pool) + .await? + .rows_affected(); + if renewed == 1 { + Ok(()) + } else { + Err(stale_lease(lease)) + } } /// Release this live claim after a pause or shutdown, without advancing its stage. @@ -140,7 +157,10 @@ impl EntityDeletionStore { } } -pub(super) async fn lock_owned(tx: &mut Tx<'_>, lease: &EntityLease) -> Result { +pub(in crate::store) async fn lock_owned( + tx: &mut Tx<'_>, + lease: &EntityLease, +) -> Result { // Lock by id first, then check expiry after any wait for that lock. An old // snapshot/transaction start time must not extend a worker's authority. let request: EntityRequest = sqlx::query_as(sqlx::AssertSqlSafe(format!( @@ -167,7 +187,7 @@ pub(super) async fn lock_owned(tx: &mut Tx<'_>, lease: &EntityLease) -> Result, request: &EntityRequest, ) -> Result<()> { diff --git a/crates/buzz-db/src/store/entity_deletion/mod.rs b/crates/buzz-db/src/store/entity_deletion/mod.rs index e78c5d719c5..56b058af032 100644 --- a/crates/buzz-db/src/store/entity_deletion/mod.rs +++ b/crates/buzz-db/src/store/entity_deletion/mod.rs @@ -22,9 +22,11 @@ impl Db { mod approvals; mod leases; +mod observations; pub(crate) mod requests; mod stages; pub use approvals::EntityApproval; +pub(super) use leases::{lock_owned, validate_approved_inventory}; pub use leases::{EntityExecution, EntityLease}; pub use requests::{inventory_digest, EntityInspection, EntityRequest}; use requests::{validate_operator, validated_inventory_digest}; diff --git a/crates/buzz-db/src/store/entity_deletion/observations.rs b/crates/buzz-db/src/store/entity_deletion/observations.rs new file mode 100644 index 00000000000..df8a16e2fcc --- /dev/null +++ b/crates/buzz-db/src/store/entity_deletion/observations.rs @@ -0,0 +1,48 @@ +//! Fenced persistence of a handler waiting for external work. + +use super::leases::{lock_owned, validate_approved_inventory}; +use super::stages::require_running_stage; +use super::*; + +impl EntityDeletionStore { + /// Save an external dependency observation without completing or advancing + /// the stage. Waiting is represented by `metadata_json.waiting`; the existing + /// stage status remains `running`. It does not schedule a retry or count a + /// failure. Future workflow routing must explicitly handle this outcome. + pub async fn save_stage_waiting( + &self, + lease: &EntityLease, + stage_id: Uuid, + observation: serde_json::Value, + ) -> Result<()> { + if !observation.is_object() { + return Err(DbError::DeletionSafety( + "external observation must be an object".into(), + )); + } + let mut tx = self.pool.begin().await?; + let request = lock_owned(&mut tx, lease).await?; + validate_approved_inventory(&mut tx, &request).await?; + require_running_stage(&mut tx, lease, stage_id).await?; + sqlx::query( + "UPDATE entity_deletion_stage_history + SET metadata_json = jsonb_set(metadata_json - 'result', '{waiting}', + $2 || jsonb_build_object('observed_at', clock_timestamp())), + last_error = NULL, updated_at = clock_timestamp() + WHERE id = $1", + ) + .bind(stage_id) + .bind(observation) + .execute(&mut *tx) + .await?; + sqlx::query( + "UPDATE entity_deletion_requests SET last_error = NULL, + next_attempt_at = NULL, updated_at = clock_timestamp() WHERE id = $1", + ) + .bind(lease.request_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(()) + } +} diff --git a/crates/buzz-db/src/store/entity_deletion/stages.rs b/crates/buzz-db/src/store/entity_deletion/stages.rs index d31be5d12b2..8d3d9edc35e 100644 --- a/crates/buzz-db/src/store/entity_deletion/stages.rs +++ b/crates/buzz-db/src/store/entity_deletion/stages.rs @@ -125,7 +125,7 @@ impl EntityDeletionStore { sqlx::query( "UPDATE entity_deletion_stage_history SET status = 'completed', finished_at = clock_timestamp(), last_error = NULL, - metadata_json = jsonb_set(metadata_json, '{result}', $2), + metadata_json = jsonb_set(metadata_json - 'waiting', '{result}', $2), updated_at = clock_timestamp() WHERE id = $1", ) .bind(stage_id) diff --git a/crates/buzz-db/src/store/entity_deletion_postgres_tests.rs b/crates/buzz-db/src/store/entity_deletion_postgres_tests.rs index c93c460ce69..787cd24e5b5 100644 --- a/crates/buzz-db/src/store/entity_deletion_postgres_tests.rs +++ b/crates/buzz-db/src/store/entity_deletion_postgres_tests.rs @@ -1,4 +1,5 @@ use super::*; +use std::time::Duration; async fn store() -> EntityDeletionStore { EntityDeletionStore { @@ -446,6 +447,85 @@ async fn approval_refuses_to_repair_missing_evidence() { ); } +#[tokio::test] +#[ignore = "requires Postgres"] +async fn dropped_heartbeat_leaves_no_open_transaction_for_the_release() { + let store = store().await; + let request = users(&store) + .submit("demo:dropped-heartbeat", "operator-a", None) + .await + .unwrap(); + store + .approve( + request.id, + "operator-b", + request.inventory_digest.as_deref().unwrap(), + ) + .await + .unwrap(); + let lease = store + .claim(request.id, "worker", Duration::from_secs(60)) + .await + .unwrap() + .expect("claim approved request"); + + let direct = store.pool.connect_options(); + let proxy = + crate::test_support::PausingProxy::spawn(direct.get_host().to_owned(), direct.get_port()) + .await; + // One connection, so the release reuses the heartbeat's. No acquire ping, + // so the heartbeat's first statement is the one in flight when it drops. + let proxied = EntityDeletionStore { + pool: sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .test_before_acquire(false) + .connect_with((*direct).clone().host("127.0.0.1").port(proxy.port)) + .await + .expect("connect through proxy"), + }; + sqlx::query("SELECT 1") + .execute(&proxied.pool) + .await + .expect("warm proxied connection"); + // sqlx returns the connection from a spawned task after a ping; pausing + // before it lands would stall the heartbeat in `acquire` instead. + tokio::time::timeout(Duration::from_secs(5), async { + while proxied.pool.num_idle() != 1 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("warm connection returned to the pool"); + + // The worker's stage `select!` drops the heartbeat whenever the handler + // wins. Holding the bytes drops it with its first round trip in flight. + proxy.set_paused(true); + assert!(tokio::time::timeout( + Duration::from_millis(100), + proxied.heartbeat(&lease, Duration::from_secs(60)), + ) + .await + .is_err()); + proxy.set_paused(false); + assert!(proxied.release(&lease).await.unwrap()); + + let lease_owner: Option = + sqlx::query_scalar("SELECT lease_owner FROM entity_deletion_requests WHERE id = $1") + .bind(request.id) + .fetch_one(&store.pool) + .await + .unwrap(); + assert_eq!(lease_owner, None, "the reported release must be committed"); + let open: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND state = 'idle in transaction'", + ) + .fetch_one(&store.pool) + .await + .unwrap(); + assert_eq!(open, 0, "no pooled session may sit inside a transaction"); +} + fn users(store: &EntityDeletionStore) -> crate::user_deletion::UserDeletionStore { Db::from_pool(store.pool.clone()).user_deletion_store() } diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index c279e4831d0..8c165c77328 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -17,6 +17,7 @@ use buzz_core::{CommunityId, StoredEvent}; use buzz_datastore_tracing::datastore_span; use crate::error::{DbError, Result}; +use crate::store::recent_pass::Range; use crate::{AdmittedTx, Db}; // Compatibility exports preserve the pre-extraction public event-store paths. @@ -84,6 +85,12 @@ pub struct EventQuery { /// Restrict results to events with an `e` tag referencing any of these event IDs (hex). /// Matched positionally, with JSONB containment as the index prefilter. pub e_tags: Option>, + /// Restrict results to events with an `a` tag referencing any of these + /// NIP-01 addresses (`::`), so references to an + /// addressable event can be read across its revisions. Matched + /// positionally, with JSONB containment as the index prefilter, like + /// [`EventQuery::e_tags`]. + pub a_tags: Option>, /// Restrict artifact rows ([`ARTIFACT_KINDS`]) to those with a `d` tag /// matching any of these values, matched positionally. Their `d_tag` /// column is NULL (not NIP-33), so this lets identity lookups match before @@ -131,6 +138,11 @@ pub struct EventQuery { /// types only, so a read path that does not set it never returns a notice /// about a type added later, such as a system channel (NIP-CL). pub notice_channel_types: Option>, + /// Match every event NIP-01 would, never through the narrowed + /// thread-reply route (see `docs/nips/NIP-CW.md`). Set by reads whose rows + /// feed an exact COUNT, which must agree with the SQL COUNT path, and by + /// filters with any `#p` value, which NIP-CW keeps on NIP-01 results. + pub exact_match: bool, } impl EventQuery { @@ -157,6 +169,7 @@ impl EventQuery { authors: None, ids: None, e_tags: None, + a_tags: None, d_tag_values: None, custom_tag: None, tag_values: Vec::new(), @@ -165,6 +178,7 @@ impl EventQuery { max_limit: None, shared_gated_reader: None, notice_channel_types: None, + exact_match: false, } } } @@ -448,7 +462,8 @@ pub async fn insert_event( /// /// This is the transaction-composition seam for callers that must keep the /// event insert open while performing related work. The caller owns commit or -/// rollback. +/// rollback. On error, roll back or drop the transaction: the event row may +/// already have been inserted before the app floor check rejected it. pub async fn insert_event_in_transaction( tx: &mut AdmittedTx, event: &Event, @@ -515,9 +530,11 @@ async fn insert_event_on( let was_inserted = result.rows_affected() > 0; if was_inserted { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id).await?; crate::store::event_follow_up::after_admitted_insert( tx, id_bytes.as_slice(), + created_at, kind_i32, channel_id, ) @@ -548,8 +565,11 @@ pub(crate) async fn query_events_with_operation( q: &EventQuery, operation: crate::observability::WriterOperation, ) -> Result> { + if let Some(answer) = answer_without_db(q) { + return answer; + } let mut conn = crate::observability::acquire_writer(pool, operation).await?; - query_events_on(&mut conn, q).await + query_events_on(&mut conn, q, ReadDeadline::PerRead).await } /// [`query_events`] on a specific session — the replica-routing path runs @@ -558,62 +578,140 @@ pub(crate) async fn query_events_with_operation( pub(crate) async fn query_events_on( conn: &mut sqlx::PgConnection, q: &EventQuery, + deadline: ReadDeadline, ) -> Result> { + if let Some(answer) = answer_without_db(q) { + return answer; + } + + // A nested parent's replies are recorded under the thread's root, so only + // a top-level target takes the thread route. + let root = match thread_reply_root(q) { + Some(root) if !is_recorded_reply(conn, q, &root, deadline).await? => Some(root), + _ => None, + }; + // Thread-reply reads must be planned with their root: a cached generic + // plan sorts every reply of a large thread. Tag and `#d` matches likewise. + let persistent = !plans_with_bound_values(q) && root.is_none(); + let limit = page_limit(q); + // Recent-first (see `recent_pass`): the newest partitions answer a page + // that fills there; older rows are read only for what is still missing. + // A thread-reply read is a `#e` lookup, which is never split. + let rows = match (root, recent_pass_split(q, Utc::now())) { + (Some(root), _) => { + let mut qb = build_thread_reply_sql(q, root); + fetch_with_read_deadline(conn, qb.build().persistent(persistent), deadline).await? + } + (None, None) => { + let mut qb = build_query_events_sql(q, Range::All, limit); + fetch_with_read_deadline(conn, qb.build().persistent(persistent), deadline).await? + } + (None, Some(split)) => { + let mut read = ReadTransaction::begin(conn, deadline).await?; + let mut rows = Vec::new(); + let mut pass = Some((Range::Recent(split), limit)); + while let Some((range, pass_limit)) = pass { + let mut qb = build_query_events_sql(q, range, pass_limit); + rows.extend(read.fetch(qb.build().persistent(persistent)).await?); + pass = crate::store::recent_pass::next(range, rows.len(), limit); + } + read.finish().await?; + rows + } + }; + + let mut out = Vec::with_capacity(rows.len()); + for row in rows { + if let Some(ev) = row_to_stored_event(row)? { + out.push(ev); + } + } + Ok(out) +} + +/// The result of `q` when its shape alone decides it: an invalid query, or one +/// that matches nothing. Every entry point checks this before it takes a +/// connection, so a match-nothing read (a NIP-01 `limit: 0` live REQ, say) +/// costs no pool acquire. +pub(crate) fn answer_without_db(q: &EventQuery) -> Option>> { // Composite cursor requires both halves. if q.before_id.is_some() && q.until.is_none() { - return Err(DbError::InvalidData( + return Some(Err(DbError::InvalidData( "before_id requires until to be set".to_string(), - )); + ))); } // global_only and channel_id are mutually exclusive. if q.global_only && q.channel_id.is_some() { - return Err(DbError::InvalidData( + return Some(Err(DbError::InvalidData( "global_only and channel_id are mutually exclusive".to_string(), - )); + ))); } - // Empty list means "match nothing" — return empty immediately. - if q.kinds.as_deref().is_some_and(|k| k.is_empty()) { - return Ok(vec![]); - } - if q.authors.as_deref().is_some_and(|a| a.is_empty()) { - return Ok(vec![]); - } - if q.ids.as_deref().is_some_and(|i| i.is_empty()) { - return Ok(vec![]); - } - if q.e_tags.as_deref().is_some_and(|e| e.is_empty()) { - return Ok(vec![]); + // A zero page, or an empty list, means "match nothing". + let matches_nothing = page_limit(q) == 0 + || q.kinds.as_deref().is_some_and(|k| k.is_empty()) + || q.authors.as_deref().is_some_and(|a| a.is_empty()) + || q.ids.as_deref().is_some_and(|i| i.is_empty()) + || q.e_tags.as_deref().is_some_and(|e| e.is_empty()) + || q.a_tags.as_deref().is_some_and(|a| a.is_empty()); + matches_nothing.then(|| Ok(vec![])) +} + +/// Where to split `q` ([`crate::store::recent_pass`]), or `None` to read it +/// whole. Lookups by id, `e`, `a` or `d` tag, and fetch-everything +/// reads (`max_limit`, the COUNT fallback) match a fixed set of rows wherever +/// they sit, so a recent pass rarely fills their page. An `OFFSET` skips rows +/// on both sides of the floor, so its split point is unknown. +fn recent_pass_split( + q: &EventQuery, + now: DateTime, +) -> Option { + let lookup = q.offset.is_some_and(|o| o > 0) + || q.ids.is_some() + || q.e_tags.is_some() + || q.a_tags.is_some() + || q.d_tag.is_some() + || q.d_tags.is_some() + || q.d_tag_values.is_some() + || q.max_limit.is_some(); + if lookup { + return None; } + crate::store::recent_pass::split_for(now, q.kinds.as_deref(), q.since, q.until) +} - let mut qb = build_query_events_sql(q); - let rows = fetch_with_read_deadline(conn, &mut qb, !has_tag_values(q)).await?; +/// The `LIMIT` [`query_events_on`] applies: the requested page, clamped. +fn page_limit(q: &EventQuery) -> i64 { + q.limit + .unwrap_or(100) + .min(q.max_limit.unwrap_or(DEFAULT_MAX_PAGE_LIMIT)) +} - let mut out = Vec::with_capacity(rows.len()); - for row in rows { - if let Some(ev) = row_to_stored_event(row)? { - out.push(ev); - } - } - Ok(out) +/// Whether `q` filters inside a MATERIALIZED CTE and sorts/limits outside it: +/// any `#e` or `#a` read. With `ORDER BY created_at LIMIT n` in the same +/// scope, the planner overestimates matches and walks each partition's pkey +/// backward, testing every community row against the reference set; the +/// fence keeps it on the GIN tags index. +fn reference_tag_fence(q: &EventQuery) -> bool { + q.e_tags.is_some() || q.a_tags.is_some() } -/// SQL for [`query_events_on`], after its match-nothing early returns. -fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { - let clamp = q.max_limit.unwrap_or(DEFAULT_MAX_PAGE_LIMIT); - let limit_val = q.limit.unwrap_or(100).min(clamp); +/// Generic SQL for [`query_events_on`], after [`answer_without_db`]: the rows +/// of `q` inside `range` (see [`crate::store::recent_pass`]), at most +/// `limit_val`. +fn build_query_events_sql( + q: &EventQuery, + range: Range, + limit_val: i64, +) -> QueryBuilder { let offset_val = q.offset.unwrap_or(0); - // e-tag reads filter inside a MATERIALIZED CTE and sort/limit outside it. - // With `ORDER BY created_at LIMIT n` in the same scope, the planner - // overestimates matches and walks each partition's pkey backward, testing - // every community row against the id set; the fence keeps it on the GIN - // tags index. - let e_tag_fence = q.e_tags.is_some(); + let reference_tag_fence = reference_tag_fence(q); + let per_channel = per_channel_scope(q); let mut qb: QueryBuilder = if let Some(ref p_hex) = q.p_tag_hex { // Join against event_mentions for #p-filtered queries (indexed). - let mut b = QueryBuilder::new(if e_tag_fence { + let mut b = QueryBuilder::new(if reference_tag_fence { "WITH m AS MATERIALIZED (" } else { "" @@ -624,14 +722,19 @@ fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { FROM events e \ INNER JOIN event_mentions m ON ", ); - push_mention_join(&mut b, q, p_hex); + push_mention_join(&mut b, q, p_hex, range); b } else { - let mut b = QueryBuilder::new(if e_tag_fence { + let mut b = QueryBuilder::new(if reference_tag_fence { "WITH m AS MATERIALIZED (" } else { "" }); + if let Some(ids) = per_channel { + b.push("SELECT e.* FROM (SELECT DISTINCT unnest(") + .push_bind(ids.to_vec()) + .push("::uuid[]) AS ch) c CROSS JOIN LATERAL ("); + } b.push( "SELECT id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id \ FROM events WHERE community_id = ", @@ -643,13 +746,50 @@ fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { // Use unqualified column names when no join, qualified when joined. let col_prefix = if q.p_tag_hex.is_some() { "e." } else { "" }; + push_event_filters(&mut qb, col_prefix, q); + // A per-channel read scopes each lateral to one channel of the set. + if per_channel.is_some() { + qb.push(" AND channel_id = c.ch"); + } else { + push_channel_scope(&mut qb, col_prefix, q); + } + if let Some(bound) = range.predicate(&format!("{col_prefix}created_at")) { + qb.push(bound); + } + + // Composite ordering for deterministic pagination across ALL callers of + // query_events (WebSocket REQ, REST endpoints, canvas, notes, etc.). + // The `id ASC` tiebreaker ensures stable results when events share the + // same second. No existing index covers this trailing column — Postgres + // sorts in memory, which is fine at current scale. If query performance + // degrades, add a composite index like `(pubkey, kind, created_at DESC, id ASC)`. + if reference_tag_fence { + qb.push(") SELECT * FROM m ORDER BY created_at DESC, id ASC LIMIT "); + } else if per_channel.is_some() { + qb.push(" ORDER BY created_at DESC, id ASC LIMIT ") + .push_bind(limit_val) + .push(") e ORDER BY e.created_at DESC, e.id ASC LIMIT "); + } else { + qb.push(format!( + " ORDER BY {col_prefix}created_at DESC, {col_prefix}id ASC LIMIT " + )); + } + qb.push_bind(limit_val); + qb.push(" OFFSET ").push_bind(offset_val); + qb +} + +/// AND every [`EventQuery`] predicate except the community, the `deleted_at` +/// test, the channel scope (`push_channel_scope`) and the `#p` join, on +/// columns qualified by `col_prefix` (`""` or `"e."`). +fn push_event_filters(qb: &mut QueryBuilder, col_prefix: &str, q: &EventQuery) { // Generic reads return only current artifact revisions, including delete // tombstones; explicit revision IDs also read earlier revisions. if q.ids.is_none() { - let table = if q.p_tag_hex.is_some() { "e" } else { "events" }; + let table = col_prefix.strip_suffix('.').unwrap_or("events"); qb.push(format!(" AND NOT ({table}.kind = 45010 AND NOT EXISTS (SELECT 1 FROM artifact_heads ah WHERE ah.community_id={table}.community_id AND ah.event_id={table}.id))")); } - push_notice_visibility(&mut qb, col_prefix, q); + push_notice_visibility(qb, col_prefix, q); if let Some(ch) = q.channel_id { qb.push(format!(" AND {col_prefix}channel_id = ")) @@ -658,32 +798,6 @@ fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { qb.push(format!(" AND {col_prefix}channel_id IS NULL")); } - // Multi-channel IN pushdown. Access-scope queries retain global events; - // explicit multi-value #h filters do not. - // - // SECURITY: Some(empty vec) means "match no channels". Access-scope - // queries still retain globals; explicit #h queries match nothing. - if let Some(ref ch_ids) = q.channel_ids { - if ch_ids.is_empty() { - if q.channel_ids_include_global { - qb.push(format!(" AND {col_prefix}channel_id IS NULL")); - } else { - qb.push(" AND FALSE"); - } - } else { - qb.push(" AND ("); - if q.channel_ids_include_global { - qb.push(format!("{col_prefix}channel_id IS NULL OR ")); - } - qb.push(format!("{col_prefix}channel_id IN (")); - let mut sep = qb.separated(", "); - for ch in ch_ids { - sep.push_bind(*ch); - } - qb.push("))"); - } - } - if let Some(ks) = q.kinds.as_deref().filter(|k| !k.is_empty()) { qb.push(format!(" AND {col_prefix}kind IN (")); let mut sep = qb.separated(", "); @@ -730,20 +844,28 @@ fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { if let Some(ref e_tags) = q.e_tags { if !e_tags.is_empty() { qb.push(" AND "); - push_exact_tag_match(&mut qb, col_prefix, "e", e_tags); + push_exact_tag_match(qb, col_prefix, "e", e_tags); + } + } + + // a-tag pushdown: the same exact match and GIN prefilter as `#e`. + if let Some(ref a_tags) = q.a_tags { + if !a_tags.is_empty() { + qb.push(" AND "); + push_exact_tag_match(qb, col_prefix, "a", a_tags); } } if let Some(ref values) = q.d_tag_values { - push_artifact_d_tag_predicate(&mut qb, col_prefix, values); + push_artifact_d_tag_predicate(qb, col_prefix, values); } if let Some((ref name, ref value)) = q.custom_tag { qb.push(" AND "); - push_exact_tag_match(&mut qb, col_prefix, name, std::slice::from_ref(value)); + push_exact_tag_match(qb, col_prefix, name, std::slice::from_ref(value)); } - push_tag_value_filters(&mut qb, col_prefix, &q.tag_values); + push_tag_value_filters(qb, col_prefix, &q.tag_values); if let Some(s) = q.since { qb.push(format!(" AND {col_prefix}created_at >= ")) @@ -767,19 +889,7 @@ fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { } } - if let Some(ref d) = q.d_tag { - qb.push(format!(" AND {col_prefix}d_tag = ")) - .push_bind(d.clone()); - } else if let Some(ref ds) = q.d_tags { - if !ds.is_empty() { - qb.push(format!(" AND {col_prefix}d_tag IN (")); - let mut sep = qb.separated(", "); - for d in ds { - sep.push_bind(d.clone()); - } - qb.push(")"); - } - } + push_d_tag_filter(qb, col_prefix, q); // Shared-gated visibility pushdown: exclude SHARED_GATED_KINDS events that // are neither authored by the reader nor explicitly shared. Applied BEFORE @@ -801,28 +911,172 @@ fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { qb.push(format!(") OR {col_prefix}pubkey = ")); qb.push_bind(reader_bytes.clone()); qb.push(" OR "); - push_exact_tag_match(&mut qb, col_prefix, "shared", &["true".to_owned()]); + push_exact_tag_match(qb, col_prefix, "shared", &["true".to_owned()]); qb.push(")"); } +} - // Composite ordering for deterministic pagination across ALL callers of - // query_events (WebSocket REQ, REST endpoints, canvas, notes, etc.). - // The `id ASC` tiebreaker ensures stable results when events share the - // same second. No existing index covers this trailing column — Postgres - // sorts in memory, which is fine at current scale. If query performance - // degrades, add a composite index like `(pubkey, kind, created_at DESC, id ASC)`. - if e_tag_fence { - qb.push(") SELECT * FROM m ORDER BY created_at DESC, id ASC LIMIT "); - } else { - qb.push(format!( - " ORDER BY {col_prefix}created_at DESC, {col_prefix}id ASC LIMIT " - )); +/// Kinds whose single-root `#e` history read is answered from +/// `thread_metadata`: channel messages, whose clients always mark the root +/// with NIP-10 `root`/`reply` tags. +const THREAD_REPLY_KINDS: [i32; 2] = [ + buzz_core::kind::KIND_STREAM_MESSAGE as i32, + buzz_core::kind::KIND_STREAM_MESSAGE_V2 as i32, +]; + +/// The candidate thread root of a "replies to this message" read: one channel, +/// one lowercase-hex `#e` value, only [`THREAD_REPLY_KINDS`], no `#p` join, no +/// author or id selector, and not an [`EventQuery::exact_match`] read. +/// [`query_events_on`] takes the thread route only when the target is not +/// itself a recorded reply (see [`is_recorded_reply`]). +/// +/// Author and id selectors stay generic: the route tests them per reply, so an +/// author with no reply in a hot thread walks the whole thread, while the +/// generic read narrows by author first. +/// +/// The generic `#e` read gathers every event that tags the root before it can +/// sort and keep a page, so a root with hundreds of thousands of replies cost +/// seconds per page. `thread_metadata` lists a root's replies newest-first in +/// `idx_thread_metadata_window`, so the page costs the same at any thread size. +/// +/// The relay writes a `thread_metadata` row only for an event whose NIP-10 +/// `reply` marker resolves to a valid ancestry. A message that names the root +/// only in a bare, `mention` or lone `root` `e` tag still matches NIP-01 `#e`, +/// but this read omits it (see `docs/nips/NIP-CW.md`). +fn thread_reply_root(q: &EventQuery) -> Option> { + let [root] = q.e_tags.as_deref()? else { + return None; + }; + let kinds = q.kinds.as_deref()?; + let routable = q.channel_id.is_some() + && !q.exact_match + && q.p_tag_hex.is_none() + && q.pubkey.is_none() + && q.authors.is_none() + && q.ids.is_none() + && !kinds.is_empty() + && kinds.iter().all(|k| THREAD_REPLY_KINDS.contains(k)) + && root.len() == 64 + && root.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')); + routable.then(|| hex::decode(root).ok()).flatten() +} + +/// Whether `id` is itself a reply. Its own replies are recorded under the +/// thread's root, so a read for them must take the generic path. +/// +/// A message gains a `thread_metadata` row when it is recorded as a reply, or +/// as a depth-0 stub (no root) once something replies to it. A stub usually +/// marks a root, but ingest also stubs a reply that has no row of its own and +/// recovers its ancestry from its NIP-10 tags, so a stub is a root only when +/// the message's own markers do not resolve to a reply. No row means nothing +/// has replied to it. One probe of `idx_thread_metadata_event_id`. +async fn is_recorded_reply( + conn: &mut sqlx::PgConnection, + q: &EventQuery, + id: &[u8], + deadline: ReadDeadline, +) -> Result { + let mut qb = QueryBuilder::new( + "SELECT tm.root_event_id IS NOT NULL AS has_root, e.tags FROM thread_metadata tm \ + LEFT JOIN events e ON e.community_id = tm.community_id \ + AND e.created_at = tm.event_created_at AND e.id = tm.event_id \ + WHERE tm.community_id = ", + ); + qb.push_bind(q.community_id.as_uuid()) + .push(" AND tm.event_id = ") + .push_bind(id.to_vec()) + // One id can carry a reply row and a stub with a fallback timestamp; + // prefer the row that answers the question. + .push(" ORDER BY (tm.root_event_id IS NOT NULL) DESC, (e.id IS NOT NULL) DESC LIMIT 1"); + let rows = fetch_with_read_deadline(conn, qb.build().persistent(true), deadline).await?; + let Some(row) = rows.first() else { + return Ok(false); + }; + if row.try_get::("has_root")? { + return Ok(true); + } + let tags: Option = row.try_get("tags")?; + let tags: Vec> = tags + .map(serde_json::from_value) + .transpose() + .map_err(|_| DbError::InvalidData("invalid message tags".into()))? + .unwrap_or_default(); + let markers = buzz_core::nip10::parse_thread_markers_from_parts(tags.iter().map(Vec::as_slice)); + Ok(markers.resolve().is_some()) +} + +/// SQL for thread-route reads: walk the root's replies newest-first +/// in `idx_thread_metadata_window`, fetch each event by primary key, and apply +/// every query predicate (the `#e` match included) before `LIMIT`. The page +/// is a subset of the generic read's, in the same order. +fn build_thread_reply_sql(q: &EventQuery, root: Vec) -> QueryBuilder { + let mut qb = QueryBuilder::new( + "SELECT e.id, e.pubkey, e.created_at, e.kind, e.tags, e.content, e.sig, e.received_at, \ + e.channel_id FROM thread_metadata tm \ + JOIN LATERAL (SELECT e.community_id, e.id, e.pubkey, e.created_at, e.kind, e.tags, \ + e.content, e.sig, e.received_at, e.channel_id, e.d_tag, e.deleted_at FROM events e \ + WHERE e.community_id = tm.community_id AND e.created_at = tm.event_created_at \ + AND e.id = tm.event_id LIMIT 1) e ON true WHERE tm.community_id = ", + ); + qb.push_bind(q.community_id.as_uuid()); + qb.push(" AND tm.root_event_id = ").push_bind(root); + // Repeat the time window on `tm` so the index scan is a range. + if let Some(s) = q.since { + qb.push(" AND tm.event_created_at >= ").push_bind(s); } - qb.push_bind(limit_val); - qb.push(" OFFSET ").push_bind(offset_val); + if let Some(u) = q.until { + qb.push(" AND tm.event_created_at <= ").push_bind(u); + } + qb.push(" AND e.deleted_at IS NULL"); + push_event_filters(&mut qb, "e.", q); + push_channel_scope(&mut qb, "e.", q); + qb.push(" ORDER BY tm.event_created_at DESC, tm.event_id ASC LIMIT "); + qb.push_bind(page_limit(q)); + qb.push(" OFFSET ").push_bind(q.offset.unwrap_or(0)); qb } +/// Most candidate rows a per-channel read ([`per_channel_scope`]) may fetch: +/// channels in the set × page limit. +/// +/// A per-channel read fetches up to `n` rows from every channel, where the set +/// read stops once the page fills. 128 busy channels at `limit 500` fetched +/// 64,000 rows (114 ms) where the set read fetched 500 (2.3 ms), and the +/// larger plan cost turned on JIT (about 0.9 s). At 7,500 candidates the +/// per-channel read was still faster than the set read and stayed under the +/// JIT threshold. Above the budget the set read runs as before. +const PER_CHANNEL_CANDIDATE_BUDGET: usize = 8_192; + +/// The channels of a read that takes them one at a time: an explicit `#h` set +/// (no global events), without a `#p` join, reference-tag fence +/// ([`reference_tag_fence`]) or offset, whose +/// channels × page limit fit [`PER_CHANNEL_CANDIDATE_BUDGET`]. +/// +/// `channel_id = ANY($set) ORDER BY created_at DESC LIMIT n` leaves the +/// planner to guess how many rows the set matches. With the ids as literals +/// (the custom plans a prepared statement runs first) it overestimates a quiet +/// set, walks each partition's pkey backward and tests every community row +/// until the page fills or the partition ends; the inflated cost adds JIT too. +/// The cold unread repair (every joined channel, no `since`) is that read. +/// Reading each channel through `idx_events_community_channel_created` up to +/// `n` rows, then keeping the newest `n` of those, returns the same page, +/// since every row of the overall top `n` is in its own channel's top `n`. +/// At most distinct channels × `n` candidates reach the outer sort, whatever +/// the statistics say; how many index entries each channel scans for them +/// still depends on the other predicates. +fn per_channel_scope(q: &EventQuery) -> Option<&[Uuid]> { + let ids = q.channel_ids.as_deref().filter(|ids| !ids.is_empty())?; + let eligible = !q.channel_ids_include_global + && q.channel_id.is_none() + && !q.global_only + && q.p_tag_hex.is_none() + && !reference_tag_fence(q) + && q.offset.unwrap_or(0) == 0 + && usize::try_from(page_limit(q)) + .is_ok_and(|n| ids.len().saturating_mul(n) <= PER_CHANNEL_CANDIDATE_BUDGET); + eligible.then_some(ids) +} + /// `#p` reads join `event_mentions` by the full event key, including /// `created_at`: mention rows copy the event's `created_at` at insert, so the /// equality is exact and turns each joined row into one primary-key probe on @@ -834,7 +1088,12 @@ fn build_query_events_sql(q: &EventQuery) -> QueryBuilder { /// produced (all of its mentions) × (channel rows since `since`) work; on /// bb-public one such REQ ran for over 45 minutes. `until` is a superset bound /// for the keyset cursor, whose exact `(created_at, id)` test stays on `e`. -fn push_mention_join(b: &mut QueryBuilder, q: &EventQuery, p_hex: &str) { +fn push_mention_join( + b: &mut QueryBuilder, + q: &EventQuery, + p_hex: &str, + range: Range, +) { b.push( "e.community_id = m.community_id AND e.id = m.event_id \ AND e.created_at = m.event_created_at \ @@ -848,6 +1107,9 @@ fn push_mention_join(b: &mut QueryBuilder, q: &EventQuery, p_hex if let Some(s) = q.since { b.push(" AND m.event_created_at >= ").push_bind(s); } + if let Some(bound) = range.predicate("m.event_created_at") { + b.push(bound); + } if let Some(u) = q.until { b.push(" AND m.event_created_at <= ").push_bind(u); } @@ -864,14 +1126,28 @@ fn push_mention_join(b: &mut QueryBuilder, q: &EventQuery, p_hex } } +/// [`READ_STATEMENT_TIMEOUT`] in seconds, as a literal, so +/// [`BEGIN_WITH_READ_DEADLINE_SQL`] can splice it into a static statement. +macro_rules! read_statement_timeout_secs { + () => { + 20 + }; +} + /// Server-side deadline for every generic event read ([`query_events_on`] and /// [`count_events_on`]: REQ history, `/query`, `/count`, aux closures), kept /// under the desktop's 30 s request timeout so a runaway query is cancelled /// once no client can still be waiting for it. It only ever tightens the /// effective `statement_timeout`: a shorter operator or caller cap is kept, /// and a disabled (`0`) or longer one is lowered to 20 s. The limit is per -/// statement, not per request. -pub const READ_STATEMENT_TIMEOUT: &str = "20s"; +/// read, not per request: the passes of a split read share one (see +/// [`ReadTransaction`]). +pub const READ_STATEMENT_TIMEOUT: &str = concat!(read_statement_timeout_secs!(), "s"); + +/// [`READ_STATEMENT_TIMEOUT`] as a duration, for the budget a split read's +/// later passes run under. +pub(crate) const READ_DEADLINE: std::time::Duration = + std::time::Duration::from_secs(read_statement_timeout_secs!()); /// Lower `statement_timeout` to `$1` unless it is already tighter; `$2` /// selects transaction-local (`true`) or session (`false`) scope. @@ -880,28 +1156,152 @@ pub(crate) const TIGHTEN_STATEMENT_TIMEOUT_SQL: &str = "SELECT set_config('state OR current_setting('statement_timeout')::interval > $1::text::interval \ THEN $1::text ELSE current_setting('statement_timeout') END, $2)"; -/// Run an event read under [`READ_STATEMENT_TIMEOUT`] without changing the -/// deadline for anything else on `conn`. `begin()` opens a transaction on an -/// autocommit writer connection or a savepoint inside the replica's read -/// transaction; rolling it back (the read has no writes to keep) reverts the -/// transaction-local `set_config` in both cases. -async fn fetch_with_read_deadline( +/// Opens a [`ReadTransaction`]: `REPEATABLE READ, READ ONLY`, so every +/// statement in it reads one snapshot. +const BEGIN_READ_SQL: &str = "BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY"; + +/// [`BEGIN_READ_SQL`] plus the [`TIGHTEN_STATEMENT_TIMEOUT_SQL`] tighten to +/// [`READ_STATEMENT_TIMEOUT`], transaction-local, as one simple-query message: +/// one round trip instead of two. +const BEGIN_WITH_READ_DEADLINE_SQL: &str = concat!( + "BEGIN ISOLATION LEVEL REPEATABLE READ, READ ONLY; \ + SELECT set_config('statement_timeout', \ + CASE WHEN current_setting('statement_timeout')::interval = interval '0' \ + OR current_setting('statement_timeout')::interval > interval '", + read_statement_timeout_secs!(), + "s' THEN '", + read_statement_timeout_secs!(), + "s' ELSE current_setting('statement_timeout') END, true)" +); + +/// How an event read runs under [`READ_STATEMENT_TIMEOUT`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ReadDeadline { + /// The session already runs under it: every reader-pool connection + /// tightens its session `statement_timeout` once, at connect (see + /// `Db::read_pool_options`), so the read skips the tighten. + Session, + /// Tighten it for this read only, as writer sessions run under a longer + /// timeout of their own. + PerRead, +} + +/// Lower `conn`'s session `statement_timeout` to [`READ_STATEMENT_TIMEOUT`] +/// unless it is already tighter. For pools whose every statement is a read: +/// run it once per new connection (`after_connect`), so no statement on that +/// pool is unbounded. +pub async fn tighten_session_read_statement_timeout( conn: &mut sqlx::PgConnection, - qb: &mut QueryBuilder, - persistent: bool, -) -> Result> { - let mut tx = sqlx::Connection::begin(&mut *conn).await?; +) -> sqlx::Result<()> { sqlx::query(TIGHTEN_STATEMENT_TIMEOUT_SQL) .bind(READ_STATEMENT_TIMEOUT) + .bind(false) + .execute(conn) + .await + .map(|_| ()) +} + +/// The statements of one event read, in one transaction that reads one +/// snapshot under one deadline. +/// +/// A read split at the recent-pass floor (see `recent_pass`) runs its passes +/// as separate statements, and they must see the same rows: under +/// `READ COMMITTED` a replacement that commits between them (a replaceable +/// event, an artifact head) can move a live row from below the floor to +/// above it, out of both passes. Outside a transaction this opens +/// `REPEATABLE READ, READ ONLY`, whose snapshot every statement reads. Inside +/// one it takes a savepoint, so a failed or cancelled statement leaves the +/// transaction usable and its locks are released when the read ends; the +/// callers that read inside a transaction are routed replica reads, already +/// `REPEATABLE READ`. +/// +/// The read runs under [`READ_STATEMENT_TIMEOUT`] without changing the +/// deadline for anything else on the connection, and its statements share +/// it: each after the first runs under what the earlier ones left. +/// [`ReadDeadline::PerRead`] tightens the deadline in the transaction or +/// savepoint. Rolling it back (the read has no writes to keep) reverts every +/// tighten. +pub(crate) struct ReadTransaction<'c> { + tx: sqlx::Transaction<'c, sqlx::Postgres>, + started: std::time::Instant, + statements: usize, +} + +impl<'c> ReadTransaction<'c> { + /// Open the read on `conn`. + pub(crate) async fn begin( + conn: &'c mut sqlx::PgConnection, + deadline: ReadDeadline, + ) -> Result { + use sqlx::Connection as _; + let per_read = deadline == ReadDeadline::PerRead; + let tx = if conn.is_in_transaction() { + let mut tx = conn.begin().await?; + if per_read { + tighten_read_deadline(&mut tx, READ_STATEMENT_TIMEOUT).await?; + } + tx + } else if per_read { + conn.begin_with(BEGIN_WITH_READ_DEADLINE_SQL).await? + } else { + conn.begin_with(BEGIN_READ_SQL).await? + }; + Ok(Self { + tx, + started: std::time::Instant::now(), + statements: 0, + }) + } + + /// Run one statement of the read. + pub(crate) async fn fetch( + &mut self, + query: sqlx::query::Query<'_, sqlx::Postgres, sqlx::postgres::PgArguments>, + ) -> Result> { + if self.statements > 0 { + let left = READ_DEADLINE + .saturating_sub(self.started.elapsed()) + .max(std::time::Duration::from_millis(1)); + tighten_read_deadline(&mut self.tx, &format!("{}ms", left.as_millis())).await?; + } + self.statements += 1; + Ok(query.fetch_all(&mut *self.tx).await?) + } + + /// End the read, rolling back everything it set. + pub(crate) async fn finish(self) -> Result<()> { + Ok(self.tx.rollback().await?) + } +} + +/// Lower the transaction-local `statement_timeout` to `timeout`. +async fn tighten_read_deadline( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + timeout: &str, +) -> Result<()> { + sqlx::query(TIGHTEN_STATEMENT_TIMEOUT_SQL) + .bind(timeout) .bind(true) - .execute(&mut *tx) - .await?; - let rows = qb - .build() - .persistent(persistent) - .fetch_all(&mut *tx) + .execute(&mut **tx) .await?; - tx.rollback().await?; + Ok(()) +} + +/// Run a single-statement event read as a [`ReadTransaction`], except on an +/// autocommit session already under the deadline, where the statement alone +/// is the read. +pub(crate) async fn fetch_with_read_deadline( + conn: &mut sqlx::PgConnection, + query: sqlx::query::Query<'_, sqlx::Postgres, sqlx::postgres::PgArguments>, + deadline: ReadDeadline, +) -> Result> { + use sqlx::Connection as _; + if !conn.is_in_transaction() && deadline == ReadDeadline::Session { + return Ok(query.fetch_all(conn).await?); + } + let mut read = ReadTransaction::begin(conn, deadline).await?; + let rows = read.fetch(query).await?; + read.finish().await?; Ok(rows) } @@ -936,12 +1336,34 @@ fn push_exact_tag_match( .push(")))"); } -/// Whether `q` carries a [`EventQuery::tag_values`] match. Such a query runs -/// as an unnamed statement, so Postgres plans it with the bound values. After -/// a few runs, a cached generic plan ignores the value and can scan every -/// group-state row in the community instead of using the `tags` GIN index. -fn has_tag_values(q: &EventQuery) -> bool { +/// Whether `q` must run as an unnamed statement, so Postgres plans it with the +/// bound values. After a few runs on a connection, Postgres can switch a named +/// statement to a cached generic plan that ignores the values: +/// - a [`EventQuery::tag_values`] match then scans every group-state row in +/// the community instead of using the `tags` GIN index; +/// - a multi-value `#d` ([`EventQuery::d_tags`]) match walks the author's +/// `created_at` index and filters `d_tag` row by row. Its `LIMIT` is never +/// reached when it asks for one row per value, so it reads every stored +/// version of the kind (relay-signed channel metadata, say) instead of +/// probing `idx_events_parameterized` once per value. +fn plans_with_bound_values(q: &EventQuery) -> bool { q.tag_values.iter().any(|(_, values)| !values.is_empty()) + || q.d_tags.as_ref().is_some_and(|ds| !ds.is_empty()) +} + +/// AND the NIP-33 `d` match: one value, or any of [`EventQuery::d_tags`] as +/// one array bind, so the number of values does not change the SQL text. +fn push_d_tag_filter(qb: &mut QueryBuilder, col_prefix: &str, q: &EventQuery) { + if let Some(ref d) = q.d_tag { + qb.push(format!(" AND {col_prefix}d_tag = ")) + .push_bind(d.clone()); + } else if let Some(ref ds) = q.d_tags { + if !ds.is_empty() { + qb.push(format!(" AND {col_prefix}d_tag = ANY(")) + .push_bind(ds.clone()) + .push(")"); + } + } } /// AND one [`push_exact_tag_match`] per non-empty [`EventQuery::tag_values`] @@ -960,6 +1382,38 @@ fn push_tag_value_filters( } } +/// AND the [`EventQuery::channel_ids`] scope, before `LIMIT`. Access-scope +/// queries retain channel-less global events; explicit multi-value `#h` +/// filters do not. +/// +/// SECURITY: `Some(empty vec)` means "match no channels": access-scope queries +/// still retain globals, explicit `#h` queries match nothing. +/// +/// The set is one array bind, so a viewer's channel count does not change the +/// SQL text. One `IN ($n, …)` bind per channel made a new statement for every +/// arity, so a read rarely reused its cached plan and was planned again on +/// each call, over every `events` partition when it has no `since`. +fn push_channel_scope(qb: &mut QueryBuilder, col_prefix: &str, q: &EventQuery) { + let Some(ref ch_ids) = q.channel_ids else { + return; + }; + if ch_ids.is_empty() { + if q.channel_ids_include_global { + qb.push(format!(" AND {col_prefix}channel_id IS NULL")); + } else { + qb.push(" AND FALSE"); + } + return; + } + qb.push(" AND ("); + if q.channel_ids_include_global { + qb.push(format!("{col_prefix}channel_id IS NULL OR ")); + } + qb.push(format!("{col_prefix}channel_id = ANY(")) + .push_bind(ch_ids.clone()) + .push("))"); +} + /// Return only membership notices whose channel type the query may see /// (NIP-CL), as [`buzz_core::filter::notice_visible`] does in `filters_match`: /// `AND (kind NOT IN (44100, 44101) OR @@ -1078,13 +1532,17 @@ pub async fn count_events(pool: &PgPool, q: &EventQuery) -> Result { crate::observability::WriterOperation::SubscriptionHistory, ) .await?; - count_events_on(&mut conn, q).await + count_events_on(&mut conn, q, ReadDeadline::PerRead).await } /// [`count_events`] on a specific session — the replica-routing path runs /// the count on the exact reader connection whose heartbeat observation /// proved its predicate. -pub(crate) async fn count_events_on(conn: &mut sqlx::PgConnection, q: &EventQuery) -> Result { +pub(crate) async fn count_events_on( + conn: &mut sqlx::PgConnection, + q: &EventQuery, + deadline: ReadDeadline, +) -> Result { // Empty list means "match nothing" — return 0 immediately. if q.kinds.as_deref().is_some_and(|k| k.is_empty()) { return Ok(0); @@ -1098,15 +1556,22 @@ pub(crate) async fn count_events_on(conn: &mut sqlx::PgConnection, q: &EventQuer if q.e_tags.as_deref().is_some_and(|e| e.is_empty()) { return Ok(0); } + if q.a_tags.as_deref().is_some_and(|a| a.is_empty()) { + return Ok(0); + } let mut qb = count_events_sql(q); // Same transaction-local deadline as `query_events_on`, so a COUNT cannot // stall indefinitely either. - let row = fetch_with_read_deadline(conn, &mut qb, !has_tag_values(q)) - .await? - .into_iter() - .next() - .ok_or_else(|| DbError::InvalidData("COUNT returned no rows".to_string()))?; + let row = fetch_with_read_deadline( + conn, + qb.build().persistent(!plans_with_bound_values(q)), + deadline, + ) + .await? + .into_iter() + .next() + .ok_or_else(|| DbError::InvalidData("COUNT returned no rows".to_string()))?; let cnt: i64 = row.try_get("cnt")?; Ok(cnt) @@ -1119,7 +1584,7 @@ fn count_events_sql(q: &EventQuery) -> QueryBuilder { "SELECT COUNT(*) as cnt FROM events e \ INNER JOIN event_mentions m ON ", ); - push_mention_join(&mut b, q, p_hex); + push_mention_join(&mut b, q, p_hex, Range::All); b } else { let mut b = QueryBuilder::new("SELECT COUNT(*) as cnt FROM events WHERE community_id = "); @@ -1144,28 +1609,7 @@ fn count_events_sql(q: &EventQuery) -> QueryBuilder { qb.push(format!(" AND {col_prefix}channel_id IS NULL")); } - // Multi-channel IN pushdown for COUNT. Access-scope queries retain global - // events; explicit multi-value #h filters do not. - if let Some(ref ch_ids) = q.channel_ids { - if ch_ids.is_empty() { - if q.channel_ids_include_global { - qb.push(format!(" AND {col_prefix}channel_id IS NULL")); - } else { - qb.push(" AND FALSE"); - } - } else { - qb.push(" AND ("); - if q.channel_ids_include_global { - qb.push(format!("{col_prefix}channel_id IS NULL OR ")); - } - qb.push(format!("{col_prefix}channel_id IN (")); - let mut sep = qb.separated(", "); - for ch in ch_ids { - sep.push_bind(*ch); - } - qb.push("))"); - } - } + push_channel_scope(&mut qb, col_prefix, q); if let Some(ks) = q.kinds.as_deref().filter(|k| !k.is_empty()) { qb.push(format!(" AND {col_prefix}kind IN (")); @@ -1210,6 +1654,13 @@ fn count_events_sql(q: &EventQuery) -> QueryBuilder { } } + if let Some(ref a_tags) = q.a_tags { + if !a_tags.is_empty() { + qb.push(" AND "); + push_exact_tag_match(&mut qb, col_prefix, "a", a_tags); + } + } + if let Some(ref values) = q.d_tag_values { push_artifact_d_tag_predicate(&mut qb, col_prefix, values); } @@ -1230,357 +1681,26 @@ fn count_events_sql(q: &EventQuery) -> QueryBuilder { .push_bind(u); } - if let Some(ref d) = q.d_tag { - qb.push(format!(" AND {col_prefix}d_tag = ")) - .push_bind(d.clone()); - } else if let Some(ref ds) = q.d_tags { - if !ds.is_empty() { - qb.push(format!(" AND {col_prefix}d_tag IN (")); - let mut sep = qb.separated(", "); - for d in ds { - sep.push_bind(d.clone()); - } - qb.push(")"); - } - } + push_d_tag_filter(&mut qb, col_prefix, q); qb } -/// SQL predicate over an `events` row for coordinates that carry no -/// historical value: NIP-RS read state and Buzz mesh heartbeats. Their -/// deletion is physical, including the mention index, so soft-deleted payloads -/// never accumulate. This is exactly the classification used by the migration -/// 0011 / 0019 purge triggers this path replaces. -macro_rules! retention_free_event_predicate { - () => { - "((kind = 30078 \ - AND d_tag ~ '^read-state:[0-9a-f]{32}$' \ - AND (SELECT count(*) \ - FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ - WHERE jsonb_typeof(tag) = 'array' AND tag->0 = '\"d\"'::jsonb) = 1 \ - AND EXISTS (SELECT 1 \ - FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ - WHERE jsonb_typeof(tag) = 'array' AND jsonb_array_length(tag) >= 2 \ - AND jsonb_typeof(tag->1) = 'string' AND tag->>0 = 'd' AND tag->>1 = d_tag) \ - AND (SELECT count(*) \ - FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ - WHERE tag = '[\"t\", \"read-state\"]'::jsonb) = 1) \ - OR (kind = 30003 \ - AND d_tag LIKE 'buzz-mesh-member-status:%' \ - AND tags @> '[[\"k\", \"buzz-mesh-status\"]]'::jsonb))" - }; -} - -/// Kinds that can hold a retention-free coordinate. Cheap Rust gate so -/// ordinary deletions skip the purge statement entirely. -fn may_be_retention_free(kind: i32) -> bool { - kind == 30078 || kind == 30003 -} +// Preserve the public event-store deletion API after the focused extraction. +pub(crate) use super::event_deletion::soft_delete_event_and_update_thread_in_tx; +pub use super::event_deletion::{ + soft_delete_by_coordinate, soft_delete_event_and_update_thread, DeletionTarget, +}; -/// Soft-delete the live row for an addressable coordinate -/// `(kind, pubkey, d_tag)` — the NIP-33 replacement key — provided it is not -/// newer than the deletion request. -/// -/// Used by `handle_a_tag_deletion` to honour NIP-09 a-tag deletions for any -/// parameterized-replaceable kind. The WHERE clause mirrors -/// `replace_parameterized_event` so the coordinate semantics stay consistent: -/// `channel_id` is intentionally NOT in the key (NIP-33 replacement is global -/// per the spec — `channel_id` is stored for query scoping, not identity). -/// -/// `deletion_created_at_secs` is the deletion event's own `created_at`. NIP-09 -/// scopes an `a`-tag deletion to versions at or before that instant, so a -/// delayed or replayed tombstone signed between two versions must not erase the -/// newer replacement. `events.created_at` is immutable per row, so the predicate -/// guarantees a tombstone can never erase a version newer than itself — the UPDATE -/// re-evaluates its WHERE clause after any lock wait, so a replacement that races -/// the deletion and lands with a later `created_at` is always spared. -/// -/// This does NOT guarantee deletion completeness when a same-coordinate -/// replacement races the deletion: the deletion may evaluate its predicate before -/// the replacement arrives, miss the incoming head, and return `Ok(false)`. That -/// outcome is state-identical to the deletion having arrived first (old head -/// gone, new head present), which is a valid Nostr ordering — Nostr never fixes -/// the order of concurrent writes from different signers, and even same-signer -/// ordering is advisory. The return value feeds only a debug log, not a -/// correctness gate. -/// -/// Returns `Ok(true)` if a row was deleted, `Ok(false)` if no live row matched -/// (already deleted, never existed, or strictly newer than the deletion). -pub async fn soft_delete_by_coordinate( +/// Returns the `created_at` timestamp of the most recent non-deleted event in a channel. +pub async fn get_last_message_at( pool: &PgPool, community_id: CommunityId, - kind: i32, - pubkey: &[u8], - d_tag: &str, - deletion_created_at_secs: i64, -) -> Result { - let deletion_created_at = DateTime::from_timestamp(deletion_created_at_secs, 0) - .ok_or(DbError::InvalidTimestamp(deletion_created_at_secs))?; - let mut tx = crate::begin_community_event_write_transaction( + channel_id: uuid::Uuid, +) -> Result>> { + let mut connection = crate::observability::acquire_writer( pool, - community_id, - crate::observability::WriterOperation::EventWrite, - ) - .await?; - let purged = if may_be_retention_free(kind) { - purge_retention_free_events( - &mut tx, - RetentionFreeTarget::Coordinate { - kind, - pubkey, - d_tag, - created_at_or_before: deletion_created_at, - }, - ) - .await? - } else { - 0 - }; - // `AND NOT COALESCE(, false)` holds the invariant in SQL rather than through - // statement order: under READ COMMITTED this UPDATE takes a fresh snapshot, - // so a retention-free head committed by a racing replacement after the - // purge ran is spared instead of soft-deleted (the "deletion arrived - // first" outcome documented above). COALESCE keeps a NULL predicate - // (e.g. NULL `d_tag`) on the ordinary soft-delete path, as the triggers do. - let result = sqlx::query(concat!( - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL \ - AND created_at <= $5 AND NOT COALESCE(", - retention_free_event_predicate!(), - ", false)" - )) - .bind(community_id.as_uuid()) - .bind(kind) - .bind(pubkey) - .bind(d_tag) - .bind(deletion_created_at) - .execute(tx.conn()) - .await?; - - tx.commit().await?; - - Ok(purged > 0 || result.rows_affected() > 0) -} - -/// Purge live retention-free rows matching `$target`, plus their mention rows, -/// and return the number of events removed. -macro_rules! purge_retention_free_sql { - ($target:literal) => { - concat!( - "WITH purged AS ( \ - DELETE FROM events \ - WHERE community_id = $1 AND ", - $target, - " AND deleted_at IS NULL AND ", - retention_free_event_predicate!(), - " RETURNING id \ - ), purged_mentions AS ( \ - DELETE FROM event_mentions mention USING purged \ - WHERE mention.community_id = $1 AND mention.event_id = purged.id \ - ) \ - SELECT count(*) FROM purged" - ) - }; -} - -/// Which live rows a deletion targets. -enum RetentionFreeTarget<'a> { - Id(&'a [u8]), - Coordinate { - kind: i32, - pubkey: &'a [u8], - d_tag: &'a str, - created_at_or_before: DateTime, - }, -} - -/// Physically delete live retention-free rows matched by `target`, plus their -/// mention rows, in the caller's transaction. The generic soft delete that -/// follows excludes the same predicate, so a retention-free row is either -/// purged here or left live, never soft-deleted. Returns the number of events -/// removed. -async fn purge_retention_free_events( - tx: &mut AdmittedTx, - target: RetentionFreeTarget<'_>, -) -> Result { - let community_id = tx.community(); - // Migration 0011 fences NIP-RS hard deletes behind a transaction-local - // opt-in. The fence and this opt-in are removed together once the - // migration-only triggers are dropped. - sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") - .execute(tx.conn()) - .await?; - - let purged: i64 = match target { - RetentionFreeTarget::Id(event_id) => { - sqlx::query_scalar(purge_retention_free_sql!("id = $2")) - .bind(community_id.as_uuid()) - .bind(event_id) - .fetch_one(tx.conn()) - .await? - } - RetentionFreeTarget::Coordinate { - kind, - pubkey, - d_tag, - created_at_or_before, - } => { - sqlx::query_scalar(purge_retention_free_sql!( - "kind = $2 AND pubkey = $3 AND d_tag = $4 AND created_at <= $5" - )) - .bind(community_id.as_uuid()) - .bind(kind) - .bind(pubkey) - .bind(d_tag) - .bind(created_at_or_before) - .fetch_one(tx.conn()) - .await? - } - }; - - Ok(purged as u64) -} - -/// Atomically soft-delete an event and decrement thread reply counters. -/// -/// Wraps the delete + counter update in a single transaction so a crash between -/// them cannot leave counters permanently inflated. Returns `Ok(true)` if the -/// event was deleted this call. -/// -/// When the target event is a kind-40100 (canvas) event, this function derives -/// the target's `kind` and `channel_id` from the database inside the same -/// transaction and acquires the same `(community, kind, channel)` advisory lock -/// used by [`insert_canvas_head_checked`] before the UPDATE. This prevents a -/// concurrent tagged write from observing a head that is simultaneously being -/// removed. The serialization invariant is owned entirely by this function; -/// callers do not classify the target kind. -pub async fn soft_delete_event_and_update_thread( - pool: &PgPool, - community_id: CommunityId, - event_id: &[u8], - parent_event_id: Option<&[u8]>, - root_event_id: Option<&[u8]>, -) -> Result { - let mut tx = crate::begin_community_event_write_transaction( - pool, - community_id, - crate::observability::WriterOperation::EventWrite, - ) - .await?; - let deleted = soft_delete_event_and_update_thread_in_tx( - &mut tx, - event_id, - parent_event_id, - root_event_id, - ) - .await?; - tx.commit().await?; - Ok(deleted) -} - -/// Transaction-scoped body of [`soft_delete_event_and_update_thread`]. -/// -/// Callers that must fence the delete with their own writes (e.g. the admin -/// action lease/marker) run this inside their transaction; the caller commits. -pub(crate) async fn soft_delete_event_and_update_thread_in_tx( - tx: &mut AdmittedTx, - event_id: &[u8], - parent_event_id: Option<&[u8]>, - root_event_id: Option<&[u8]>, -) -> Result { - let community_id = tx.community(); - use crate::store::replaceable::event_replacement_lock_key; - - // Derive the target event's kind and channel_id inside the transaction so - // that the serialization decision cannot be bypassed by any caller. - let target: Option<(i32, Option)> = sqlx::query_as( - "SELECT kind, channel_id FROM events \ - WHERE community_id = $1 AND id = $2", - ) - .bind(community_id.as_uuid()) - .bind(event_id) - .fetch_optional(tx.conn()) - .await?; - - // Relay-signed move removals are the source channel's only replay record. - if target.is_some_and(|(kind, _)| kind == 45011) { - return Err(DbError::InvalidData( - "artifact removal markers cannot be deleted".into(), - )); - } - - if let Some((kind, Some(channel_id))) = target { - if kind == KIND_CANVAS as i32 { - let lock_key = event_replacement_lock_key( - community_id, - kind, - &[], - Some(channel_id.as_bytes().as_slice()), - ); - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(lock_key) - .execute(tx.conn()) - .await?; - } - } - - let purged = if target.is_some_and(|(kind, _)| may_be_retention_free(kind)) { - purge_retention_free_events(tx, RetentionFreeTarget::Id(event_id)).await? - } else { - 0 - }; - let result = sqlx::query(concat!( - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL AND NOT COALESCE(", - retention_free_event_predicate!(), - ", false)" - )) - .bind(community_id.as_uuid()) - .bind(event_id) - .execute(tx.conn()) - .await?; - - let deleted = purged > 0 || result.rows_affected() > 0; - - if deleted { - if let Some(pid) = parent_event_id { - sqlx::query( - "UPDATE thread_metadata \ - SET reply_count = GREATEST(reply_count - 1, 0) \ - WHERE community_id = $1 AND event_id = $2", - ) - .bind(community_id.as_uuid()) - .bind(pid) - .execute(tx.conn()) - .await?; - - if let Some(root_id) = root_event_id { - sqlx::query( - "UPDATE thread_metadata \ - SET descendant_count = GREATEST(descendant_count - 1, 0) \ - WHERE community_id = $1 AND event_id = $2", - ) - .bind(community_id.as_uuid()) - .bind(root_id) - .execute(tx.conn()) - .await?; - } - } - } - - Ok(deleted) -} - -/// Returns the `created_at` timestamp of the most recent non-deleted event in a channel. -pub async fn get_last_message_at( - pool: &PgPool, - community_id: CommunityId, - channel_id: uuid::Uuid, -) -> Result>> { - let mut connection = crate::observability::acquire_writer( - pool, - crate::observability::WriterOperation::SubscriptionHistory, + crate::observability::WriterOperation::SubscriptionHistory, ) .await?; let row = sqlx::query( @@ -1789,9 +1909,7 @@ pub(crate) async fn get_events_by_ids_with_operation( get_events_by_ids_on(&mut conn, community_id, ids).await } -/// [`get_events_by_ids`] on a specific session — the replica-routing path -/// runs the query on the exact reader connection whose heartbeat -/// observation proved its predicate. +/// [`get_events_by_ids`] on a specific session. pub(crate) async fn get_events_by_ids_on( conn: &mut sqlx::PgConnection, community_id: CommunityId, @@ -1905,9 +2023,11 @@ pub(crate) async fn insert_event_with_thread_metadata_tx( let was_inserted = result.rows_affected() > 0; if was_inserted { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id).await?; crate::store::event_follow_up::after_admitted_insert( tx, id_bytes.as_slice(), + created_at, kind_i32, channel_id, ) @@ -2344,13 +2464,17 @@ impl Db { /// unset, even covered-eligible queries stay on the writer, so merging /// this seam is a true no-op until the budget is configured. Every /// failure fails closed to the writer, except a statement-timeout cancel - /// (57014), which is surfaced rather than re-run. + /// (57014), which is surfaced rather than re-run, and a busy reader, + /// which rejects the read as retryable (see [`Db::route_read`]). #[datastore_span(name = "query_events_routed", system = "postgresql")] pub async fn query_events_routed( &self, path: &'static str, q: &EventQuery, ) -> Result> { + if let Some(answer) = crate::event::answer_without_db(q) { + return answer; + } let predicate = crate::RoutePredicate::for_query(q, self.replica_read_max_age.is_some()); match self .route_read( @@ -2358,10 +2482,12 @@ impl Db { predicate, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { crate::RouteDecision::Replica(mut tx, _entry, reason) => { - match crate::event::query_events_on(&mut tx, q).await { + match crate::event::query_events_on(&mut tx, q, crate::event::ReadDeadline::Session) + .await + { Ok(events) => { Self::record_route(path, "replica", reason); Ok(events) @@ -2377,6 +2503,9 @@ impl Db { // writer rather than surfacing a routed error. tracing::warn!(path, "replica read failed; re-running on writer: {e}"); Self::record_route(path, "writer", "replica_error"); + // Release the reader and its history permit before the + // writer re-run, so a replica-error burst can't fill the cap. + drop(tx); crate::event::query_events_with_operation( &self.pool, q, @@ -2411,16 +2540,21 @@ impl Db { path: &'static str, q: &EventQuery, ) -> Result> { + if let Some(answer) = crate::event::answer_without_db(q) { + return answer; + } match self .route_read( path, crate::RoutePredicate::Bounded, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { crate::RouteDecision::Replica(mut tx, _entry, reason) => { - match crate::event::query_events_on(&mut tx, q).await { + match crate::event::query_events_on(&mut tx, q, crate::event::ReadDeadline::Session) + .await + { Ok(events) => { Self::record_route(path, "replica", reason); Ok(events) @@ -2434,6 +2568,9 @@ impl Db { Err(e) => { tracing::warn!(path, "replica read failed; re-running on writer: {e}"); Self::record_route(path, "writer", "replica_error"); + // Release the reader and its history permit before the + // writer re-run, so a replica-error burst can't fill the cap. + drop(tx); crate::event::query_events_with_operation( &self.pool, q, @@ -2481,10 +2618,12 @@ impl Db { crate::RoutePredicate::Bounded, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { crate::RouteDecision::Replica(mut tx, _entry, reason) => { - match crate::event::count_events_on(&mut tx, q).await { + match crate::event::count_events_on(&mut tx, q, crate::event::ReadDeadline::Session) + .await + { Ok(count) => { Self::record_route(path, "replica", reason); Ok(count) @@ -2498,6 +2637,9 @@ impl Db { Err(e) => { tracing::warn!(path, "replica count failed; re-running on writer: {e}"); Self::record_route(path, "writer", "replica_error"); + // Release the reader and its history permit before the + // writer re-run, so a replica-error burst can't fill the cap. + drop(tx); crate::event::count_events(&self.pool, q).await } } @@ -2720,65 +2862,6 @@ impl Db { .await } - /// [`Db::get_events_by_ids`] with replica routing — same contract and - /// classification-table requirement as [`Db::query_events_routed`]. - /// - /// By-id fetches route on the BOUNDED arm only: an id list carries no - /// channel pin, so no fence floor can prove insert-completeness — the - /// covered arm is structurally unavailable. Used for FTS hit hydration, - /// where a missing row degrades to a skipped search hit downstream. - #[datastore_span(name = "get_events_by_ids_routed", system = "postgresql")] - pub async fn get_events_by_ids_routed( - &self, - path: &'static str, - community_id: CommunityId, - ids: &[&[u8]], - ) -> Result> { - match self - .route_read( - path, - crate::RoutePredicate::Bounded, - crate::observability::ReaderOperation::SubscriptionHistory, - ) - .await - { - crate::RouteDecision::Replica(mut tx, _entry, reason) => { - match crate::event::get_events_by_ids_on(&mut tx, community_id, ids).await { - Ok(events) => { - Self::record_route(path, "replica", reason); - Ok(events) - } - // Surface a cancel instead of re-running it on the writer; see - // `DbError::is_statement_cancelled` for the trade-off. - Err(e) if e.is_statement_cancelled() => { - Self::record_route(path, "replica", "statement_cancelled"); - Err(e) - } - Err(e) => { - tracing::warn!(path, "replica read failed; re-running on writer: {e}"); - Self::record_route(path, "writer", "replica_error"); - crate::event::get_events_by_ids_with_operation( - &self.pool, - community_id, - ids, - crate::observability::WriterOperation::SubscriptionHistory, - ) - .await - } - } - } - crate::RouteDecision::Writer => { - crate::event::get_events_by_ids_with_operation( - &self.pool, - community_id, - ids, - crate::observability::WriterOperation::SubscriptionHistory, - ) - .await - } - } - } - /// Atomically insert an event AND its thread metadata in a single transaction. #[datastore_span(name = "insert_event_with_thread_metadata", system = "postgresql")] pub async fn insert_event_with_thread_metadata( @@ -2810,6 +2893,58 @@ impl Db { Ok(result) } + /// Store a kind 5 / 9005 deletion and soft-delete its `targets` in one + /// transaction, so an accepted deletion never leaves its target live. + /// + /// The targets are soft-deleted even when the deletion is a duplicate, so + /// resending a deletion repairs a target an earlier write left live. Ingest + /// accepts the resend only within its timestamp window, so this does not + /// repair older rows. + /// Returns `(StoredEvent, was_inserted, deleted)`, where `deleted[i]` + /// tells whether `targets[i]` was soft-deleted by this call. + #[datastore_span(name = "insert_deletion_event", system = "postgresql")] + pub async fn insert_deletion_event( + &self, + community_id: CommunityId, + event: &nostr::Event, + channel_id: Option, + thread_meta: Option>, + targets: &[crate::event::DeletionTarget<'_>], + ) -> Result<(StoredEvent, bool, Vec)> { + let mut tx = crate::begin_community_event_write_transaction( + &self.pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + tx.set_push_enqueue(self.push_enqueue.clone()); + let (stored, inserted) = crate::event::insert_event_with_thread_metadata_tx( + &mut tx, + event, + channel_id, + thread_meta, + ) + .await?; + if inserted { + crate::insert_mentions_in_transaction(&mut tx, event, channel_id).await?; + } + let mut deleted = Vec::with_capacity(targets.len()); + for target in targets { + deleted.push( + crate::event::soft_delete_event_and_update_thread_in_tx( + &mut tx, + target.event_id, + Some(target.created_at), + target.parent_event_id, + target.root_event_id, + ) + .await?, + ); + } + tx.commit().await?; + Ok((stored, inserted, deleted)) + } + /// Soft-delete NIP-29 discovery events for a channel created by a specific relay pubkey. #[datastore_span(name = "soft_delete_discovery_events", system = "postgresql")] pub async fn soft_delete_discovery_events( @@ -2871,7 +3006,7 @@ mod e_tag_filter_shape_tests { let mut q = EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())); q.kinds = Some(vec![7]); q.e_tags = Some((0..188).map(|i| format!("{i:064x}")).collect()); - let qb = build_query_events_sql(&q); + let qb = build_query_events_sql(&q, Range::All, page_limit(&q)); let sql = qb.sql().as_str().to_owned(); assert!(sql.starts_with("WITH m AS MATERIALIZED (SELECT ")); @@ -2884,13 +3019,171 @@ mod e_tag_filter_shape_tests { assert!(sql[fence_end..].contains("ORDER BY created_at DESC, id ASC LIMIT ")); } + /// Only a one-channel, one-root read of channel-message kinds without a + /// `#p` join takes the thread route; everything else stays generic. + #[test] + fn thread_reply_route_admits_only_single_root_message_reads() { + let root = "ab".repeat(32); + let routed = || { + let mut q = EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())); + q.channel_id = Some(uuid::Uuid::nil()); + q.kinds = Some(vec![9, 40002]); + q.e_tags = Some(vec![root.clone()]); + q + }; + let q = routed(); + let sql = build_thread_reply_sql(&q, thread_reply_root(&q).unwrap()) + .sql() + .as_str() + .to_owned(); + assert!(sql.contains("FROM thread_metadata tm")); + assert!(!sql.contains("MATERIALIZED")); + assert!(sql.contains("tags @> ANY("), "the #e match still applies"); + assert!(sql.contains("ORDER BY tm.event_created_at DESC, tm.event_id ASC LIMIT ")); + + type Change = fn(&mut EventQuery); + let generic: [(&str, Change); 10] = [ + ("two roots", |q| { + q.e_tags = Some(vec!["ab".repeat(32), "cd".repeat(32)]) + }), + ("reaction kind", |q| q.kinds = Some(vec![9, 7])), + ("no kinds", |q| q.kinds = None), + ("no channel", |q| q.channel_id = None), + ("uppercase root", |q| q.e_tags = Some(vec!["AB".repeat(32)])), + ("p join", |q| q.p_tag_hex = Some("cd".repeat(32))), + ("exact match", |q| q.exact_match = true), + ("authors", |q| q.authors = Some(vec![vec![0xcd; 32]])), + ("pubkey", |q| q.pubkey = Some(vec![0xcd; 32])), + ("ids", |q| q.ids = Some(vec![vec![0xcd; 32]])), + ]; + for (label, change) in generic { + let mut q = routed(); + change(&mut q); + assert!(thread_reply_root(&q).is_none(), "{label}"); + let sql = build_query_events_sql(&q, Range::All, page_limit(&q)) + .sql() + .as_str() + .to_owned(); + assert!(!sql.contains("thread_metadata"), "{label}"); + } + } + + /// An `#a` read is a reference lookup like `#e`, so it is fenced the same + /// way; COUNT applies the same match. + #[test] + fn a_tag_query_filters_in_materialized_fence() { + let mut q = EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())); + q.kinds = Some(vec![7]); + q.a_tags = Some(vec![format!("30175:{}:persona", "ab".repeat(32))]); + let sql = build_query_events_sql(&q, Range::All, page_limit(&q)) + .sql() + .as_str() + .to_owned(); + + assert!(sql.starts_with("WITH m AS MATERIALIZED (SELECT ")); + assert_eq!(sql.matches("tags @> ANY(").count(), 1); + let fence_end = sql.find(") SELECT * FROM m ").expect("fence closes"); + assert!(!sql[..fence_end].contains("LIMIT")); + assert!(count_events_sql(&q).sql().as_str().contains("tags @> ANY(")); + } + #[test] fn non_e_tag_query_is_not_fenced() { let q = EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())); - let qb = build_query_events_sql(&q); + let qb = build_query_events_sql(&q, Range::All, page_limit(&q)); assert!(!qb.sql().as_str().contains("MATERIALIZED")); } + /// Each pass bounds `created_at` with literals so Postgres prunes + /// partitions while planning: the recent pass on both sides, the older + /// pass below the floor. A `#p` read bounds the mention side too. An + /// unsplit read and the COUNT carry no bound. + #[test] + fn split_passes_bound_created_at_with_a_literal() { + let at = |m| chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, m, 1, 0, 0, 0).unwrap(); + let split = crate::store::recent_pass::Split { + floor: at(10), + ceiling: Some(at(12)), + older: true, + }; + let floor = "'2026-10-01T00:00:00Z'::timestamptz"; + let ceiling = "'2026-12-01T00:00:00Z'::timestamptz"; + let sql = |q: &EventQuery, range| { + build_query_events_sql(q, range, 7) + .sql() + .as_str() + .to_owned() + }; + let mut q = EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())); + q.kinds = Some(vec![9]); + let recent = sql(&q, Range::Recent(split)); + for bound in [ + format!(" AND created_at >= {floor}"), + format!(" AND created_at < {ceiling}"), + ] { + assert!(recent.contains(&bound), "{recent}"); + } + let older = sql(&q, Range::Older(split.floor)); + assert!( + older.contains(&format!(" AND created_at < {floor}")), + "{older}" + ); + assert!(!older.contains(ceiling), "{older}"); + let whole = sql(&q, Range::All); + assert!(!whole.contains("::timestamptz"), "{whole}"); + + q.p_tag_hex = Some("ab".repeat(32)); + let bounds = [ + (Range::Recent(split), vec![(">=", floor), ("<", ceiling)]), + (Range::Older(split.floor), vec![("<", floor)]), + ]; + for (range, ops) in bounds { + let mention = sql(&q, range); + for column in ["e.created_at", "m.event_created_at"] { + for &(op, lit) in &ops { + let bound = format!(" AND {column} {op} {lit}"); + assert!(mention.contains(&bound), "{mention}"); + } + } + } + let count = count_events_sql(&q).sql().as_str().to_owned(); + assert!(!count.contains("::timestamptz"), "{count}"); + } + + /// Which reads are split: page reads are; offset reads, lookups that + /// match a fixed row set and fetch-everything reads are not. + #[test] + fn recent_pass_skips_lookups() { + let now = Utc::now(); + let base = || { + let mut q = EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())); + q.kinds = Some(vec![9]); + q + }; + assert!(recent_pass_split(&base(), now).is_some(), "page read"); + let mut first_page = base(); + first_page.offset = Some(0); + assert!(recent_pass_split(&first_page, now).is_some(), "offset 0"); + type Narrow = fn(&mut EventQuery); + let lookups: [(&str, Narrow); 8] = [ + ("offset", |q| q.offset = Some(1)), + ("ids", |q| q.ids = Some(vec![vec![0; 32]])), + ("e tags", |q| q.e_tags = Some(vec!["00".repeat(32)])), + ("a tags", |q| q.a_tags = Some(vec!["30175:00:x".into()])), + ("d tag", |q| q.d_tag = Some("x".into())), + ("d tags", |q| q.d_tags = Some(vec!["x".into()])), + ("artifact d tags", |q| { + q.d_tag_values = Some(vec!["x".into()]) + }), + ("max limit", |q| q.max_limit = Some(10_000)), + ]; + for (label, set) in lookups { + let mut q = base(); + set(&mut q); + assert!(recent_pass_split(&q, now).is_none(), "{label}"); + } + } + /// `#p` reads bound the mention side (bb-public runaway REQ): the join /// carries the event's `created_at`, and `since`/`until` also bound /// `m.event_created_at`, for both the page SELECT and the COUNT. @@ -2902,7 +3195,10 @@ mod e_tag_filter_shape_tests { q.since = Some(Utc::now()); q.until = Some(Utc::now()); q.kinds = Some(vec![9]); - let select = build_query_events_sql(&q).sql().as_str().to_owned(); + let select = build_query_events_sql(&q, Range::All, page_limit(&q)) + .sql() + .as_str() + .to_owned(); let count = count_events_sql(&q).sql().as_str().to_owned(); for (label, sql) in [("select", select), ("count", count)] { assert!( @@ -2923,16 +3219,139 @@ mod e_tag_filter_shape_tests { q.since = None; q.until = None; q.kinds = None; - let unbounded = build_query_events_sql(&q).sql().as_str().to_owned(); + let unbounded = build_query_events_sql(&q, Range::All, page_limit(&q)) + .sql() + .as_str() + .to_owned(); assert!(!unbounded.contains("m.event_created_at >=")); assert!(!unbounded.contains("m.event_created_at <=")); assert!(!unbounded.contains("m.event_kind")); } + + /// A multi-value `#d` read binds its values as one array, so the number of + /// values does not change the SQL text, in both the page SELECT and the + /// COUNT. One `IN ($n, …)` bind per value made a new statement (and a new + /// `pg_stat_statements` entry) for every arity. + #[test] + fn d_tag_sql_does_not_depend_on_value_count() { + let sql = |n: usize| { + let mut q = EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())); + q.kinds = Some(vec![39000]); + q.pubkey = Some(vec![7; 32]); + q.d_tags = Some((0..n).map(|i| format!("d{i}")).collect()); + ( + build_query_events_sql(&q, Range::All, page_limit(&q)) + .sql() + .as_str() + .to_owned(), + count_events_sql(&q).sql().as_str().to_owned(), + ) + }; + let two = sql(2); + assert_eq!(two, sql(128)); + for text in [&two.0, &two.1] { + assert!(text.contains("d_tag = ANY($"), "{text}"); + assert!(!text.contains("d_tag IN ("), "{text}"); + } + } + + /// The channel scope is one array bind: a viewer's channel count must not + /// change the SQL text, or each count is its own statement that is planned + /// again on every call. Holds for the `#p` join and plain reads, for + /// access scope and explicit `#h`, in both the page SELECT and the COUNT. + /// A plain explicit `#h` page within the candidate budget unnests the + /// bind and reads each channel; over it, the page is the set read. + #[test] + fn channel_scope_sql_does_not_depend_on_channel_count() { + let sql = |p_tag: bool, include_global: bool, n: usize| { + let mut q = EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())); + q.p_tag_hex = p_tag.then(|| "ab".repeat(32)); + q.kinds = Some(vec![9]); + q.channel_ids = Some((0..n).map(|_| uuid::Uuid::new_v4()).collect()); + q.channel_ids_include_global = include_global; + ( + build_query_events_sql(&q, Range::All, page_limit(&q)) + .sql() + .as_str() + .to_owned(), + count_events_sql(&q).sql().as_str().to_owned(), + ) + }; + for p_tag in [true, false] { + for include_global in [true, false] { + let one = sql(p_tag, include_global, 1); + assert_eq!(one, sql(p_tag, include_global, 40)); + let per_channel = !p_tag && !include_global; + assert_eq!( + one.0.contains("unnest($") && one.0.contains("channel_id = c.ch"), + per_channel, + "{}", + one.0 + ); + let set_reads = if per_channel { + vec![&one.1] + } else { + vec![&one.0, &one.1] + }; + for text in set_reads { + assert!(text.contains("channel_id = ANY($"), "{text}"); + assert!(!text.contains("channel_id IN ("), "{text}"); + assert_eq!( + text.contains("channel_id IS NULL OR "), + include_global, + "{text}" + ); + } + } + } + } + + /// Only a plain explicit `#h` page within the candidate budget reads + /// channel by channel: global events, a `#p` join, a reference-tag fence, an + /// offset, an empty set or a set × limit over the budget keep their own + /// SQL. + #[test] + fn per_channel_scope_eligibility() { + let base = || EventQuery { + channel_ids: Some(vec![uuid::Uuid::new_v4(), uuid::Uuid::new_v4()]), + channel_ids_include_global: false, + ..EventQuery::for_community(CommunityId::from_uuid(uuid::Uuid::nil())) + }; + assert!(per_channel_scope(&base()).is_some()); + let mut offset_zero = base(); + offset_zero.offset = Some(0); + assert!(per_channel_scope(&offset_zero).is_some()); + let at_budget = |channels: usize, limit: i64| EventQuery { + channel_ids: Some((0..channels).map(|_| uuid::Uuid::new_v4()).collect()), + limit: Some(limit), + ..base() + }; + assert!(per_channel_scope(&at_budget(16, 512)).is_some()); + assert!(per_channel_scope(&at_budget(17, 512)).is_none()); + assert!(per_channel_scope(&at_budget(128, 500)).is_none()); + // The clamped page limit counts, not the requested one. + assert!(per_channel_scope(&at_budget(8, 5_000)).is_some()); + type Edit = fn(&mut EventQuery); + let others: [(&str, Edit); 6] = [ + ("global", |q| q.channel_ids_include_global = true), + ("#p", |q| q.p_tag_hex = Some("ab".repeat(32))), + ("#e", |q| q.e_tags = Some(vec!["cd".repeat(32)])), + ("#a", |q| q.a_tags = Some(vec!["30175:cd:x".into()])), + ("offset", |q| q.offset = Some(1)), + ("empty", |q| q.channel_ids = Some(Vec::new())), + ]; + for (label, set) in others { + let mut q = base(); + set(&mut q); + assert!(per_channel_scope(&q).is_none(), "{label}"); + } + } } #[cfg(test)] mod postgres_tests { use super::*; + use crate::test_support::ScratchDb; use nostr::{EventBuilder, Keys, Kind, Tag}; const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 @@ -2989,45 +3408,765 @@ mod postgres_tests { .bind(like) .fetch_one(&mut *conn) .await - .expect("read prepared statements") + .expect("read prepared statements") + } + + /// Label/creator matches and multi-value `#d` reads must keep + /// parameter-aware planning. A cached generic plan ignores the values: a + /// label match scans every group-state row in the community instead of + /// using the `tags` GIN index, and a `#d` read walks the author's + /// `created_at` index and reads every stored version of the kind. The `#d` + /// read still returns and counts exactly the requested addresses. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn value_matched_queries_are_not_cached_as_prepared_statements() { + let pool = setup_pool().await; + let community = CommunityId::from_uuid(make_test_community(&pool).await); + let keys = Keys::generate(); + let mut addressed = Vec::new(); + for d in ["a", "b", "c"] { + let event = EventBuilder::new(Kind::Custom(30023), "") + .tags([Tag::parse(["d", d]).unwrap()]) + .sign_with_keys(&keys) + .unwrap(); + insert_event(&pool, community, &event, None) + .await + .expect("insert addressable event"); + addressed.push((d, event.id)); + } + let mut conn = pool.acquire().await.expect("acquire"); + // Clear SQLx's statement cache and Postgres's prepared statements + // together; a raw `DEALLOCATE ALL` would leave the client cache + // pointing at statements the server no longer has. + sqlx::Connection::clear_cached_statements(&mut *conn) + .await + .expect("clear prepared statements"); + + let mut label = EventQuery::for_community(community); + label.kinds = Some(vec![39000]); + label.tag_values = vec![("t".to_owned(), vec!["for-you".to_owned()])]; + let mut d_tags = EventQuery::for_community(community); + d_tags.kinds = Some(vec![30023]); + d_tags.pubkey = Some(keys.public_key().to_bytes().to_vec()); + d_tags.d_tags = Some(vec!["a".to_owned(), "c".to_owned()]); + for (q, statement) in [(&label, "%tags @> ANY(%"), (&d_tags, "%d_tag = ANY(%")] { + for _ in 0..6 { + query_events_on(&mut conn, q, ReadDeadline::PerRead) + .await + .expect("value-matched query"); + count_events_on(&mut conn, q, ReadDeadline::PerRead) + .await + .expect("value-matched count"); + } + assert_eq!(prepared_like(&mut conn, statement).await, 0, "{statement}"); + } + + let mut page: Vec<_> = query_events_on(&mut conn, &d_tags, ReadDeadline::PerRead) + .await + .expect("d-tag page") + .into_iter() + .map(|stored| stored.event.id) + .collect(); + page.sort(); + let mut expected: Vec<_> = addressed + .iter() + .filter(|(d, _)| *d != "b") + .map(|(_, id)| *id) + .collect(); + expected.sort(); + assert_eq!(page, expected, "exactly the requested addresses"); + assert_eq!( + count_events_on(&mut conn, &d_tags, ReadDeadline::PerRead) + .await + .expect("d-tag count"), + 2 + ); + + // Control: the same query without a value match stays a cached + // statement, so the checks above can see one. + label.tag_values.clear(); + query_events_on(&mut conn, &label, ReadDeadline::PerRead) + .await + .expect("plain query"); + assert!(prepared_like(&mut conn, "%FROM events%").await > 0); + } + + /// Access-scoped `#p` reads for viewers with different channel counts + /// share one cached statement on a connection, so Postgres can keep its + /// plan instead of planning every read again. Every scope, empty included, + /// still returns and counts exactly its own rows. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_scoped_mention_reads_share_one_prepared_statement() { + let pool = setup_pool().await; + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let mut channels = Vec::new(); + for _ in 0..3 { + channels.push(make_test_channel(&pool, community_uuid, None).await); + } + let mut conn = pool.acquire().await.expect("acquire"); + // Clear SQLx's statement cache and Postgres's prepared statements + // together; a raw `DEALLOCATE ALL` would leave the client cache + // pointing at statements the server no longer has. + sqlx::Connection::clear_cached_statements(&mut *conn) + .await + .expect("clear prepared statements"); + for n in 1..=channels.len() { + let q = EventQuery { + kinds: Some(vec![9]), + p_tag_hex: Some("ab".repeat(32)), + channel_ids: Some(channels[..n].to_vec()), + ..EventQuery::for_community(community) + }; + query_events_on(&mut conn, &q, ReadDeadline::PerRead) + .await + .expect("mention read"); + } + // Each read is a recent pass (empty here) and then the older pass: one + // statement of each, shared by every channel count. + assert_eq!( + prepared_like(&mut conn, "%JOIN event_mentions%").await, + 2, + "one recent and one older statement for every channel count" + ); + drop(conn); + + // The array bind keeps each scope's rows: one mention of the target in + // each scoped channel, one global, and one in a channel no scope names. + let db = crate::Db::from_pool(pool.clone()); + let author = Keys::generate(); + let target = "ab".repeat(32); + let mention = |content: String| { + EventBuilder::new(Kind::Custom(9), content) + .tags([Tag::parse(["p", target.as_str()]).expect("p tag")]) + .sign_with_keys(&author) + .expect("sign mention") + }; + let mut in_channel = Vec::new(); + for (i, channel) in channels.iter().enumerate() { + let event = mention(format!("in channel {i}")); + db.insert_event(community, &event, Some(*channel)) + .await + .expect("insert channel mention"); + in_channel.push(event.id); + } + let global = mention("global".into()); + db.insert_event(community, &global, None) + .await + .expect("insert global mention"); + let outside_channel = make_test_channel(&pool, community_uuid, None).await; + db.insert_event(community, &mention("outside".into()), Some(outside_channel)) + .await + .expect("insert out-of-scope mention"); + + for n in 0..=channels.len() { + for include_global in [true, false] { + let q = EventQuery { + kinds: Some(vec![9]), + p_tag_hex: Some(target.clone()), + channel_ids: Some(channels[..n].to_vec()), + channel_ids_include_global: include_global, + ..EventQuery::for_community(community) + }; + let mut expected = in_channel[..n].to_vec(); + if include_global { + expected.push(global.id); + } + expected.sort(); + let mut page: Vec<_> = query_events(&pool, &q) + .await + .expect("mention page") + .into_iter() + .map(|stored| stored.event.id) + .collect(); + page.sort(); + assert_eq!( + page, expected, + "{n} channels, include_global={include_global}: page" + ); + assert_eq!( + count_events(&pool, &q).await.expect("mention count"), + expected.len() as i64, + "{n} channels, include_global={include_global}: count" + ); + } + } + } + + /// An explicit channel set is read one channel at a time and returns the + /// set read's page: newest first across channels with id ties broken + /// ascending, one channel holding the whole page, other kinds and other + /// channels taking no slot, a repeated id read once, keyset cursors and + /// `since`, and older rows the recent pass leaves missing. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn per_channel_reads_match_the_set_read() { + let pool = setup_pool().await; + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let mut channels = Vec::new(); + for _ in 0..4 { + channels.push(make_test_channel(&pool, community_uuid, None).await); + } + let (busy, quiet, empty, outside) = (channels[0], channels[1], channels[2], channels[3]); + let author = Keys::generate(); + let now = Utc::now().timestamp() as u64; + let floor = crate::store::recent_pass::floor_at(Utc::now()).timestamp() as u64; + let mut matching = Vec::new(); + let mut insert = |channel: Uuid, kind: u16, at: u64, matches: bool| { + let event = + EventBuilder::new(Kind::Custom(kind), format!("{kind} at {at} in {channel}")) + .custom_created_at(nostr::Timestamp::from(at)) + .sign_with_keys(&author) + .expect("sign"); + if matches { + matching.push((at, event.id)); + } + (channel, event) + }; + let mut events = Vec::new(); + // The busy channel alone holds the newest five rows. + for i in 0..5 { + events.push(insert(busy, 9, now - 10 - i, true)); + } + // Newer rows of another kind or another channel take no slot. + events.push(insert(busy, 7, now - 1, false)); + events.push(insert(outside, 9, now - 2, false)); + // A tie across channels, then older rows on both sides of the floor. + events.push(insert(busy, 9, now - 100, true)); + events.push(insert(quiet, 9, now - 100, true)); + events.push(insert(quiet, 9, now - 200, true)); + events.push(insert(busy, 9, floor - 86_400, true)); + events.push(insert(quiet, 9, floor - 2 * 86_400, true)); + for (channel, event) in &events { + // Rows already in storage: the floor rejects the aged ones. + crate::test_support::insert_historical_event(&pool, community, event, *channel).await; + } + matching.sort_by(|a, b| { + b.0.cmp(&a.0) + .then_with(|| a.1.as_bytes().cmp(b.1.as_bytes())) + }); + let expected: Vec<_> = matching.iter().map(|(_, id)| *id).collect(); + + let mut conn = pool.acquire().await.expect("acquire"); + sqlx::Connection::clear_cached_statements(&mut *conn) + .await + .expect("clear prepared statements"); + let read = |limit: i64| EventQuery { + kinds: Some(vec![9]), + channel_ids: Some(vec![busy, quiet, empty, busy]), + channel_ids_include_global: false, + limit: Some(limit), + ..EventQuery::for_community(community) + }; + let ids = |rows: Vec| rows.into_iter().map(|r| r.event.id).collect::>(); + + for limit in 1..=expected.len() as i64 + 1 { + let page = query_events_on(&mut conn, &read(limit), ReadDeadline::PerRead) + .await + .expect("page"); + let want = &expected[..expected.len().min(limit as usize)]; + assert_eq!(ids(page), want, "limit {limit}"); + } + assert!( + prepared_like(&mut conn, "%CROSS JOIN LATERAL%channel_id = c.ch%").await >= 1, + "the set was read per channel" + ); + assert_eq!( + prepared_like(&mut conn, "%channel_id = ANY(%").await, + 0, + "no set read ran" + ); + + // Keyset pages walk the same order, across the tie and the floor. + let first = query_events_on(&mut conn, &read(6), ReadDeadline::PerRead) + .await + .expect("first page"); + let last = first.last().expect("full first page").clone(); + let mut next = read(6); + next.until = Some( + DateTime::from_timestamp(last.event.created_at.as_secs() as i64, 0).expect("until"), + ); + next.before_id = Some(last.event.id.as_bytes().to_vec()); + let page = query_events_on(&mut conn, &next, ReadDeadline::PerRead) + .await + .expect("next page"); + assert_eq!(ids(first), expected[..6]); + assert_eq!(ids(page), expected[6..]); + + let mut since = read(10); + since.since = Some(DateTime::from_timestamp((now - 100) as i64, 0).expect("since")); + let page = query_events_on(&mut conn, &since, ReadDeadline::PerRead) + .await + .expect("since page"); + assert_eq!(ids(page), expected[..7]); + } + + /// The `events` partitions one pass of `q` over `range` locks, run in a + /// transaction of its own on `conn`, after checking that it returns + /// `rows` rows. Run it under `plan_cache_mode = force_generic_plan` to see + /// what a cached generic plan locks. + async fn locked_partitions( + conn: &mut sqlx::PgConnection, + q: &EventQuery, + range: Range, + rows: usize, + ) -> std::collections::BTreeSet { + let mut tx = sqlx::Connection::begin(conn).await.expect("begin"); + let mut qb = build_query_events_sql(q, range, 10); + let read = qb + .build() + .persistent(true) + .fetch_all(&mut *tx) + .await + .expect("pass"); + assert_eq!(read.len(), rows, "the pass reads every row: {range:?}"); + let locked: Vec = sqlx::query_scalar( + "SELECT c.relname::text FROM pg_locks l \ + JOIN pg_class c ON c.oid = l.relation \ + JOIN pg_inherits i ON i.inhrelid = c.oid \ + WHERE l.pid = pg_backend_pid() \ + AND i.inhparent = 'events'::regclass", + ) + .fetch_all(&mut *tx) + .await + .expect("locked partitions"); + tx.rollback().await.expect("rollback"); + locked.into_iter().collect() + } + + /// The recent pass of a regular-kind read locks only the partitions + /// between its floor and ceiling, even as a cached generic plan. Without + /// the ceiling (a read that may match latest-state kinds) it also locks + /// the monthlies made ahead of time and the open-ended last partition. + /// Mutation: drop the ceiling from `Range::predicate`, or set it for + /// every split read → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn recent_pass_locks_only_the_partitions_below_its_ceiling() { + use crate::store::recent_pass::{ceiling_at, split_for}; + let pool = setup_pool().await; + let db = crate::Db::from_pool(pool.clone()); + // The layout a running relay keeps: dated monthlies through the + // months ahead, then an open-ended catch-all. + db.maintain_partitions( + crate::partition::PARTITION_MANAGER_MONTHS_AHEAD, + crate::partition::PartitionMaintenancePolicy { + create_enabled: true, + advance_enabled: true, + }, + ) + .await + .expect("maintain partitions"); + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let channel = make_test_channel(&pool, community_uuid, None).await; + + let now = Utc::now(); + let ceiled = split_for(now, Some(&[9]), None, None).expect("split"); + let open = split_for(now, Some(&[9, 39002]), None, None).expect("split"); + assert_eq!(ceiled.ceiling, Some(ceiling_at(now))); + assert_eq!(open.ceiling, None); + + // One row at each edge of the ceiled range names its partitions. + let author = Keys::generate(); + let mut expected = std::collections::BTreeSet::new(); + let last = ceiling_at(now) - chrono::Duration::seconds(1); + for at in [ceiled.floor, now, last] { + let event = EventBuilder::new(Kind::Custom(9), format!("at {at}")) + .custom_created_at(nostr::Timestamp::from(at.timestamp() as u64)) + .sign_with_keys(&author) + .expect("sign"); + crate::test_support::insert_historical_event(&pool, community, &event, channel).await; + let partition: String = + sqlx::query_scalar("SELECT tableoid::regclass::text FROM events WHERE id = $1") + .bind(event.id.as_bytes().to_vec()) + .fetch_one(&pool) + .await + .expect("partition"); + expected.insert(partition); + } + + let mut conn = pool.acquire().await.expect("acquire"); + sqlx::query("SET plan_cache_mode = force_generic_plan") + .execute(&mut *conn) + .await + .expect("force generic plans"); + let q = EventQuery { + kinds: Some(vec![9]), + channel_id: Some(channel), + ..EventQuery::for_community(community) + }; + let ceiled_locks = locked_partitions(&mut conn, &q, Range::Recent(ceiled), 3).await; + assert_eq!(ceiled_locks, expected, "partitions below the ceiling"); + let open_locks = locked_partitions(&mut conn, &q, Range::Recent(open), 3).await; + assert!( + open_locks.is_superset(&ceiled_locks) && open_locks.len() > ceiled_locks.len(), + "without the ceiling the pass also locks the later partitions: {open_locks:?}" + ); + } + + /// A read whose own `since` is at or above the floor, such as a `#p` + /// mention REQ from an agent reconnecting, is one recent pass: it returns + /// every matching row and runs no older pass. As a cached generic plan, + /// its literal floor and ceiling lock only the partitions between them, + /// where the `since` bind alone (the read whole) locks every partition. + /// Mutation: drop the `since` case from `split_for`, or run the older + /// pass after it → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn since_bounded_mention_read_locks_only_recent_partitions() { + use crate::store::recent_pass::{ceiling_at, floor_at, next}; + let pool = setup_pool().await; + let db = crate::Db::from_pool(pool.clone()); + db.maintain_partitions( + crate::partition::PARTITION_MANAGER_MONTHS_AHEAD, + crate::partition::PartitionMaintenancePolicy { + create_enabled: true, + advance_enabled: true, + }, + ) + .await + .expect("maintain partitions"); + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let channel = make_test_channel(&pool, community_uuid, None).await; + + // Mentions of the target at the floor, now and a second below the + // ceiling, newest first, and one the day before the floor. + let now = Utc::now(); + let floor = floor_at(now); + let author = Keys::generate(); + let target = "ab".repeat(32); + let mut recent = Vec::new(); + let mut expected = std::collections::BTreeSet::new(); + let last = ceiling_at(now) - chrono::Duration::seconds(1); + for at in [last, now, floor, floor - chrono::Duration::days(1)] { + let event = EventBuilder::new(Kind::Custom(9), format!("at {at}")) + .tags([Tag::parse(["p", target.as_str()]).expect("p tag")]) + .custom_created_at(nostr::Timestamp::from(at.timestamp() as u64)) + .sign_with_keys(&author) + .expect("sign"); + crate::test_support::insert_historical_event(&pool, community, &event, channel).await; + if at >= floor { + recent.push(event.id); + let partition: String = + sqlx::query_scalar("SELECT tableoid::regclass::text FROM events WHERE id = $1") + .bind(event.id.as_bytes().to_vec()) + .fetch_one(&pool) + .await + .expect("partition"); + expected.insert(partition); + } + } + + let q = EventQuery { + kinds: Some(vec![9]), + p_tag_hex: Some(target.clone()), + since: Some(floor), + limit: Some(10), + ..EventQuery::for_community(community) + }; + let split = recent_pass_split(&q, now).expect("a since-bounded read has a recent pass"); + assert!(!split.older, "rows below `since` cannot match"); + assert_eq!(next(Range::Recent(split), recent.len(), 10), None); + + // The production read: every matching row, from exactly the recent + // pass's statement, so the lock checks below bind what it prepared. + let mut conn = pool.acquire().await.expect("acquire"); + sqlx::Connection::clear_cached_statements(&mut *conn) + .await + .expect("clear prepared statements"); + let page = query_events_on(&mut conn, &q, ReadDeadline::PerRead) + .await + .expect("mention page"); + let ids: Vec<_> = page.into_iter().map(|r| r.event.id).collect(); + assert_eq!(ids, recent); + let prepared: Vec = sqlx::query_scalar( + "SELECT statement FROM pg_prepared_statements WHERE statement LIKE $1", + ) + .bind("%JOIN event_mentions%") + .fetch_all(&mut *conn) + .await + .expect("read prepared statements"); + let recent_pass = build_query_events_sql(&q, Range::Recent(split), 10) + .sql() + .as_str() + .to_owned(); + assert_eq!(prepared, [recent_pass], "one pass, bounded by literals"); + + sqlx::query("SET plan_cache_mode = force_generic_plan") + .execute(&mut *conn) + .await + .expect("force generic plans"); + let bounded = locked_partitions(&mut conn, &q, Range::Recent(split), recent.len()).await; + assert_eq!( + bounded, expected, + "partitions between the floor and ceiling" + ); + let bind_only = locked_partitions(&mut conn, &q, Range::All, recent.len()).await; + let every: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_inherits WHERE inhparent = 'events'::regclass", + ) + .fetch_one(&mut *conn) + .await + .expect("partitions"); + assert_eq!( + bind_only.len() as i64, + every, + "the `since` bind alone locks every partition: {bind_only:?}" + ); + } + + /// A newest-first page read split at the floor returns the rows the + /// unsplit read returns: the recent pass alone when it fills the page, + /// otherwise followed by the older pass for just the missing rows. + /// Prepared statements show which passes ran. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn split_page_reads_match_the_unsplit_read() { + let pool = setup_pool().await; + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let channel = make_test_channel(&pool, community_uuid, None).await; + let author = Keys::generate(); + let now = Utc::now().timestamp() as u64; + let floor = crate::store::recent_pass::floor_at(Utc::now()).timestamp() as u64; + // Three rows inside the recent window, two before it, newest first. + let mut newest_first = Vec::new(); + for at in [ + now - 10, + now - 20, + now - 30, + floor - 86_400, + floor - 2 * 86_400, + ] { + let event = EventBuilder::new(Kind::Custom(9), format!("at {at}")) + .custom_created_at(nostr::Timestamp::from(at)) + .sign_with_keys(&author) + .expect("sign"); + crate::test_support::insert_historical_event(&pool, community, &event, channel).await; + newest_first.push(event.id); + } + + let mut conn = pool.acquire().await.expect("acquire"); + sqlx::Connection::clear_cached_statements(&mut *conn) + .await + .expect("clear prepared statements"); + let read = |limit: i64, offset: i64| EventQuery { + kinds: Some(vec![9]), + channel_id: Some(channel), + limit: Some(limit), + offset: Some(offset), + ..EventQuery::for_community(community) + }; + let ids = |rows: Vec| rows.into_iter().map(|r| r.event.id).collect::>(); + // The recent pass of this kind:9 read also stops at the ceiling, so + // the older pass is told apart by its `<` bound at the floor. + let floor_lit = + crate::store::recent_pass::floor_at(Utc::now()).format("%Y-%m-%dT%H:%M:%SZ"); + let ceiling_lit = + crate::store::recent_pass::ceiling_at(Utc::now()).format("%Y-%m-%dT%H:%M:%SZ"); + let recent = &format!( + "%FROM events WHERE%created_at >= '{floor_lit}'::timestamptz \ + AND created_at < '{ceiling_lit}'::timestamptz%" + ); + let older = &format!("%FROM events WHERE%created_at < '{floor_lit}'::timestamptz%"); + let all = "%FROM events WHERE%"; + + // Full recent page: answered by the recent pass alone. + let page = query_events_on(&mut conn, &read(3, 0), ReadDeadline::PerRead) + .await + .expect("recent page"); + assert_eq!(ids(page), newest_first[..3]); + assert_eq!(prepared_like(&mut conn, recent).await, 1, "recent pass ran"); + assert_eq!(prepared_like(&mut conn, all).await, 1, "nothing else ran"); + + // Short recent pages: the older pass adds only the missing rows. + for limit in [4, 5, 6] { + let page = query_events_on(&mut conn, &read(limit, 0), ReadDeadline::PerRead) + .await + .expect("split page"); + let expected = &newest_first[..newest_first.len().min(limit as usize)]; + assert_eq!(ids(page), expected, "limit {limit}"); + } + assert_eq!(prepared_like(&mut conn, older).await, 1, "older pass ran"); + assert_eq!(prepared_like(&mut conn, all).await, 2, "no unsplit read"); + + // An offset spans the floor, so the read is not split. + let page = query_events_on(&mut conn, &read(2, 1), ReadDeadline::PerRead) + .await + .expect("offset page"); + assert_eq!(ids(page), newest_first[1..3]); + let page = query_events_on(&mut conn, &read(3, 2), ReadDeadline::PerRead) + .await + .expect("offset page across the floor"); + assert_eq!(ids(page), newest_first[2..5]); + assert_eq!(prepared_like(&mut conn, all).await, 3, "unsplit read ran"); + + // A cursor below the floor is not split either: still exact. + let mut below = read(5, 0); + below.until = Some(DateTime::from_timestamp((floor - 1) as i64, 0).expect("until")); + let page = query_events_on(&mut conn, &below, ReadDeadline::PerRead) + .await + .expect("cursor page"); + assert_eq!(ids(page), newest_first[3..]); + + // A failed older pass fails the read; it never passes the recent rows + // off as a short page. Another session locks the partition of a row + // from before every dated monthly, which only the older pass plans + // (the recent rows' partition can hold rows below the floor too). + let ancient = EventBuilder::new(Kind::Custom(9), "ancient") + .custom_created_at(nostr::Timestamp::from(1_748_736_000)) // 2025-06-01 + .sign_with_keys(&author) + .expect("sign"); + crate::test_support::insert_historical_event(&pool, community, &ancient, channel).await; + let partition_of = |id: nostr::EventId| { + let pool = pool.clone(); + async move { + sqlx::query_scalar::<_, String>( + "SELECT tableoid::regclass::text FROM events WHERE id = $1", + ) + .bind(id.as_bytes().to_vec()) + .fetch_one(&pool) + .await + .expect("partition") + } + }; + let old_partition = partition_of(ancient.id).await; + assert_ne!(old_partition, partition_of(newest_first[0]).await); + let mut locker = pool.begin().await.expect("begin locker"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "LOCK TABLE {old_partition} IN ACCESS EXCLUSIVE MODE" + ))) + .execute(&mut *locker) + .await + .expect("lock old partition"); + sqlx::query("SET lock_timeout = '200ms'") + .execute(&mut *conn) + .await + .expect("set lock_timeout"); + let page = query_events_on(&mut conn, &read(3, 0), ReadDeadline::PerRead) + .await + .expect("a full recent page never touches the old partition"); + assert_eq!(ids(page), newest_first[..3]); + let failed = query_events_on(&mut conn, &read(5, 0), ReadDeadline::PerRead).await; + assert!( + failed.is_err(), + "a failed older pass must fail the read, got {:?} rows", + failed.map(|rows| rows.len()) + ); + locker.rollback().await.expect("release lock"); + sqlx::query("RESET lock_timeout") + .execute(&mut *conn) + .await + .expect("reset lock_timeout"); } - /// A label or creator match must keep parameter-aware planning. A cached - /// generic plan ignores the label value and scans every group-state row in - /// the community instead of using the `tags` GIN index. + /// The passes of a split read share one snapshot: a replacement that + /// commits between them neither drops the row it replaces nor shows the + /// row it adds. Both deadline modes open the read the same way. #[tokio::test] #[ignore = "requires Postgres"] - async fn tag_value_queries_are_not_cached_as_prepared_statements() { + async fn split_read_passes_share_one_snapshot() { let pool = setup_pool().await; - let community = CommunityId::from_uuid(make_test_community(&pool).await); - let mut conn = pool.acquire().await.expect("acquire"); - sqlx::query("DEALLOCATE ALL") - .execute(&mut *conn) - .await - .expect("clear prepared statements"); - let mut q = EventQuery::for_community(community); - q.kinds = Some(vec![39000]); - q.tag_values = vec![("t".to_owned(), vec!["for-you".to_owned()])]; - for _ in 0..6 { - query_events_on(&mut conn, &q).await.expect("label query"); - count_events_on(&mut conn, &q).await.expect("label count"); + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + for deadline in [ReadDeadline::PerRead, ReadDeadline::Session] { + let channel = make_test_channel(&pool, community_uuid, None).await; + let q = EventQuery { + kinds: Some(vec![9]), + channel_id: Some(channel), + limit: Some(10), + ..EventQuery::for_community(community) + }; + let (page, expected) = crate::test_support::replace_between_passes( + &pool, + community, + channel, + move |mut conn| async move { + query_events_on(&mut conn, &q, deadline) + .await + .expect("split read") + .into_iter() + .map(|stored| stored.event.id) + .collect::>() + }, + ) + .await; + assert_eq!(page, expected, "{deadline:?}"); } - assert_eq!(prepared_like(&mut conn, "%tags @> ANY(%").await, 0); + } - // Control: the same query without a tag match stays a cached statement, - // so the check above can see one. - q.tag_values.clear(); - query_events_on(&mut conn, &q).await.expect("plain query"); - assert!(prepared_like(&mut conn, "%FROM events%").await > 0); + /// The statements of one read share its deadline: each after the first + /// runs under what the earlier ones left, and ending the read restores + /// the connection's own. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn read_statements_share_one_deadline() { + use sqlx::Connection as _; + let pool = setup_pool().await; + let timeout_ms = || { + sqlx::query( + "SELECT (EXTRACT(EPOCH FROM current_setting('statement_timeout')::interval) \ + * 1000)::float8", + ) + }; + let full = READ_DEADLINE.as_millis() as f64; + for case in ["per read", "session", "inside a transaction"] { + let mut conn = pool.acquire().await.expect("acquire").detach(); + let deadline = match case { + "session" => { + tighten_session_read_statement_timeout(&mut conn) + .await + .expect("session deadline"); + ReadDeadline::Session + } + _ => ReadDeadline::PerRead, + }; + let mut outer = None; + let conn: &mut sqlx::PgConnection = if case == "inside a transaction" { + outer = Some(conn.begin().await.expect("begin outer")); + outer.as_mut().expect("outer") + } else { + &mut conn + }; + let before: String = sqlx::query_scalar("SHOW statement_timeout") + .fetch_one(&mut *conn) + .await + .expect("show timeout"); + let mut read = ReadTransaction::begin(&mut *conn, deadline) + .await + .expect("begin read"); + let first: f64 = read.fetch(timeout_ms()).await.expect("first")[0].get(0); + let second: f64 = read.fetch(timeout_ms()).await.expect("second")[0].get(0); + read.finish().await.expect("finish"); + assert_eq!( + first, full, + "{case}: the first statement gets the whole deadline" + ); + assert!( + (1.0..full).contains(&second), + "{case}: the second gets what is left, got {second} ms" + ); + let after: String = sqlx::query_scalar("SHOW statement_timeout") + .fetch_one(&mut *conn) + .await + .expect("show timeout"); + assert_eq!(after, before, "{case}: restored"); + drop(outer); + } } /// Effective `statement_timeout` observed *inside* the read deadline, and /// the value restored on `conn` afterwards. async fn deadline_inside_and_after(conn: &mut sqlx::PgConnection) -> (String, String) { let mut qb = QueryBuilder::new("SELECT current_setting('statement_timeout')"); - let rows = fetch_with_read_deadline(conn, &mut qb, true) - .await - .expect("deadline read"); + let rows = + fetch_with_read_deadline(conn, qb.build().persistent(true), ReadDeadline::PerRead) + .await + .expect("deadline read"); let inside: String = rows[0].get(0); let after: String = sqlx::query_scalar("SHOW statement_timeout") .fetch_one(&mut *conn) @@ -3047,6 +4186,7 @@ mod postgres_tests { let keys = Keys::generate(); let now = nostr::Timestamp::now().as_secs(); let target = "ab".repeat(32); + let address = format!("30175:{target}:persona"); let insert = |kind: u16, tag: Vec<&str>, at: u64| { let event = EventBuilder::new(Kind::Custom(kind), "") .tags([Tag::parse(tag).unwrap()]) @@ -3105,6 +4245,17 @@ mod postgres_tests { q }, }, + Case { + label: "a tag shifted right", + kind: 7, + real: vec!["a", &address], + decoy: vec!["x", "a", &address], + query: { + let mut q = EventQuery::for_community(community); + q.a_tags = Some(vec![address.clone()]); + q + }, + }, Case { label: "artifact d tag shifted right", kind: artifact_kind, @@ -3139,6 +4290,274 @@ mod postgres_tests { } } + /// A single-root `#e` read for channel messages is served from + /// `thread_metadata`: newest first, nested replies and both message kinds + /// included, deleted replies excluded, keyset pages exact, never a cached + /// statement. A message naming the root in a bare `e` tag has no thread + /// row, so it is omitted, while any read the route does not take (here, + /// one that also asks for reactions) still returns it. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn thread_reply_reads_use_thread_metadata() { + let pool = setup_pool().await; + let db = Db::from_pool(pool.clone()); + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let channel = make_test_channel(&pool, community_uuid, None).await; + let keys = Keys::generate(); + // Inside the `created_at` floor (960 s) even with the later offsets. + let now = nostr::Timestamp::now().as_secs() - 600; + let h = channel.to_string(); + let message = |kind: u16, tags: Vec>, at: u64| { + EventBuilder::new(Kind::Custom(kind), "") + .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) + .custom_created_at(nostr::Timestamp::from(at)) + .sign_with_keys(&keys) + .unwrap() + }; + let ts = |ev: &nostr::Event| { + DateTime::from_timestamp(ev.created_at.as_secs() as i64, 0).unwrap() + }; + + let root = message(9, vec![vec!["h".into(), h.clone()]], now); + insert_event(&pool, community, &root, Some(channel)) + .await + .unwrap(); + let root_hex = root.id.to_hex(); + let root_id = root.id.as_bytes(); + + // A reply as ingest records one: `reply` names the parent (the root + // for a direct reply), and a nested reply also names the root. + let reply = |kind: u16, parent: Option<&nostr::Event>, at: u64| { + let mut tags = vec![vec!["h".into(), h.clone()]]; + if parent.is_some() { + tags.push(vec![ + "e".into(), + root_hex.clone(), + String::new(), + "root".into(), + ]); + } + tags.push(vec![ + "e".into(), + parent.map_or(root_hex.clone(), |p| p.id.to_hex()), + String::new(), + "reply".into(), + ]); + message(kind, tags, at) + }; + let mut expected = Vec::new(); + let mut first = None; + for (i, kind) in [9, 40002, 9, 9, 9].into_iter().enumerate() { + let ev = reply(kind, None, now + 1 + i as u64); + db.insert_event_with_thread_metadata( + community, + &ev, + Some(channel), + Some(ThreadMetadataParams { + event_id: ev.id.as_bytes(), + event_created_at: ts(&ev), + channel_id: channel, + parent_event_id: Some(root_id), + parent_event_created_at: Some(ts(&root)), + root_event_id: Some(root_id), + root_event_created_at: Some(ts(&root)), + depth: 1, + broadcast: false, + }), + ) + .await + .unwrap(); + expected.push(ev.id); + first.get_or_insert(ev); + } + let first = first.unwrap(); + let nested = reply(9, Some(&first), now + 10); + db.insert_event_with_thread_metadata( + community, + &nested, + Some(channel), + Some(ThreadMetadataParams { + event_id: nested.id.as_bytes(), + event_created_at: ts(&nested), + channel_id: channel, + parent_event_id: Some(first.id.as_bytes()), + parent_event_created_at: Some(ts(&first)), + root_event_id: Some(root_id), + root_event_created_at: Some(ts(&root)), + depth: 2, + broadcast: false, + }), + ) + .await + .unwrap(); + expected.push(nested.id); + let deleted = reply(9, None, now + 11); + db.insert_event_with_thread_metadata( + community, + &deleted, + Some(channel), + Some(ThreadMetadataParams { + event_id: deleted.id.as_bytes(), + event_created_at: ts(&deleted), + channel_id: channel, + parent_event_id: Some(root_id), + parent_event_created_at: Some(ts(&root)), + root_event_id: Some(root_id), + root_event_created_at: Some(ts(&root)), + depth: 1, + broadcast: false, + }), + ) + .await + .unwrap(); + soft_delete_event_and_update_thread( + &pool, + community, + deleted.id.as_bytes(), + Some(root_id), + Some(root_id), + ) + .await + .unwrap(); + // Ingest records no thread row for a bare or a lone `root` e tag. + let mut unrecorded = Vec::new(); + for (i, marker) in [None, Some("root")].into_iter().enumerate() { + let mut e = vec!["e".to_string(), root_hex.clone()]; + if let Some(m) = marker { + e.extend([String::new(), m.into()]); + } + let ev = message(9, vec![vec!["h".into(), h.clone()], e], now + 12 + i as u64); + insert_event(&pool, community, &ev, Some(channel)) + .await + .unwrap(); + unrecorded.insert(0, ev.id); + } + expected.reverse(); + + let ids = |rows: Vec| rows.into_iter().map(|r| r.event.id).collect::>(); + let mut q = EventQuery::for_community(community); + q.channel_id = Some(channel); + q.kinds = Some(vec![9, 40002]); + q.e_tags = Some(vec![root_hex.clone()]); + q.limit = Some(100); + assert!(thread_reply_root(&q).is_some()); + assert_eq!(ids(query_events(&pool, &q).await.unwrap()), expected); + + let mut generic = q.clone(); + generic.kinds = Some(vec![9, 40002, 7]); + assert!(thread_reply_root(&generic).is_none()); + let with_unrecorded = [unrecorded, expected.clone()].concat(); + assert_eq!( + ids(query_events(&pool, &generic).await.unwrap()), + with_unrecorded + ); + // A COUNT fallback must see the same set as the SQL COUNT path. + let mut exact = q.clone(); + exact.exact_match = true; + assert_eq!( + ids(query_events(&pool, &exact).await.unwrap()), + with_unrecorded + ); + + // The root has its depth-0 stub row yet is not a reply; P is. + let mut conn = pool.acquire().await.expect("acquire"); + let stub: i64 = sqlx::query_scalar( + "SELECT count(*) FROM thread_metadata WHERE community_id = $1 AND event_id = $2", + ) + .bind(community.as_uuid()) + .bind(root_id.to_vec()) + .fetch_one(&mut *conn) + .await + .unwrap(); + assert_eq!(stub, 1, "ingest leaves a stub row for the root"); + for (id, reply) in [(root_id, false), (first.id.as_bytes(), true)] { + let got = is_recorded_reply(&mut conn, &q, id, ReadDeadline::PerRead).await; + assert_eq!(got.unwrap(), reply); + } + + // A nested parent's replies are recorded under the root, so reading + // them falls back to the generic path and still finds them. + let mut nested_parent = q.clone(); + nested_parent.e_tags = Some(vec![first.id.to_hex()]); + assert!(thread_reply_root(&nested_parent).is_some()); + assert_eq!( + ids(query_events(&pool, &nested_parent).await.unwrap()), + vec![nested.id] + ); + + // A legacy reply L, stored without its own thread row, gains a rootless + // stub when D replies to it. Its markers still make it a reply, so a + // read of L's replies falls back and finds D. + let legacy = message( + 9, + vec![ + vec!["h".into(), h.clone()], + vec!["e".into(), root_hex.clone(), String::new(), "reply".into()], + ], + now + 14, + ); + insert_event(&pool, community, &legacy, Some(channel)) + .await + .unwrap(); + let d = reply(9, Some(&legacy), now + 15); + db.insert_event_with_thread_metadata( + community, + &d, + Some(channel), + Some(ThreadMetadataParams { + event_id: d.id.as_bytes(), + event_created_at: ts(&d), + channel_id: channel, + parent_event_id: Some(legacy.id.as_bytes()), + parent_event_created_at: Some(ts(&legacy)), + root_event_id: Some(root_id), + root_event_created_at: Some(ts(&root)), + depth: 2, + broadcast: false, + }), + ) + .await + .unwrap(); + expected.insert(0, d.id); + let got = is_recorded_reply(&mut conn, &q, legacy.id.as_bytes(), ReadDeadline::PerRead); + assert!( + got.await.unwrap(), + "a stubbed legacy reply is still a reply" + ); + let mut legacy_parent = q.clone(); + legacy_parent.e_tags = Some(vec![legacy.id.to_hex()]); + assert_eq!( + ids(query_events(&pool, &legacy_parent).await.unwrap()), + vec![d.id] + ); + + // Keyset pages of two cover the same order. + let mut paged = Vec::new(); + let mut page = q.clone(); + page.limit = Some(2); + loop { + let rows = query_events(&pool, &page).await.unwrap(); + let Some(last) = rows.last() else { break }; + page.until = + Some(DateTime::from_timestamp(last.event.created_at.as_secs() as i64, 0).unwrap()); + page.before_id = Some(last.event.id.as_bytes().to_vec()); + paged.extend(ids(rows)); + } + assert_eq!(paged, expected); + + sqlx::Connection::clear_cached_statements(&mut *conn) + .await + .expect("clear prepared statements"); + for _ in 0..6 { + query_events_on(&mut conn, &q, ReadDeadline::PerRead) + .await + .expect("thread read"); + } + // The routed read is unnamed; the fixed-shape reply probe may be cached. + assert_eq!(prepared_like(&mut conn, "%tm.root_event_id = %").await, 0); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn shared_gate_rejects_positional_decoy() { @@ -3222,7 +4641,12 @@ mod postgres_tests { .expect("set session timeout"); // Autocommit connection (writer path). let mut qb = QueryBuilder::new("SELECT 1/0"); - let err = fetch_with_read_deadline(&mut conn, &mut qb, true).await; + let err = fetch_with_read_deadline( + &mut conn, + qb.build().persistent(true), + ReadDeadline::PerRead, + ) + .await; assert!(err.is_err(), "division by zero must fail"); let after: String = sqlx::query_scalar("SHOW statement_timeout") .fetch_one(&mut *conn) @@ -3234,7 +4658,9 @@ mod postgres_tests { // the failed savepoint must roll back and leave the outer tx usable. let mut tx = sqlx::Connection::begin(&mut *conn).await.expect("begin"); let mut qb = QueryBuilder::new("SELECT 1/0"); - let err = fetch_with_read_deadline(&mut tx, &mut qb, true).await; + let err = + fetch_with_read_deadline(&mut tx, qb.build().persistent(true), ReadDeadline::PerRead) + .await; assert!(err.is_err(), "division by zero must fail"); let after: String = sqlx::query_scalar("SHOW statement_timeout") .fetch_one(&mut *tx) @@ -3248,6 +4674,49 @@ mod postgres_tests { .expect("reset"); } + /// Inside a replica read session's transaction, `ReadDeadline::Session` + /// skips the tighten (the reader pool installs the deadline at connect) + /// but still reads under a savepoint, so the read's locks end with it and + /// a later DDL on the replica is not blocked by an idle session. + /// `PerRead` in the same transaction still tightens. + /// Mutation: tighten for `Session`, or drop its savepoint → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn session_deadline_reads_skip_the_tighten_and_release_locks() { + let pool = setup_pool().await; + let mut tx = pool.begin().await.expect("begin session"); + sqlx::query("SET LOCAL statement_timeout = '1min'") + .execute(&mut *tx) + .await + .expect("set session timeout"); + let mut qb = QueryBuilder::new( + "SELECT current_setting('statement_timeout'), (SELECT count(*) FROM events)", + ); + let rows = + fetch_with_read_deadline(&mut tx, qb.build().persistent(true), ReadDeadline::Session) + .await + .expect("session read"); + let inside: String = rows[0].get(0); + assert_eq!(inside, "1min", "Session must not tighten"); + let held: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_locks \ + WHERE pid = pg_backend_pid() AND relation = 'events'::regclass", + ) + .fetch_one(&mut *tx) + .await + .expect("count locks"); + assert_eq!(held, 0, "a Session read must release its locks"); + + let mut qb = QueryBuilder::new("SELECT current_setting('statement_timeout')"); + let rows = + fetch_with_read_deadline(&mut tx, qb.build().persistent(true), ReadDeadline::PerRead) + .await + .expect("per-read read"); + let inside: String = rows[0].get(0); + assert_eq!(inside, READ_STATEMENT_TIMEOUT, "PerRead tightens"); + tx.rollback().await.expect("rollback"); + } + /// Pins the dispatch: a plain (non-`#e`) read — the agent `#p` + `#h` + /// `since` REQ shape that ran away on bb-public — through the production /// `query_events_on` is cancelled at the 20 s deadline even with the @@ -3276,7 +4745,7 @@ mod postgres_tests { let started = std::time::Instant::now(); let result = tokio::time::timeout( std::time::Duration::from_secs(40), - query_events_on(&mut conn, &q), + query_events_on(&mut conn, &q, ReadDeadline::PerRead), ) .await .expect("deadline must fire before the 40 s guard"); @@ -3316,7 +4785,7 @@ mod postgres_tests { let started = std::time::Instant::now(); let result = tokio::time::timeout( std::time::Duration::from_secs(40), - count_events_on(&mut conn, &q), + count_events_on(&mut conn, &q, ReadDeadline::PerRead), ) .await .expect("deadline must fire before the 40 s guard"); @@ -4346,16 +5815,21 @@ mod postgres_tests { // ─── canvas CAS tests ───────────────────────────────────────────────────── - fn make_canvas_event_at(content: &str, created_at: u64) -> nostr::Event { - make_event_at(buzz_core::kind::KIND_CANVAS as u16, content, created_at) + fn make_canvas_event_at(base: u64, content: &str, created_at: u64) -> nostr::Event { + // Each test owns its fresh base; logical seconds and ties stay explicit. + make_event_at( + buzz_core::kind::KIND_CANVAS as u16, + content, + base + created_at, + ) } /// Build two canvas events sharing `created_at`, returned `(lower, higher)` /// by event id. Regenerates until the ids differ (always, since keys differ) /// so tests can assert deterministic head ordering on the id tiebreak. - fn same_second_ordered_pair(created_at: u64) -> (nostr::Event, nostr::Event) { - let a = make_canvas_event_at("# A", created_at); - let b = make_canvas_event_at("# B", created_at); + fn same_second_ordered_pair(base: u64, created_at: u64) -> (nostr::Event, nostr::Event) { + let a = make_canvas_event_at(base, "# A", created_at); + let b = make_canvas_event_at(base, "# B", created_at); if a.id.as_bytes() <= b.id.as_bytes() { (a, b) } else { @@ -4363,6 +5837,20 @@ mod postgres_tests { } } + #[test] + fn canvas_fixture_base_is_owned_by_each_test() { + let first_base = 1_700_000_000; + let second_base = first_base + crate::replica_fence::CREATED_AT_FLOOR_SECS as u64 * 2; + let first = make_canvas_event_at(first_base, "first test", 1000); + let second = make_canvas_event_at(second_base, "later test", 1000); + assert_eq!(first.created_at.as_secs(), first_base + 1000); + assert_eq!(second.created_at.as_secs(), second_base + 1000); + let (lower, higher) = same_second_ordered_pair(second_base, 1000); + assert_eq!(lower.created_at, higher.created_at); + assert_eq!(lower.created_at.as_secs(), second_base + 1000); + assert!(lower.id.as_bytes() < higher.id.as_bytes()); + } + #[tokio::test] async fn canvas_head_checked_rejects_non_canvas_kinds_before_opening_a_transaction() { // A lazy pool that is never connected: the kind check must reject @@ -4390,10 +5878,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_expect_no_head_creates_first_canvas() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let event = make_canvas_event_at("# First", 1000); + let event = make_canvas_event_at(canvas_base, "# First", 1000); let (_, status) = insert_canvas_head_checked( &pool, @@ -4410,10 +5899,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_expect_no_head_rejects_when_head_exists() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let first = make_canvas_event_at("# First", 1000); + let first = make_canvas_event_at(canvas_base, "# First", 1000); insert_canvas_head_checked( &pool, community, @@ -4424,7 +5914,7 @@ mod postgres_tests { .await .expect("first canvas"); - let second = make_canvas_event_at("# Racing create", 1001); + let second = make_canvas_event_at(canvas_base, "# Racing create", 1001); let (_, status) = insert_canvas_head_checked( &pool, community, @@ -4450,10 +5940,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_expected_head_matches_and_advances() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let first = make_canvas_event_at("# First", 1000); + let first = make_canvas_event_at(canvas_base, "# First", 1000); insert_canvas_head_checked( &pool, community, @@ -4464,7 +5955,7 @@ mod postgres_tests { .await .expect("first canvas"); - let second = make_canvas_event_at("# Second", 1001); + let second = make_canvas_event_at(canvas_base, "# Second", 1001); let head = first.id.as_bytes(); let (_, status) = insert_canvas_head_checked( &pool, @@ -4481,10 +5972,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_expected_head_mismatch_rejects() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let first = make_canvas_event_at("# First", 1000); + let first = make_canvas_event_at(canvas_base, "# First", 1000); insert_canvas_head_checked( &pool, community, @@ -4495,7 +5987,7 @@ mod postgres_tests { .await .expect("first canvas"); - let stale = make_canvas_event_at("# Stale edit", 1002); + let stale = make_canvas_event_at(canvas_base, "# Stale edit", 1002); let wrong_head = [0u8; 32]; let (_, status) = insert_canvas_head_checked( &pool, @@ -4512,10 +6004,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_expected_head_missing_rejects() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let event = make_canvas_event_at("# Edit with no head", 1000); + let event = make_canvas_event_at(canvas_base, "# Edit with no head", 1000); let some_head = [1u8; 32]; let (_, status) = insert_canvas_head_checked( @@ -4533,10 +6026,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_replay_of_head_is_duplicate() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let event = make_canvas_event_at("# First", 1000); + let event = make_canvas_event_at(canvas_base, "# First", 1000); insert_canvas_head_checked( &pool, community, @@ -4568,10 +6062,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_replay_skips_stale_precondition() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let event = make_canvas_event_at("# First", 1000); + let event = make_canvas_event_at(canvas_base, "# First", 1000); insert_canvas_head_checked( &pool, community, @@ -4603,11 +6098,12 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_rejects_same_second_higher_id() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let (lower, higher) = same_second_ordered_pair(1000); + let (lower, higher) = same_second_ordered_pair(canvas_base, 1000); insert_canvas_head_checked( &pool, community, @@ -4646,11 +6142,12 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_accepts_same_second_lower_id() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let (lower, higher) = same_second_ordered_pair(1000); + let (lower, higher) = same_second_ordered_pair(canvas_base, 1000); // Seed the higher-id event as the head first. insert_canvas_head_checked( &pool, @@ -4680,10 +6177,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_rejects_behind_clock_writer() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let head = make_canvas_event_at("# Head", 2000); + let head = make_canvas_event_at(canvas_base, "# Head", 2000); insert_canvas_head_checked( &pool, community, @@ -4695,7 +6193,7 @@ mod postgres_tests { .expect("head at t=2000"); // Writer's clock is behind — created_at earlier than head. - let behind = make_canvas_event_at("# Behind clock", 1100); + let behind = make_canvas_event_at(canvas_base, "# Behind clock", 1100); let (_, status) = insert_canvas_head_checked( &pool, community, @@ -4779,12 +6277,13 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_deleted_replay_returns_revision_mismatch() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; // H: seed the initial head. - let head = make_canvas_event_at("# Head", 1000); + let head = make_canvas_event_at(canvas_base, "# Head", 1000); insert_canvas_head_checked( &pool, community, @@ -4797,7 +6296,7 @@ mod postgres_tests { let head_id = head.id.to_bytes().to_vec(); // A: insert a second revision. - let a = make_canvas_event_at("# A", 1001); + let a = make_canvas_event_at(canvas_base, "# A", 1001); insert_canvas_head_checked( &pool, community, @@ -4902,11 +6401,12 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_concurrent_authors_only_one_advances() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; - let base = make_canvas_event_at("# Base", 1000); + let base = make_canvas_event_at(canvas_base, "# Base", 1000); insert_canvas_head_checked( &pool, community, @@ -4931,8 +6431,8 @@ mod postgres_tests { // Both edits assert `base` as their head and are timestamped strictly // ahead of it (writer discipline), so neither trips SupersedeFailed — // only the advisory-lock serialization decides the winner. - let a = make_canvas_event_at("# Author A", 1001); - let b = make_canvas_event_at("# Author B", 1002); + let a = make_canvas_event_at(canvas_base, "# Author A", 1001); + let b = make_canvas_event_at(canvas_base, "# Author B", 1002); let (pool_a, pool_b) = (pool.clone(), pool.clone()); let (id_a, id_b) = (base_id.clone(), base_id.clone()); @@ -5043,6 +6543,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_checked_concurrent_first_create_only_one_wins() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; @@ -5056,8 +6557,8 @@ mod postgres_tests { .await .expect("blocker acquires key"); - let a = make_canvas_event_at("# First A", 1000); - let b = make_canvas_event_at("# First B", 1001); + let a = make_canvas_event_at(canvas_base, "# First A", 1000); + let b = make_canvas_event_at(canvas_base, "# First B", 1001); let (pool_a, pool_b) = (pool.clone(), pool.clone()); let ta = tokio::spawn(async move { @@ -5164,6 +6665,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn db_untagged_canvas_append_serializes_on_advisory_key() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let db = crate::Db::from_pool(pool.clone()); let community = CommunityId::from_uuid(make_test_community(&pool).await); @@ -5177,7 +6679,7 @@ mod postgres_tests { .await .expect("holder acquires key"); - let event = make_canvas_event_at("# Untagged", 1000); + let event = make_canvas_event_at(canvas_base, "# Untagged", 1000); let write_task = tokio::spawn(async move { db.insert_event_with_thread_metadata(community, &event, Some(channel), None) .await @@ -5219,13 +6721,14 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn channel_head_canvas_deletion_serializes_on_advisory_key() { + let canvas_base = nostr::Timestamp::now().as_secs() - 1000; let pool = setup_pool().await; let community = CommunityId::from_uuid(make_test_community(&pool).await); let channel = make_test_channel(&pool, community.as_uuid().to_owned(), None).await; let lock_key = canvas_lock_key(community, channel); // Insert a canvas event to delete. - let event = make_canvas_event_at("# To delete", 1000); + let event = make_canvas_event_at(canvas_base, "# To delete", 1000); insert_canvas_head_checked( &pool, community, @@ -5290,37 +6793,6 @@ mod postgres_tests { ); } - async fn admin_url() -> String { - crate::test_support::database_url() - } - - async fn create_scratch_db(admin: &PgPool, prefix: &str) -> (PgPool, String) { - let name = format!("{}_{}", prefix, Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(admin) - .await - .expect("create scratch db"); - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); - let pool = PgPool::connect(&scratch_url) - .await - .expect("connect scratch db"); - crate::migration::run_migrations(&pool) - .await - .expect("migrate scratch db"); - (pool, name) - } - - async fn drop_scratch_db(admin: &PgPool, pool: PgPool, name: &str) { - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(admin) - .await; - } - fn make_mentioning_event(mentioned_hex: &str) -> nostr::Event { EventBuilder::new(Kind::Custom(9), "mentions someone") .tags(vec![Tag::parse(["p", mentioned_hex]).expect("p tag")]) @@ -5349,10 +6821,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn insert_event_mention_failure_rolls_back_the_event_insert() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin database"); - let (scratch_pool, name) = create_scratch_db(&admin, "event_mention_rollback").await; + let (scratch_pool, _scratch) = ScratchDb::migrated( + &crate::test_support::database_url(), + "event_mention_rollback", + ) + .await; install_mention_failure_injection(&scratch_pool).await; let db = Db::from_pool(scratch_pool.clone()); @@ -5380,8 +6853,6 @@ mod postgres_tests { persisted, 0, "event must not persist when mention indexing fails atomically" ); - - drop_scratch_db(&admin, scratch_pool, &name).await; } #[tokio::test] @@ -5417,10 +6888,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn insert_event_with_thread_metadata_mention_failure_rolls_back_the_event_insert() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin database"); - let (scratch_pool, name) = create_scratch_db(&admin, "event_thread_mention_rollback").await; + let (scratch_pool, _scratch) = ScratchDb::migrated( + &crate::test_support::database_url(), + "event_thread_mention_rollback", + ) + .await; install_mention_failure_injection(&scratch_pool).await; let db = Db::from_pool(scratch_pool.clone()); @@ -5481,8 +6953,161 @@ mod postgres_tests { thread_meta_count, 0, "thread metadata must not persist when mention indexing fails atomically" ); + } + + async fn target_deleted_at(pool: &PgPool, community: Uuid, id: &[u8]) -> Option> { + sqlx::query_scalar("SELECT deleted_at FROM events WHERE community_id = $1 AND id = $2") + .bind(community) + .bind(id) + .fetch_one(pool) + .await + .expect("read target deleted_at") + } + + async fn event_count(pool: &PgPool, community: Uuid, id: &[u8]) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id = $1 AND id = $2") + .bind(community) + .bind(id) + .fetch_one(pool) + .await + .expect("count event rows") + } + + fn deletion_of(target: &nostr::Event) -> nostr::Event { + EventBuilder::new(Kind::Custom(5), "") + .tags(vec![Tag::parse(["e", &target.id.to_hex()]).expect("e tag")]) + .sign_with_keys(&Keys::generate()) + .expect("sign deletion") + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn insert_deletion_event_target_failure_stores_nothing_and_resend_applies() { + let (pool, _scratch) = ScratchDb::migrated( + &crate::test_support::database_url(), + "deletion_target_rollback", + ) + .await; + let db = Db::from_pool(pool.clone()); + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let channel = make_test_channel(&pool, community_uuid, None).await; + + let reaction = make_event_with_kind_and_tags(7, vec![]); + db.insert_event(community, &reaction, Some(channel)) + .await + .expect("insert reaction"); + let deletion = deletion_of(&reaction); + let targets = [DeletionTarget { + event_id: reaction.id.as_bytes(), + created_at: DateTime::from_timestamp(reaction.created_at.as_secs() as i64, 0) + .expect("target timestamp"), + parent_event_id: None, + root_event_id: None, + }]; + + sqlx::query( + "CREATE FUNCTION reject_test_soft_delete() RETURNS trigger AS $$ \ + BEGIN RAISE EXCEPTION 'injected soft-delete failure'; END; \ + $$ LANGUAGE plpgsql", + ) + .execute(&pool) + .await + .expect("create failure function"); + sqlx::query( + "CREATE TRIGGER reject_test_soft_delete BEFORE UPDATE ON events \ + FOR EACH ROW WHEN (OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL) \ + EXECUTE FUNCTION reject_test_soft_delete()", + ) + .execute(&pool) + .await + .expect("install failure injection"); + + let error = db + .insert_deletion_event(community, &deletion, Some(channel), None, &targets) + .await + .expect_err("a failed target soft-delete must fail the deletion"); + assert!( + error.to_string().contains("injected soft-delete failure"), + "unexpected error: {error}" + ); + assert_eq!( + event_count(&pool, community_uuid, deletion.id.as_bytes()).await, + 0, + "the deletion must not be stored while its target stays live" + ); + assert!( + target_deleted_at(&pool, community_uuid, reaction.id.as_bytes()) + .await + .is_none(), + "the failed transaction must leave the target as it was" + ); + + sqlx::query("DROP TRIGGER reject_test_soft_delete ON events") + .execute(&pool) + .await + .expect("remove failure injection"); + let (_, inserted, deleted) = db + .insert_deletion_event(community, &deletion, Some(channel), None, &targets) + .await + .expect("resend after the failure clears"); + assert!(inserted, "the resend stores the deletion"); + assert_eq!(deleted, vec![true]); + assert!( + target_deleted_at(&pool, community_uuid, reaction.id.as_bytes()) + .await + .is_some() + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn insert_deletion_event_resend_repairs_a_live_target() { + let pool = setup_pool().await; + let db = Db::from_pool(pool.clone()); + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let channel = make_test_channel(&pool, community_uuid, None).await; + + let reaction = make_event_with_kind_and_tags(7, vec![]); + db.insert_event(community, &reaction, Some(channel)) + .await + .expect("insert reaction"); + // A deletion stored by a write that never soft-deleted its target. + let deletion = deletion_of(&reaction); + db.insert_event(community, &deletion, Some(channel)) + .await + .expect("insert torn deletion"); + let targets = [DeletionTarget { + event_id: reaction.id.as_bytes(), + created_at: DateTime::from_timestamp(reaction.created_at.as_secs() as i64, 0) + .expect("target timestamp"), + parent_event_id: None, + root_event_id: None, + }]; + + let (_, inserted, deleted) = db + .insert_deletion_event(community, &deletion, Some(channel), None, &targets) + .await + .expect("resend the deletion"); + assert!(!inserted, "the deletion was already stored"); + assert_eq!( + deleted, + vec![true], + "the resend soft-deletes the live target" + ); + assert!( + target_deleted_at(&pool, community_uuid, reaction.id.as_bytes()) + .await + .is_some() + ); - drop_scratch_db(&admin, scratch_pool, &name).await; + let (_, inserted, deleted) = db + .insert_deletion_event(community, &deletion, Some(channel), None, &targets) + .await + .expect("resend again"); + assert!(!inserted); + assert_eq!(deleted, vec![false], "an applied deletion changes nothing"); } #[tokio::test] diff --git a/crates/buzz-db/src/store/event_deletion.rs b/crates/buzz-db/src/store/event_deletion.rs new file mode 100644 index 00000000000..44f0dfee153 --- /dev/null +++ b/crates/buzz-db/src/store/event_deletion.rs @@ -0,0 +1,406 @@ +//! Atomic event deletion, retention-free purging, and thread accounting. + +use buzz_core::{kind::KIND_CANVAS, CommunityId}; +use chrono::{DateTime, Utc}; +use sqlx::PgPool; +use uuid::Uuid; + +use crate::{ + error::{DbError, Result}, + AdmittedTx, +}; + +/// SQL predicate over an `events` row for coordinates that carry no +/// historical value: NIP-RS read state and Buzz mesh heartbeats. Their +/// deletion is physical, including the mention index, so soft-deleted payloads +/// never accumulate. This is exactly the classification used by the migration +/// 0011 / 0019 purge triggers this path replaces. +macro_rules! retention_free_event_predicate { + () => { + "((kind = 30078 \ + AND d_tag ~ '^read-state:[0-9a-f]{32}$' \ + AND (SELECT count(*) \ + FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ + WHERE jsonb_typeof(tag) = 'array' AND tag->0 = '\"d\"'::jsonb) = 1 \ + AND EXISTS (SELECT 1 \ + FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ + WHERE jsonb_typeof(tag) = 'array' AND jsonb_array_length(tag) >= 2 \ + AND jsonb_typeof(tag->1) = 'string' AND tag->>0 = 'd' AND tag->>1 = d_tag) \ + AND (SELECT count(*) \ + FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \ + WHERE tag = '[\"t\", \"read-state\"]'::jsonb) = 1) \ + OR (kind = 30003 \ + AND d_tag LIKE 'buzz-mesh-member-status:%' \ + AND tags @> '[[\"k\", \"buzz-mesh-status\"]]'::jsonb))" + }; +} + +/// Kinds that can hold a retention-free coordinate. Cheap Rust gate so +/// ordinary deletions skip the purge statement entirely. +fn may_be_retention_free(kind: i32) -> bool { + kind == 30078 || kind == 30003 +} + +/// Soft-delete the live row for an addressable coordinate +/// `(kind, pubkey, d_tag)` — the NIP-33 replacement key — provided it is not +/// newer than the deletion request. +/// +/// Used by `handle_a_tag_deletion` to honour NIP-09 a-tag deletions for any +/// parameterized-replaceable kind. The WHERE clause mirrors +/// `replace_parameterized_event` so the coordinate semantics stay consistent: +/// `channel_id` is intentionally NOT in the key (NIP-33 replacement is global +/// per the spec — `channel_id` is stored for query scoping, not identity). +/// +/// `deletion_created_at_secs` is the deletion event's own `created_at`. NIP-09 +/// scopes an `a`-tag deletion to versions at or before that instant, so a +/// delayed or replayed tombstone signed between two versions must not erase the +/// newer replacement. `events.created_at` is immutable per row, so the predicate +/// guarantees a tombstone can never erase a version newer than itself — the UPDATE +/// re-evaluates its WHERE clause after any lock wait, so a replacement that races +/// the deletion and lands with a later `created_at` is always spared. +/// +/// This does NOT guarantee deletion completeness when a same-coordinate +/// replacement races the deletion: the deletion may evaluate its predicate before +/// the replacement arrives, miss the incoming head, and return `Ok(false)`. That +/// outcome is state-identical to the deletion having arrived first (old head +/// gone, new head present), which is a valid Nostr ordering — Nostr never fixes +/// the order of concurrent writes from different signers, and even same-signer +/// ordering is advisory. The return value feeds only a debug log, not a +/// correctness gate. +/// +/// Returns `Ok(true)` if a row was deleted, `Ok(false)` if no live row matched +/// (already deleted, never existed, or strictly newer than the deletion). +pub async fn soft_delete_by_coordinate( + pool: &PgPool, + community_id: CommunityId, + kind: i32, + pubkey: &[u8], + d_tag: &str, + deletion_created_at_secs: i64, +) -> Result { + let deletion_created_at = DateTime::from_timestamp(deletion_created_at_secs, 0) + .ok_or(DbError::InvalidTimestamp(deletion_created_at_secs))?; + let mut tx = crate::begin_community_event_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let purged = if may_be_retention_free(kind) { + purge_retention_free_events( + &mut tx, + RetentionFreeTarget::Coordinate { + kind, + pubkey, + d_tag, + created_at_or_before: deletion_created_at, + }, + ) + .await? + } else { + 0 + }; + // `AND NOT COALESCE(, false)` holds the invariant in SQL rather than through + // statement order: under READ COMMITTED this UPDATE takes a fresh snapshot, + // so a retention-free head committed by a racing replacement after the + // purge ran is spared instead of soft-deleted (the "deletion arrived + // first" outcome documented above). COALESCE keeps a NULL predicate + // (e.g. NULL `d_tag`) on the ordinary soft-delete path, as the triggers do. + let result = sqlx::query(concat!( + "UPDATE events SET deleted_at = NOW() \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL \ + AND created_at <= $5 AND NOT COALESCE(", + retention_free_event_predicate!(), + ", false)" + )) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey) + .bind(d_tag) + .bind(deletion_created_at) + .execute(tx.conn()) + .await?; + + tx.commit().await?; + + Ok(purged > 0 || result.rows_affected() > 0) +} + +/// Purge live retention-free rows matching `$target`, plus their mention rows, +/// and return the number of events removed. +macro_rules! purge_retention_free_sql { + ($target:literal) => { + concat!( + "WITH purged AS ( \ + DELETE FROM events \ + WHERE community_id = $1 AND ", + $target, + " AND deleted_at IS NULL AND ", + retention_free_event_predicate!(), + " RETURNING id \ + ), purged_mentions AS ( \ + DELETE FROM event_mentions mention USING purged \ + WHERE mention.community_id = $1 AND mention.event_id = purged.id \ + ) \ + SELECT count(*) FROM purged" + ) + }; +} + +// The known-target statements below are executed in production and referenced +// directly by the pruning tests. They run with `.persistent(false)`: a cached +// prepared statement may switch to a generic plan after five executions, and on +// PostgreSQL 16 a generic plan takes `AccessShareLock` on every `events` +// partition (and its indexes) during plan validation, before runtime pruning. +// An unnamed statement is always planned with its bound parameters, so only the +// partition selected by `created_at` is locked. +const SELECT_KNOWN_EVENT_SQL: &str = "SELECT kind, channel_id, created_at FROM events \ + WHERE community_id = $1 AND id = $2 AND created_at = $3"; +const SOFT_DELETE_KNOWN_EVENT_SQL: &str = concat!( + "UPDATE events SET deleted_at = NOW() \ + WHERE community_id = $1 AND id = $2 AND created_at = $3 \ + AND deleted_at IS NULL AND NOT COALESCE(", + retention_free_event_predicate!(), + ", false)" +); +const PURGE_KNOWN_EVENT_SQL: &str = purge_retention_free_sql!("id = $2 AND created_at = $3"); + +/// Which live rows a deletion targets. +enum RetentionFreeTarget<'a> { + Event { + event_id: &'a [u8], + created_at: DateTime, + }, + Coordinate { + kind: i32, + pubkey: &'a [u8], + d_tag: &'a str, + created_at_or_before: DateTime, + }, +} + +/// Physically delete live retention-free rows matched by `target`, plus their +/// mention rows, in the caller's transaction. The generic soft delete that +/// follows excludes the same predicate, so a retention-free row is either +/// purged here or left live, never soft-deleted. Returns the number of events +/// removed. +async fn purge_retention_free_events( + tx: &mut AdmittedTx, + target: RetentionFreeTarget<'_>, +) -> Result { + let community_id = tx.community(); + // Migration 0011 fences NIP-RS hard deletes behind a transaction-local + // opt-in. The fence and this opt-in are removed together once the + // migration-only triggers are dropped. + sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") + .execute(tx.conn()) + .await?; + + let purged: i64 = match target { + RetentionFreeTarget::Event { + event_id, + created_at, + } => { + sqlx::query_scalar(PURGE_KNOWN_EVENT_SQL) + .persistent(false) + .bind(community_id.as_uuid()) + .bind(event_id) + .bind(created_at) + .fetch_one(tx.conn()) + .await? + } + RetentionFreeTarget::Coordinate { + kind, + pubkey, + d_tag, + created_at_or_before, + } => { + sqlx::query_scalar(purge_retention_free_sql!( + "kind = $2 AND pubkey = $3 AND d_tag = $4 AND created_at <= $5" + )) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey) + .bind(d_tag) + .bind(created_at_or_before) + .fetch_one(tx.conn()) + .await? + } + }; + + Ok(purged as u64) +} + +/// An event a NIP-09 (kind 5) or NIP-29 (kind 9005) deletion soft-deletes in +/// the deletion's own insert transaction, with the thread it belongs to. +#[derive(Clone, Copy, Debug)] +pub struct DeletionTarget<'a> { + /// The event to soft-delete. + pub event_id: &'a [u8], + /// The target's exact signed timestamp, not the deletion's timestamp. + pub created_at: DateTime, + /// Its direct parent, whose `reply_count` drops when it is deleted. + pub parent_event_id: Option<&'a [u8]>, + /// Its thread root, whose `descendant_count` drops when it is deleted. + pub root_event_id: Option<&'a [u8]>, +} + +/// Atomically soft-delete an event and decrement thread reply counters. +/// +/// Wraps the delete + counter update in a single transaction so a crash between +/// them cannot leave counters permanently inflated. Returns `Ok(true)` if the +/// event was deleted this call. +/// +/// When the target event is a kind-40100 (canvas) event, this function derives +/// the target's `kind` and `channel_id` from the database inside the same +/// transaction and acquires the same `(community, kind, channel)` advisory lock +/// used by [`super::event::insert_canvas_head_checked`] before the UPDATE. This prevents a +/// concurrent tagged write from observing a head that is simultaneously being +/// removed. The serialization invariant is owned entirely by this function; +/// callers do not classify the target kind. +pub async fn soft_delete_event_and_update_thread( + pool: &PgPool, + community_id: CommunityId, + event_id: &[u8], + parent_event_id: Option<&[u8]>, + root_event_id: Option<&[u8]>, +) -> Result { + let mut tx = crate::begin_community_event_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let deleted = soft_delete_event_and_update_thread_in_tx( + &mut tx, + event_id, + None, + parent_event_id, + root_event_id, + ) + .await?; + tx.commit().await?; + Ok(deleted) +} + +/// Transaction-scoped body of [`soft_delete_event_and_update_thread`]. +/// +/// Callers that must fence the delete with their own writes (e.g. the admin +/// action lease/marker) run this inside their transaction; the caller commits. +/// `None` discovers the target timestamp once; `Some` never falls back to ID-only. +pub(crate) async fn soft_delete_event_and_update_thread_in_tx( + tx: &mut AdmittedTx, + event_id: &[u8], + created_at: Option>, + parent_event_id: Option<&[u8]>, + root_event_id: Option<&[u8]>, +) -> Result { + let community_id = tx.community(); + use crate::store::replaceable::event_replacement_lock_key; + + // ID-only compatibility callers discover the immutable timestamp once. + // Planned targets already have it; every subsequent events-table access + // uses the exact partition key. Kind/channel remain canonical DB reads, + // never caller-supplied classification (including for deleted rows). + let target: Option<(i32, Option, DateTime)> = match created_at { + Some(created_at) => { + sqlx::query_as(SELECT_KNOWN_EVENT_SQL) + .persistent(false) + .bind(community_id.as_uuid()) + .bind(event_id) + .bind(created_at) + .fetch_optional(tx.conn()) + .await? + } + None => { + sqlx::query_as( + "SELECT kind, channel_id, created_at FROM events \ + WHERE community_id = $1 AND id = $2", + ) + .bind(community_id.as_uuid()) + .bind(event_id) + .fetch_optional(tx.conn()) + .await? + } + }; + let Some((kind, channel_id, created_at)) = target else { + return Ok(false); + }; + + // Relay-signed move removals are the source channel's only replay record. + if kind == 45011 { + return Err(DbError::InvalidData( + "artifact removal markers cannot be deleted".into(), + )); + } + + if let Some(channel_id) = channel_id { + if kind == KIND_CANVAS as i32 { + let lock_key = event_replacement_lock_key( + community_id, + kind, + &[], + Some(channel_id.as_bytes().as_slice()), + ); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(lock_key) + .execute(tx.conn()) + .await?; + } + } + + let purged = if may_be_retention_free(kind) { + purge_retention_free_events( + tx, + RetentionFreeTarget::Event { + event_id, + created_at, + }, + ) + .await? + } else { + 0 + }; + let result = sqlx::query(SOFT_DELETE_KNOWN_EVENT_SQL) + .persistent(false) + .bind(community_id.as_uuid()) + .bind(event_id) + .bind(created_at) + .execute(tx.conn()) + .await?; + + let deleted = purged > 0 || result.rows_affected() > 0; + + if deleted { + sqlx::query("UPDATE artifact_heads SET modified_at=clock_timestamp() WHERE community_id=$1 AND artifact_id=(SELECT artifact_id FROM artifact_revisions WHERE community_id=$1 AND event_id=$2) AND event_id=$2") + .bind(community_id.as_uuid()).bind(event_id).execute(tx.conn()).await?; + if let Some(pid) = parent_event_id { + sqlx::query( + "UPDATE thread_metadata \ + SET reply_count = GREATEST(reply_count - 1, 0) \ + WHERE community_id = $1 AND event_id = $2", + ) + .bind(community_id.as_uuid()) + .bind(pid) + .execute(tx.conn()) + .await?; + + if let Some(root_id) = root_event_id { + sqlx::query( + "UPDATE thread_metadata \ + SET descendant_count = GREATEST(descendant_count - 1, 0) \ + WHERE community_id = $1 AND event_id = $2", + ) + .bind(community_id.as_uuid()) + .bind(root_id) + .execute(tx.conn()) + .await?; + } + } + } + + Ok(deleted) +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/event_deletion/postgres_tests.rs b/crates/buzz-db/src/store/event_deletion/postgres_tests.rs new file mode 100644 index 00000000000..51317d38818 --- /dev/null +++ b/crates/buzz-db/src/store/event_deletion/postgres_tests.rs @@ -0,0 +1,597 @@ +//! Functional coverage through admitted production deletion entry points. + +use super::*; +use crate::{event::ThreadMetadataParams, Db}; +use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; +use sqlx::postgres::PgPoolOptions; + +const JAN: u64 = 1_768_003_200; // 2026-01-10 UTC +const MAY: u64 = 1_778_371_200; // 2026-05-10 UTC + +async fn fixture() -> (Db, CommunityId, Uuid) { + let pool = PgPoolOptions::new() + .max_connections(1) + .connect(&crate::test_support::database_url()) + .await + .expect("test database"); + let db = Db::from_pool(pool); + let (community, channel) = tenant(&db.pool).await; + (db, community, channel) +} + +async fn tenant(pool: &PgPool) -> (CommunityId, Uuid) { + let community = Uuid::new_v4(); + let channel = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("deletion-{}.example", community.simple())) + .execute(pool) + .await + .expect("community"); + sqlx::query( + "INSERT INTO channels (id, community_id, name, created_by) VALUES ($1,$2,'deletion',$3)", + ) + .bind(channel) + .bind(community) + .bind(vec![7_u8; 32]) + .execute(pool) + .await + .expect("channel"); + (CommunityId::from_uuid(community), channel) +} + +fn event(kind: u16, secs: u64, tags: Vec) -> nostr::Event { + EventBuilder::new(Kind::Custom(kind), "deletion test") + .tags(tags) + .custom_created_at(Timestamp::from(secs)) + .sign_with_keys(&Keys::generate()) + .expect("signed event") +} + +/// Seed `event` as a row already in storage. The serving writers reject a +/// channel event older than the `created_at` floor, and these tests pin +/// months far in the past; the deletion paths under test still run for real. +async fn seed(db: &Db, community: CommunityId, event: &nostr::Event, channel: Uuid) { + crate::test_support::insert_historical_event(&db.pool, community, event, channel).await; +} + +/// [`seed`] for a reply or root that also carries thread metadata. +async fn seed_with_thread( + db: &Db, + community: CommunityId, + event: &nostr::Event, + channel: Uuid, + meta: ThreadMetadataParams<'_>, +) { + crate::test_support::insert_historical_event_with_thread_metadata( + &db.pool, community, event, channel, meta, + ) + .await; +} + +fn timestamp(event: &nostr::Event) -> DateTime { + DateTime::from_timestamp(event.created_at.as_secs() as i64, 0).expect("timestamp") +} + +fn target(event: &nostr::Event) -> DeletionTarget<'_> { + DeletionTarget { + event_id: event.id.as_bytes(), + created_at: timestamp(event), + parent_event_id: None, + root_event_id: None, + } +} + +async fn counts(db: &Db, community: CommunityId, id: &[u8]) -> (i64, i64, i64) { + let (rows, live): (i64, i64) = sqlx::query_as( + "SELECT count(*), count(*) FILTER (WHERE deleted_at IS NULL) FROM events WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()).bind(id).fetch_one(&db.pool).await.expect("event counts"); + let mentions = sqlx::query_scalar( + "SELECT count(*) FROM event_mentions WHERE community_id=$1 AND event_id=$2", + ) + .bind(community.as_uuid()) + .bind(id) + .fetch_one(&db.pool) + .await + .expect("mention counts"); + (rows, live, mentions) +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn known_targets_across_months_are_exact_and_tenant_scoped() { + let (db, community, channel) = fixture().await; + let (other, other_channel) = tenant(&db.pool).await; + let jan = event(7, JAN, vec![]); + let may = event(7, MAY, vec![]); + for ev in [&jan, &may] { + seed(&db, community, ev, channel).await; + seed(&db, other, ev, other_channel).await; + } + // Deliberately older than both targets: e-target deletion has no inferred + // chronology, and the deletion's month is not a target key. It is stored + // without a channel, since a channel event this old is below the floor. + let deletion = event(5, JAN - 86_400, vec![]); + let missing = event(7, JAN + 1, vec![]); + let wrong = DeletionTarget { + created_at: timestamp(&may), + ..target(&jan) + }; + let (_, inserted, deleted) = db + .insert_deletion_event( + community, + &deletion, + None, + None, + &[wrong, target(&missing), target(&jan), target(&may)], + ) + .await + .expect("delete targets"); + assert!(inserted); + assert_eq!(deleted, [false, false, true, true]); + for ev in [&jan, &may] { + assert_eq!(counts(&db, community, ev.id.as_bytes()).await.1, 0); + assert_eq!(counts(&db, other, ev.id.as_bytes()).await.1, 1); + } + assert_eq!( + db.insert_deletion_event( + community, + &deletion, + None, + None, + &[target(&jan), target(&may)] + ) + .await + .expect("replay") + .2, + [false, false] + ); + // ID-only callers still work and discover the immutable timestamp in tx. + assert!( + soft_delete_event_and_update_thread(&db.pool, other, jan.id.as_bytes(), None, None) + .await + .expect("compatibility delete") + ); + assert!(!soft_delete_event_and_update_thread( + &db.pool, + other, + missing.id.as_bytes(), + None, + None + ) + .await + .expect("missing compatibility target")); +} + +async fn retention_free_contract() { + let (db, community, channel) = fixture().await; + let (other, other_channel) = tenant(&db.pool).await; + let slot = format!("read-state:{}", "b".repeat(32)); + let marker = event(45011, JAN, vec![]); + seed(&db, community, &marker, channel).await; + for (kind, d, extra) in [ + (30078, slot.as_str(), ["t", "read-state"]), + ( + 30003, + "buzz-mesh-member-status:test", + ["k", "buzz-mesh-status"], + ), + ] { + for secs in [JAN, MAY] { + let tags = vec![ + Tag::parse(["d", d]).expect("d"), + Tag::parse(extra).expect("classification"), + Tag::parse(["p", &"c".repeat(64)]).expect("mention"), + ]; + let ev = event(kind, secs, tags); + for (tenant, ch) in [(community, channel), (other, other_channel)] { + // Each event has its own author, so nothing is superseded and + // storing it is the whole replacement. + seed(&db, tenant, &ev, ch).await; + assert_eq!(counts(&db, tenant, ev.id.as_bytes()).await, (1, 1, 1)); + } + let deletion = event(5, JAN - 1, vec![]); + let wrong = DeletionTarget { + created_at: timestamp(&ev) + chrono::Duration::seconds(1), + ..target(&ev) + }; + assert_eq!( + db.insert_deletion_event(community, &deletion, None, None, &[wrong]) + .await + .expect("wrong timestamp") + .2, + [false] + ); + assert_eq!(counts(&db, community, ev.id.as_bytes()).await, (1, 1, 1)); + // A later forbidden target must roll back both the physical purge + // and its mention cleanup, including the migration NIP-RS guard. + assert!(db + .insert_deletion_event( + community, + &deletion, + None, + None, + &[target(&ev), target(&marker)] + ) + .await + .is_err()); + assert_eq!(counts(&db, community, ev.id.as_bytes()).await, (1, 1, 1)); + assert_eq!( + db.insert_deletion_event(community, &deletion, None, None, &[target(&ev)]) + .await + .expect("hard purge") + .2, + [true] + ); + assert_eq!(counts(&db, community, ev.id.as_bytes()).await, (0, 0, 0)); + assert_eq!(counts(&db, other, ev.id.as_bytes()).await, (1, 1, 1)); + assert_eq!( + db.insert_deletion_event(community, &deletion, None, None, &[target(&ev)]) + .await + .expect("replay purge") + .2, + [false] + ); + assert!(soft_delete_event_and_update_thread( + &db.pool, + other, + ev.id.as_bytes(), + None, + None + ) + .await + .expect("ID-only purge")); + assert_eq!(counts(&db, other, ev.id.as_bytes()).await, (0, 0, 0)); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn known_target_retention_free_purge_cleans_mentions() { + retention_free_contract().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_known_target_retention_free_purge_cleans_mentions() { + crate::migration::run_migrations( + &PgPool::connect(&crate::test_support::database_url()) + .await + .expect("migration pool"), + ) + .await + .expect("migrate"); + retention_free_contract().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn known_target_batch_rollback_then_replay_repairs_and_counts_once() { + let (db, community, channel) = fixture().await; + let root = event(9, JAN, vec![]); + seed_with_thread( + &db, + community, + &root, + channel, + ThreadMetadataParams { + event_id: root.id.as_bytes(), + event_created_at: timestamp(&root), + channel_id: channel, + parent_event_id: None, + parent_event_created_at: None, + root_event_id: None, + root_event_created_at: None, + depth: 0, + broadcast: false, + }, + ) + .await; + let reply = event(9, MAY, vec![]); + seed_with_thread( + &db, + community, + &reply, + channel, + ThreadMetadataParams { + event_id: reply.id.as_bytes(), + event_created_at: timestamp(&reply), + channel_id: channel, + parent_event_id: Some(root.id.as_bytes()), + parent_event_created_at: Some(timestamp(&root)), + root_event_id: Some(root.id.as_bytes()), + root_event_created_at: Some(timestamp(&root)), + depth: 1, + broadcast: false, + }, + ) + .await; + let counter = || async { + sqlx::query_as::<_, (i32, i32)>("SELECT reply_count, descendant_count FROM thread_metadata WHERE community_id=$1 AND event_id=$2") + .bind(community.as_uuid()).bind(root.id.as_bytes().as_slice()) + .fetch_one(&db.pool).await.expect("counters") + }; + assert_eq!(counter().await, (1, 1)); + // A forbidden removal marker makes the second target fail after the first + // was mutated. No test-only triggers or copied deletion implementation. + let marker = event(45011, JAN, vec![]); + seed(&db, community, &marker, channel).await; + let reply_target = DeletionTarget { + parent_event_id: Some(root.id.as_bytes()), + root_event_id: Some(root.id.as_bytes()), + ..target(&reply) + }; + // Stored without a channel on this attempt: a channel event this old is + // below the floor, which would fail the write before the targets run. + let deletion = event(5, MAY + 1, vec![]); + assert!(db + .insert_deletion_event( + community, + &deletion, + None, + None, + &[reply_target, target(&marker)] + ) + .await + .is_err()); + assert_eq!(counts(&db, community, deletion.id.as_bytes()).await.0, 0); + assert_eq!(counts(&db, community, reply.id.as_bytes()).await.1, 1); + assert_eq!(counter().await, (1, 1)); + // Emulate a historical torn write, then concurrently replay it from two + // independent connections: exactly one transition decrements counters. + seed(&db, community, &deletion, channel).await; + let concurrent = Db::from_pool( + PgPool::connect(&crate::test_support::database_url()) + .await + .expect("independent pool"), + ); + let targets = [reply_target]; + let (a, b) = tokio::join!( + db.insert_deletion_event(community, &deletion, Some(channel), None, &targets), + concurrent.insert_deletion_event(community, &deletion, Some(channel), None, &targets), + ); + let (_, inserted_a, a) = a.expect("first replay"); + let (_, inserted_b, b) = b.expect("second replay"); + assert!(!inserted_a && !inserted_b); + assert_ne!(a, b); + assert_eq!(counter().await, (0, 0)); + assert_eq!( + db.insert_deletion_event(community, &deletion, Some(channel), None, &targets) + .await + .expect("repeat replay") + .2, + [false] + ); + assert_eq!(counter().await, (0, 0)); +} + +fn event_relations(plan: &serde_json::Value, relations: &mut Vec) { + if let Some(name) = plan.get("Relation Name").and_then(|name| name.as_str()) { + // Generic plans can list nonexecuted target tables / subplans. Only + // executed relation-access nodes measure runtime pruning. + if name.starts_with("events_p") + && plan + .get("Actual Loops") + .and_then(|loops| loops.as_u64()) + .unwrap_or(0) + > 0 + { + relations.push(name.to_owned()); + } + } + match plan { + serde_json::Value::Array(items) => { + for item in items { + event_relations(item, relations); + } + } + serde_json::Value::Object(items) => { + for item in items.values() { + event_relations(item, relations); + } + } + _ => {} + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn production_known_target_statements_prune_to_one_month() { + let (db, community, channel) = fixture().await; + let slot = format!("read-state:{}", "a".repeat(32)); + let ev = event( + 30078, + JAN, + vec![ + Tag::parse(["d", &slot]).expect("d"), + Tag::parse(["t", "read-state"]).expect("t"), + ], + ); + seed(&db, community, &ev, channel).await; + let deletion = event(5, MAY, vec![]); + db.insert_deletion_event(community, &deletion, None, None, &[target(&ev)]) + .await + .expect("exercise production statements"); + // Explain the exact statements production executes, with their real + // bindings. Production runs them unnamed (`.persistent(false)`), so they + // are planned with the bound parameters; the lock test below covers the + // generic-plan hazard of a cached prepared statement. ANALYZE executes the + // real statement, but every EXPLAIN is rolled back. + for statement in [ + SELECT_KNOWN_EVENT_SQL, + SOFT_DELETE_KNOWN_EVENT_SQL, + PURGE_KNOWN_EVENT_SQL, + ] { + assert!( + statement.contains("created_at = $3"), + "missing partition key: {statement}" + ); + let mut tx = crate::begin_community_event_write_transaction( + &db.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .expect("admit explain"); + sqlx::query("SET LOCAL plan_cache_mode = force_custom_plan") + .execute(tx.conn()) + .await + .expect("plan mode"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "PREPARE deletion_pruning_probe (uuid, bytea, timestamptz) AS {statement}" + ))) + .execute(tx.conn()) + .await + .expect("prepare production SQL"); + let explain = format!( + "EXPLAIN (ANALYZE, FORMAT JSON) EXECUTE deletion_pruning_probe ('{}', decode('{}', 'hex'), '{}')", + community.as_uuid(), ev.id.to_hex(), timestamp(&ev).to_rfc3339() + ); + let plan: serde_json::Value = sqlx::query_scalar(sqlx::AssertSqlSafe(explain)) + .fetch_one(tx.conn()) + .await + .expect("production EXPLAIN"); + let mut relations = vec![]; + event_relations(&plan, &mut relations); + assert!(!relations.is_empty(), "no event access: {plan}"); + assert!( + relations.iter().all(|name| name == "events_p2026_01"), + "unrelated monthly partitions: {plan}" + ); + sqlx::query("DEALLOCATE deletion_pruning_probe") + .execute(tx.conn()) + .await + .expect("deallocate probe"); + tx.rollback().await.expect("rollback explain"); + } +} + +/// Monthly `events` partitions (not their indexes) this backend holds a +/// relation lock on right now. +async fn locked_event_partitions(tx: &mut AdmittedTx) -> Vec { + sqlx::query_scalar( + "SELECT DISTINCT c.relname::text FROM pg_locks l \ + JOIN pg_class c ON c.oid = l.relation \ + WHERE l.locktype = 'relation' AND l.pid = pg_backend_pid() \ + AND c.relkind = 'r' AND c.relname LIKE 'events\\_p%' ORDER BY 1", + ) + .fetch_all(tx.conn()) + .await + .expect("observe partition locks") +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn production_known_target_deletion_locks_one_partition() { + let (db, community, channel) = fixture().await; + let slot = format!("read-state:{}", "b".repeat(32)); + let ev = event( + 30078, + JAN, + vec![ + Tag::parse(["d", &slot]).expect("d"), + Tag::parse(["t", "read-state"]).expect("t"), + ], + ); + seed(&db, community, &ev, channel).await; + // The assertion is only meaningful if other partitions exist to be locked. + let partitions: i64 = + sqlx::query_scalar("SELECT count(*) FROM pg_inherits WHERE inhparent = 'events'::regclass") + .fetch_one(&db.pool) + .await + .expect("partition count"); + assert!(partitions > 1, "need several partitions, got {partitions}"); + + // The fixture pool has one connection, so every round reuses its + // statement cache. A persistent prepared statement is custom-planned for + // its first five executions and may then flip to a generic plan, which + // locks every partition during plan validation; the production statements + // are unnamed and must lock only the target month in every round. + for round in 0..10 { + let mut tx = crate::begin_community_event_write_transaction( + &db.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .expect("admit deletion"); + // Known-target select, purge and soft delete all run on the production + // path (read-state events are retention-free). + let deleted = soft_delete_event_and_update_thread_in_tx( + &mut tx, + ev.id.as_bytes(), + Some(timestamp(&ev)), + None, + None, + ) + .await + .expect("production deletion"); + assert!(deleted, "round {round}"); + let locked = locked_event_partitions(&mut tx).await; + // Roll back so the next round deletes the same row again. + tx.rollback().await.expect("rollback"); + assert_eq!( + locked, + ["events_p2026_01"], + "round {round}: known-target deletion must lock only the target month" + ); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn known_canvas_target_uses_canonical_replacement_lock() { + let (db, community, channel) = fixture().await; + let canvas = event(KIND_CANVAS as u16, JAN, vec![]); + seed(&db, community, &canvas, channel).await; + // The fixture's single connection identifies the backend that will delete. + let deleter_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&db.pool) + .await + .expect("deleter pid"); + let observer = PgPool::connect(&crate::test_support::database_url()) + .await + .expect("lock pool"); + let mut holder = observer.begin().await.expect("holder transaction"); + let key = crate::store::replaceable::event_replacement_lock_key( + community, + KIND_CANVAS as i32, + &[], + Some(channel.as_bytes().as_slice()), + ); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(key) + .execute(&mut *holder) + .await + .expect("hold replacement key"); + let delete_db = Db::from_pool(db.pool.clone()); + let id = canvas.id.to_bytes(); + let delete = tokio::spawn(async move { + // No channel: a channel event this old is below the floor. + let deletion = event(5, MAY, vec![]); + delete_db + .insert_deletion_event(community, &deletion, None, None, &[target(&canvas)]) + .await + }); + // Observe an actual advisory-lock wait, not merely a task that hasn't yet + // been scheduled. Removing the canonical lock makes this test fail. + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_locks WHERE pid=$1 AND locktype='advisory' AND NOT granted)") + .bind(deleter_pid).fetch_one(&mut *holder).await.expect("observe lock wait"); + if waiting { break; } + assert!(!delete.is_finished(), "known canvas deletion bypassed replacement lock"); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }).await.expect("deletion must wait on replacement lock"); + holder.rollback().await.expect("release replacement key"); + let result = tokio::time::timeout(std::time::Duration::from_secs(5), delete) + .await + .expect("delete completes") + .expect("join") + .expect("delete"); + assert_eq!(result.2, [true]); + assert_eq!(counts(&db, community, &id).await.1, 0); +} diff --git a/crates/buzz-db/src/store/event_floor_postgres_tests.rs b/crates/buzz-db/src/store/event_floor_postgres_tests.rs new file mode 100644 index 00000000000..24898fa7a1d --- /dev/null +++ b/crates/buzz-db/src/store/event_floor_postgres_tests.rs @@ -0,0 +1,434 @@ +//! App-floor regressions with every floor-trigger clone disabled in the +//! nextest-provided per-test database, so the DB backstop cannot mask a bypass. + +use buzz_core::CommunityId; +use chrono::{DateTime, Utc}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; +use sqlx::postgres::PgPoolOptions; +use uuid::Uuid; + +use crate::replica_fence::{ + probe_once, ReplicaFence, CREATED_AT_FLOOR_SECS, FENCE_CLOCK_MARGIN_SECS, +}; +use crate::{event, AdmittedTx, Db, DbError}; + +async fn fixture() -> (Db, CommunityId, Uuid, Keys) { + let pool = PgPoolOptions::new() + .max_connections(4) + .connect(&crate::test_support::database_url()) + .await + .expect("isolated test database"); + sqlx::query("ALTER TABLE events DISABLE TRIGGER events_created_at_floor") + .execute(&pool) + .await + .expect("disable floor trigger recursively on the partitioned table"); + let (total, enabled): (i64, i64) = sqlx::query_as( + "SELECT count(*), count(*) FILTER (WHERE tgenabled <> 'D') FROM pg_trigger \ + WHERE tgname = 'events_created_at_floor' \ + AND tgrelid IN (SELECT relid FROM pg_partition_tree('events'))", + ) + .fetch_one(&pool) + .await + .expect("check every trigger clone"); + assert!(total > 0, "the test must disable an existing backstop"); + assert_eq!(enabled, 0, "no partition may mask a missing app check"); + let community = CommunityId::from_uuid(Uuid::new_v4()); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(format!("floor-{}.invalid", community.as_uuid())) + .execute(&pool) + .await + .expect("community"); + let channel = Uuid::new_v4(); + let keys = Keys::generate(); + sqlx::query( + "INSERT INTO channels (id, community_id, name, created_by) VALUES ($1,$2,'floor',$3)", + ) + .bind(channel) + .bind(community.as_uuid()) + .bind(keys.public_key().to_bytes().as_slice()) + .execute(&pool) + .await + .expect("channel"); + (Db::from_pool(pool), community, channel, keys) +} + +async fn database_clock(db: &Db) -> DateTime { + sqlx::query_scalar("SELECT clock_timestamp()") + .fetch_one(db.pool()) + .await + .expect("database clock") +} + +fn signed(keys: &Keys, kind: u16, channel: Uuid, time: DateTime) -> Event { + EventBuilder::new(Kind::Custom(kind), "floor-test") + .tags([Tag::parse(["d", &channel.to_string()]).expect("coordinate")]) + .custom_created_at(Timestamp::from(time.timestamp() as u64)) + .sign_with_keys(keys) + .expect("signed event") +} + +async fn count(db: &Db, community: CommunityId, event: &Event) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .fetch_one(db.pool()) + .await + .expect("event count") +} + +async fn begin(db: &Db, community: CommunityId) -> AdmittedTx { + db.begin_event_write_transaction(community) + .await + .expect("admission") +} + +fn rejected(result: crate::Result) { + assert!( + matches!(result, Err(DbError::CreatedAtFloorRejected)), + "expected the typed app-floor rejection, got {result:?}" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn insert_event_floor_rejects_old_and_accepts_fresh() { + let (db, community, channel, keys) = fixture().await; + let now = database_clock(&db).await; + let old = signed( + &keys, + 9, + channel, + now - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + 60), + ); + rejected(event::insert_event(db.pool(), community, &old, Some(channel)).await); + assert_eq!(count(&db, community, &old).await, 0); + let fresh = signed(&keys, 9, channel, now); + assert!( + event::insert_event(db.pool(), community, &fresh, Some(channel)) + .await + .expect("fresh") + .1 + ); + assert_eq!(count(&db, community, &fresh).await, 1); + // Channel-NULL history is structurally outside covered windows. + assert!( + event::insert_event(db.pool(), community, &old, None) + .await + .expect("NULL-channel history") + .1 + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn insert_event_floor_accepts_expired_duplicate() { + let (db, community, channel, keys) = fixture().await; + let old = signed( + &keys, + 9, + channel, + database_clock(&db).await - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + 60), + ); + crate::test_support::insert_historical_event(db.pool(), community, &old, channel).await; + let (_, inserted) = event::insert_event(db.pool(), community, &old, Some(channel)) + .await + .expect("expired duplicate is idempotent"); + assert!(!inserted); + assert_eq!(count(&db, community, &old).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn thread_metadata_event_floor_accepts_expired_duplicate() { + let (db, community, channel, keys) = fixture().await; + let time = database_clock(&db).await - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + 60); + let old = signed(&keys, 9, channel, time); + crate::test_support::insert_historical_event(db.pool(), community, &old, channel).await; + let mut tx = begin(&db, community).await; + let meta = event::ThreadMetadataParams { + event_id: old.id.as_bytes(), + event_created_at: DateTime::from_timestamp(old.created_at.as_secs() as i64, 0) + .expect("timestamp"), + channel_id: channel, + parent_event_id: None, + parent_event_created_at: None, + root_event_id: None, + root_event_created_at: None, + depth: 0, + broadcast: true, + }; + let (_, inserted) = + event::insert_event_with_thread_metadata_tx(&mut tx, &old, Some(channel), Some(meta)) + .await + .expect("expired duplicate is idempotent"); + assert!(!inserted); + tx.commit().await.expect("commit duplicate result"); + assert_eq!(count(&db, community, &old).await, 1); + let metadata: i64 = sqlx::query_scalar( + "SELECT count(*) FROM thread_metadata WHERE community_id=$1 AND event_id=$2", + ) + .bind(community.as_uuid()) + .bind(old.id.as_bytes().as_slice()) + .fetch_one(db.pool()) + .await + .expect("metadata count"); + assert_eq!(metadata, 0, "a duplicate must not run thread follow-ups"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn thread_metadata_event_floor_rejects_old_and_accepts_fresh() { + let (db, community, channel, keys) = fixture().await; + let now = database_clock(&db).await; + for (time, old) in [ + ( + now - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + 60), + true, + ), + (now, false), + ] { + let event = signed(&keys, 9, channel, time); + let meta = event::ThreadMetadataParams { + event_id: event.id.as_bytes().as_slice(), + event_created_at: time, + channel_id: channel, + parent_event_id: None, + parent_event_created_at: None, + root_event_id: None, + root_event_created_at: None, + depth: 0, + broadcast: false, + }; + let mut tx = begin(&db, community).await; + let result = + event::insert_event_with_thread_metadata_tx(&mut tx, &event, Some(channel), Some(meta)) + .await; + if old { + rejected(result); + tx.rollback().await.expect("rollback refusal"); + assert_eq!(count(&db, community, &event).await, 0); + } else { + assert!(result.expect("fresh").1); + tx.commit().await.expect("commit"); + assert_eq!(count(&db, community, &event).await, 1); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn parameterized_event_floor_rejects_old_and_accepts_fresh() { + let (db, community, channel, keys) = fixture().await; + let now = database_clock(&db).await; + let old = signed( + &keys, + 30078, + channel, + now - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + 60), + ); + rejected( + db.replace_parameterized_event(community, &old, &channel.to_string(), Some(channel)) + .await, + ); + assert_eq!(count(&db, community, &old).await, 0); + let fresh = signed(&keys, 30078, channel, now); + assert!( + db.replace_parameterized_event(community, &fresh, &channel.to_string(), Some(channel)) + .await + .expect("fresh") + .1 + ); + assert_eq!(count(&db, community, &fresh).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn addressable_event_floor_rejects_old_and_accepts_fresh() { + let (db, community, channel, keys) = fixture().await; + let now = database_clock(&db).await; + let old = signed( + &keys, + 39000, + channel, + now - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + 60), + ); + rejected( + db.replace_addressable_event(community, &old, Some(channel)) + .await, + ); + assert_eq!(count(&db, community, &old).await, 0); + let fresh = signed(&keys, 39000, channel, now); + assert!( + db.replace_addressable_event(community, &fresh, Some(channel)) + .await + .expect("fresh") + .1 + ); + assert_eq!(count(&db, community, &fresh).await, 1); +} + +/// Seed an aged, stored and then soft-deleted event, as NIP-09 leaves it. +async fn soft_deleted_aged( + db: &Db, + community: CommunityId, + channel: Uuid, + keys: &Keys, + kind: u16, +) -> Event { + let now = database_clock(db).await; + let aged = signed( + keys, + kind, + channel, + now - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + 60), + ); + crate::test_support::insert_historical_event(db.pool(), community, &aged, channel).await; + sqlx::query("UPDATE events SET deleted_at = now() WHERE community_id = $1 AND id = $2") + .bind(community.as_uuid()) + .bind(aged.id.as_bytes().as_slice()) + .execute(db.pool()) + .await + .expect("soft-delete"); + aged +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn parameterized_replay_of_soft_deleted_aged_event_is_a_duplicate() { + let (db, community, channel, keys) = fixture().await; + let aged = soft_deleted_aged(&db, community, channel, &keys, 30078).await; + let (_, stored) = db + .replace_parameterized_event(community, &aged, &channel.to_string(), Some(channel)) + .await + .expect("replay of a stored id is a duplicate, not a floor rejection"); + assert!(!stored); + assert_eq!(count(&db, community, &aged).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn addressable_replay_of_soft_deleted_aged_event_is_a_duplicate() { + let (db, community, channel, keys) = fixture().await; + let aged = soft_deleted_aged(&db, community, channel, &keys, 39000).await; + let (_, stored) = db + .replace_addressable_event(community, &aged, Some(channel)) + .await + .expect("replay of a stored id is a duplicate, not a floor rejection"); + assert!(!stored); + assert_eq!(count(&db, community, &aged).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn member_snapshot_event_floor_rejects_old_and_accepts_fresh() { + let (db, community, channel, keys) = fixture().await; + let now = database_clock(&db).await; + let old = signed( + &keys, + 39002, + channel, + now - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + 60), + ); + let mut snapshot = db + .lock_member_snapshot(community, channel, &keys.public_key().to_bytes()) + .await + .expect("snapshot"); + rejected(snapshot.replace_member_event(&old).await); + // A refusal must leave the held snapshot usable and write no event. + assert_eq!(count(&db, community, &old).await, 0); + let fresh = signed(&keys, 39002, channel, now); + assert!( + snapshot + .replace_member_event(&fresh) + .await + .expect("fresh") + .1 + ); + snapshot.release().await.expect("commit snapshot"); + assert_eq!(count(&db, community, &fresh).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cluster_global_event_floor_held_transaction_cannot_write_below_probe_wall() { + let (db, community, channel, keys) = fixture().await; + let mut tx = begin(&db, community).await; + let start: DateTime = sqlx::query_scalar("SELECT now()") + .fetch_one(tx.conn()) + .await + .expect("transaction start"); + let entry = probe_once(db.pool(), &ReplicaFence::new()) + .await + .expect("heartbeat while writer is open"); + assert!( + entry.fence_wall + <= start - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS + FENCE_CLOCK_MARGIN_SECS) + ); + let below_wall = signed( + &keys, + 9, + channel, + entry.fence_wall - chrono::Duration::seconds(1), + ); + sqlx::query("SAVEPOINT rejected_floor_insert") + .execute(tx.conn()) + .await + .expect("isolate rejected insert"); + rejected(event::insert_event_in_transaction(&mut tx, &below_wall, Some(channel)).await); + // The check runs after INSERT. Roll back that write before continuing in + // the same held transaction, just as a caller must on any insert failure. + sqlx::query("ROLLBACK TO SAVEPOINT rejected_floor_insert") + .execute(tx.conn()) + .await + .expect("roll back rejected row"); + sqlx::query("RELEASE SAVEPOINT rejected_floor_insert") + .execute(tx.conn()) + .await + .expect("release rejection savepoint"); + // Sample just after the probe; a near-floor accepted insert is above its + // wall even when this transaction commits after the heartbeat. + let fresh = signed( + &keys, + 9, + channel, + database_clock(&db).await - chrono::Duration::seconds(CREATED_AT_FLOOR_SECS - 5), + ); + let created_at = + DateTime::from_timestamp(fresh.created_at.as_secs() as i64, 0).expect("timestamp"); + assert!(created_at > entry.fence_wall); + assert!( + event::insert_event_in_transaction(&mut tx, &fresh, Some(channel)) + .await + .expect("near floor") + .1 + ); + tx.commit().await.expect("commit after probe"); + assert_eq!(count(&db, community, &below_wall).await, 0); + assert_eq!(count(&db, community, &fresh).await, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn event_floor_samples_statement_clock_after_transaction_start() { + let (db, community, channel, keys) = fixture().await; + let mut tx = begin(&db, community).await; + // The smallest integral event timestamp inside the floor at BEGIN. + let secs: i64 = + sqlx::query_scalar("SELECT ceil(extract(epoch FROM now()) - $1::double precision)::bigint") + .bind(CREATED_AT_FLOOR_SECS as f64) + .fetch_one(tx.conn()) + .await + .expect("BEGIN boundary"); + let time = DateTime::from_timestamp(secs, 0).expect("timestamp"); + // Wait on the DB clock until this exact boundary expires (at most 1.1 s), + // not an arbitrary delay and not a Rust clock. now() remains frozen inside. + tokio::time::timeout(std::time::Duration::from_secs(3), + sqlx::query("SELECT pg_sleep(GREATEST(0, extract(epoch FROM ($1::timestamptz + make_interval(secs => $2::double precision) - clock_timestamp()))) + 0.1)") + .bind(time).bind(CREATED_AT_FLOOR_SECS as f64).execute(tx.conn())) + .await.expect("bounded boundary wait").expect("database wait"); + let event = signed(&keys, 9, channel, time); + rejected(event::insert_event_in_transaction(&mut tx, &event, Some(channel)).await); + tx.rollback().await.expect("rollback"); + assert_eq!(count(&db, community, &event).await, 0); +} diff --git a/crates/buzz-db/src/store/event_follow_up.rs b/crates/buzz-db/src/store/event_follow_up.rs index d2853b4d89d..b649d80b112 100644 --- a/crates/buzz-db/src/store/event_follow_up.rs +++ b/crates/buzz-db/src/store/event_follow_up.rs @@ -2,8 +2,9 @@ //! //! Two pieces of work follow every durable event insert: //! -//! - **Push match enqueue.** Eligible event IDs are staged in memory. Commit -//! submits them to a bounded best-effort worker using a dedicated connection. +//! - **Push match enqueue.** Eligible event IDs and signed timestamps are staged +//! in memory. Commit submits them to a bounded best-effort worker using a +//! dedicated connection. //! Push errors, delays, overload, and shutdown can drop wakes, never messages. //! - **Channel TTL refresh.** A channel-scoped event pushes its ephemeral //! channel's `ttl_deadline` forward. [`AdmittedTx`] records the channel and @@ -19,6 +20,7 @@ use std::collections::BTreeSet; use buzz_core::CommunityId; +use chrono::{DateTime, Utc}; use sqlx::PgConnection; use uuid::Uuid; @@ -37,14 +39,17 @@ const SQLSTATE_LOCK_NOT_AVAILABLE: &str = "55P03"; /// Follow-up for an event row inserted in an admitted transaction. /// /// Call only when the INSERT affected a row, after releasing any savepoint -/// that may roll it back. Stages push work for after commit and records TTL work. +/// that may roll it back. `created_at` must be the signed timestamp bound by +/// the INSERT, not receipt time. Stages push work for after commit and records +/// TTL work. pub(crate) async fn after_admitted_insert( tx: &mut AdmittedTx, event_id: &[u8], + created_at: DateTime, kind: i32, channel_id: Option, ) -> Result<()> { - tx.record_push_event(event_id, kind); + tx.record_push_event(event_id, created_at, kind); tx.record_channel_event(channel_id, kind); Ok(()) } diff --git a/crates/buzz-db/src/store/event_follow_up_postgres_tests.rs b/crates/buzz-db/src/store/event_follow_up_postgres_tests.rs index 68b68e20e21..e6beb22b514 100644 --- a/crates/buzz-db/src/store/event_follow_up_postgres_tests.rs +++ b/crates/buzz-db/src/store/event_follow_up_postgres_tests.rs @@ -1027,13 +1027,30 @@ async fn assert_async_isolation(db: &Db, community: CommunityId, keys: &Keys) { endpoint_grant, max_class, subscriptions, expires_at, updated_at) \ SELECT $1, author, installation_id, source_event_id, source_created_at, generation, \ active, endpoint_enabled, endpoint_hash, endpoint_grant, max_class, \ - subscriptions, expires_at, clock_timestamp() FROM push_leases WHERE community_id=$2", + subscriptions, expires_at, \ + (SELECT received_at + interval '1 second' FROM events WHERE community_id=$1 AND id=$3) \ + FROM push_leases WHERE community_id=$2", ) .bind(later.as_uuid()) .bind(community.as_uuid()) + .bind(before_enrollment.id.as_bytes().as_slice()) .execute(&mut *activation) .await .unwrap(); + let leases_strictly_newer: bool = sqlx::query_scalar( + "SELECT count(*) > 0 AND bool_and(l.updated_at > e.received_at) \ + FROM push_leases l JOIN events e ON e.community_id=l.community_id \ + WHERE l.community_id=$1 AND e.id=$2", + ) + .bind(later.as_uuid()) + .bind(before_enrollment.id.as_bytes().as_slice()) + .fetch_one(&mut *activation) + .await + .unwrap(); + assert!( + leases_strictly_newer, + "fixture leases must follow recorded receipt" + ); activation.commit().await.unwrap(); assert_eq!(match_count(&isolated, later, &before_enrollment).await, 0); assert_eq!( diff --git a/crates/buzz-db/src/store/event_hydration.rs b/crates/buzz-db/src/store/event_hydration.rs new file mode 100644 index 00000000000..5058dedc66f --- /dev/null +++ b/crates/buzz-db/src/store/event_hydration.rs @@ -0,0 +1,141 @@ +//! Exact, bounded search-hit hydration without probing every events partition. + +use buzz_core::{CommunityId, StoredEvent}; +use buzz_datastore_tracing::datastore_span; +use chrono::{DateTime, Utc}; +use sqlx::{PgConnection, QueryBuilder}; + +use crate::{Db, DbError, Result, RouteDecision, RoutePredicate}; + +const MAX_BATCH: usize = 500; + +type Lookup = ([u8; 32], DateTime); + +fn validate(hits: &[([u8; 32], i64)]) -> Result> { + if hits.len() > MAX_BATCH { + return Err(DbError::InvalidData( + "event hydration exceeds 500 hits".into(), + )); + } + let mut keys = Vec::with_capacity(hits.len()); + for &(id, seconds) in hits { + let timestamp = DateTime::from_timestamp(seconds, 0) + .filter(|_| seconds >= 0) + .ok_or(DbError::InvalidTimestamp(seconds))?; + keys.push((id, timestamp)); + } + // SQL IN semantics: duplicate inputs must not multiply hydrated rows. + keys.sort_unstable(); + keys.dedup(); + Ok(keys) +} + +fn lookup_sql(community: CommunityId, keys: &[Lookup]) -> QueryBuilder { + let mut query = QueryBuilder::new( + "SELECT id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id \ + FROM events WHERE community_id = ", + ); + query.push_bind(community.as_uuid()); + query.push(" AND deleted_at IS NULL AND ("); + for (index, (id, timestamp)) in keys.iter().enumerate() { + if index != 0 { + query.push(" OR "); + } + // Keep each id paired with its exact timestamp, not two independent IN + // lists. Scalar partition-key predicates allow both plan-time pruning + // and executor startup pruning when PostgreSQL chooses a generic plan. + query.push("(created_at = ").push_bind(*timestamp); + query.push(" AND id = ").push_bind(id.to_vec()).push(")"); + } + query.push(")"); + query +} + +async fn lookup_on( + conn: &mut PgConnection, + community: CommunityId, + keys: &[Lookup], +) -> Result> { + // Not a cached prepared statement: after five runs PostgreSQL may switch it + // to a generic plan, which on PG16 prunes only at executor startup, after + // every `events` partition and index is already locked. The SQL text also + // varies with the batch size, which would fill the statement cache. + let rows = lookup_sql(community, keys) + .build() + .persistent(false) + .fetch_all(conn) + .await?; + let mut events = Vec::with_capacity(rows.len()); + for row in rows { + if let Some(event) = crate::event::row_to_stored_event(row)? { + events.push(event); + } + } + Ok(events) +} + +impl Db { + /// Hydrate non-deleted search hits by paired `(id, created_at)` keys. + /// + /// Accepts at most 500 inputs (including duplicates), with nonnegative Unix + /// seconds representable by chrono; invalid input errors before any checkout. + /// Empty input returns immediately. Results are unordered and duplicates do + /// not multiply rows; callers retain responsibility for search ordering and + /// visibility. A stale, missing, deleted or wrong-community key is omitted. + /// + /// Routing is bounded-only: an id list carries no channel pin, so no fence + /// floor can prove insert-completeness, and timestamps enable partition + /// pruning, not a completeness proof. A missing row degrades to a skipped + /// search hit downstream. The caller must use a classified search-hydration + /// path (see [`Db::query_events_routed`] for the classification contract). + #[datastore_span(name = "get_events_by_ids_at_routed", system = "postgresql")] + pub async fn get_events_by_ids_at_routed( + &self, + path: &'static str, + community: CommunityId, + hits: &[([u8; 32], i64)], + ) -> Result> { + let keys = validate(hits)?; + if keys.is_empty() { + return Ok(Vec::new()); + } + match self + .route_read( + path, + RoutePredicate::Bounded, + crate::observability::ReaderOperation::SubscriptionHistory, + ) + .await? + { + RouteDecision::Replica(mut tx, _entry, reason) => { + match lookup_on(&mut tx, community, &keys).await { + Ok(events) => { + Self::record_route(path, "replica", reason); + return Ok(events); + } + Err(error) if error.is_statement_cancelled() => { + Self::record_route(path, "replica", "statement_cancelled"); + return Err(error); + } + Err(error) => { + tracing::warn!(path, "replica read failed; re-running on writer: {error}"); + Self::record_route(path, "writer", "replica_error"); + // Release the reader and its history permit before the + // writer re-run, so a replica-error burst can't fill the cap. + drop(tx); + } + } + } + RouteDecision::Writer => {} + } + let mut conn = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::SubscriptionHistory, + ) + .await?; + lookup_on(&mut conn, community, &keys).await + } +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/event_hydration/postgres_tests.rs b/crates/buzz-db/src/store/event_hydration/postgres_tests.rs new file mode 100644 index 00000000000..5e8acf1b407 --- /dev/null +++ b/crates/buzz-db/src/store/event_hydration/postgres_tests.rs @@ -0,0 +1,434 @@ +use super::*; +use nostr::{EventBuilder, Keys, Kind, Timestamp}; +use sqlx::{PgConnection, PgPool, Row}; +use std::collections::BTreeSet; +use uuid::Uuid; + +const JAN: i64 = 1_768_435_200; // 2026-01-15 UTC +const MAR: i64 = 1_773_532_800; // 2026-03-15 UTC + +async fn fixture() -> (Db, CommunityId, CommunityId, Keys) { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool); + let mut communities = Vec::new(); + for _ in 0..2 { + communities.push( + db.ensure_configured_community(&format!("hydrate-{}.local", Uuid::new_v4())) + .await + .unwrap() + .id, + ); + } + (db, communities[0], communities[1], Keys::generate()) +} + +fn event(keys: &Keys, content: &str, seconds: i64) -> nostr::Event { + EventBuilder::new(Kind::Custom(9), content) + .custom_created_at(Timestamp::from(seconds as u64)) + .sign_with_keys(keys) + .unwrap() +} + +fn key(event: &nostr::Event) -> ([u8; 32], i64) { + (event.id.to_bytes(), event.created_at.as_secs() as i64) +} + +fn ids(events: &[StoredEvent]) -> BTreeSet<[u8; 32]> { + events + .iter() + .map(|event| event.event.id.to_bytes()) + .collect() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn hydration_exact_pairs_across_months_and_scopes() { + let (db, a, b, keys) = fixture().await; + let jan = event(&keys, "January", JAN); + let same_second = event(&keys, "January same second", JAN); + let march = event(&keys, "March", MAR); + let deleted = event(&keys, "deleted", JAN + 1); + let foreign = event(&keys, "foreign", MAR); + for event in [&jan, &same_second, &march, &deleted] { + db.insert_event(a, event, None).await.unwrap(); + } + // Same signed event in two communities is legal. A's tombstone must not + // fall through to B's live copy. + db.insert_event(b, &deleted, None).await.unwrap(); + db.insert_event(b, &foreign, None).await.unwrap(); + sqlx::query("UPDATE events SET deleted_at = now() WHERE community_id = $1 AND id = $2 AND created_at = $3") + .bind(a.as_uuid()).bind(deleted.id.to_bytes().to_vec()) + .bind(DateTime::from_timestamp(JAN + 1, 0).unwrap()) + .execute(&db.pool).await.unwrap(); + + let hits = [ + key(&march), + key(&jan), + key(&same_second), + key(&jan), + key(&deleted), + key(&foreign), + ([0xff; 32], JAN), + ]; + let found = db + .get_events_by_ids_at_routed("req_search_hydrate", a, &hits) + .await + .unwrap(); + assert_eq!(found.len(), 3, "duplicate inputs must not multiply rows"); + assert_eq!( + ids(&found), + [ + jan.id.to_bytes(), + same_second.id.to_bytes(), + march.id.to_bytes() + ] + .into() + ); + assert_eq!( + ids(&db + .get_events_by_ids_at_routed( + "profile_search_hydrate", + b, + &[key(&deleted), key(&foreign), key(&jan)] + ) + .await + .unwrap()), + [deleted.id.to_bytes(), foreign.id.to_bytes()].into() + ); + + // Both timestamps and both IDs are real, but neither PAIR exists. This + // fails if the production predicate becomes independent id/time IN lists. + let crossed = [(jan.id.to_bytes(), MAR), (march.id.to_bytes(), JAN)]; + assert!(db + .get_events_by_ids_at_routed("bridge_search_hydrate", a, &crossed) + .await + .unwrap() + .is_empty()); + assert!(db + .get_events_by_ids_at_routed("req_search_hydrate", a, &[(jan.id.to_bytes(), JAN + 1)]) + .await + .unwrap() + .is_empty()); + + // Existing ID-only callers retain their contract. + let raw = [jan.id.as_bytes().as_slice(), march.id.as_bytes().as_slice()]; + assert_eq!(db.get_events_by_ids(a, &raw).await.unwrap().len(), 2); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn hydration_rejects_invalid_or_oversized_batches_before_checkout() { + // A closed pool makes any accidental database access fail. Invalid inputs + // must still return the input error, and empty input must succeed. + let (db, community, _, _) = fixture().await; + db.pool.close().await; + for seconds in [-1, i64::MIN, i64::MAX] { + assert!( + matches!(db.get_events_by_ids_at_routed("req_search_hydrate", community, &[([0; 32], seconds)]).await, + Err(DbError::InvalidTimestamp(value)) if value == seconds) + ); + } + assert!(matches!( + db.get_events_by_ids_at_routed( + "req_search_hydrate", + community, + &vec![([0; 32], JAN); MAX_BATCH + 1] + ) + .await, + Err(DbError::InvalidData(_)) + )); + assert!(db + .get_events_by_ids_at_routed("req_search_hydrate", community, &[]) + .await + .unwrap() + .is_empty()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn hydration_accepts_full_bounded_batch_and_deduplicates() { + let (db, community, _, keys) = fixture().await; + let event = event(&keys, "full batch", JAN); + db.insert_event(community, &event, None).await.unwrap(); + let found = db + .get_events_by_ids_at_routed( + "req_search_hydrate", + community, + &vec![key(&event); MAX_BATCH], + ) + .await + .unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].event.id, event.id); + // Exercise the full 1001-bind SQL shape too, not just deduplication down + // to one predicate. Other keys are intentionally absent. + let mut distinct = Vec::with_capacity(MAX_BATCH); + for n in 0..MAX_BATCH - 1 { + let mut id = [0; 32]; + id[..8].copy_from_slice(&(n as u64).to_be_bytes()); + distinct.push((id, JAN)); + } + distinct.push(key(&event)); + let found = db + .get_events_by_ids_at_routed("req_search_hydrate", community, &distinct) + .await + .unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].event.id, event.id); +} + +fn executed_relations(node: &serde_json::Value, out: &mut BTreeSet) { + if node["Actual Loops"].as_u64().unwrap_or(0) > 0 { + if let Some(name) = node["Relation Name"].as_str() { + out.insert(name.to_owned()); + } + } + if let Some(children) = node["Plans"].as_array() { + for child in children { + executed_relations(child, out); + } + } +} + +/// Partitions of `events` that `conn`'s open transaction holds a relation lock +/// on. Indexes are excluded (`relkind = 'r'`), the partitioned parent too. +async fn locked_event_partitions(conn: &mut PgConnection) -> BTreeSet { + sqlx::query_scalar( + "SELECT c.relname::text FROM pg_locks l JOIN pg_class c ON c.oid = l.relation \ + WHERE l.locktype = 'relation' AND l.pid = pg_backend_pid() \ + AND c.relkind = 'r' AND c.relname LIKE 'events\\_p%'", + ) + .fetch_all(conn) + .await + .unwrap() + .into_iter() + .collect() +} + +/// Pins what the hydration lookup LOCKS, not just what it executes: the +/// partitions other than the requested months must stay unlocked. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn hydration_lookup_locks_only_the_requested_partitions() { + let (db, community, _, keys) = fixture().await; + let jan = event(&keys, "lock January", JAN); + let march = event(&keys, "lock March", MAR); + for event in [&jan, &march] { + db.insert_event(community, event, None).await.unwrap(); + } + // Mixed present/absent keys across both months, at the full batch size. + let mut large = vec![key(&jan), key(&march)]; + for n in 0..MAX_BATCH - large.len() { + let mut id = [0; 32]; + id[..8].copy_from_slice(&(n as u64).to_be_bytes()); + large.push((id, if n % 2 == 0 { JAN } else { MAR })); + } + let cases = [ + (vec![key(&jan)], vec!["events_p2026_01"], 1), + (vec![key(&march)], vec!["events_p2026_03"], 1), + ( + vec![key(&jan), key(&march)], + vec!["events_p2026_01", "events_p2026_03"], + 2, + ), + (large, vec!["events_p2026_01", "events_p2026_03"], 2), + ]; + // Run the production `lookup_on` repeatedly on ONE session. A cached + // prepared statement is eligible to flip to a generic plan after five + // executions, and on PG16+ a generic plan locks every partition at + // executor startup before pruning. The unnamed statement used in + // production is planned afresh with its parameter values every time. + let mut conn = db.pool.acquire().await.unwrap(); + for round in 0..8 { + for (hits, expected_locks, expected_rows) in &cases { + let keys = validate(hits).unwrap(); + let mut tx = sqlx::Connection::begin(&mut *conn).await.unwrap(); + let found = lookup_on(&mut tx, community, &keys).await.unwrap(); + assert_eq!(found.len(), *expected_rows, "round {round}"); + let locked = locked_event_partitions(&mut tx).await; + tx.rollback().await.unwrap(); + let expected: BTreeSet = expected_locks + .iter() + .map(|name| (*name).to_owned()) + .collect(); + assert_eq!( + locked, + expected, + "round {round}, {} keys: lookup_on locked unrelated events partitions", + keys.len() + ); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn hydration_production_sql_executes_only_requested_partitions() { + let (db, community, _, keys) = fixture().await; + let jan = event(&keys, "plan January", JAN); + let march = event(&keys, "plan March", MAR); + let wrong_time = event(&keys, "plan January, requested in March", JAN); + for event in [&jan, &march, &wrong_time] { + db.insert_event(community, event, None).await.unwrap(); + } + // Reuse the tiny fixture for the full 1001-bind shape. Missing keys span + // both months; the third seeded event must NOT match its requested time. + // Independent id/time IN lists would incorrectly return that third row. + let mut large_hits = vec![key(&jan), key(&march), (wrong_time.id.to_bytes(), MAR)]; + for n in 0..MAX_BATCH - large_hits.len() { + let mut id = [0; 32]; + id[..8].copy_from_slice(&(n as u64).to_be_bytes()); + large_hits.push((id, if n % 2 == 0 { JAN } else { MAR })); + } + assert_eq!(large_hits.len(), 500); + assert_eq!( + large_hits.iter().copied().collect::>().len(), + 500 + ); + let cases = [ + (vec![key(&jan)], 1), + (vec![key(&jan), key(&march)], 2), + (large_hits, 2), + ]; + let mut conn = db.pool.acquire().await.unwrap(); + // EXPLAIN ANALYZE the actual production builder, not a copied + // approximation, as a custom plan (the plan the production statement is + // executed with). It reports relations EXECUTED, not relations LOCKED: the + // generic-plan lock behavior is pinned by + // `hydration_lookup_locks_only_the_requested_partitions`. + for (hits, expected_rows) in &cases { + let validated = validate(hits).unwrap(); + assert_eq!(validated.len(), hits.len(), "plan keys must stay distinct"); + let query = lookup_sql(community, &validated); + sqlx::query("SET plan_cache_mode = force_custom_plan") + .execute(&mut *conn) + .await + .unwrap(); + sqlx::query(sqlx::AssertSqlSafe(format!( + "PREPARE hydration_plan AS {}", + query.sql().as_str() + ))) + .execute(&mut *conn) + .await + .unwrap(); + let mut arguments = vec![format!("'{}'::uuid", community.as_uuid())]; + for (id, timestamp) in &validated { + arguments.push(format!("'{}'::timestamptz", timestamp.to_rfc3339())); + arguments.push(format!("decode('{}', 'hex')", hex::encode(id))); + } + let plan: serde_json::Value = sqlx::query(sqlx::AssertSqlSafe(format!( + "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) EXECUTE hydration_plan({})", + arguments.join(", ") + ))) + .fetch_one(&mut *conn) + .await + .unwrap() + .get(0); + let mut relations = BTreeSet::new(); + executed_relations(&plan[0]["Plan"], &mut relations); + let expected: BTreeSet = if hits.len() == 1 { + ["events_p2026_01".to_owned()].into() + } else { + ["events_p2026_01".to_owned(), "events_p2026_03".to_owned()].into() + }; + assert_eq!( + relations, + expected, + "{} keys: unrelated partitions executed: {plan}", + hits.len() + ); + assert_eq!( + plan[0]["Plan"]["Actual Rows"].as_u64(), + Some(*expected_rows), + "{} keys: unexpected hydrated row count: {plan}", + hits.len() + ); + sqlx::query("DEALLOCATE hydration_plan") + .execute(&mut *conn) + .await + .unwrap(); + } + sqlx::query("RESET plan_cache_mode") + .execute(&mut *conn) + .await + .unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn channel_create_resend_requires_exact_timestamp_and_live_community_row() { + use crate::channel::{ChannelCreate, ChannelType, ChannelVisibility, NewChannel}; + let (db, a, b, keys) = fixture().await; + let channel_id = Uuid::new_v4(); + let creator = keys.public_key().to_bytes(); + // Created now: the serving writer rejects a channel event older than the + // `created_at` floor, and the first create must succeed. The malformed + // March row below still differs from it in the partition key. + let created_at = Timestamp::now(); + let event = EventBuilder::new(Kind::Custom(9007), "channel create") + .custom_created_at(created_at) + .sign_with_keys(&keys) + .unwrap(); + let channel = || NewChannel { + name: "exact-resend", + channel_type: ChannelType::Stream, + visibility: ChannelVisibility::Private, + description: None, + created_by: &creator, + ttl_seconds: None, + labels: &[], + unlisted: false, + members: &[], + }; + assert!(matches!( + db.create_channel_with_event(a, channel_id, channel(), &event) + .await + .unwrap(), + ChannelCreate::Created(_) + )); + assert!(matches!( + db.create_channel_with_event(a, channel_id, channel(), &event) + .await + .unwrap(), + ChannelCreate::Exists { resent: true } + )); + // Keep a live exact-key copy in B so community scope is independently + // falsifiable even when A's copy is deleted or has a mismatched key. + db.insert_event(b, &event, None).await.unwrap(); + sqlx::query("UPDATE events SET deleted_at = now() WHERE community_id = $1 AND id = $2 AND created_at = $3") + .bind(a.as_uuid()).bind(event.id.to_bytes().to_vec()) + .bind(DateTime::from_timestamp(created_at.as_secs() as i64, 0).unwrap()) + .execute(&db.pool).await.unwrap(); + assert!(matches!( + db.create_channel_with_event(a, channel_id, channel(), &event) + .await + .unwrap(), + ChannelCreate::Exists { resent: false } + )); + // Deliberately malformed storage: id alone matches a live row in A, but + // its partition key does not. This catches removal of created_at equality. + sqlx::query( + "UPDATE events SET deleted_at = NULL, created_at = $3 WHERE community_id = $1 AND id = $2", + ) + .bind(a.as_uuid()) + .bind(event.id.to_bytes().to_vec()) + .bind(DateTime::from_timestamp(MAR, 0).unwrap()) + .execute(&db.pool) + .await + .unwrap(); + assert!(matches!( + db.create_channel_with_event(a, channel_id, channel(), &event) + .await + .unwrap(), + ChannelCreate::Exists { resent: false } + )); + let mut invalid = event.clone(); + invalid.created_at = Timestamp::from(u64::MAX); + assert!(matches!( + db.create_channel_with_event(a, channel_id, channel(), &invalid) + .await, + Err(DbError::InvalidTimestamp(_)) + )); +} diff --git a/crates/buzz-db/src/store/feed.rs b/crates/buzz-db/src/store/feed.rs index 1094c948e82..598053eaa4a 100644 --- a/crates/buzz-db/src/store/feed.rs +++ b/crates/buzz-db/src/store/feed.rs @@ -365,7 +365,7 @@ impl Db { RoutePredicate::Bounded, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { RouteDecision::Replica(mut tx, _entry, reason) => match crate::feed::query_mentions_on( &mut tx, @@ -390,6 +390,9 @@ impl Db { Err(e) => { tracing::warn!(path, "replica read failed; re-running on writer: {e}"); Self::record_route(path, "writer", "replica_error"); + // Release the reader and its history permit before the + // writer re-run, so a replica-error burst can't fill the cap. + drop(tx); crate::feed::query_mentions( &self.pool, community, @@ -455,7 +458,7 @@ impl Db { RoutePredicate::Bounded, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { RouteDecision::Replica(mut tx, _entry, reason) => { match crate::feed::query_needs_action_on( @@ -481,6 +484,9 @@ impl Db { Err(e) => { tracing::warn!(path, "replica read failed; re-running on writer: {e}"); Self::record_route(path, "writer", "replica_error"); + // Release the reader and its history permit before the + // writer re-run, so a replica-error burst can't fill the cap. + drop(tx); crate::feed::query_needs_action( &self.pool, community, @@ -538,7 +544,7 @@ impl Db { RoutePredicate::Bounded, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { RouteDecision::Replica(mut tx, _entry, reason) => match crate::feed::query_activity_on( &mut tx, @@ -562,6 +568,9 @@ impl Db { Err(e) => { tracing::warn!(path, "replica read failed; re-running on writer: {e}"); Self::record_route(path, "writer", "replica_error"); + // Release the reader and its history permit before the + // writer re-run, so a replica-error burst can't fill the cap. + drop(tx); crate::feed::query_activity( &self.pool, community, diff --git a/crates/buzz-db/src/store/leader_lock.rs b/crates/buzz-db/src/store/leader_lock.rs new file mode 100644 index 00000000000..6558bd32735 --- /dev/null +++ b/crates/buzz-db/src/store/leader_lock.rs @@ -0,0 +1,115 @@ +//! Deployment-wide leader election over PostgreSQL session advisory locks. + +use buzz_datastore_tracing::datastore_span; +use sqlx::postgres::PgConnection; +use sqlx::Connection as _; + +use crate::error::Result; +use crate::{observability, Db}; + +/// Owns the detached Postgres session holding a deployment-wide leader advisory lock. +/// +/// The connection deliberately does not return to the main pool: session advisory +/// locks must remain bound to this exact physical connection, and each leader-only +/// loop (the usage poller, storage-usage delivery) pings it before working. +pub struct SessionLeader { + connection: PgConnection, +} + +impl SessionLeader { + /// Returns whether the lock-owning session is still reachable. + /// + /// Bounded to 5 seconds — a blackholed connection (no RST) would otherwise + /// stall the entire poller tick until the OS TCP timeout. + pub async fn is_live(&mut self) -> bool { + tokio::time::timeout(std::time::Duration::from_secs(5), self.connection.ping()) + .await + .is_ok_and(|r| r.is_ok()) + } +} + +impl Db { + /// Try to acquire the detached session advisory lock `lock_key`, making this + /// replica the leader for the job that key names. + /// + /// The returned guard owns the exact connection that acquired the lock. It is + /// detached from the shared pool so a stable leader neither returns a locked + /// session to other callers nor permanently consumes a pool slot. Dropping the + /// guard closes the connection and releases the session-scoped lock. + #[datastore_span(name = "try_lock_session_leader", system = "postgresql")] + pub async fn try_lock_session_leader(&self, lock_key: i64) -> Result> { + let mut connection = observability::acquire_writer_with_legacy_metrics( + &self.pool, + observability::WriterOperation::Maintenance, + ) + .await?; + let acquired = sqlx::query_scalar::<_, bool>("SELECT pg_try_advisory_lock($1)") + .bind(lock_key) + .fetch_one(&mut *connection) + .await?; + if acquired { + Ok(Some(SessionLeader { + connection: connection.detach(), + })) + } else { + Ok(None) + } + } +} + +#[cfg(test)] +mod postgres_tests { + use super::*; + use crate::test_support::ScratchDb; + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn test_session_leader_lock_has_single_owner_and_releases_on_drop() { + // Use a private scratch database — not the shared TEST_DATABASE_URL. + // Postgres advisory locks are per-database; hardcoding the production + // USAGE_METRICS_LOCK_KEY (0x4255_5A5A_4D45_5452) on the shared test DB + // races any live buzz-relay on the same database (see #3619). + let admin_url = crate::test_support::database_url(); + let (pool, _scratch) = ScratchDb::migrated(&admin_url, "usage_metrics_lock").await; + let first = Db::from_pool(pool.clone()); + let second = Db::from_pool(pool.clone()); + // Same key as production (`buzz-relay` USAGE_METRICS_LOCK_KEY) — safe here + // because the scratch DB is empty of other holders. + let key = 0x4255_5A5A_4D45_5452; + + let mut leader = first + .try_lock_session_leader(key) + .await + .expect("first lock attempt") + .expect("first database handle becomes leader"); + assert!(leader.is_live().await, "lock owner remains reachable"); + assert!( + second + .try_lock_session_leader(key) + .await + .expect("second lock attempt") + .is_none(), + "another session cannot become leader while the guard exists" + ); + + drop(leader); + // Dropping closes the socket; the server releases the session lock only + // once its backend observes the disconnect, so poll briefly. + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); + let successor = loop { + let attempt = second + .try_lock_session_leader(key) + .await + .expect("lock attempt after leader drop"); + if attempt.is_some() || tokio::time::Instant::now() >= deadline { + break attempt; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + }; + assert!( + successor.is_some(), + "dropping the detached session releases its advisory lock" + ); + drop(successor); + } +} diff --git a/crates/buzz-db/src/store/legacy_channel_types_postgres_tests.rs b/crates/buzz-db/src/store/legacy_channel_types_postgres_tests.rs index d13823f81e9..5a6c8d72d86 100644 --- a/crates/buzz-db/src/store/legacy_channel_types_postgres_tests.rs +++ b/crates/buzz-db/src/store/legacy_channel_types_postgres_tests.rs @@ -2,6 +2,7 @@ //! (NIP-CL). The relay must leave out a channel type that it adds later, not //! only `system`: a client sees a channel only if it knows the channel's type. +use crate::test_support::ScratchDb; use crate::Db; use buzz_core::CommunityId; use nostr::Keys; @@ -13,29 +14,18 @@ use uuid::Uuid; pub(super) const FUTURE_TYPE: &str = "future_type"; /// A migrated scratch database with [`FUTURE_TYPE`] in `channel_type`, so the -/// shared test database keeps its schema. Returns `(db, admin, name)`. -pub(super) async fn scratch_db_with_future_type() -> (Db, PgPool, String) { - let url = crate::test_support::database_url(); - let admin = PgPool::connect(&url).await.expect("connect admin"); - let name = format!("legacy_types_{}", Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(&admin) - .await - .expect("create scratch db"); - let base = &url[..url.rfind('/').expect("db url has a path")]; - let pool = PgPool::connect(&format!("{base}/{name}")) - .await - .expect("connect scratch db"); - crate::migration::run_migrations(&pool) - .await - .expect("migrate scratch db"); +/// shared test database keeps its schema. Dropping the guard drops the +/// database. +pub(super) async fn scratch_db_with_future_type() -> (Db, ScratchDb) { + let (pool, scratch) = + ScratchDb::migrated(&crate::test_support::database_url(), "legacy_types").await; sqlx::query(sqlx::AssertSqlSafe(format!( "ALTER TYPE channel_type ADD VALUE '{FUTURE_TYPE}'" ))) .execute(&pool) .await .expect("add future channel type"); - (Db::from_pool(pool), admin, name) + (Db::from_pool(pool), scratch) } async fn insert_channel( @@ -80,7 +70,7 @@ async fn insert_channel( #[tokio::test] #[ignore = "requires Postgres"] async fn reads_that_name_no_channel_leave_out_a_type_added_later() { - let (db, admin, name) = scratch_db_with_future_type().await; + let (db, _scratch) = scratch_db_with_future_type().await; let pool = db.pool.clone(); let community = CommunityId::from_uuid(Uuid::new_v4()); sqlx::query("INSERT INTO communities(id,host) VALUES($1,$2)") @@ -148,11 +138,4 @@ async fn reads_that_name_no_channel_leave_out_a_type_added_later() { joined.sort(); legacy.sort(); assert_eq!(joined, legacy, "sidebar roster"); - - db.pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(&admin) - .await; } diff --git a/crates/buzz-db/src/store/media.rs b/crates/buzz-db/src/store/media.rs new file mode 100644 index 00000000000..9f5551ab2e2 --- /dev/null +++ b/crates/buzz-db/src/store/media.rs @@ -0,0 +1,510 @@ +//! Fresh media reads use primary-database event and channel state. +use crate::{Db, DbError, Result}; +use buzz_core::{kind, media::reference_hashes, CommunityId}; +use buzz_datastore_tracing::datastore_span; +use futures_util::TryStreamExt; +use sqlx::{Postgres, QueryBuilder, Row}; + +// Unqualified tags lets this exact expression serve indexes and aliased probes. +// Keep DDL/catalog and Rust target parity covered by the PostgreSQL tests. +pub(crate) const MEDIA_EDIT_TARGET_SQL: &str = r#"decode(lower(jsonb_path_query_first(tags, 'strict $[*] ? (@[0] == "e" && @[1] like_regex "^[0-9A-Fa-f]{64}$")[1]', '{}'::jsonb, true) #>> '{}'), 'hex')"#; + +// Short indexed authorization probes cannot amortize LLVM compilation. +// Partitioned permission plans can compile for seconds before reading any row. +// Ordinary database work retains its configured JIT policy. +pub(super) const MEDIA_LOOKUP_SETTINGS_SQL: &str = + "SET LOCAL statement_timeout = '2s'; SET LOCAL jit = off"; + +fn edit_governed_kinds_sql() -> String { + buzz_core::media::EDIT_GOVERNED_KINDS + .iter() + .map(u16::to_string) + .collect::>() + .join(",") +} + +fn edit_target(alias: &str) -> String { + MEDIA_EDIT_TARGET_SQL.replacen("(tags,", &format!("({alias}.tags,"), 1) +} + +pub(super) fn latest_message_edit_sql() -> String { + format!("SELECT e.* FROM events e WHERE e.community_id=$1 AND e.channel_id=$2 AND e.kind=40003 AND e.deleted_at IS NULL AND {}=$3 ORDER BY e.created_at DESC,e.id DESC LIMIT 1", edit_target("e")) +} + +/// Result of a complete live-reference lookup, for bounded denial metrics. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MediaAccess { + /// A current readable reference. + Allowed, + /// Uploaded bytes with no past publication boundary or current reference. + UploaderPreview, + /// No published reference or upload proof exists. + NoReference, + /// References exist but none is currently readable. + Restricted, +} + +/// Original message and its latest live edit in one primary-database snapshot. +#[derive(Debug)] +pub struct MessageEditState { + /// Live original, authorized for the reader's explicitly named channel. + pub original: nostr::Event, + /// Complete replacement, if a live edit exists. + pub edit: Option, +} + +impl Db { + /// Read effective edit metadata using the normalized-target + /// index. Channel membership, source liveness and edit selection share a + /// repeatable-read primary snapshot; no replica or membership cache is used. + pub async fn message_edit_state( + &self, + community: CommunityId, + channel: uuid::Uuid, + target: &[u8], + reader: &[u8], + ) -> Result> { + let mut tx = self.pool.begin().await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + .execute(&mut *tx) + .await?; + sqlx::raw_sql(MEDIA_LOOKUP_SETTINGS_SQL) + .execute(&mut *tx) + .await?; + // Mirrors channel_members::{get_accessible_channel_ids, + // get_readable_named_only_channels}. + // The channel is explicitly named by this read, so open unlisted and + // named-only channels follow the normal explicit-channel read policy. + let original_sql = format!("SELECT e.* FROM events e JOIN channels c ON c.community_id=e.community_id AND c.id=e.channel_id WHERE e.community_id=$1 AND e.channel_id=$2 AND e.id=$3 AND e.kind IN ({}) AND e.deleted_at IS NULL AND c.deleted_at IS NULL AND (c.visibility='open' OR EXISTS (SELECT 1 FROM channel_members cm WHERE cm.community_id=c.community_id AND cm.channel_id=c.id AND cm.pubkey=$4 AND cm.removed_at IS NULL))", edit_governed_kinds_sql()); + let original = sqlx::query(sqlx::AssertSqlSafe(original_sql)) + .bind(community.as_uuid()) + .bind(channel) + .bind(target) + .bind(reader) + .fetch_optional(&mut *tx) + .await?; + let Some(original) = original else { + tx.commit().await?; + return Ok(None); + }; + let original = super::event::row_to_stored_event(original)? + .ok_or_else(|| DbError::InvalidData("unreadable original message row".into()))? + .event; + let sql = latest_message_edit_sql(); + let edit = sqlx::query(sqlx::AssertSqlSafe(sql)) + .bind(community.as_uuid()) + .bind(channel) + .bind(target) + .fetch_optional(&mut *tx) + .await? + .map(|row| { + super::event::row_to_stored_event(row)? + .map(|stored| stored.event) + .ok_or_else(|| DbError::InvalidData("unreadable latest edit row".into())) + }) + .transpose()?; + tx.commit().await?; + Ok(Some(MessageEditState { original, edit })) + } + + /// Record possession after the upload pipeline verified the actual bytes. + /// Independent of optional audit and moderation records; admission fences deletion. + #[datastore_span(name = "record_media_upload", system = "postgresql")] + pub async fn record_media_upload( + &self, + community: CommunityId, + sha256: &str, + pubkey: &[u8], + ) -> Result<()> { + let mut tx = crate::begin_community_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + sqlx::query("INSERT INTO media_uploaders (community_id, sha256, pubkey) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING") + .bind(community.as_uuid()).bind(sha256).bind(pubkey).execute(tx.conn()).await?; + tx.commit().await?; + Ok(()) + } + + /// Record a sticky publication boundary before dispatch, even if the later + /// command fails. This grants no read access and survives source purging. + pub async fn record_media_publications( + &self, + community: CommunityId, + hashes: Vec, + ) -> Result<()> { + let mut tx = crate::begin_community_write_transaction( + &self.pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + sqlx::query("INSERT INTO media_publications (community_id,sha256) SELECT $1, unnest($2::text[]) ON CONFLICT DO NOTHING") + .bind(community.as_uuid()).bind(hashes).execute(tx.conn()).await?; + tx.commit().await?; + Ok(()) + } + + /// Resolve an attachment through live references, never a membership cache + /// or read replica. A repeatable-read snapshot covers both indexed references + /// and profile fallback, including the absence check for uploader previews. + /// `visible` is the ordinary relay REQ visibility predicate. + #[allow(clippy::too_many_arguments)] // Complete tenant/media/reader authority stays explicit. + #[datastore_span(name = "media_access", system = "postgresql")] + pub async fn media_access( + &self, + community: CommunityId, + sha256: &str, + ext: &str, + base: &str, + pubkey: &[u8], + for_publication: bool, + visible: fn(&nostr::Event, &[u8]) -> bool, + ) -> Result { + let _permit = tokio::time::timeout( + std::time::Duration::from_millis(500), + self.media_authorization_slots.acquire(), + ) + .await + .map_err(|_| DbError::MediaAuthorizationCapacity)? + .map_err(|_| DbError::MediaAuthorizationCapacity)?; + let connection = crate::observability::acquire_writer( + &self.pool, + crate::observability::WriterOperation::Authorization, + ) + .await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + let result = async { + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + .execute(&mut *tx) + .await?; + sqlx::raw_sql(MEDIA_LOOKUP_SETTINGS_SQL) + .execute(&mut *tx) + .await?; + let uploaded: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM media_uploaders WHERE community_id=$1 AND sha256=$2 AND pubkey=$3)") + .bind(community.as_uuid()).bind(sha256).bind(pubkey).fetch_one(&mut *tx).await?; + if uploaded && for_publication { + return Ok(MediaAccess::Allowed); + } + + let needles = media_reference_needles(sha256, ext, base); + let mut referenced = false; + let mut scanned_bytes = 0usize; + // Prefer readable live references before counting any inaccessible rows. + // The second pass only classifies absence; it can stop at the first real reference. + for readable_only in [true, false] { + for probe in 0..4 { + let mut query = media_reference_query( + community, + sha256, + pubkey, + &needles, + probe, + readable_only, + ); + // Stream candidates: a frequently shared hash must not allocate + // 1,025 full message bodies before finding the first readable one. + let statement = query.build(); + let mut rows = statement.fetch(&mut *tx); + let mut count = 0; + while let Some(row) = rows.try_next().await? { + count += 1; + let content: &str = row.try_get("content")?; + let tags: serde_json::Value = row.try_get("tags")?; + scanned_bytes = scanned_bytes + .saturating_add(content.len()) + .saturating_add(tags.to_string().len()); + if count > 1024 || scanned_bytes > 16 * 1024 * 1024 { + return Err(DbError::InvalidData( + "media reference work budget exceeded".into(), + )); + } + let readable: bool = row.try_get("readable")?; + let stored = crate::event::row_to_stored_event(row)?.ok_or_else(|| { + DbError::InvalidData("malformed media reference event".into()) + })?; + let event = &stored.event; + if !reference_hashes(event, base).contains(sha256) { + continue; + } + referenced = true; + if !readable_only { + break; + } + let kind = event.kind.as_u16() as u32; + let tagged = event.tags.iter().any(|tag| matches!(tag.as_slice(), [name, value, ..] if name == "p" && value == &hex::encode(pubkey))); + let private_ok = (!kind::P_GATED_KINDS.contains(&kind) || tagged) + && (kind != kind::KIND_AGENT_ENGRAM + || event.pubkey.as_bytes() == pubkey + || tagged); + if readable && private_ok && visible(event, pubkey) { + return Ok(MediaAccess::Allowed); + } + } + if referenced && !readable_only { + break; + } + } + if referenced && !readable_only { + break; + } + } + // Community icons are current community state; commands validate their + // structured URLs before updating this row. They grant community access. + let icon: Option = sqlx::query_scalar("SELECT icon FROM communities WHERE id=$1") + .bind(community.as_uuid()) + .fetch_one(&mut *tx) + .await?; + if icon + .as_deref() + .and_then(|value| buzz_core::media::local_hash(value, base)) + .as_deref() + == Some(sha256) + { + return Ok(MediaAccess::Allowed); + } + let published: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM media_publications WHERE community_id=$1 AND sha256=$2)", + ) + .bind(community.as_uuid()) + .bind(sha256) + .fetch_one(&mut *tx) + .await?; + if referenced || published { + Ok(MediaAccess::Restricted) + } else if uploaded { + Ok(MediaAccess::UploaderPreview) + } else { + Ok(MediaAccess::NoReference) + } + }.await; + // Dropping a streaming lookup queues rollback asynchronously. Await it + // while the permit is held so response completion cannot free capacity + // while the writer is still draining the query/transaction. + tx.rollback().await?; + result + } +} + +pub(super) fn media_reference_query( + community: CommunityId, + sha256: &str, + pubkey: &[u8], + needles: &[serde_json::Value], + probe: usize, + readable_only: bool, +) -> QueryBuilder { + let mut query = QueryBuilder::::new(""); + query.push("SELECT id,pubkey,created_at,kind,tags,content,sig,received_at,channel_id,"); + query.push(if readable_only { "true" } else { "false" }); + query.push(" AS readable FROM ("); + query.push("SELECT e.id,e.pubkey,e.created_at,e.kind,"); + query.push(if probe == 3 { + "jsonb_path_query_array(e.tags, 'strict $[*] ? (@[0] == \"link-preview\")') AS tags," + } else { + "e.tags," + }); + query.push( + "e.content,e.sig,e.received_at,e.channel_id, \ + (e.deleted_at IS NULL AND (e.channel_id IS NULL OR EXISTS ( \ + SELECT 1 FROM channels c WHERE c.community_id=e.community_id AND c.id=e.channel_id \ + AND c.deleted_at IS NULL AND (c.visibility='open' OR EXISTS ( \ + SELECT 1 FROM channel_members m WHERE m.community_id=c.community_id AND m.channel_id=c.id \ + AND m.removed_at IS NULL AND m.pubkey=" + ); + query + .push_bind(pubkey) + .push(format!( + ")))) AND (e.kind <> 40003 OR EXISTS (SELECT 1 FROM events original \ + WHERE original.community_id=e.community_id AND original.channel_id=e.channel_id \ + AND original.deleted_at IS NULL AND original.kind IN ({}) \ + AND ", + edit_governed_kinds_sql(), + )) + .push(edit_target("e")) + .push( + "=original.id AND NOT EXISTS (SELECT 1 FROM events newer \ + WHERE newer.community_id=e.community_id AND newer.channel_id=e.channel_id \ + AND newer.kind=40003 AND newer.deleted_at IS NULL \ + AND (newer.created_at,newer.id) > (e.created_at,e.id) AND ", + ) + .push(edit_target("newer")) + .push("=original.id))) "); + if probe == 3 { + // The renderer retains snapshots unless the original or any live + // edit suppresses them; later body edits never undo suppression. + query.push(format!("AND e.kind IN ({}) AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(e.tags) marker(value) WHERE marker.value='[\"link-preview\",\"none\"]'::jsonb) AND EXISTS (SELECT 1 FROM events edit WHERE edit.community_id=e.community_id AND edit.channel_id=e.channel_id AND edit.kind=40003 AND edit.deleted_at IS NULL AND ", edit_governed_kinds_sql())) + .push(edit_target("edit")).push("=e.id) AND NOT EXISTS (SELECT 1 FROM events suppressed WHERE suppressed.community_id=e.community_id AND suppressed.channel_id=e.channel_id AND suppressed.kind=40003 AND suppressed.deleted_at IS NULL AND ") + .push(edit_target("suppressed")).push("=e.id AND EXISTS (SELECT 1 FROM jsonb_array_elements(suppressed.tags) marker(value) WHERE marker.value='[\"link-preview\",\"none\"]'::jsonb))"); + } else { + query.push(format!("AND (e.kind NOT IN ({}) OR NOT EXISTS (SELECT 1 FROM events edit WHERE edit.community_id=e.community_id AND edit.channel_id=e.channel_id AND edit.kind=40003 AND edit.deleted_at IS NULL AND ", edit_governed_kinds_sql())) + .push(edit_target("edit")).push("=e.id))"); + } + query + .push(") AS readable FROM events e WHERE e.community_id=") + .push_bind(*community.as_uuid()) + .push(" AND e.deleted_at IS NULL"); + if probe == 2 { + // Never scan message bodies. Only profiles and personas have content references; + // current profiles are indexed by community/kind/deleted_at. + query + .push(" AND e.kind IN (0,30175) AND e.deleted_at IS NULL AND (strpos(e.content, ") + .push_bind(sha256) + .push(") > 0) AND CASE WHEN e.content IS JSON OBJECT THEN ((e.kind=0 AND ((jsonb_typeof(COALESCE(e.content::jsonb->'picture', e.content::jsonb->'image'))='string' AND strpos(COALESCE(e.content::jsonb->'picture',e.content::jsonb->'image') #>> '{}', ") + .push_bind(sha256) + .push(") > 0) OR (jsonb_typeof(e.content::jsonb->'banner')='string' AND strpos(e.content::jsonb->>'banner', ") + .push_bind(sha256) + .push(") > 0))) OR (e.kind=30175 AND jsonb_typeof(e.content::jsonb->'avatar_url')='string' AND strpos(e.content::jsonb->>'avatar_url', ") + .push_bind(sha256) + .push(") > 0)) ELSE false END"); + } else { + query.push(" AND ("); + let selected = if probe == 0 { + &needles[..1] + } else { + &needles[1..] + }; + for (i, tag) in ["imeta", "picture", "emoji", "link-preview"] + .into_iter() + .enumerate() + { + let matching: Vec = selected + .iter() + .filter(|needle| { + needle[0][0].as_str() == Some(tag) && (probe != 3 || tag == "link-preview") + }) + .cloned() + .collect(); + if i > 0 { + query.push(" OR "); + } + query.push("("); + if tag == "picture" { + query.push("e.kind=39000 AND "); + } + if tag == "emoji" { + query.push("e.kind IN (10030,30030,30180) AND "); + } + let preview_urls = (tag == "link-preview").then(|| { + matching + .iter() + .filter_map(|needle| needle[0][1].as_str().map(str::to_owned)) + .collect::>() + }); + query + .push("e.tags @> ANY(") + .push_bind(matching) + .push("::jsonb[])"); + if tag == "imeta" && probe == 0 { + // A bare x marker is not a reference. Require the matching URL + // in that same tag before charging this row to the work budget. + let urls: Vec = needles + .iter() + .filter_map(|needle| needle[0][1].as_str()) + .filter(|value| value.starts_with("url ")) + .map(|value| serde_json::json!([value])) + .collect(); + query.push(" AND EXISTS (SELECT 1 FROM jsonb_array_elements(e.tags) AS imeta(value) WHERE imeta.value @> ") + .push_bind(serde_json::json!(["imeta", format!("x {sha256}")])) + .push(" AND imeta.value @> ANY(").push_bind(urls).push("::jsonb[]))"); + } + if let Some(urls) = preview_urls { + // Containment ignores array positions. Recheck the actual + // snapshot fields before non-counting rows consume the budget. + query.push(" AND EXISTS (SELECT 1 FROM jsonb_array_elements(e.tags) AS preview(value) \ + WHERE preview.value->>0='link-preview' AND preview.value->>1='snapshot' \ + AND preview.value->>2='1' AND CASE WHEN jsonb_typeof(preview.value)='array' \ + THEN jsonb_array_length(preview.value)=11 ELSE false END \ + AND (preview.value->>7 = ANY(") + .push_bind(urls.clone()).push("::text[]) OR preview.value->>9 = ANY(") + .push_bind(urls).push("::text[])))"); + } + query.push(")"); + } + query.push(")"); + } + query.push(") candidate"); + if readable_only { + query.push(" WHERE readable"); + // Match the ordinary visibility classes before budgeting candidates. + // The relay predicate still performs its authoritative final check. + let gated: Vec = kind::P_GATED_KINDS + .iter() + .chain(kind::RESULT_GATED_KINDS) + .map(|kind| *kind as i32) + .collect(); + let author_only: Vec = kind::AUTHOR_ONLY_KINDS + .iter() + .map(|kind| *kind as i32) + .collect(); + let shared: Vec = kind::SHARED_GATED_KINDS + .iter() + .map(|kind| *kind as i32) + .collect(); + query + .push(" AND (kind <> ALL(") + .push_bind(gated) + .push(") OR tags @> ") + .push_bind(serde_json::json!([["p", hex::encode(pubkey)]])) + .push(")"); + query + .push(" AND (kind <> ALL(") + .push_bind(author_only) + .push(") OR pubkey=") + .push_bind(pubkey) + .push(")"); + query + .push(" AND (kind <> ") + .push_bind(kind::KIND_AGENT_ENGRAM as i32) + .push(" OR pubkey=") + .push_bind(pubkey) + .push(" OR tags @> ") + .push_bind(serde_json::json!([["p", hex::encode(pubkey)]])) + .push(")"); + query.push(" AND (kind <> ALL(").push_bind(shared).push(") OR pubkey=").push_bind(pubkey) + .push(" OR jsonb_path_query_array(tags, 'strict $[*] ? (@[0] == \"shared\")') = '[[\"shared\",\"true\"]]'::jsonb)"); + } + if probe == 2 { + query + .push(" ORDER BY (strpos(content, ") + .push_bind(sha256) + .push(") > 0) DESC, created_at ASC, id ASC"); + } + query.push(" LIMIT 1025"); + query +} + +pub(super) fn media_reference_needles( + sha256: &str, + ext: &str, + base: &str, +) -> Vec { + let mut needles = vec![serde_json::json!([["imeta", format!("x {sha256}")]])]; + let mut bases = vec!["/media".to_owned(), base.trim_end_matches('/').to_owned()]; + // Both schemes have historically appeared in tenant descriptor URLs. + if let Some(rest) = base.strip_prefix("https://") { + bases.push(format!("http://{rest}")); + } + if let Some(rest) = base.strip_prefix("http://") { + bases.push(format!("https://{rest}")); + } + for prefix in bases { + for suffix in [ + String::new(), + format!(".{ext}"), + ".thumb.jpg".into(), + ".thumb.webp".into(), + ] { + let url = format!("{prefix}/{sha256}{suffix}"); + for field in ["url", "image"] { + needles.push(serde_json::json!([["imeta", format!("{field} {url}")]])); + } + needles.push(serde_json::json!([["link-preview", url]])); + needles.push(serde_json::json!([["picture", url]])); + needles.push(serde_json::json!([["emoji", url]])); + } + } + needles +} diff --git a/crates/buzz-db/src/store/media_plan_fixture.sql b/crates/buzz-db/src/store/media_plan_fixture.sql new file mode 100644 index 00000000000..0282a9bb8ab --- /dev/null +++ b/crates/buzz-db/src/store/media_plan_fixture.sql @@ -0,0 +1,52 @@ +CREATE SCHEMA media_access_plan; +SET LOCAL search_path TO media_access_plan,public; +CREATE TABLE media_access_plan.channels(community_id uuid,id uuid,deleted_at timestamptz,visibility text); +CREATE TABLE media_access_plan.channel_members(community_id uuid,channel_id uuid,pubkey bytea,removed_at timestamptz); +CREATE INDEX plan_members ON media_access_plan.channel_members(community_id,channel_id,pubkey); +CREATE INDEX plan_channels ON media_access_plan.channels(community_id,id); +INSERT INTO media_access_plan.channels SELECT '00000000-0000-0000-0000-000000000001',md5(g::text)::uuid,NULL,CASE WHEN g%2=0 THEN 'open' ELSE 'private' END FROM generate_series(0,255) g; +INSERT INTO media_access_plan.channel_members SELECT community_id,id,decode(repeat('1',64),'hex'),NULL FROM media_access_plan.channels WHERE visibility='private'; +CREATE TABLE media_access_plan.events (LIKE public.events INCLUDING DEFAULTS INCLUDING GENERATED) PARTITION BY RANGE (created_at); +CREATE TABLE media_access_plan.events_2025_01 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-01-01') TO ('2025-02-01'); +CREATE TABLE media_access_plan.events_2025_02 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-02-01') TO ('2025-03-01'); +CREATE TABLE media_access_plan.events_2025_03 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-03-01') TO ('2025-04-01'); +CREATE TABLE media_access_plan.events_2025_04 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-04-01') TO ('2025-05-01'); +CREATE TABLE media_access_plan.events_2025_05 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-05-01') TO ('2025-06-01'); +CREATE TABLE media_access_plan.events_2025_06 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-06-01') TO ('2025-07-01'); +CREATE TABLE media_access_plan.events_2025_07 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-07-01') TO ('2025-08-01'); +CREATE TABLE media_access_plan.events_2025_08 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-08-01') TO ('2025-09-01'); +CREATE TABLE media_access_plan.events_2025_09 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-09-01') TO ('2025-10-01'); +CREATE TABLE media_access_plan.events_2025_10 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-10-01') TO ('2025-11-01'); +CREATE TABLE media_access_plan.events_2025_11 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-11-01') TO ('2025-12-01'); +CREATE TABLE media_access_plan.events_2025_12 PARTITION OF media_access_plan.events FOR VALUES FROM ('2025-12-01') TO ('2026-01-01'); +CREATE TABLE media_access_plan.events_2026_01 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-01-01') TO ('2026-02-01'); +CREATE TABLE media_access_plan.events_2026_02 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-02-01') TO ('2026-03-01'); +CREATE TABLE media_access_plan.events_2026_03 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-03-01') TO ('2026-04-01'); +CREATE TABLE media_access_plan.events_2026_04 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-04-01') TO ('2026-05-01'); +CREATE TABLE media_access_plan.events_2026_05 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-05-01') TO ('2026-06-01'); +CREATE TABLE media_access_plan.events_2026_06 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-06-01') TO ('2026-07-01'); +CREATE TABLE media_access_plan.events_2026_07 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-07-01') TO ('2026-08-01'); +CREATE TABLE media_access_plan.events_2026_08 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-08-01') TO ('2026-09-01'); +CREATE TABLE media_access_plan.events_2026_09 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-09-01') TO ('2026-10-01'); +CREATE TABLE media_access_plan.events_2026_10 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-10-01') TO ('2026-11-01'); +CREATE TABLE media_access_plan.events_2026_11 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-11-01') TO ('2026-12-01'); +CREATE TABLE media_access_plan.events_2026_12 PARTITION OF media_access_plan.events FOR VALUES FROM ('2026-12-01') TO ('2027-01-01'); +CREATE INDEX media_access_plan_tags ON media_access_plan.events USING gin(tags jsonb_path_ops); +CREATE INDEX media_access_plan_id ON media_access_plan.events(community_id,id,created_at DESC); +CREATE INDEX media_access_plan_channel ON media_access_plan.events(community_id,channel_id,created_at DESC,id); +CREATE INDEX media_access_plan_kind ON media_access_plan.events(community_id,kind,created_at DESC,id); +CREATE INDEX media_access_plan_addressable ON media_access_plan.events(community_id,kind,pubkey,channel_id,deleted_at); +INSERT INTO media_access_plan.events(community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id) +SELECT '00000000-0000-0000-0000-000000000001', decode(md5(g::text)||md5(g::text),'hex'), decode(repeat('1',64),'hex'), + '2025-01-01'::timestamptz + (g/50000) * interval '1 month', CASE WHEN g%100=2 THEN 0 WHEN g%4=3 THEN 40003 ELSE 9 END, + CASE WHEN g%50000=0 THEN jsonb_build_array(jsonb_build_array('imeta','x '||repeat('a',64),'url https://plan.example/media/'||repeat('a',64)||'.bin')) + WHEN g%4=3 THEN jsonb_build_array(jsonb_build_array('e',upper(md5((g-2)::text)||md5((g-2)::text))),jsonb_build_array('imeta','x '||CASE WHEN g%50000=3 THEN repeat('a',64) ELSE md5(g::text)||md5(g::text) END,'url https://plan.example/media/'||CASE WHEN g%50000=7 THEN repeat('a',64) ELSE md5(g::text)||md5(g::text) END||'.bin')) + WHEN g%50000=1 THEN jsonb_build_array(jsonb_build_array('imeta','url https://plan.example/media/'||repeat('a',64)||'.bin')) + ELSE jsonb_build_array(jsonb_build_array('imeta','x '||encode(decode(md5(g::text)||md5(g::text),'hex'),'hex'))) END, + CASE WHEN g=2 THEN '{"picture":"https://plan.example/media/'||repeat('a',64)||'.bin"}' ELSE 'ordinary content' END, + decode(repeat('2',128),'hex'), md5(((g/4)%256)::text)::uuid FROM generate_series(0,1199999) g; +-- Finish bulk-load GIN maintenance as autovacuum does in steady state. +-- Otherwise every URL alternative repeatedly scans the bulk insert pending list. +SELECT gin_clean_pending_list(inhrelid) FROM pg_inherits +WHERE inhparent='media_access_plan.media_access_plan_tags'::regclass; +ANALYZE media_access_plan.events; diff --git a/crates/buzz-db/src/store/media_postgres_tests.rs b/crates/buzz-db/src/store/media_postgres_tests.rs new file mode 100644 index 00000000000..5c57e3b4021 --- /dev/null +++ b/crates/buzz-db/src/store/media_postgres_tests.rs @@ -0,0 +1,760 @@ +use super::media::MediaAccess; +use crate::{ + channel::{ChannelType, ChannelVisibility}, + Db, +}; +use buzz_core::CommunityId; +use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp}; + +async fn allowed( + db: &Db, + community: CommunityId, + hash: &str, + base: &str, + keys: &Keys, +) -> MediaAccess { + db.media_access( + community, + hash, + "bin", + base, + keys.public_key().as_bytes(), + false, + |_, _| true, + ) + .await + .unwrap() +} +fn attachment( + keys: &Keys, + hash: &str, + channel: uuid::Uuid, + kind: u16, + target: Option<&Event>, + at: u64, +) -> Event { + let mut tags = vec![Tag::parse(["h", &channel.to_string()]).unwrap()]; + if !hash.is_empty() { + tags.push( + Tag::parse([ + "imeta", + &format!("url /media/{hash}.bin"), + &format!("x {hash}"), + ]) + .unwrap(), + ); + } + if let Some(target) = target { + tags.push(Tag::parse(["e", &target.id.to_hex().to_uppercase()]).unwrap()); + } + EventBuilder::new(Kind::Custom(kind), "media") + .tags(tags) + .custom_created_at(Timestamp::from(at)) + .sign_with_keys(keys) + .unwrap() +} +#[tokio::test] +#[ignore = "requires Postgres"] +async fn edits_deletion_legacy_profiles_and_publication_boundaries() { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool); + let host = format!("media-db-{}.example", uuid::Uuid::new_v4()); + let community = db.ensure_configured_community(&host).await.unwrap().id; + let base = format!("https://{host}/media"); + let owner = Keys::generate(); + let outsider = Keys::generate(); + db.ensure_user(community, owner.public_key().as_bytes()) + .await + .unwrap(); + let channel = db + .create_channel( + community, + "media", + ChannelType::Stream, + ChannelVisibility::Private, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id; + let a = "a".repeat(64); + let b = "b".repeat(64); + db.record_media_upload(community, &a, owner.public_key().as_bytes()) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &a, &base, &owner).await, + MediaAccess::UploaderPreview + ); + assert_eq!( + allowed(&db, community, &a, &base, &outsider).await, + MediaAccess::NoReference + ); + let now = Timestamp::now().as_secs(); + let original = attachment(&owner, &a, channel, 9, None, now); + db.record_media_publications(community, vec![a.clone(), b.clone()]) + .await + .unwrap(); + db.insert_event(community, &original, Some(channel)) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &a, &base, &owner).await, + MediaAccess::Allowed + ); + assert_eq!( + allowed(&db, community, &a, &base, &outsider).await, + MediaAccess::Restricted + ); + let decoy = attachment(&owner, "", channel, 9, None, now + 1); + db.insert_event(community, &decoy, Some(channel)) + .await + .unwrap(); + let edit = attachment(&owner, &b, channel, 40003, Some(&original), now + 1); + let edit = EventBuilder::new(Kind::Custom(40003), &edit.content) + .tags(edit.tags.iter().cloned()) + .tags([Tag::parse(["e", &decoy.id.to_hex()]).unwrap()]) + .custom_created_at(Timestamp::from(now + 1)) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &edit, Some(channel)) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &a, &base, &owner).await, + MediaAccess::Restricted, + "edit drops original attachment" + ); + assert_eq!( + allowed(&db, community, &b, &base, &owner).await, + MediaAccess::Allowed + ); + sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(original.id.as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &b, &base, &owner).await, + MediaAccess::Restricted, + "a second e tag cannot substitute for the deleted edit target" + ); + sqlx::query("UPDATE events SET deleted_at=NULL WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(original.id.as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + let edit2 = attachment(&owner, "", channel, 40003, Some(&original), now + 2); + db.insert_event(community, &edit2, Some(channel)) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &b, &base, &owner).await, + MediaAccess::Restricted, + "newest edit alone supplies references" + ); + sqlx::query("DELETE FROM events WHERE community_id=$1") + .bind(community.as_uuid()) + .execute(db.pool()) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &a, &base, &owner).await, + MediaAccess::Restricted, + "purge must not resurrect uploader preview" + ); + // Profiles predate recording and therefore need no grant backfill. + sqlx::query(r#"INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig) + SELECT $1,decode(md5(g::text)||md5(g::text),'hex'),decode(md5(g::text)||md5(g::text),'hex'),now(),0,'[]', + '{"name":"\u00e9"}',decode(repeat('a',128),'hex') FROM generate_series(1,1100) g"#) + .bind(community.as_uuid()).execute(db.pool()).await.unwrap(); + let profile = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":format!("{base}/{a}.bin")}).to_string(), + ) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &profile, None).await.unwrap(); + assert_eq!( + allowed(&db, community, &a, &base, &outsider).await, + MediaAccess::Allowed + ); + sqlx::query("DELETE FROM events WHERE community_id=$1 AND kind=0 AND pubkey<>$2") + .bind(community.as_uuid()) + .bind(owner.public_key().as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(profile.id.as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &a, &base, &outsider).await, + MediaAccess::Restricted, + "superseded avatar grants nothing" + ); + // Image-only profiles remain readable. Over-encoded animation hashes do not + // widen profile candidates beyond direct hash matches. + let encoded = format!("{base}/{a}.bin") + .replace(':', "%3A") + .replace('/', "%2F") + .replace('a', "%61"); + for (content, expected) in [ + ( + serde_json::json!({"image":format!("{base}/{a}.bin")}), + MediaAccess::Allowed, + ), + ( + serde_json::json!({"picture":format!("https://foreign/poster.png#buzz-anim={encoded}")}), + MediaAccess::Restricted, + ), + ] { + let current = EventBuilder::new(Kind::Metadata, content.to_string()) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, ¤t, None).await.unwrap(); + assert_eq!( + allowed(&db, community, &a, &base, &outsider).await, + expected + ); + sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(current.id.as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &a, &base, &owner).await, + MediaAccess::Restricted + ); + } + // A tenant never borrows another tenant's proof or publication. + let other = db + .ensure_configured_community(&format!("other-{}.example", uuid::Uuid::new_v4())) + .await + .unwrap() + .id; + assert_eq!( + allowed(&db, other, &a, &base, &owner).await, + MediaAccess::NoReference + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn popular_media_prefers_live_readable_references_and_bounds_work() { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool); + let host = format!("popular-media-{}.example", uuid::Uuid::new_v4()); + let community = db.ensure_configured_community(&host).await.unwrap().id; + let base = format!("https://{host}/media"); + let owner = Keys::generate(); + let reader = Keys::generate(); + db.ensure_user(community, owner.public_key().as_bytes()) + .await + .unwrap(); + let channel = db + .create_channel( + community, + "popular", + ChannelType::Stream, + ChannelVisibility::Private, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id; + let hash = "c".repeat(64); + let emoji_url = format!("{base}/{hash}.bin"); + // Non-counting reactions and superseded sets must never consume the budget. + sqlx::query("INSERT INTO events (community_id,id,pubkey,created_at,kind,tags,content,sig,deleted_at) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),$2,now(),CASE WHEN n%2=0 THEN 7 ELSE 30030 END,$3,'emoji',decode(repeat('00',64),'hex'),CASE WHEN n%2=1 THEN now() ELSE NULL END FROM generate_series(1,2052) n") + .bind(community.as_uuid()).bind(owner.public_key().as_bytes().as_slice()) + .bind(serde_json::json!([["emoji","popular",emoji_url]])) + .execute(db.pool()).await.unwrap(); + let live = EventBuilder::new(Kind::Custom(30030), "") + .tags([ + Tag::parse(["d", "current"]).unwrap(), + Tag::parse(["emoji", "popular", &emoji_url]).unwrap(), + ]) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &live, None).await.unwrap(); + assert_eq!( + allowed(&db, community, &hash, &base, &reader).await, + MediaAccess::Allowed + ); + let shared_hash = "d".repeat(64); + sqlx::query("INSERT INTO events (community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),$2,now(),9,$3,'private',decode(repeat('00',64),'hex'),$4 FROM generate_series(3000,4050) n") + .bind(community.as_uuid()).bind(owner.public_key().as_bytes().as_slice()) + .bind(serde_json::json!([["imeta",format!("x {shared_hash}"),format!("url /media/{shared_hash}.bin")]])) + .bind(channel).execute(db.pool()).await.unwrap(); + let public = attachment( + &owner, + &shared_hash, + channel, + 1, + None, + Timestamp::now().as_secs(), + ); + db.insert_event(community, &public, None).await.unwrap(); + assert_eq!( + allowed(&db, community, &shared_hash, &base, &reader).await, + MediaAccess::Allowed + ); + // Page-position preview URLs never count, even when they fill a whole + // older partition before the real image-position reference. + let open = db + .create_channel( + community, + "preview-decoys", + ChannelType::Stream, + ChannelVisibility::Open, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id; + let snapshot_hash = "f".repeat(64); + let snapshot_url = format!("{base}/{snapshot_hash}.png"); + sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),$2,'2025-01-01'::timestamptz,9,$3,$4,decode(repeat('00',64),'hex'),$5 FROM generate_series(6000,7024) n") + .bind(community.as_uuid()).bind(owner.public_key().as_bytes().as_slice()) + .bind(serde_json::json!([["h",open.to_string()],["link-preview","snapshot","1",snapshot_url,"title","site","description","","","",""]])) + .bind(&snapshot_url).bind(open).execute(db.pool()).await.unwrap(); + let snapshot = EventBuilder::new(Kind::Custom(9), "https://page.example/") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse([ + "link-preview", + "snapshot", + "1", + "https://page.example/", + "title", + "site", + "description", + &snapshot_url, + &snapshot_hash, + "", + "", + ]) + .unwrap(), + ]) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &snapshot, Some(channel)) + .await + .unwrap(); + assert_eq!( + db.media_access( + community, + &snapshot_hash, + "png", + &base, + owner.public_key().as_bytes(), + false, + |_, _| true + ) + .await + .expect("page-position decoys must not exhaust the image-reference budget"), + MediaAccess::Allowed + ); + // More than a full budget of unrelated, ordinary animated profiles must + // not turn a private denial or an absent hash into authorization-unavailable. + let poster = "2".repeat(64); + let animation = format!("{base}/{}.png", "3".repeat(64)) + .replace(':', "%3A") + .replace('/', "%2F"); + // Python-style ensure_ascii JSON leaves ordinary non-ASCII names escaped, + // while the unrelated URL hash remains plain ASCII. Keep literal escapes in + // the signed/stored content, rather than serializing a decoded Rust string. + let profile_content = format!( + r#"{{"name":"Jos\u00e9 \ud83d\udc1d","picture":"{base}/{poster}.png#buzz-anim={animation}"}}"# + ); + assert!(profile_content.contains(r"\u00e9")); + assert_eq!( + serde_json::from_str::(&profile_content).unwrap()["name"], + "José 🐝" + ); + let profiles: Vec<_> = (0..1100) + .map(|_| { + let event = EventBuilder::new(Kind::Metadata, &profile_content) + .sign_with_keys(&Keys::generate()) + .unwrap(); + serde_json::to_value(event).unwrap() + }) + .collect(); + sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig) SELECT $1,decode(p->>'id','hex'),decode(p->>'pubkey','hex'),to_timestamp((p->>'created_at')::bigint),0,p->'tags',p->>'content',decode(p->>'sig','hex') FROM jsonb_array_elements($2) p") + .bind(community.as_uuid()).bind(serde_json::Value::Array(profiles)).execute(db.pool()).await.unwrap(); + let private_denial = db + .media_access( + community, + &snapshot_hash, + "png", + &base, + reader.public_key().as_bytes(), + false, + |_, _| true, + ) + .await; + let absent = db + .media_access( + community, + &"1".repeat(64), + "bin", + &base, + reader.public_key().as_bytes(), + false, + |_, _| true, + ) + .await; + assert!( + matches!(private_denial, Ok(MediaAccess::Restricted)) + && matches!(absent, Ok(MediaAccess::NoReference)), + "escaped-name decoys: private={private_denial:?}, absent={absent:?}" + ); + // A direct ASCII hash remains readable among escaped-name decoys. A hash + // whose own ASCII characters are Unicode-escaped needs republication. + let canonical_hash = "4".repeat(64); + for (profile_hash, expected) in [ + (canonical_hash.clone(), MediaAccess::Allowed), + (r"\u0034".repeat(64), MediaAccess::Restricted), + ] { + let profile = EventBuilder::new( + Kind::Metadata, + format!(r#"{{"name":"Jos\u00e9","picture":"{base}/{profile_hash}.bin"}}"#), + ) + .sign_with_keys(&Keys::generate()) + .unwrap(); + db.insert_event(community, &profile, None).await.unwrap(); + db.record_media_publications(community, vec![canonical_hash.clone()]) + .await + .unwrap(); + assert_eq!( + allowed(&db, community, &canonical_hash, &base, &reader).await, + expected + ); + sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(profile.id.as_bytes().as_slice()) + .execute(db.pool()) + .await + .unwrap(); + } + // An oversized readable row must fail closed without buffering all candidates. + let huge_hash = "e".repeat(64); + let huge = EventBuilder::new(Kind::Custom(1), "z".repeat(16 * 1024 * 1024 + 1)) + .tags([Tag::parse([ + "imeta", + &format!("x {huge_hash}"), + &format!("url /media/{huge_hash}.bin"), + ]) + .unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &huge, None).await.unwrap(); + let error = db + .media_access( + community, + &huge_hash, + "bin", + &base, + reader.public_key().as_bytes(), + false, + |_, _| true, + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("work budget"), "{error}"); + // Capacity saturation has a bounded wait before attempting to acquire a writer. + let permits = db.media_authorization_slots.available_permits(); + let _held = db + .media_authorization_slots + .acquire_many(permits as u32) + .await + .unwrap(); + let error = db + .media_access( + community, + &hash, + "bin", + &base, + reader.public_key().as_bytes(), + false, + |_, _| true, + ) + .await + .unwrap_err(); + assert!( + matches!(error, crate::DbError::MediaAuthorizationCapacity), + "{error}" + ); + // Poll until the request is queued, then release capacity without a delay. + let reader_pubkey = reader.public_key(); + let waiting = db.media_access( + community, + &hash, + "bin", + &base, + reader_pubkey.as_bytes(), + false, + |_, _| true, + ); + tokio::pin!(waiting); + assert!(futures_util::poll!(waiting.as_mut()).is_pending()); + drop(_held); + assert_eq!(waiting.await.unwrap(), MediaAccess::Allowed); + + assert_eq!( + sqlx::query_scalar::<_, i32>("SELECT 1") + .fetch_one(db.pool()) + .await + .unwrap(), + 1 + ); +} + +/// Explain the actual complete statement, including channel and edit joins. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn media_reference_full_query_plans() { + use sqlx::{Execute, Row}; + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let mut tx = pool.begin().await.unwrap(); + let fixture = include_str!("media_plan_fixture.sql"); + sqlx::raw_sql(fixture).execute(&mut *tx).await.unwrap(); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE INDEX idx_events_media_edit_target ON media_access_plan.events (community_id,channel_id, ({}),created_at DESC,id DESC) WHERE kind=40003 AND deleted_at IS NULL", super::media::MEDIA_EDIT_TARGET_SQL))) + .execute(&mut *tx).await.unwrap(); + sqlx::query("SET LOCAL jit = on") + .execute(&mut *tx) + .await + .unwrap(); + let jit_available: bool = sqlx::query_scalar("SELECT pg_jit_available()") + .fetch_one(&mut *tx) + .await + .unwrap(); + sqlx::raw_sql(super::media::MEDIA_LOOKUP_SETTINGS_SQL) + .execute(&mut *tx) + .await + .unwrap(); + let jit: String = sqlx::query_scalar("SHOW jit") + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!( + jit, "off", + "the production transaction must not compile partitioned authorization probes" + ); + println!( + "PostgreSQL: {}; JIT available: {}; authorization jit={jit}", + sqlx::query_scalar::<_, String>("SELECT version()") + .fetch_one(&mut *tx) + .await + .unwrap(), + jit_available + ); + let community = CommunityId::from_uuid(uuid::Uuid::from_u128(1)); + let hash = "a".repeat(64); + let reader = [0x11; 32]; + let needles = super::media::media_reference_needles(&hash, "bin", "https://plan.example/media"); + for readable_only in [true, false] { + for probe in 0..4 { + let mut builder = super::media::media_reference_query( + community, + &hash, + &reader, + &needles, + probe, + readable_only, + ); + let mut statement = builder.build(); + let args = statement.take_arguments().unwrap().unwrap(); + let sql = format!( + "EXPLAIN (ANALYZE, BUFFERS, COSTS ON) {}", + statement.sql().as_str() + ); + // Only the production QueryBuilder SQL is prefixed; all values stay bound. + let rows = sqlx::query_with(sqlx::AssertSqlSafe(sql), args) + .fetch_all(&mut *tx) + .await + .unwrap(); + println!("FULL_QUERY_PROBE_{probe}_READABLE_{readable_only}: 24 partitions, 1200000 rows including 300000 live edits across 256 channels"); + let plan = rows + .iter() + .map(|row| row.get::(0)) + .collect::>() + .join("\n"); + if readable_only && probe < 2 { + let names: Vec = sqlx::query_scalar("SELECT c.relname::text FROM pg_inherits h JOIN pg_class c ON c.oid=h.inhrelid WHERE h.inhparent='media_access_plan.idx_events_media_edit_target'::regclass") + .fetch_all(&mut *tx).await.unwrap(); + assert!( + names.iter().any(|name| plan.contains(name)), + "edit-target index absent: {plan}" + ); + } + let execution_ms: f64 = plan + .lines() + .find_map(|line| line.strip_prefix("Execution Time: ")) + .and_then(|value| value.strip_suffix(" ms")) + .unwrap() + .parse() + .unwrap(); + assert!( + execution_ms < 1000.0, + "authorization probe must retain headroom under its 2s timeout: {plan}" + ); + for row in rows { + println!("{}", row.get::(0)); + } + } + } + // The isolation wrapper owns this database. Commit the fixture so a fresh + // production Db handle can read it, with server-side JIT enabled by default. + tx.commit().await.unwrap(); + let production_pool = sqlx::postgres::PgPoolOptions::new().max_connections(1) + .after_connect(|connection,_| Box::pin(async move { + sqlx::raw_sql("SET search_path=media_access_plan,public; SET jit=on; SET statement_timeout='2s'") + .execute(connection).await?; + Ok(()) + })) + .connect(&crate::test_support::database_url()).await.unwrap(); + let channel: uuid::Uuid = sqlx::query_scalar( + "SELECT id FROM media_access_plan.channels WHERE visibility='open' LIMIT 1", + ) + .fetch_one(&production_pool) + .await + .unwrap(); + let url_hash = "b".repeat(64); + let event = EventBuilder::new(Kind::Custom(9), "URL-only legacy attachment") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse([ + "imeta", + &format!("url https://plan.example/media/{url_hash}.bin"), + ]) + .unwrap(), + ]) + .sign_with_keys(&Keys::generate()) + .unwrap(); + sqlx::query("INSERT INTO media_access_plan.events(community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id) VALUES($1,$2,$3,$4,9,$5,$6,$7,$8)") + .bind(community.as_uuid()).bind(event.id.as_bytes().as_slice()).bind(event.pubkey.to_bytes().as_slice()) + .bind(chrono::DateTime::from_timestamp(event.created_at.as_secs() as i64,0).unwrap()) + .bind(serde_json::to_value(&event.tags).unwrap()).bind(&event.content) + .bind(event.sig.serialize().as_slice()).bind(channel).execute(&production_pool).await.unwrap(); + let db = Db::from_pool(production_pool.clone()); + let production_started = std::time::Instant::now(); + let access = db + .media_access( + community, + &url_hash, + "bin", + "https://plan.example/media", + &reader, + false, + |_, _| true, + ) + .await + .expect("production URL-only lookup must apply the bounded non-JIT policy"); + println!( + "PRODUCTION_URL_ONLY_LOOKUP_MS: {}", + production_started.elapsed().as_secs_f64() * 1000.0 + ); + assert_eq!(access, MediaAccess::Allowed); + assert_eq!( + sqlx::query_scalar::<_, String>("SHOW jit") + .fetch_one(&production_pool) + .await + .unwrap(), + "on", + "lookup rollback must restore the pooled connection's JIT setting" + ); + production_pool.close().await; +} + +/// Compare the production Rust target rule to SQL, the catalog and new partitions. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn media_edit_target_sql_parity_and_partition_inheritance() { + use serde_json::json; + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let mut tx = pool.begin().await.unwrap(); + let expression = super::media::MEDIA_EDIT_TARGET_SQL; + let a = "aB".repeat(32); + let b = "C".repeat(64); + let cases = [ + json!([["e", a.to_uppercase()]]), + json!([["e", a]]), + json!([["e", "bad"], ["e", a], ["e", b]]), + json!([["e", a], ["e", b]]), + json!([["e"], ["e", 23], ["e", a]]), + json!([["e"]]), + json!([["e", 23]]), + json!([null, ["e", a]]), + json!(null), + json!([]), + ]; + let absent: Option> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT {expression} FROM (SELECT NULL::jsonb AS tags) input" + ))) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert!(absent.is_none()); + let keys = Keys::generate(); + for tags in cases { + // Non-string historical tags cannot be signed by the Rust SDK; omit + // malformed tags when constructing its reference input. + let valid_tags: Vec = tags + .as_array() + .into_iter() + .flatten() + .filter_map(|tag| { + let values: Option> = + tag.as_array()?.iter().map(|v| v.as_str()).collect(); + Tag::parse(values?).ok() + }) + .collect(); + let event = EventBuilder::new(Kind::Custom(40003), "") + .tags(valid_tags) + .sign_with_keys(&keys) + .unwrap(); + let expected = buzz_core::media::first_edit_target(&event); + let actual: Option> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!( + "SELECT {expression} FROM (SELECT $1::jsonb AS tags) input" + ))) + .bind(&tags) + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(actual, expected, "tags={tags}"); + } + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE TEMP TABLE media_expected_target(tags jsonb); CREATE INDEX media_expected_target_idx ON media_expected_target (({expression}));"))) + .execute(&mut *tx).await.unwrap(); + let expressions: Vec = sqlx::query_scalar("SELECT pg_get_expr(indexprs,indrelid) FROM pg_index WHERE indexrelid IN ('media_expected_target_idx'::regclass,'public.idx_events_media_edit_target'::regclass) ORDER BY indexrelid") + .fetch_all(&mut *tx).await.unwrap(); + assert_eq!(expressions.len(), 2); + assert_eq!(expressions[0], expressions[1]); + sqlx::raw_sql("CREATE TABLE media_partition_parent (LIKE public.events INCLUDING ALL) PARTITION BY RANGE (created_at); CREATE TABLE media_future_partition PARTITION OF media_partition_parent FOR VALUES FROM ('2099-01-01') TO ('2099-02-01');") + .execute(&mut *tx).await.unwrap(); + let inherited: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_index i JOIN pg_inherits h ON h.inhrelid=i.indexrelid JOIN pg_index parent ON parent.indexrelid=h.inhparent WHERE i.indrelid='media_future_partition'::regclass AND parent.indexprs IS NOT NULL AND i.indisvalid AND pg_get_expr(i.indexprs,i.indrelid)=(SELECT pg_get_expr(indexprs,indrelid) FROM pg_index WHERE indexrelid='public.idx_events_media_edit_target'::regclass))") + .fetch_one(&mut *tx).await.unwrap(); + assert!(inherited); + tx.rollback().await.unwrap(); +} diff --git a/crates/buzz-db/src/store/membership_snapshot.rs b/crates/buzz-db/src/store/membership_snapshot.rs new file mode 100644 index 00000000000..d0fededffc7 --- /dev/null +++ b/crates/buzz-db/src/store/membership_snapshot.rs @@ -0,0 +1,182 @@ +//! Bounded, primary-only projections of the viewer's canonical memberships. + +use buzz_core::CommunityId; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use sqlx::Row; +use uuid::Uuid; + +use crate::{observability, Db, DbError, Result}; + +/// Maximum memberships in a complete NIP-CL version-1 response. +pub const MAX_CHANNELS: usize = 4096; +/// Maximum encoded response bytes, including the signed event and envelope. +pub const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024; +/// Types understood by version 1, in canonical wire order. +pub const CHANNEL_TYPES: &[&str] = &["dm", "forum", "stream", "system", "workflow"]; + +/// Exactly the fields needed to establish the viewer's membership. +/// Field declaration order is part of the snapshot content-identity encoding. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ViewerMembership { + /// Canonical channel UUID. + pub id: Uuid, + /// This viewer's role; never a list of other members. + pub role: String, + /// Channel type, within the explicitly requested scope. + pub channel_type: String, + /// Current channel visibility, independently of membership. + pub visibility: String, + /// Archived channels remain memberships, with read-only behavior. + pub archived: bool, +} + +/// A complete projection at one primary statement's MVCC cut. +#[derive(Debug)] +pub struct MembershipSnapshot { + /// Content identity, never an ordered revision or a live-delivery cursor. + pub snapshot_id: String, + /// Every active membership in the requested types, sorted by channel UUID. + pub channels: Vec, +} + +// No events, rosters, profiles, other-member aggregates or replica routing. +// Probe one additional row; never silently certify a capped set as complete. +// Keep the lookup dependent on the viewer row to avoid a community-wide scan. +// Probe two rows so an accidental loss of the tenant/key predicate cannot hide +// a duplicate behind LIMIT 1: strict ID validation below then fails closed. +// The outer probe counts AFTER type/deletion filters. +const SNAPSHOT_SQL: &str = "SELECT cm.channel_id AS id, cm.role::text AS role, + c.channel_type, c.visibility, c.archived + FROM channel_members cm + CROSS JOIN LATERAL ( + SELECT c.channel_type::text AS channel_type, c.visibility::text AS visibility, + c.archived_at IS NOT NULL AS archived + FROM channels c + WHERE c.community_id = cm.community_id AND c.id = cm.channel_id + AND (NOT $5 OR (c.visibility = 'open' AND NOT c.unlisted)) + AND c.deleted_at IS NULL AND c.channel_type = ANY($3::text[]::channel_type[]) + LIMIT 2 + ) c + WHERE cm.community_id = $1 AND cm.pubkey = $2 AND cm.removed_at IS NULL + ORDER BY cm.channel_id LIMIT $4"; + +/// Validate the explicit type scope without silently dropping unknown types. +pub fn valid_types(types: &[String]) -> bool { + !types.is_empty() + && types.len() <= CHANNEL_TYPES.len() + && types.iter().all(|t| CHANNEL_TYPES.contains(&t.as_str())) + && types.windows(2).all(|pair| pair[0] < pair[1]) +} + +/// Public mode accepts only listed channel types, never DMs or system channels. +pub fn valid_public_types(types: &[String]) -> bool { + valid_types(types) + && types + .iter() + .all(|t| ["forum", "stream", "workflow"].contains(&t.as_str())) +} + +impl Db { + /// Project only the viewer's active memberships from one primary MVCC cut. + /// + /// Archive/visibility/role/deletion changes share the same statement cut. + /// Hidden DMs are deliberately included; NIP-DV owns hiding separately. + /// No full-roster or per-user projection cache is consulted or maintained. + pub async fn membership_snapshot( + &self, + community: CommunityId, + viewer: &nostr::PublicKey, + types: &[String], + ) -> Result { + self.project_memberships(community, viewer, types, false) + .await + } + + /// Project a subject's listed open memberships at one primary statement cut. + pub async fn public_memberships( + &self, + community: CommunityId, + subject: &nostr::PublicKey, + types: &[String], + ) -> Result { + self.project_memberships(community, subject, types, true) + .await + } + + async fn project_memberships( + &self, + community: CommunityId, + viewer: &nostr::PublicKey, + types: &[String], + public: bool, + ) -> Result { + if !valid_types(types) || (public && !valid_public_types(types)) { + return Err(DbError::InvalidData("invalid membership type scope".into())); + } + let started = std::time::Instant::now(); + let mut conn = observability::acquire_writer( + &self.pool, + observability::WriterOperation::Authorization, + ) + .await?; + let rows = sqlx::query(SNAPSHOT_SQL) + .bind(community.as_uuid()) + .bind(viewer.to_bytes().to_vec()) + .bind(types) + .bind((MAX_CHANNELS + 1) as i64) + .bind(public) + .fetch_all(&mut *conn) + .await?; + metrics::histogram!("buzz_membership_snapshot_query_seconds", "mode" => if public {"membership_public"} else {"membership_snapshot"}) + .record(started.elapsed().as_secs_f64()); + if rows.len() > MAX_CHANNELS { + return Err(DbError::MembershipSnapshotTooLarge); + } + let channels = rows + .into_iter() + .map(|row| { + let entry = ViewerMembership { + id: row.try_get("id")?, + role: row.try_get("role")?, + channel_type: row.try_get("channel_type")?, + visibility: row.try_get("visibility")?, + archived: row.try_get("archived")?, + }; + if !["owner", "admin", "member", "bot", "guest"].contains(&entry.role.as_str()) + || !types.contains(&entry.channel_type) + || !["open", "private"].contains(&entry.visibility.as_str()) + || (public && entry.visibility != "open") + { + return Err(DbError::InvalidData( + "invalid membership projection row".into(), + )); + } + Ok(entry) + }) + .collect::>>()?; + if channels.windows(2).any(|pair| pair[0].id >= pair[1].id) { + return Err(DbError::InvalidData( + "membership projection IDs are not unique and ordered".into(), + )); + } + let identity = serde_json::to_vec(&( + if public { + "nip-cl-public-membership-v1" + } else { + "nip-cl-membership-state-v1" + }, + community.as_uuid(), + viewer.to_hex(), + types, + &channels, + ))?; + Ok(MembershipSnapshot { + snapshot_id: hex::encode(Sha256::digest(identity)), + channels, + }) + } +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/membership_snapshot/postgres_tests.rs b/crates/buzz-db/src/store/membership_snapshot/postgres_tests.rs new file mode 100644 index 00000000000..eb7dace21af --- /dev/null +++ b/crates/buzz-db/src/store/membership_snapshot/postgres_tests.rs @@ -0,0 +1,520 @@ +use super::*; +use nostr::Keys; +use sqlx::{postgres::PgPoolOptions, PgPool}; +use std::time::Duration; + +async fn fixture(count: usize) -> (Db, PgPool, CommunityId, Keys, Vec) { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool.clone()); + let community = db + .ensure_configured_community(&format!("membership-{}.local", Uuid::new_v4().simple())) + .await + .unwrap() + .id; + let viewer = Keys::generate(); + let ids: Vec = (0..count).map(|_| Uuid::new_v4()).collect(); + let mut tx = crate::begin_community_write_transaction( + &pool, + community, + observability::WriterOperation::EventWrite, + ) + .await + .unwrap(); + sqlx::query( + "INSERT INTO channels (community_id,id,name,created_by) + SELECT $1,id,id::text,$3 FROM unnest($2::uuid[]) id", + ) + .bind(community.as_uuid()) + .bind(&ids) + .bind(viewer.public_key().to_bytes().to_vec()) + .execute(tx.conn()) + .await + .unwrap(); + sqlx::query( + "INSERT INTO channel_members (community_id,channel_id,pubkey,role) + SELECT $1,id,$3,'owner' FROM unnest($2::uuid[]) id", + ) + .bind(community.as_uuid()) + .bind(&ids) + .bind(viewer.public_key().to_bytes().to_vec()) + .execute(tx.conn()) + .await + .unwrap(); + tx.commit().await.unwrap(); + (db, pool, community, viewer, ids) +} + +fn all_types() -> Vec { + CHANNEL_TYPES.iter().map(|s| s.to_string()).collect() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn membership_snapshot_scope_roles_types_archive_hidden_and_overflow() { + let (db, pool, community, viewer, ids) = fixture(8).await; + for (i, (kind, role)) in CHANNEL_TYPES + .iter() + .zip(["owner", "admin", "member", "bot", "guest"]) + .enumerate() + { + sqlx::query( + "UPDATE channels SET channel_type=$3::channel_type, visibility='private', + archived_at=CASE WHEN $4 THEN now() ELSE NULL END WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(ids[i]) + .bind(kind) + .bind(i == 1) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "UPDATE channel_members SET role=$3::member_role, hidden_at=now() + WHERE community_id=$1 AND channel_id=$2", + ) + .bind(community.as_uuid()) + .bind(ids[i]) + .bind(role) + .execute(&pool) + .await + .unwrap(); + } + sqlx::query("UPDATE channels SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(ids[5]) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "UPDATE channel_members SET removed_at=now() WHERE community_id=$1 AND channel_id=$2", + ) + .bind(community.as_uuid()) + .bind(ids[6]) + .execute(&pool) + .await + .unwrap(); + // Open but not a member is excluded as well. + sqlx::query("DELETE FROM channel_members WHERE community_id=$1 AND channel_id=$2") + .bind(community.as_uuid()) + .bind(ids[7]) + .execute(&pool) + .await + .unwrap(); + let dead = PgPoolOptions::new() + .connect_lazy("postgres://unused@127.0.0.1:1/absent") + .unwrap(); + dead.close().await; + let routed = Db::from_pools(pool.clone(), dead); + let cut = routed + .membership_snapshot(community, &viewer.public_key(), &all_types()) + .await + .unwrap(); + assert_eq!(cut.channels.len(), 5); + assert!(cut.channels.windows(2).all(|p| p[0].id < p[1].id)); + for (i, role) in ["owner", "admin", "member", "bot", "guest"] + .iter() + .enumerate() + { + let row = cut.channels.iter().find(|c| c.id == ids[i]).unwrap(); + assert_eq!(&row.role, role); + assert_eq!(row.channel_type, CHANNEL_TYPES[i]); + assert_eq!(row.visibility, "private"); + assert_eq!(row.archived, i == 1); + } + let systems = db + .membership_snapshot(community, &viewer.public_key(), &["system".into()]) + .await + .unwrap(); + assert_eq!(systems.channels.len(), 1); + assert_ne!(cut.snapshot_id, systems.snapshot_id); + let other = db + .membership_snapshot(community, &Keys::generate().public_key(), &all_types()) + .await + .unwrap(); + assert!(other.channels.is_empty()); + let other_tenant = db + .ensure_configured_community(&format!("other-{}.local", Uuid::new_v4().simple())) + .await + .unwrap() + .id; + assert!(db + .membership_snapshot(other_tenant, &viewer.public_key(), &all_types()) + .await + .unwrap() + .channels + .is_empty()); + // Same UUID in another tenant is legal. A lost tenant predicate must + // produce a duplicate that fails closed, independently of physical order. + let shared_id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO channels (community_id,id,name,created_by,channel_type,visibility,archived_at) + VALUES ($1,$2,'collision-other',$3,'system','private',now())", + ) + .bind(other_tenant.as_uuid()) + .bind(shared_id) + .bind(Keys::generate().public_key().to_bytes().to_vec()) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO channels (community_id,id,name,created_by,channel_type,visibility) + VALUES ($1,$2,'collision-own',$3,'stream','open')", + ) + .bind(community.as_uuid()) + .bind(shared_id) + .bind(viewer.public_key().to_bytes().to_vec()) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO channel_members (community_id,channel_id,pubkey,role) VALUES ($1,$2,$3,'guest')") + .bind(community.as_uuid()).bind(shared_id).bind(viewer.public_key().to_bytes().to_vec()) + .execute(&pool).await.unwrap(); + let collision_cut = db + .membership_snapshot(community, &viewer.public_key(), &all_types()) + .await + .unwrap(); + let entries: Vec<_> = collision_cut + .channels + .iter() + .filter(|c| c.id == shared_id) + .collect(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].channel_type, "stream"); + assert_eq!(entries[0].visibility, "open"); + assert_eq!(entries[0].role, "guest"); + assert!(!entries[0].archived); + assert!(db + .membership_snapshot(community, &viewer.public_key(), &["unknown".into()]) + .await + .is_err()); + let (db, _, community, viewer, _) = fixture(MAX_CHANNELS + 1).await; + assert!(matches!( + db.membership_snapshot(community, &viewer.public_key(), &all_types()) + .await, + Err(DbError::MembershipSnapshotTooLarge) + )); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn membership_snapshot_468_channels_size_independent_of_other_members_and_index_plan() { + let (db, pool, community, viewer, ids) = fixture(468).await; + let before = db + .membership_snapshot(community, &viewer.public_key(), &all_types()) + .await + .unwrap(); + let bytes = serde_json::to_vec(&before.channels).unwrap().len(); + for (i, id) in ids.iter().enumerate() { + let members = [5898, 5847, 5307, 3314, 2007].get(i).copied().unwrap_or(5); + sqlx::query( + "INSERT INTO channel_members (community_id,channel_id,pubkey) + SELECT $1,$2,decode(md5(n::text)||md5(n::text),'hex') FROM generate_series(1,$3) n", + ) + .bind(community.as_uuid()) + .bind(id) + .bind(members - 1) + .execute(&pool) + .await + .unwrap(); + } + // The community also has DMs and open channels the viewer cannot discover. + // This prevents a tiny all-member community from rewarding a directory scan. + let other = Keys::generate().public_key().to_bytes().to_vec(); + sqlx::query( + "INSERT INTO channels (community_id,id,name,created_by,channel_type,visibility) + SELECT $1, md5('nonmember-'||n::text)::uuid, 'nonmember-'||n::text, $2, + CASE WHEN n%2=0 THEN 'dm' ELSE 'stream' END::channel_type, + CASE WHEN n%2=0 THEN 'private' ELSE 'open' END::channel_visibility + FROM generate_series(1,20000) n", + ) + .bind(community.as_uuid()) + .bind(&other) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO channel_members (community_id,channel_id,pubkey) + SELECT $1,md5('nonmember-'||n::text)::uuid,$2 FROM generate_series(1,20000) n", + ) + .bind(community.as_uuid()) + .bind(other) + .execute(&pool) + .await + .unwrap(); + sqlx::raw_sql("ANALYZE channel_members; ANALYZE channels") + .execute(&pool) + .await + .unwrap(); + let start = std::time::Instant::now(); + let after = db + .membership_snapshot(community, &viewer.public_key(), &all_types()) + .await + .unwrap(); + assert_eq!(before.channels, after.channels); + assert_eq!(before.snapshot_id, after.snapshot_id); + assert_eq!(bytes, serde_json::to_vec(&after.channels).unwrap().len()); + let row = sqlx::query(sqlx::AssertSqlSafe(format!( + "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {SNAPSHOT_SQL}" + ))) + .bind(community.as_uuid()) + .bind(viewer.public_key().to_bytes().to_vec()) + .bind(all_types()) + .bind((MAX_CHANNELS + 1) as i64) + .bind(false) + .fetch_one(&pool) + .await + .unwrap(); + let plan: serde_json::Value = row.get(0); + let mut nodes = vec![&plan[0]["Plan"]]; + let mut scanned_members = false; + let mut viewer_index = false; + let mut channel_key_lookup = false; + while let Some(node) = nodes.pop() { + if let Some(children) = node["Plans"].as_array() { + nodes.extend(children); + } + if node["Index Name"] == "idx_channel_members_pubkey" { + viewer_index = true; + } + if node["Relation Name"] == "channel_members" { + assert_eq!(node["Actual Rows"], 468, "{plan}"); + assert_eq!(node["Actual Loops"], 1, "{plan}"); + scanned_members = true; + } + if node["Relation Name"] == "channels" { + assert!( + matches!( + node["Index Name"].as_str(), + Some("channels_pkey" | "idx_channels_id_live") + ), + "{plan}" + ); + assert_eq!(node["Actual Loops"], 468, "{plan}"); + let rows = node["Actual Rows"].as_u64().unwrap(); + let filtered = node["Rows Removed by Filter"].as_u64().unwrap_or(0); + assert!(rows <= 1 && filtered <= 1, "{plan}"); + assert!( + rows * node["Actual Loops"].as_u64().unwrap() <= 468, + "{plan}" + ); + channel_key_lookup = true; + } + } + assert!( + scanned_members && viewer_index && channel_key_lookup, + "{plan}" + ); + println!( + "468-channel projection with 20000 unrelated channels: bytes={bytes}, query_ms={}\n{}", + start.elapsed().as_secs_f64() * 1000.0, + serde_json::to_string_pretty(&plan).unwrap() + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cluster_global_membership_snapshot_role_and_removal_commit_during_statement_keep_one_cut() +{ + let (db, pool, community, viewer, ids) = fixture(4).await; + let before = db + .membership_snapshot(community, &viewer.public_key(), &all_types()) + .await + .unwrap(); + // A private view pauses the REAL production query without changing its SQL. + // The gate runs under its statement snapshot while public canonical rows change. + let schema = format!("membership_gate_{}", Uuid::new_v4().simple()); + let lock_key = i64::from_be_bytes(Uuid::new_v4().as_bytes()[..8].try_into().unwrap()); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}; + CREATE FUNCTION {schema}.gate() RETURNS boolean LANGUAGE plpgsql VOLATILE AS + $$ BEGIN PERFORM pg_advisory_xact_lock({lock_key}); RETURN true; END $$; + CREATE VIEW {schema}.channel_members AS SELECT cm.* FROM public.channel_members cm WHERE {schema}.gate()"))) + .execute(&pool).await.unwrap(); + let application = schema.clone(); + let path = schema.clone(); + let isolated = PgPoolOptions::new() + .max_connections(1) + .after_connect(move |c, _| { + let setup = format!( + "SET search_path TO {path},pg_catalog,public; SET application_name='{path}'" + ); + Box::pin(async move { + sqlx::raw_sql(sqlx::AssertSqlSafe(setup)).execute(c).await?; + Ok(()) + }) + }) + .connect(&crate::test_support::database_url()) + .await + .unwrap(); + let snapshot_db = Db::from_pool(isolated); + let mut blocker = pool.acquire().await.unwrap(); + sqlx::query("SELECT pg_advisory_lock($1)") + .bind(lock_key) + .execute(&mut *blocker) + .await + .unwrap(); + let reader = snapshot_db.clone(); + let pubkey = viewer.public_key(); + let pending = tokio::spawn(async move { + reader + .membership_snapshot(community, &pubkey, &all_types()) + .await + }); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_stat_activity + WHERE application_name=$1 AND wait_event='advisory')", + ) + .bind(&application) + .fetch_one(&pool) + .await + .unwrap(); + if waiting { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("production projection must reach statement gate"); + let mut tx = pool.begin().await.unwrap(); + sqlx::query("UPDATE channel_members SET role='guest' WHERE community_id=$1 AND channel_id=$2") + .bind(community.as_uuid()) + .bind(ids[0]) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query( + "UPDATE channel_members SET removed_at=now() WHERE community_id=$1 AND channel_id=$2", + ) + .bind(community.as_uuid()) + .bind(ids[1]) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("UPDATE channels SET archived_at=now() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(ids[2]) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("UPDATE channels SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(ids[3]) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); + sqlx::query("SELECT pg_advisory_unlock($1)") + .bind(lock_key) + .execute(&mut *blocker) + .await + .unwrap(); + let cut = pending.await.unwrap().unwrap(); + assert_eq!(cut.channels, before.channels); + assert_eq!(cut.snapshot_id, before.snapshot_id); + let next = snapshot_db + .membership_snapshot(community, &viewer.public_key(), &all_types()) + .await + .unwrap(); + assert_eq!(next.channels.len(), 2); + assert_eq!( + next.channels.iter().find(|c| c.id == ids[0]).unwrap().role, + "guest" + ); + assert!( + next.channels + .iter() + .find(|c| c.id == ids[2]) + .unwrap() + .archived + ); + assert!(!next + .channels + .iter() + .any(|c| c.id == ids[1] || c.id == ids[3])); + assert_ne!(next.snapshot_id, cut.snapshot_id); + sqlx::query(sqlx::AssertSqlSafe(format!("DROP SCHEMA {schema} CASCADE"))) + .execute(&pool) + .await + .unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn public_memberships_exclude_private_unlisted_removed_deleted_and_other_types() { + let (db, pool, community, subject, ids) = fixture(9).await; + for (index, kind) in [ + (0, "stream"), + (1, "stream"), + (2, "stream"), + (3, "dm"), + (4, "system"), + (5, "stream"), + (6, "stream"), + (7, "forum"), + (8, "workflow"), + ] { + sqlx::query("UPDATE channels SET channel_type=$3::channel_type, visibility=$4::channel_visibility, unlisted=$5, deleted_at=CASE WHEN $6 THEN now() ELSE NULL END, archived_at=CASE WHEN $7 THEN now() ELSE NULL END WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()).bind(ids[index]).bind(kind) + .bind(if index == 1 {"private"} else {"open"}).bind(index == 2) + .bind(index == 5).bind(index == 7).execute(&pool).await.unwrap(); + } + sqlx::query( + "UPDATE channel_members SET removed_at=now() WHERE community_id=$1 AND channel_id=$2", + ) + .bind(community.as_uuid()) + .bind(ids[6]) + .execute(&pool) + .await + .unwrap(); + sqlx::query("UPDATE channel_members SET role='guest' WHERE community_id=$1 AND channel_id=$2") + .bind(community.as_uuid()) + .bind(ids[7]) + .execute(&pool) + .await + .unwrap(); + let types = vec!["forum".into(), "stream".into(), "workflow".into()]; + let snapshot = db + .public_memberships(community, &subject.public_key(), &types) + .await + .unwrap(); + let mut expected = vec![ids[0], ids[7], ids[8]]; + expected.sort(); + assert_eq!( + snapshot.channels.iter().map(|c| c.id).collect::>(), + expected + ); + assert!(snapshot.channels.iter().all(|c| c.visibility == "open")); + let archived = snapshot.channels.iter().find(|c| c.id == ids[7]).unwrap(); + assert_eq!(archived.role, "guest"); + assert!(archived.archived); + let identity = serde_json::to_vec(&( + "nip-cl-public-membership-v1", + community.as_uuid(), + subject.public_key().to_hex(), + &types, + &snapshot.channels, + )) + .unwrap(); + assert_eq!(snapshot.snapshot_id, hex::encode(Sha256::digest(identity))); + assert_ne!( + snapshot.snapshot_id, + db.membership_snapshot(community, &subject.public_key(), &types) + .await + .unwrap() + .snapshot_id + ); + assert!(db + .public_memberships(community, &subject.public_key(), &all_types()) + .await + .is_err()); + assert!(db + .public_memberships(community, &Keys::generate().public_key(), &types) + .await + .unwrap() + .channels + .is_empty()); +} diff --git a/crates/buzz-db/src/store/message_edit_state_postgres_tests.rs b/crates/buzz-db/src/store/message_edit_state_postgres_tests.rs new file mode 100644 index 00000000000..a9d99247d82 --- /dev/null +++ b/crates/buzz-db/src/store/message_edit_state_postgres_tests.rs @@ -0,0 +1,309 @@ +use super::media::latest_message_edit_sql; +use crate::{ + channel::{ChannelType, ChannelVisibility}, + Db, +}; +use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn effective_edit_uses_target_index_and_fresh_channel_authorization() { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool.clone()); + let community = db + .ensure_configured_community("effective-edit.example") + .await + .unwrap() + .id; + let owner = Keys::generate(); + let outsider = Keys::generate(); + db.ensure_user(community, owner.public_key().as_bytes()) + .await + .unwrap(); + let channel = db + .create_channel( + community, + "edit", + ChannelType::Stream, + ChannelVisibility::Private, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id; + let original = EventBuilder::new(Kind::Custom(45001), "original") + .tags([Tag::parse(["h", &channel.to_string()]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &original, Some(channel)) + .await + .unwrap(); + let tags = vec![ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["e", &original.id.to_hex().to_uppercase()]).unwrap(), + ]; + let edit = EventBuilder::new(Kind::Custom(40003), "replacement") + .tags(tags) + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() + 1)) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &edit, Some(channel)) + .await + .unwrap(); + // More unrelated edits than the old channel-wide cap; they must not + // affect lookup cost or prevent editing this message. Synthetic IDs are + // intentional: these rows are unrelated fixtures and must never be read. + sqlx::query("INSERT INTO events (community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),$2,now(),40003,$3,'unrelated',$4,$5 FROM generate_series(1,10001) n") + .bind(community.as_uuid()).bind(owner.public_key().as_bytes().as_slice()) + .bind(serde_json::json!([["h",channel.to_string()],["e","f".repeat(64)]])) + .bind(edit.sig.serialize().as_slice()).bind(channel).execute(&pool).await.unwrap(); + sqlx::query("ANALYZE events").execute(&pool).await.unwrap(); + let snapshot = db + .message_edit_state( + community, + channel, + original.id.as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(snapshot.original.id, original.id); + assert_eq!(snapshot.edit.unwrap().id, edit.id); + assert!(db + .message_edit_state( + community, + channel, + original.id.as_bytes(), + outsider.public_key().as_bytes() + ) + .await + .unwrap() + .is_none()); + db.ensure_user(community, outsider.public_key().as_bytes()) + .await + .unwrap(); + db.add_member( + community, + channel, + outsider.public_key().as_bytes(), + crate::channel::MemberRole::Member, + Some(owner.public_key().as_bytes()), + ) + .await + .unwrap(); + assert!(db + .message_edit_state( + community, + channel, + original.id.as_bytes(), + outsider.public_key().as_bytes() + ) + .await + .unwrap() + .is_some()); + db.remove_member( + community, + channel, + outsider.public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap(); + assert!(db + .message_edit_state( + community, + channel, + original.id.as_bytes(), + outsider.public_key().as_bytes() + ) + .await + .unwrap() + .is_none()); + let sql = format!("EXPLAIN (FORMAT JSON) {}", latest_message_edit_sql()); + let plan: serde_json::Value = sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) + .bind(community.as_uuid()) + .bind(channel) + .bind(original.id.as_bytes().as_slice()) + .fetch_one(&pool) + .await + .unwrap(); + let plan = plan.to_string(); + let child_indexes: Vec = sqlx::query_scalar("SELECT child.relname FROM pg_inherits inheritance JOIN pg_class child ON child.oid=inheritance.inhrelid WHERE inheritance.inhparent='idx_events_media_edit_target'::regclass") + .fetch_all(&pool).await.unwrap(); + assert!( + child_indexes.iter().any(|index| plan.contains(index)), + "{plan}" + ); + assert!( + plan.contains("decode(lower("), + "target must be an index condition: {plan}" + ); + assert!(!plan.contains("Seq Scan"), "{plan}"); + db.soft_delete_event_and_update_thread(community, edit.id.as_bytes(), None, None) + .await + .unwrap(); + assert!(db + .message_edit_state( + community, + channel, + original.id.as_bytes(), + owner.public_key().as_bytes() + ) + .await + .unwrap() + .unwrap() + .edit + .is_none()); + db.soft_delete_event_and_update_thread(community, original.id.as_bytes(), None, None) + .await + .unwrap(); + assert!(db + .message_edit_state( + community, + channel, + original.id.as_bytes(), + owner.public_key().as_bytes() + ) + .await + .unwrap() + .is_none()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn historical_edit_preflight_matches_selected_live_edit() { + let sql = include_str!("../../../../docs/sql/private-media-edit-preflight.sql"); + // The checked-in operator query uses the exact normalized target expression. + assert!(sql.contains(super::media::MEDIA_EDIT_TARGET_SQL)); + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool.clone()); + let community = db + .ensure_configured_community("preflight.example") + .await + .unwrap() + .id; + let owner = Keys::generate(); + db.ensure_user(community, owner.public_key().as_bytes()) + .await + .unwrap(); + let mut channels = Vec::new(); + for name in ["originals", "decoys"] { + channels.push( + db.create_channel( + community, + name, + ChannelType::Stream, + ChannelVisibility::Private, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id, + ); + } + let now = Timestamp::now().as_secs(); + for (index, kind, scenario, denied) in [ + (1, 45001, "empty", true), + (2, 45003, "later-retained", false), + (3, 40008, "deleted", false), + (4, 45001, "mixed", true), + (5, 45003, "cross-channel", false), + (6, 9, "control", true), + (7, 45001, "deleted-original", true), + ] { + let hash = format!("{index:064x}"); + let media = [vec![ + "imeta".into(), + format!("url https://preflight.example/media/{hash}"), + format!("x {hash}"), + ]]; + let original = EventBuilder::new(Kind::Custom(kind), scenario) + .tags([ + Tag::parse(["h", &channels[0].to_string()]).unwrap(), + Tag::parse(media[0].clone()).unwrap(), + ]) + .custom_created_at(Timestamp::from(now - 20)) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &original, Some(channels[0])) + .await + .unwrap(); + let channel = if scenario == "cross-channel" { + channels[1] + } else { + channels[0] + }; + let target = if scenario == "mixed" { + original.id.to_hex().to_uppercase() + } else { + original.id.to_hex() + }; + let empty = EventBuilder::new(Kind::Custom(40003), "empty") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["e", &target]).unwrap(), + ]) + .custom_created_at(Timestamp::from(now - 2)) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &empty, Some(channel)) + .await + .unwrap(); + if scenario == "later-retained" { + let retained = EventBuilder::new(Kind::Custom(40003), "retained") + .tags([ + Tag::parse(["h", &channels[0].to_string()]).unwrap(), + Tag::parse(["e", &original.id.to_hex()]).unwrap(), + Tag::parse(media[0].clone()).unwrap(), + ]) + .custom_created_at(Timestamp::from(now - 1)) + .sign_with_keys(&owner) + .unwrap(); + db.insert_event(community, &retained, Some(channels[0])) + .await + .unwrap(); + } + if scenario == "deleted" { + db.soft_delete_event_and_update_thread(community, empty.id.as_bytes(), None, None) + .await + .unwrap(); + } + if scenario == "deleted-original" { + db.soft_delete_event_and_update_thread(community, original.id.as_bytes(), None, None) + .await + .unwrap(); + } + let access = db + .media_access( + community, + &hash, + "", + "https://preflight.example/media", + owner.public_key().as_bytes(), + false, + |_, _| true, + ) + .await + .unwrap(); + assert_eq!( + access == super::media::MediaAccess::Allowed, + !denied, + "{scenario}" + ); + } + let counts: Vec<(i32, i64)> = sqlx::query_as(sql) + .bind(community.as_uuid()) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(counts, vec![(45001, 2)]); +} diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index f3ea643ba41..6fad41294c4 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -14,6 +14,8 @@ pub mod channel; pub mod channel_members; /// Community lifecycle and host-map persistence. pub mod community; +/// Monotonic community auth policy and operator acceptance receipts. +pub mod community_auth; /// Durable whole-community deletion lifecycle and PostgreSQL adapter. pub mod deletion; /// Direct message channel persistence. @@ -22,20 +24,34 @@ pub mod dm; pub mod entity_deletion; /// Event storage and retrieval. pub mod event; +/// Atomic event deletion and retention-free purging. +mod event_deletion; /// App-owned push enqueue and channel TTL refresh for inserted events. pub(crate) mod event_follow_up; +mod event_hydration; /// Per-community NIP-FI issuer bindings. pub mod nip_fi_binding; +/// Recent-first passes for newest-first `events` page reads. +pub(crate) mod recent_pass; /// User-specific deletion submission and inventory preparation. pub mod user_deletion; +/// Operator-global user restrictions and identity-lock primitives. +pub mod user_deletion_fences; #[cfg(test)] mod event_follow_up_postgres_tests; +#[cfg(test)] +mod event_floor_postgres_tests; + /// Home feed queries. pub mod feed; /// Git repository name registry (NIP-34 kind:30617). pub mod git_repo; +/// Deployment-wide leader election over session advisory locks. +pub mod leader_lock; +/// Compact viewer membership projections. +pub mod membership_snapshot; /// Community moderation: reports, bans/timeouts, audit actions. pub mod moderation; /// Deployment-global operator-listener mention registrations and delivery queues. @@ -70,8 +86,6 @@ pub mod storage_accounting; pub mod thread; /// Strict newest-first thread windows and auxiliary scans. pub mod thread_window; -/// Per-community usage rollup queries for Prometheus gauges. -pub mod usage; /// User profile persistence. pub mod user; /// Workflow, run, and approval persistence. @@ -81,6 +95,9 @@ pub mod workflow; pub mod artifact; mod artifact_query; +/// Timestamp-based incremental artifact reads. +pub mod artifact_sync; +pub use artifact_query::{ArtifactSnapshot, SnapshotDenied}; #[cfg(test)] mod artifact_postgres_tests; @@ -91,5 +108,19 @@ mod legacy_channel_types_postgres_tests; #[cfg(test)] mod unlisted_channels_postgres_tests; +#[cfg(test)] +mod channel_name_postgres_tests; + #[cfg(test)] mod admission_postgres_tests; + +/// Durable NIP-FI verified-profile projection state. +pub mod verified_profiles; + +/// Live reference authorization and upload possession. +pub mod media; + +#[cfg(test)] +mod media_postgres_tests; +#[cfg(test)] +mod message_edit_state_postgres_tests; diff --git a/crates/buzz-db/src/store/moderation.rs b/crates/buzz-db/src/store/moderation.rs index 00bcb3af879..6720fcb0ebf 100644 --- a/crates/buzz-db/src/store/moderation.rs +++ b/crates/buzz-db/src/store/moderation.rs @@ -20,7 +20,7 @@ use sqlx::{PgPool, Row as _}; use uuid::Uuid; use crate::error::Result; -use crate::{CommunityId, Db}; +use crate::{CommunityId, Db, ReadAt}; /// What a report points at. Exactly one target class per report row. #[derive(Debug, Clone, PartialEq, Eq)] @@ -360,6 +360,7 @@ pub async fn ban_member( crate::observability::WriterOperation::Authorization, ) .await?; + crate::relay_invite::lock_admission(tx.conn(), community).await?; sqlx::query( r#" INSERT INTO community_bans ( @@ -380,8 +381,8 @@ pub async fn ban_member( .bind(actor) .execute(tx.conn()) .await?; + crate::relay_invite::revoke_banned_issuer_invites(tx.conn(), community, pubkey).await?; tx.commit().await?; - Ok(()) } @@ -548,6 +549,7 @@ pub async fn timeout_member( crate::observability::WriterOperation::Authorization, ) .await?; + crate::relay_invite::lock_admission(tx.conn(), community).await?; sqlx::query( r#" INSERT INTO community_bans ( @@ -567,8 +569,8 @@ pub async fn timeout_member( .bind(actor) .execute(tx.conn()) .await?; + crate::relay_invite::revoke_banned_issuer_invites(tx.conn(), community, pubkey).await?; tx.commit().await?; - Ok(()) } @@ -612,6 +614,8 @@ pub async fn untimeout_member( pub struct RestrictionState { /// Currently banned (row exists, `banned`, unexpired). pub banned: bool, + /// Banned by the key's own row, not only its agent owner's. + pub own_banned: bool, /// Active timeout expiry, if in the future. pub muted_until: Option>, } @@ -627,16 +631,30 @@ pub async fn restriction_state( community: CommunityId, pubkey: &[u8], ) -> Result { + Ok(restriction_state_read_at(pool, community, pubkey) + .await? + .value) +} + +/// [`restriction_state`], with when its connection was checked out. +pub async fn restriction_state_read_at( + pool: &PgPool, + community: CommunityId, + pubkey: &[u8], +) -> Result> { let mut connection = crate::observability::acquire_writer( pool, crate::observability::WriterOperation::Authorization, ) .await?; + let read_at = std::time::Instant::now(); let row = sqlx::query( r#" SELECT COALESCE(bool_or(banned AND (ban_expires_at IS NULL OR ban_expires_at > now())), false) AS banned, + COALESCE(bool_or(pubkey = $2 AND banned AND (ban_expires_at IS NULL OR ban_expires_at > now())), false) + AS own_banned, max(CASE WHEN muted_until > now() THEN muted_until END) AS muted_until FROM community_bans WHERE community_id = $1 @@ -653,9 +671,13 @@ pub async fn restriction_state( .fetch_one(&mut *connection) .await?; - Ok(RestrictionState { - banned: row.try_get("banned")?, - muted_until: row.try_get("muted_until")?, + Ok(ReadAt { + value: RestrictionState { + banned: row.try_get("banned")?, + own_banned: row.try_get("own_banned")?, + muted_until: row.try_get("muted_until")?, + }, + read_at, }) } @@ -1018,13 +1040,26 @@ impl Db { /// Fetch the effective (own or agent-owner) ban/timeout restriction state /// for enforcement hot paths. - #[datastore_span(name = "moderation_restriction_state", system = "postgresql")] pub async fn moderation_restriction_state( &self, community: CommunityId, pubkey: &[u8], ) -> Result { - restriction_state(&self.pool, community, pubkey).await + Ok(self + .moderation_restriction_state_read_at(community, pubkey) + .await? + .value) + } + + /// [`Self::moderation_restriction_state`], with when its connection was + /// checked out, for caches that bound staleness from the read. + #[datastore_span(name = "moderation_restriction_state", system = "postgresql")] + pub async fn moderation_restriction_state_read_at( + &self, + community: CommunityId, + pubkey: &[u8], + ) -> Result> { + restriction_state_read_at(&self.pool, community, pubkey).await } /// Fetch the full ban/timeout row for a member pubkey. diff --git a/crates/buzz-db/src/store/nip_fi_binding.rs b/crates/buzz-db/src/store/nip_fi_binding.rs index cca7a2e2b6a..79be374790d 100644 --- a/crates/buzz-db/src/store/nip_fi_binding.rs +++ b/crates/buzz-db/src/store/nip_fi_binding.rs @@ -19,6 +19,8 @@ pub enum NipFiUnbind { NotBound, /// The issuer is the community's last one and was kept. LastIssuer, + /// The last issuer is required by durable community policy, even with `allow_last`. + RequiredIssuer, } /// A community's stored NIP-FI binding, as returned to the operator route. @@ -94,10 +96,11 @@ impl Db { } /// Remove one issuer from a community, refusing to remove its last one - /// unless `allow_last`. + /// unless `allow_last` and the community does not require NIP-FI. /// - /// The bound rows are locked first, so two concurrent unbinds of a - /// community's two issuers cannot both succeed and leave it empty. An + /// The community row is locked before issuer rows, serializing with policy + /// acceptance and binding edits. Two concurrent unbinds of a community's + /// two issuers cannot both succeed and leave it empty. An /// empty community looks never-provisioned and the next backfill would /// rebind it; archive or delete the community to stop it logging in. #[datastore_span(name = "unbind_nip_fi_issuer", system = "postgresql")] @@ -116,6 +119,12 @@ impl Db { self.deletion_store() .guard_transaction(&mut tx, community) .await?; + let requires_nip_fi: Option = sqlx::query_scalar( + "SELECT requires_nip_fi FROM communities WHERE id = $1 FOR NO KEY UPDATE", + ) + .bind(community.as_uuid()) + .fetch_optional(&mut *tx) + .await?; let bound: Vec = sqlx::query_scalar( "SELECT issuer FROM community_nip_fi_issuers WHERE community_id = $1 FOR UPDATE", ) @@ -124,6 +133,8 @@ impl Db { .await?; let outcome = if !bound.iter().any(|bound| bound == issuer) { NipFiUnbind::NotBound + } else if bound.len() == 1 && requires_nip_fi == Some(true) { + NipFiUnbind::RequiredIssuer } else if bound.len() == 1 && !allow_last { NipFiUnbind::LastIssuer } else { @@ -234,7 +245,8 @@ impl Db { /// than aborting the batch. The community rows are then locked, as /// [`Db::bind_nip_fi_issuers`] does, so an operator bind that commits after /// the caller listed the community wins and the default is not added - /// beside it. Returns the number of new rows. + /// beside it. Required communities need explicit operator repair and are + /// never rebound by this bulk backfill. Returns the number of new rows. #[datastore_span(name = "bind_nip_fi_issuers_to_active", system = "postgresql")] pub async fn bind_nip_fi_issuers_to_active( &self, @@ -245,6 +257,13 @@ impl Db { return Ok(0); } let ids: Vec = communities.iter().map(|id| *id.as_uuid()).collect(); + // Lock in community-id order; `Uuid` and Postgres `uuid` both order bytewise. + let mut sorted = communities.to_vec(); + sorted.sort_unstable(); + let lock_keys: Vec = sorted + .into_iter() + .map(crate::deletion::community_deletion_lock_key) + .collect(); let connection = crate::observability::acquire_writer( &self.pool, crate::observability::WriterOperation::Authorization, @@ -252,10 +271,10 @@ impl Db { .await?; let mut tx = Transaction::begin(connection, None).await?; sqlx::query( - "SELECT pg_advisory_xact_lock_shared(community_deletion_lock_key(id)) \ - FROM unnest($1::uuid[]) AS id ORDER BY id", + "SELECT pg_advisory_xact_lock_shared(hashtextextended(key, 0)) \ + FROM unnest($1::text[]) WITH ORDINALITY AS k(key, ord) ORDER BY ord", ) - .bind(&ids) + .bind(&lock_keys) .execute(&mut *tx) .await?; sqlx::query("SELECT 1 FROM communities WHERE id = ANY($1) ORDER BY id FOR NO KEY UPDATE") @@ -270,6 +289,7 @@ impl Db { WHERE c.id = ANY($1) AND c.deletion_state = 'active' AND c.deleted_at IS NULL + AND NOT c.requires_nip_fi AND NOT EXISTS ( SELECT 1 FROM community_nip_fi_issuers b WHERE b.community_id = c.id ) @@ -600,6 +620,99 @@ mod postgres_tests { assert!(!community_exists(&db, &bootstrap).await); } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn initial_policy_is_atomic_and_replays_preserve_current_state() { + let db = setup_db().await; + let keys = nostr::Keys::generate(); + for required in [false, true] { + let host = unique_host("initial-policy"); + let owner = nostr::Keys::generate().public_key().to_hex(); + let write = db + .create_community_with_owner_and_nip_fi_policy( + &host, + &owner, + &issuers(), + required, + &keys, + ) + .await + .unwrap(); + let CreateCommunityWithOwnerResult::Created(record) = write.outcome else { + panic!("not created") + }; + assert!(record.created); + assert_eq!(record.requires_nip_fi, required); + let before = db.community_auth_policy(record.id).await.unwrap().unwrap(); + assert_eq!(before.requires_nip_fi, required); + assert_eq!(before.policy_generation, i64::from(required)); + assert_eq!(bound(&db, &host).await, Some(issuers())); + let owners = db.list_communities_owned_by(&owner).await.unwrap(); + assert_eq!(owners.communities[0].id, record.id); + // Changed policy and issuer configuration never rewrite a committed row. + let changed = ["https://other.example".to_owned()]; + for bindings in [&[][..], changed.as_slice()] { + let retry = db + .create_community_with_owner_and_nip_fi_policy( + &host, &owner, bindings, !required, &keys, + ) + .await + .unwrap(); + let CreateCommunityWithOwnerResult::Created(retry) = retry.outcome else { + panic!("not replayed") + }; + assert!(!retry.created); + assert_eq!(retry.requires_nip_fi, required); + assert_eq!( + db.community_auth_policy(record.id).await.unwrap().unwrap(), + before + ); + assert_eq!(bound(&db, &host).await, Some(issuers())); + } + // Model an operator disable. A later true replay must report the stored false. + sqlx::query("UPDATE communities SET requires_nip_fi = false, policy_generation = policy_generation + 1 WHERE id = $1") + .bind(record.id.as_uuid()).execute(&db.pool).await.unwrap(); + let disabled = db.community_auth_policy(record.id).await.unwrap().unwrap(); + let replay = db + .create_community_with_owner_and_nip_fi_policy(&host, &owner, &[], true, &keys) + .await + .unwrap(); + let CreateCommunityWithOwnerResult::Created(replay) = replay.outcome else { + panic!("not replayed") + }; + assert!(!replay.created); + assert!(!replay.requires_nip_fi); + assert_eq!( + db.community_auth_policy(record.id).await.unwrap().unwrap(), + disabled + ); + assert_eq!(bound(&db, &host).await, Some(issuers())); + let conflict = db + .create_community_with_owner_and_nip_fi_policy( + &host, + &nostr::Keys::generate().public_key().to_hex(), + &[], + true, + &keys, + ) + .await + .unwrap(); + assert_eq!(conflict.outcome, CreateCommunityWithOwnerResult::HostExists); + } + for bindings in [vec![], vec![String::new()]] { + let host = unique_host("refused-initial-policy"); + let refusal = db + .create_community_with_owner_and_nip_fi_policy(&host, OWNER, &bindings, true, &keys) + .await; + if bindings.is_empty() { + assert!(matches!(refusal, Err(crate::DbError::NipFiBindingRequired))); + } else { + assert!(refusal.is_err()); + } + assert!(!community_exists(&db, &host).await); + } + } + // Deletion takes its exclusive lock, then the community row. A bind that // held the row while waiting for that lock would deadlock with it. // Mutation: locking the row before `guard_transaction` in @@ -618,8 +731,8 @@ mod postgres_tests { .fetch_one(&mut *deletion) .await .expect("pid"); - sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(id.as_uuid()) + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(crate::deletion::community_deletion_lock_key(id)) .execute(&mut *deletion) .await .expect("exclusive deletion lock"); diff --git a/crates/buzz-db/src/store/operator_listener.rs b/crates/buzz-db/src/store/operator_listener.rs index 18d9c1cca07..08983b36d2e 100644 --- a/crates/buzz-db/src/store/operator_listener.rs +++ b/crates/buzz-db/src/store/operator_listener.rs @@ -70,7 +70,9 @@ fn event_targets(event: &Event) -> Vec> { let mut targets = Vec::new(); for tag in event.tags.iter() { let parts = tag.as_slice(); - if parts.first().map(String::as_str) != Some("p") { + if parts.first().map(String::as_str) != Some("p") + || buzz_core::filter::is_workflow_owner_attribution(event, tag) + { continue; } let Some(value) = parts.get(1) else { @@ -523,6 +525,30 @@ mod tests { assert!(!is_listener_mention_kind(1)); assert!(!is_listener_mention_kind(40003)); } + + #[test] + fn a_workflow_owner_attribution_is_not_a_listener_target() { + let owner = nostr::Keys::generate().public_key(); + let agent = nostr::Keys::generate().public_key(); + let targets = |mention_owner: bool| { + let mut tags = vec![ + nostr::Tag::parse(["p", &owner.to_hex(), "", "owner"]).unwrap(), + nostr::Tag::parse(["buzz:workflow", "true"]).unwrap(), + nostr::Tag::public_key(agent), + ]; + if mention_owner { + tags.push(nostr::Tag::public_key(owner)); + } + let event = nostr::EventBuilder::new(nostr::Kind::Custom(9), "run") + .tags(tags) + .sign_with_keys(&nostr::Keys::generate()) + .unwrap(); + event_targets(&event) + }; + let bytes = |pubkey: nostr::PublicKey| pubkey.to_bytes().to_vec(); + assert_eq!(targets(false), vec![bytes(agent)]); + assert_eq!(targets(true), vec![bytes(agent), bytes(owner)]); + } } #[cfg(test)] diff --git a/crates/buzz-db/src/store/partition/maintenance.rs b/crates/buzz-db/src/store/partition/maintenance.rs index 04a09fdbc9b..cf624d266ae 100644 --- a/crates/buzz-db/src/store/partition/maintenance.rs +++ b/crates/buzz-db/src/store/partition/maintenance.rs @@ -11,7 +11,8 @@ //! lock, then the catch-all, in the order writers take them, waiting only on //! the parent and failing fast on any other contention; //! 3. re-audits under those locks and refuses if the plan changed; and -//! 4. re-audits the changed catalog and verifies index and constraint +//! 4. copies the parent's explicit table-level SELECT grants to new children; +//! 5. re-audits the changed catalog and verifies index and constraint //! inheritance before commit. //! //! A populated catch-all is always refused before any lock is taken: moving @@ -22,7 +23,7 @@ use std::time::Duration; use chrono::{DateTime, Datelike, Utc}; use serde::Serialize; use sqlx::{Connection, PgConnection, PgPool, Row}; -use tracing::info; +use tracing::{info, warn}; use super::{ add_months, audit_partition_catalog_at, audit_table_on, month_start, partition_name, @@ -554,7 +555,42 @@ async fn apply_change( now: DateTime, ) -> Result { let mut transaction = connection.begin().await?; - configure_maintenance_transaction(&mut transaction).await?; + let attempt = attempt_change(&mut transaction, table, months_ahead, policy, now).await; + // End the transaction before the next table starts, on failure too. + // PostgreSQL sends a failed statement's error before its backend aborts + // and releases the advisory lock, and a dropped transaction only queues + // its ROLLBACK. Either way the next table's probe could find the lock + // still held and report `skipped_locked`. A completed ROLLBACK proves the + // lock is free. + match attempt { + Ok(LockedAttempt::Committed(change)) => { + transaction.commit().await?; + Ok(LockedAttempt::Committed(change)) + } + Ok(attempt) => { + transaction.rollback().await?; + Ok(attempt) + } + Err(error) => { + if let Err(rollback) = transaction.rollback().await { + warn!(table, %rollback, "partition maintenance rollback failed"); + } + Err(error) + } + } +} + +/// Plan and apply `table`'s change inside the caller's transaction. A +/// `Committed` result is ready to commit; [`apply_change`] ends the +/// transaction on every path. +async fn attempt_change( + transaction: &mut PgConnection, + table: &'static str, + months_ahead: i32, + policy: PartitionMaintenancePolicy, + now: DateTime, +) -> Result { + configure_maintenance_transaction(transaction).await?; let acquired: bool = crate::observability::observe_advisory_lock( crate::observability::LockType::PartitionMaintenance, @@ -567,28 +603,18 @@ async fn apply_change( ) .await?; if !acquired { - transaction.rollback().await?; return Ok(LockedAttempt::SkippedLocked); } // Re-plan while serialized against other managers but before any table // lock. A runner that lost a race sees the winner's committed layout here // and stops, instead of mistaking the winner's monthlies for collisions. - let serialized = audit_table_on(&mut transaction, table, months_ahead, now).await?; + let serialized = audit_table_on(transaction, table, months_ahead, now).await?; let expected = match plan_maintenance(&serialized, policy) { MaintenancePlan::Apply(change) => change, - MaintenancePlan::Noop => { - transaction.rollback().await?; - return Ok(LockedAttempt::Unchanged); - } - MaintenancePlan::Disabled => { - transaction.rollback().await?; - return Ok(LockedAttempt::Disabled); - } - MaintenancePlan::Refuse(reason) => { - transaction.rollback().await?; - return Ok(LockedAttempt::Refused(reason)); - } + MaintenancePlan::Noop => return Ok(LockedAttempt::Unchanged), + MaintenancePlan::Disabled => return Ok(LockedAttempt::Disabled), + MaintenancePlan::Refuse(reason) => return Ok(LockedAttempt::Refused(reason)), }; // Reject misnamed relations before any lock can cost a parent outage. if let Some(name) = colliding_relation( @@ -598,19 +624,16 @@ async fn apply_change( ) .await? { - transaction.rollback().await?; return Ok(LockedAttempt::Refused(collision_message(&name))); } // Refuse an unproven lock set before taking any lock. - let parent = maintenance_parent(&mut transaction, table).await?; + let parent = maintenance_parent(transaction, table).await?; if let Some(reason) = parent.refusal { - transaction.rollback().await?; return Ok(LockedAttempt::Refused(reason)); } if let Some(catch_all) = &expected.catch_all { - if let Some(reason) = catch_all_foreign_key_refusal(&mut transaction, catch_all).await? { - transaction.rollback().await?; + if let Some(reason) = catch_all_foreign_key_refusal(transaction, catch_all).await? { return Ok(LockedAttempt::Refused(reason)); } } @@ -619,7 +642,7 @@ async fn apply_change( // a counterpart while holding the parent could deadlock with such a writer. // ONLY: without it PostgreSQL locks every historical child in turn. lock( - &mut transaction, + transaction, &format!( "LOCK TABLE ONLY {} IN ACCESS EXCLUSIVE MODE", qualified_relation_name(&parent.schema, table) @@ -631,9 +654,8 @@ async fn apply_change( // attaching would then wait on its table while holding the parent. Adding // or dropping a foreign key on or to the parent needs a lock that // conflicts with this one, so the set cannot change from here on. - let parent = maintenance_parent(&mut transaction, table).await?; + let parent = maintenance_parent(transaction, table).await?; if let Some(reason) = parent.refusal { - transaction.rollback().await?; return Ok(LockedAttempt::Refused(reason)); } // Attaching a partition adds its foreign key under SHARE ROW EXCLUSIVE on @@ -646,7 +668,7 @@ async fn apply_change( // catch-all with any other foreign key is refused before and after its lock. for counterpart in &parent.counterparts { lock( - &mut transaction, + transaction, &format!("LOCK TABLE ONLY {counterpart} IN SHARE ROW EXCLUSIVE MODE NOWAIT"), ) .await?; @@ -655,7 +677,7 @@ async fn apply_change( // child while holding the parent. if let Some(catch_all) = &expected.catch_all { lock( - &mut transaction, + transaction, &format!( "LOCK TABLE ONLY {} IN ACCESS EXCLUSIVE MODE NOWAIT", qualified_relation_name(&catch_all.schema, &catch_all.name) @@ -664,30 +686,19 @@ async fn apply_change( .await?; // Foreign-key DDL on or to the catch-all conflicts with this lock but // not with the parent's, so only this check is authoritative. - if let Some(reason) = catch_all_foreign_key_refusal(&mut transaction, catch_all).await? { - transaction.rollback().await?; + if let Some(reason) = catch_all_foreign_key_refusal(transaction, catch_all).await? { return Ok(LockedAttempt::Refused(reason)); } } // Close the window between the serialized audit and the table locks. - let locked = audit_table_on(&mut transaction, table, months_ahead, now).await?; + let locked = audit_table_on(transaction, table, months_ahead, now).await?; match plan_maintenance(&locked, policy) { MaintenancePlan::Apply(change) if change == expected => {} - MaintenancePlan::Noop => { - transaction.rollback().await?; - return Ok(LockedAttempt::Unchanged); - } - MaintenancePlan::Disabled => { - transaction.rollback().await?; - return Ok(LockedAttempt::Disabled); - } - MaintenancePlan::Refuse(reason) => { - transaction.rollback().await?; - return Ok(LockedAttempt::Refused(reason)); - } + MaintenancePlan::Noop => return Ok(LockedAttempt::Unchanged), + MaintenancePlan::Disabled => return Ok(LockedAttempt::Disabled), + MaintenancePlan::Refuse(reason) => return Ok(LockedAttempt::Refused(reason)), MaintenancePlan::Apply(_) => { - transaction.rollback().await?; return Err(DbError::InvalidData( "partition catalog changed between the audit and the maintenance locks".to_string(), )); @@ -697,7 +708,7 @@ async fn apply_change( let parent_relation = qualified_relation_name(&parent.schema, table); if let Some(catch_all) = &expected.catch_all { execute_ddl( - &mut transaction, + transaction, format!( "DROP TABLE {}", qualified_relation_name(&catch_all.schema, &catch_all.name) @@ -708,7 +719,7 @@ async fn apply_change( for month in &expected.create { let end = next_month(*month)?; execute_ddl( - &mut transaction, + transaction, format!( "CREATE TABLE {} PARTITION OF {parent_relation} \ FOR VALUES FROM ('{}') TO ('{}')", @@ -721,7 +732,7 @@ async fn apply_change( } if let Some(catch_all) = &expected.catch_all { execute_ddl( - &mut transaction, + transaction, format!( "CREATE TABLE {} PARTITION OF {parent_relation} \ FOR VALUES FROM ('{}') TO (MAXVALUE)", @@ -732,20 +743,51 @@ async fn apply_change( .await?; } - let after = audit_table_on(&mut transaction, table, months_ahead, now).await?; - let verified = verify_applied(&locked, &after, &expected).and( - verify_inheritance(&mut transaction, parent.oid, &expected.target_names(table)).await?, - ); + let new_children = expected.target_names(table); + grant_parent_readers(transaction, parent.oid, &parent.schema, &new_children).await?; + + let after = audit_table_on(transaction, table, months_ahead, now).await?; + let verified = verify_applied(&locked, &after, &expected) + .and(verify_inheritance(transaction, parent.oid, &new_children).await?); if let Err(reason) = verified { - transaction.rollback().await?; return Err(DbError::InvalidData(format!( "partition maintenance failed its postcondition and rolled back: {reason}" ))); } - transaction.commit().await?; Ok(LockedAttempt::Committed(expected)) } +/// The parent ACL is the reader policy; never copy writes or grant options. +/// `quote_ident` handles role names containing quotes. +/// PUBLIC is an ACL grantee too, but must remain an unquoted SQL keyword. +async fn grant_parent_readers( + connection: &mut PgConnection, + parent_oid: i64, + schema: &str, + children: &[String], +) -> Result<()> { + let grants: Vec = sqlx::query_scalar( + "SELECT DISTINCT pg_catalog.format(\ + 'GRANT SELECT ON TABLE %I.%I TO %s', $2::text, child, \ + CASE WHEN acl.grantee = 0 THEN 'PUBLIC' \ + ELSE pg_catalog.quote_ident(pg_catalog.pg_get_userbyid(acl.grantee)) END) \ + FROM pg_catalog.pg_class parent \ + CROSS JOIN LATERAL pg_catalog.aclexplode(parent.relacl) acl \ + CROSS JOIN pg_catalog.unnest($3::text[]) child \ + WHERE parent.oid = $1::bigint::oid \ + AND acl.privilege_type = 'SELECT' AND acl.grantee <> parent.relowner", + ) + .bind(parent_oid) + .bind(schema) + .bind(children) + .fetch_all(&mut *connection) + .await?; + for grant in grants { + execute_ddl(connection, grant).await?; + } + Ok(()) +} + async fn configure_maintenance_transaction(connection: &mut PgConnection) -> Result<()> { pin_catalog_rendering(connection).await?; for (setting, value) in [ diff --git a/crates/buzz-db/src/store/partition/maintenance_tests.rs b/crates/buzz-db/src/store/partition/maintenance_tests.rs index cc7d05c1699..1de67c68c66 100644 --- a/crates/buzz-db/src/store/partition/maintenance_tests.rs +++ b/crates/buzz-db/src/store/partition/maintenance_tests.rs @@ -408,6 +408,7 @@ mod postgres_tests { catalog_snapshot, create_child, fixed_now, scratch_pool, scratch_pool_with_max_connections, seed_parents, }; + use crate::test_support::ScratchDb; /// The repaired incident layout for both managed parents, optionally with /// outgoing foreign keys to a `communities` counterpart. @@ -584,6 +585,184 @@ mod postgres_tests { .any(|child| child.name == format!("{}_p2026_09", table.table)))); } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn cluster_global_parent_readers_follow_monthly_creation_and_catch_all_advancement() { + use crate::store::partition::quote_identifier; + + let (pool, scratch) = scratch_pool().await; + seed_parents(&pool).await; + let reader = format!("{}_r\"x", scratch.name); + let writer = format!("{}_writer", scratch.name); + for role in [&reader, &writer] { + execute_ddl( + &mut pool.acquire().await.unwrap(), + format!("CREATE ROLE {}", quote_identifier(role)), + ) + .await + .unwrap(); + } + for statement in [ + format!( + "GRANT USAGE ON SCHEMA {} TO {}, {}", + scratch.name, + quote_identifier(&reader), + quote_identifier(&writer) + ), + format!( + "GRANT SELECT ON events TO {} WITH GRANT OPTION", + quote_identifier(&reader) + ), + format!( + "GRANT INSERT, UPDATE ON events TO {}", + quote_identifier(&reader) + ), + format!( + "GRANT INSERT, SELECT (id) ON events TO {}", + quote_identifier(&writer) + ), + "GRANT SELECT ON delivery_log TO PUBLIC".to_string(), + "CREATE TABLE unrelated (id BIGINT)".to_string(), + ] { + execute_ddl(&mut pool.acquire().await.unwrap(), statement) + .await + .unwrap(); + } + for table in PARTITIONED_TABLES { + create_child( + &pool, + table, + &format!("{table}_p_past"), + "MINVALUE", + "'2026-09-01'", + ) + .await; + } + + maintain_partitions_at(&pool, 0, CREATE_ONLY, fixed_now()) + .await + .expect("create uncovered September"); + let can = |role: String, relation: String, privilege: &'static str| { + let pool = pool.clone(); + async move { + sqlx::query_scalar::<_, bool>("SELECT has_table_privilege($1, $2, $3)") + .bind(role) + .bind(relation) + .bind(privilege) + .fetch_one(&pool) + .await + .unwrap() + } + }; + let mut direct_read = pool.begin().await.unwrap(); + execute_ddl( + &mut direct_read, + format!("SET LOCAL ROLE {}", quote_identifier(&reader)), + ) + .await + .unwrap(); + sqlx::query("SELECT * FROM events_p2026_09 LIMIT 0") + .execute(&mut *direct_read) + .await + .expect("parent reader can query the new child directly"); + direct_read.rollback().await.unwrap(); + assert!(can(reader.clone(), "events_p2026_09".into(), "SELECT").await); + for privilege in ["INSERT", "UPDATE", "SELECT WITH GRANT OPTION"] { + assert!(!can(reader.clone(), "events_p2026_09".into(), privilege).await); + } + for relation in [ + "events_p2026_09", + "events_p_past", + "delivery_log_p_past", + "unrelated", + ] { + assert!(!can(writer.clone(), relation.into(), "SELECT").await); + } + assert!(!can(reader.clone(), "events_p_past".into(), "SELECT").await); + assert!(!can(reader.clone(), "unrelated".into(), "SELECT").await); + assert!(can(writer.clone(), "delivery_log_p2026_09".into(), "SELECT").await); + + // The next rotation uses the current parent ACL, not a cached reader list. + for statement in [ + format!("REVOKE SELECT ON events FROM {}", quote_identifier(&reader)), + format!("GRANT SELECT ON events TO {}", quote_identifier(&writer)), + ] { + execute_ddl(&mut pool.acquire().await.unwrap(), statement) + .await + .unwrap(); + } + for table in PARTITIONED_TABLES { + create_child( + &pool, + table, + &format!("{table}_p_future"), + "'2026-10-01'", + "MAXVALUE", + ) + .await; + } + maintain_partitions_at(&pool, 1, ADVANCE, fixed_now()) + .await + .expect("replace catch-all and grant new readers"); + for relation in ["events_p2026_10", "events_p_future"] { + assert!(can(writer.clone(), relation.into(), "SELECT").await); + assert!(!can(writer.clone(), relation.into(), "INSERT").await); + assert!(!can(reader.clone(), relation.into(), "SELECT").await); + } + for relation in ["delivery_log_p2026_10", "delivery_log_p_future"] { + assert!(can(reader.clone(), relation.into(), "SELECT").await); + assert!(!can(reader.clone(), relation.into(), "INSERT").await); + } + let before = catalog_snapshot(&pool).await; + maintain_partitions_at(&pool, 1, ADVANCE, fixed_now()) + .await + .unwrap(); + assert_eq!(catalog_snapshot(&pool).await, before); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn cluster_global_reader_grant_failure_rolls_back_partition_replacement() { + let (pool, scratch) = scratch_pool().await; + seed_repaired_layout(&pool, false).await; + sqlx::query("GRANT SELECT ON events TO PUBLIC") + .execute(&pool) + .await + .unwrap(); + let before = catalog_snapshot(&pool).await; + sqlx::query( + "CREATE FUNCTION reject_partition_grant() RETURNS event_trigger \ + LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected grant failure'; END $$", + ) + .execute(&pool) + .await + .unwrap(); + execute_ddl( + &mut pool.acquire().await.unwrap(), + format!( + "CREATE EVENT TRIGGER {}_grant_failure ON ddl_command_start \ + WHEN TAG IN ('GRANT') EXECUTE FUNCTION reject_partition_grant()", + scratch.name + ), + ) + .await + .unwrap(); + + let result = maintain(&pool).await; + assert!( + matches!(result, Err(DbError::InvalidData(ref message)) + if message.contains("events error") && message.contains("injected grant failure")), + "{result:?}" + ); + let events = |snapshot: Vec<(String, String, String, i64)>| { + snapshot + .into_iter() + .filter(|(name, ..)| name.starts_with("events_")) + .collect::>() + }; + assert_eq!(events(catalog_snapshot(&pool).await), events(before)); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn populated_catch_all_is_refused_before_any_lock() { @@ -1395,18 +1574,10 @@ mod postgres_tests { /// Runs every migration in a dedicated database, then the passes a relay /// would run at `fixed_now()`. The database is dropped before returning. async fn fresh_install_passes() -> Result { - let base_url = crate::test_support::database_url(); - let admin = PgPool::connect(&base_url) - .await - .expect("connect admin database"); - let database = format!("buzz_partition_fresh_{}", uuid::Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {database}"))) - .execute(&admin) - .await - .expect("create fresh-install database"); - let (base_prefix, _) = base_url.rsplit_once('/').expect("database url has a path"); + let database = + ScratchDb::create(&crate::test_support::database_url(), "buzz_partition_fresh").await; let passes = async { - let pool = PgPool::connect(&format!("{base_prefix}/{database}")).await?; + let pool = PgPool::connect(database.url()).await?; let result = async { crate::migration::run_migrations(&pool).await?; let now = fixed_now(); @@ -1433,12 +1604,6 @@ mod postgres_tests { result } .await; - sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE {database} WITH (FORCE)" - ))) - .execute(&admin) - .await - .expect("drop fresh-install database"); passes } diff --git a/crates/buzz-db/src/store/personal_read/participation_postgres_tests.rs b/crates/buzz-db/src/store/personal_read/participation_postgres_tests.rs index 5a3d3a0acad..2800b9b1804 100644 --- a/crates/buzz-db/src/store/personal_read/participation_postgres_tests.rs +++ b/crates/buzz-db/src/store/personal_read/participation_postgres_tests.rs @@ -70,10 +70,8 @@ impl World { .custom_created_at(Timestamp::from(at)) .sign_with_keys(author) .unwrap(); - self.db - .insert_event(self.community, &event, Some(channel)) - .await - .unwrap(); + crate::test_support::insert_historical_event(&self.pool, self.community, &event, channel) + .await; event } diff --git a/crates/buzz-db/src/store/personal_read/postgres_tests.rs b/crates/buzz-db/src/store/personal_read/postgres_tests.rs index 99da1ff848c..81423e445f5 100644 --- a/crates/buzz-db/src/store/personal_read/postgres_tests.rs +++ b/crates/buzz-db/src/store/personal_read/postgres_tests.rs @@ -164,8 +164,9 @@ async fn personal_read_sidebar_author_window_excludes_expired_and_late_old_messa "an empty author-time window has nothing unread" ); assert_eq!(row.latest_id.as_deref(), Some(latest.id.to_hex().as_str())); - // Acceptance time is irrelevant: a message accepted now with an author - // time beyond the horizon stays out; one authored now is counted. + // Stored historical data with an author time beyond the horizon stays out; + // one authored now is counted. The serving writer now rejects the old + // timestamp, so seed the historical row through unarmed fixture SQL. let now = nostr::Timestamp::now().as_secs(); for (age, unread, mentions) in [(40 * 86400, false, 0), (0, true, 1)] { let event = EventBuilder::new(Kind::Custom(9), "accepted now") @@ -173,9 +174,7 @@ async fn personal_read_sidebar_author_window_excludes_expired_and_late_old_messa .custom_created_at(nostr::Timestamp::from(now - age)) .sign_with_keys(&Keys::generate()) .unwrap(); - db.insert_event(community, &event, Some(channel)) - .await - .unwrap(); + crate::test_support::insert_historical_event(&pool, community, &event, channel).await; let row = &sidebar(&db, community, &actor).await.channels[0]; assert_eq!((row.unread, row.mentions), (unread, mentions), "age={age}"); } diff --git a/crates/buzz-db/src/store/personal_read/threads_postgres_tests.rs b/crates/buzz-db/src/store/personal_read/threads_postgres_tests.rs index 2bb86aab8da..09786f55856 100644 --- a/crates/buzz-db/src/store/personal_read/threads_postgres_tests.rs +++ b/crates/buzz-db/src/store/personal_read/threads_postgres_tests.rs @@ -32,9 +32,7 @@ async fn post_as( .custom_created_at(nostr::Timestamp::from(at)) .sign_with_keys(author) .unwrap(); - db.insert_event(community, &event, Some(channel)) - .await - .unwrap(); + crate::test_support::insert_historical_event(&db.pool, community, &event, channel).await; event } diff --git a/crates/buzz-db/src/store/push.rs b/crates/buzz-db/src/store/push.rs index ce3a734a43a..44f693c4116 100644 --- a/crates/buzz-db/src/store/push.rs +++ b/crates/buzz-db/src/store/push.rs @@ -366,6 +366,7 @@ pub async fn accept_lease_event( crate::store::event_follow_up::after_admitted_insert( &mut tx, event.id.as_bytes().as_slice(), + created_at, 30350, None, ) @@ -2889,6 +2890,8 @@ mod postgres_tests { &pool, community, raced.id.as_bytes().to_vec(), + DateTime::from_timestamp(raced.created_at.as_secs() as i64, 0) + .expect("signed timestamp"), (held_tx, release_rx), ) .await diff --git a/crates/buzz-db/src/store/reaction.rs b/crates/buzz-db/src/store/reaction.rs index 6c910edb805..51062b6cddb 100644 --- a/crates/buzz-db/src/store/reaction.rs +++ b/crates/buzz-db/src/store/reaction.rs @@ -731,6 +731,7 @@ impl Db { #[cfg(test)] mod postgres_tests { use super::*; + use crate::test_support::ScratchDb; use crate::{ error::DbError, event::{get_event_by_id, insert_event}, @@ -776,37 +777,6 @@ mod postgres_tests { id } - async fn admin_url() -> String { - crate::test_support::database_url() - } - - async fn create_scratch_db(admin: &PgPool, prefix: &str) -> (PgPool, String) { - let name = format!("{}_{}", prefix, Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(admin) - .await - .expect("create scratch db"); - let base = admin_url().await; - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); - let pool = PgPool::connect(&scratch_url) - .await - .expect("connect scratch db"); - crate::migration::run_migrations(&pool) - .await - .expect("migrate scratch db"); - (pool, name) - } - - async fn drop_scratch_db(admin: &PgPool, pool: PgPool, name: &str) { - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(admin) - .await; - } - async fn install_mention_failure_injection(pool: &PgPool) { sqlx::query( "CREATE FUNCTION reject_test_mention() RETURNS trigger AS $$ \ @@ -1143,11 +1113,11 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn reaction_insert_with_thread_metadata_mention_failure_rolls_back_everything() { - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin database"); - let (scratch_pool, name) = - create_scratch_db(&admin, "reaction_thread_mention_rollback").await; + let (scratch_pool, _scratch) = ScratchDb::migrated( + &crate::test_support::database_url(), + "reaction_thread_mention_rollback", + ) + .await; install_mention_failure_injection(&scratch_pool).await; let db = Db::from_pool(scratch_pool.clone()); @@ -1235,8 +1205,6 @@ mod postgres_tests { thread_meta_count, 0, "thread metadata must not persist when mention indexing fails" ); - - drop_scratch_db(&admin, scratch_pool, &name).await; } #[tokio::test] @@ -1501,7 +1469,12 @@ mod postgres_tests { .await .expect("load community host"); let submitted = store - .submit(&host, "test-operator", Some("reaction fence regression")) + .submit( + Some(&host), + "test-operator", + Some("reaction fence regression"), + None, + ) .await .expect("submit deletion request"); let empty_digest = crate::deletion::KeyStreamDigest::new().finish().0; @@ -1623,8 +1596,10 @@ mod postgres_tests { let mut contender = pool.begin().await.expect("begin exclusive contender"); let exclusive_taken: bool = - sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community_uuid) + sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))") + .bind(crate::deletion::community_deletion_lock_key( + buzz_core::CommunityId::from_uuid(community_uuid), + )) .fetch_one(&mut *contender) .await .expect("probe exclusive community-deletion lock"); @@ -1645,8 +1620,10 @@ mod postgres_tests { let mut released = pool.begin().await.expect("begin post-release contender"); let exclusive_after_release: bool = - sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community_uuid) + sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))") + .bind(crate::deletion::community_deletion_lock_key( + buzz_core::CommunityId::from_uuid(community_uuid), + )) .fetch_one(&mut *released) .await .expect("probe exclusive lock after release"); diff --git a/crates/buzz-db/src/store/recent_pass.rs b/crates/buzz-db/src/store/recent_pass.rs new file mode 100644 index 00000000000..a4dd5d2ef33 --- /dev/null +++ b/crates/buzz-db/src/store/recent_pass.rs @@ -0,0 +1,449 @@ +//! Recent-first newest-first page reads over the partitioned `events` table. +//! +//! `events` is range-partitioned by month on `created_at`, and every partition +//! carries the full index set. A read with no `created_at` lower bound cannot +//! prune partitions, so Postgres plans and locks every partition and every +//! partition index: about 200 relations. Only 16 fit a backend's fast-path +//! lock slots; the rest go through the shared lock table, whose partition +//! locks every backend contends on (`LWLock:LockManager`). +//! +//! A newest-first page (`ORDER BY created_at DESC … LIMIT n`) usually lies in +//! the newest partitions, so it is split ([`split_for`], [`next`]) at a floor, +//! the start of the previous UTC month: +//! +//! 1. The *recent* pass reads `created_at >= floor`. When it returns `n` +//! rows, they are the page: every row at or above the floor sorts before +//! every row below it. A read of regular kinds only also stops at a +//! ceiling ([`ceiling_at`]), so it does not plan the empty monthly +//! partitions made ahead of time or the open-ended last one. +//! 2. Otherwise the *older* pass reads `created_at < floor` for the rows +//! still missing, and they follow the recent rows. The two ranges are +//! disjoint, so no row is read twice and the page is exact, provided both +//! passes read one snapshot (the stores run them in one `REPEATABLE READ` +//! transaction, `ReadTransaction`). +//! +//! A read whose own `since` is at or above the floor matches no row below +//! it, so its recent pass is the whole read and no older pass follows. The +//! floor literal is still worth adding: `since` is a bind parameter, which a +//! cached generic plan prunes only at execution, after it has locked every +//! partition. Live REQs with a recent `since` (agents reconnecting, `#p` +//! mention reads) are that read. +//! +//! The bounds are SQL literals, so Postgres prunes when it plans the +//! statement, cached generic plans included. They change about once a month, +//! so the prepared-statement cache keeps one statement per pass and shape. + +use buzz_core::kind::{is_parameterized_replaceable, is_replaceable}; +use chrono::{DateTime, Datelike, Duration, TimeZone, Utc}; + +/// How far ahead of a relay's clock a regular-kind row's `created_at` can be, +/// with margin. +/// +/// Ingest rejects events more than 900 s ahead of the accepting relay's clock +/// (`MAX_TIMESTAMP_DRIFT_SECS` in `buzz-relay`'s ingest handler), and the +/// regular-kind events the relay signs itself are stamped with its clock. The +/// margin over 900 s covers the clock difference between the relay that wrote +/// a row and the one reading it. It costs one extra planned partition in the +/// last hour of a month. +/// +/// Replaceable and addressable rows have no such bound: the relay stamps its +/// own replacements one second past the live row when that is later than +/// `now`, so a coordinate replaced faster than once a second runs ahead. +pub(crate) const MAX_FUTURE: Duration = Duration::hours(1); + +/// Where a split page read divides: see the module docs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Split { + /// The recent pass reads at or above it; the older pass below it. + pub(crate) floor: DateTime, + /// The recent pass reads below it, when set. No row the read can match + /// sits at or above it. + pub(crate) ceiling: Option>, + /// Whether rows below the floor can match, so a short recent pass is + /// followed by the older pass. False when the read's own `since` is at + /// or above the floor: the recent pass is then the whole read. + pub(crate) older: bool, +} + +/// The `created_at` range one pass of a page read covers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Range { + /// Every row: the read is not split. + All, + /// `created_at >= floor`, and `created_at < ceiling` when set. + Recent(Split), + /// `created_at < floor`. + Older(DateTime), +} + +impl Range { + /// The range as a SQL predicate on `column` (` AND …`), or `None` for + /// [`Range::All`]. + /// + /// The bounds are literals, not binds: Postgres prunes partitions on a + /// literal while it plans, including in a cached generic plan, while a + /// generic plan with a bind parameter prunes only at execution, after it + /// has locked every partition. The text is chrono's fixed-format + /// rendering of a UTC timestamp, digits and separators only, so it + /// carries no caller input. + pub(crate) fn predicate(self, column: &str) -> Option { + let bound = |op: &str, at: DateTime| { + format!( + " AND {column} {op} '{}'::timestamptz", + at.format("%Y-%m-%dT%H:%M:%SZ") + ) + }; + match self { + Range::All => None, + Range::Recent(split) => { + let ceiling = split.ceiling.map(|c| bound("<", c)); + Some(bound(">=", split.floor) + ceiling.as_deref().unwrap_or("")) + } + Range::Older(floor) => Some(bound("<", floor)), + } + } +} + +/// 00:00 UTC on the first day of the month `offset` months from `at`'s. +fn month_start(at: DateTime, offset: i32) -> DateTime { + let months = at.year() * 12 + at.month0() as i32 + offset; + Utc.with_ymd_and_hms( + months.div_euclid(12), + months.rem_euclid(12) as u32 + 1, + 1, + 0, + 0, + 0, + ) + .single() + .unwrap_or(DateTime::::MIN_UTC) +} + +/// The floor at `now`: 00:00 UTC on the first day of the previous month, so +/// the recent pass reads the current and previous monthly partitions. +pub(crate) fn floor_at(now: DateTime) -> DateTime { + month_start(now, -1) +} + +/// The ceiling at `now`: 00:00 UTC on the first day of the month after +/// `now` + [`MAX_FUTURE`], so the recent pass of a regular-kind read plans +/// only the previous and current monthly partitions (and the next one in the +/// last hour of a month). +pub(crate) fn ceiling_at(now: DateTime) -> DateTime { + month_start(now + MAX_FUTURE, 1) +} + +/// Where to split a page read, or `None` to read it whole: its own bounds +/// already exclude everything newer than the floor, or its rows are +/// latest-state records that rarely fill a page above the floor, so a split +/// would only add a second statement. A read whose `since` is at or above the +/// floor gets a recent pass with no older pass after it (see the module +/// docs), whatever its kinds. The recent pass has a ceiling only when every +/// kind is regular (see [`MAX_FUTURE`]). +/// +/// `kinds` are the read's kinds (`None`: any); `since`/`until` its bounds. +pub(crate) fn split_for( + now: DateTime, + kinds: Option<&[i32]>, + since: Option>, + until: Option>, +) -> Option { + let floor = floor_at(now); + // Replaceable and addressable rows are latest-state records, often months + // old, and few per author. + let latest_state = |k: i32| { + u32::try_from(k).is_ok_and(|k| is_replaceable(k) || is_parameterized_replaceable(k)) + }; + let kinds = kinds.filter(|ks| !ks.is_empty()); + let latest_state_only = kinds.is_some_and(|ks| ks.iter().all(|&k| latest_state(k))); + let regular_only = kinds.is_some_and(|ks| !ks.iter().any(|&k| latest_state(k))); + let since_prunes = since.is_some_and(|s| s >= floor); + let until_before_floor = until.is_some_and(|u| u < floor); + let split = |older| Split { + floor, + ceiling: regular_only.then(|| ceiling_at(now)), + older, + }; + if since_prunes { + return (!until_before_floor).then(|| split(false)); + } + (!latest_state_only && !until_before_floor).then(|| split(true)) +} + +/// The pass to run after `range` once the read holds `found` of its `limit` +/// rows, with that pass's limit: the older pass for the rows still missing +/// after a short recent pass, otherwise none. `limit` is the SQL `LIMIT`. +pub(crate) fn next(range: Range, found: usize, limit: i64) -> Option<(Range, i64)> { + let Range::Recent(split) = range else { + return None; + }; + let found = i64::try_from(found).unwrap_or(i64::MAX); + (split.older && found < limit).then(|| (Range::Older(split.floor), limit - found)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(y: i32, m: u32, d: u32) -> DateTime { + Utc.with_ymd_and_hms(y, m, d, 12, 34, 56).single().unwrap() + } + + fn midnight(y: i32, m: u32, d: u32) -> DateTime { + Utc.with_ymd_and_hms(y, m, d, 0, 0, 0).single().unwrap() + } + + #[test] + fn floor_is_the_start_of_the_previous_month() { + assert_eq!(floor_at(at(2026, 11, 4)), midnight(2026, 10, 1)); + assert_eq!(floor_at(at(2026, 11, 30)), midnight(2026, 10, 1)); + assert_eq!(floor_at(at(2027, 1, 1)), midnight(2026, 12, 1)); + assert_eq!(floor_at(at(2026, 3, 31)), midnight(2026, 2, 1)); + } + + /// The ceiling is the start of the next month, or of the one after once + /// `now` + [`MAX_FUTURE`] reaches the next month: a row the relay can + /// still accept is always below it. + #[test] + fn ceiling_is_the_start_of_the_next_month_after_max_future() { + let ceiling = ceiling_at; + assert_eq!(ceiling(at(2026, 11, 4)), midnight(2026, 12, 1)); + assert_eq!(ceiling(midnight(2026, 11, 1)), midnight(2026, 12, 1)); + assert_eq!(ceiling(at(2026, 12, 31)), midnight(2027, 1, 1)); + let month_end = midnight(2026, 12, 1); + let second = Duration::seconds(1); + assert_eq!( + ceiling(month_end - MAX_FUTURE - second), + month_end, + "before the margin" + ); + assert_eq!( + ceiling(month_end - MAX_FUTURE), + midnight(2027, 1, 1), + "inside the margin" + ); + assert_eq!( + ceiling(midnight(2026, 12, 31) + Duration::hours(23)), + midnight(2027, 2, 1) + ); + for now in [at(2026, 11, 4), month_end - second, midnight(2026, 12, 31)] { + assert!(ceiling(now) > now + MAX_FUTURE, "{now}"); + } + } + + #[test] + fn predicates_are_fixed_utc_literals() { + let floor = midnight(2026, 10, 1); + let split = Split { + floor, + ceiling: Some(midnight(2026, 12, 1)), + older: true, + }; + assert_eq!(Range::All.predicate("e.created_at"), None); + assert_eq!( + Range::Recent(split).predicate("e.created_at").as_deref(), + Some( + " AND e.created_at >= '2026-10-01T00:00:00Z'::timestamptz \ + AND e.created_at < '2026-12-01T00:00:00Z'::timestamptz" + ) + ); + let open = Split { + ceiling: None, + ..split + }; + assert_eq!( + Range::Recent(open).predicate("e.created_at").as_deref(), + Some(" AND e.created_at >= '2026-10-01T00:00:00Z'::timestamptz") + ); + assert_eq!( + Range::Older(floor).predicate("created_at").as_deref(), + Some(" AND created_at < '2026-10-01T00:00:00Z'::timestamptz") + ); + } + + /// Which reads are split, which recent passes stop at the ceiling, and + /// which are the whole read: (kinds, since, until) → `WHOLE` (not split), + /// `CEILED` or `OPEN` (recent pass, then the older pass if short), or + /// `CEILED_ONLY` or `OPEN_ONLY` (recent pass, no older pass). + #[test] + fn split_eligibility() { + // (ceiled, older) + const WHOLE: Option<(bool, bool)> = None; + const CEILED: Option<(bool, bool)> = Some((true, true)); + const OPEN: Option<(bool, bool)> = Some((false, true)); + const CEILED_ONLY: Option<(bool, bool)> = Some((true, false)); + const OPEN_ONLY: Option<(bool, bool)> = Some((false, false)); + let now = at(2026, 11, 4); + let floor = floor_at(now); + let day = Duration::days(1); + // (label, kinds, since, until, outcome) + type Case<'a> = ( + &'a str, + Option<&'a [i32]>, + Option>, + Option>, + Option<(bool, bool)>, + ); + let cases: &[Case] = &[ + ("unbounded messages", Some(&[9, 40002]), None, None, CEILED), + ("any kind", None, None, None, OPEN), + ("no kinds listed", Some(&[]), None, None, OPEN), + ( + "since older than the floor", + Some(&[9]), + Some(floor - day), + None, + CEILED, + ), + ( + "since at the floor", + Some(&[9]), + Some(floor), + None, + CEILED_ONLY, + ), + ( + "recent since", + Some(&[9]), + Some(now - day), + None, + CEILED_ONLY, + ), + ( + "recent since, any kind", + None, + Some(now - day), + None, + OPEN_ONLY, + ), + ( + "recent since, addressable only", + Some(&[39002]), + Some(now - day), + None, + OPEN_ONLY, + ), + ( + "recent since, until before the floor", + Some(&[9]), + Some(now - day), + Some(floor - day), + WHOLE, + ), + ("until at the floor", Some(&[9]), None, Some(floor), CEILED), + ( + "until before the floor", + Some(&[9]), + None, + Some(floor - day), + WHOLE, + ), + ("replaceable only", Some(&[0, 10002]), None, None, WHOLE), + ("addressable only", Some(&[39002]), None, None, WHOLE), + ( + "mixed with an addressable kind", + Some(&[39002, 9]), + None, + None, + OPEN, + ), + ( + "mixed with a replaceable kind", + Some(&[9, 13534]), + None, + None, + OPEN, + ), + ( + "negative kind is not replaceable", + Some(&[-1]), + None, + None, + CEILED, + ), + ]; + for &(label, kinds, since, until, outcome) in cases { + let expected = outcome.map(|(ceiled, older)| Split { + floor, + ceiling: ceiled.then(|| ceiling_at(now)), + older, + }); + assert_eq!(split_for(now, kinds, since, until), expected, "{label}"); + } + } + + /// The passes against an in-memory table of `created_at` values, newest + /// first, driven the way the stores drive them: the newest `limit` rows, + /// in order, for every limit, split or not, reading each row at most once. + #[test] + fn passes_return_the_newest_rows_and_read_each_row_once() { + let day = Duration::days(1); + let floor = midnight(2026, 10, 1); + let ceiling = midnight(2026, 12, 1); + // Four at or above the floor (one exactly at it, one a second below + // the ceiling), two below. No row sits at or above the ceiling. + let table = [ + ceiling - Duration::seconds(1), + floor + day * 3, + floor + day, + floor, + floor - day, + floor - day * 9, + ]; + let recent = 4; + for limit in 0..=table.len() as i64 + 1 { + let expected: Vec<_> = table.iter().copied().take(limit as usize).collect(); + let ceiled = Split { + floor, + ceiling: Some(ceiling), + older: true, + }; + let open = Split { + ceiling: None, + ..ceiled + }; + // A read whose `since` is at or above the floor: only the rows + // at or above it match. + let since_floor = Split { + older: false, + ..ceiled + }; + for split in [None, Some(ceiled), Some(open), Some(since_floor)] { + let expected: Vec<_> = match split { + Some(s) if !s.older => { + expected.iter().copied().filter(|&t| t >= floor).collect() + } + _ => expected.clone(), + }; + let mut passes = Vec::new(); + let mut rows = Vec::new(); + let mut pass = Some((split.map_or(Range::All, Range::Recent), limit)); + while let Some((range, n)) = pass { + passes.push((range, n)); + rows.extend( + table + .iter() + .copied() + .filter(|&t| match range { + Range::All => true, + Range::Recent(s) => s.floor <= t && s.ceiling.is_none_or(|c| t < c), + Range::Older(f) => t < f, + }) + .take(n as usize), + ); + pass = next(range, rows.len(), limit); + } + assert_eq!(rows, expected, "split {split:?}, limit {limit}"); + let expected_passes = match split { + None => vec![(Range::All, limit)], + Some(s) if limit <= recent || !s.older => vec![(Range::Recent(s), limit)], + Some(s) => vec![ + (Range::Recent(s), limit), + (Range::Older(s.floor), limit - recent), + ], + }; + assert_eq!(passes, expected_passes, "split {split:?}, limit {limit}"); + } + } + } +} diff --git a/crates/buzz-db/src/store/relay_admin_actions.rs b/crates/buzz-db/src/store/relay_admin_actions.rs index 6c819d3d245..fc2fb32c987 100644 --- a/crates/buzz-db/src/store/relay_admin_actions.rs +++ b/crates/buzz-db/src/store/relay_admin_actions.rs @@ -473,8 +473,9 @@ pub async fn execute_ban_with_marker( crate::observability::WriterOperation::Authorization, ) .await?; + crate::relay_invite::lock_admission(tx.conn(), community_id).await?; - // Verify lease ownership first — abort without touching domain rows if the + // Verify lease ownership before domain writes — abort if the // lease is already gone. This prevents the commit entirely on a stale worker. let owned: bool = sqlx::query_scalar( r#" @@ -523,6 +524,9 @@ pub async fn execute_ban_with_marker( .execute(tx.conn()) .await?; + crate::relay_invite::revoke_banned_issuer_invites(tx.conn(), community_id, target_pubkey) + .await?; + let marker = sqlx::query( r#" UPDATE relay_admin_actions @@ -569,6 +573,7 @@ pub async fn execute_timeout_with_marker( crate::observability::WriterOperation::Authorization, ) .await?; + crate::relay_invite::lock_admission(tx.conn(), community_id).await?; let owned: bool = sqlx::query_scalar( r#" @@ -616,6 +621,9 @@ pub async fn execute_timeout_with_marker( .execute(tx.conn()) .await?; + crate::relay_invite::revoke_banned_issuer_invites(tx.conn(), community_id, target_pubkey) + .await?; + let marker = sqlx::query( r#" UPDATE relay_admin_actions @@ -713,7 +721,7 @@ pub async fn execute_kick_with_marker( let kick = sqlx::query( r#" UPDATE channel_members - SET removed_at = NOW(), removed_by = $1 + SET removed_at = clock_timestamp(), sync_modified_at = clock_timestamp(), removed_by = $1 WHERE community_id = $2 AND channel_id = $3 AND pubkey = $4 AND removed_at IS NULL "#, ) @@ -803,16 +811,35 @@ pub async fn execute_delete_with_marker( .fetch_optional(tx.conn()) .await?; + // NIP-AR: an artifact revision leaves current state only through its own + // `op=delete` or a kind-9005 redaction. Both are fanned out, so open syncs + // see them; this delete would retire a head with no live signal. + let target: Option<(i32, chrono::DateTime)> = + sqlx::query_as("SELECT kind, created_at FROM events WHERE community_id = $1 AND id = $2") + .bind(community_id.as_uuid()) + .bind(target_event_id) + .fetch_optional(tx.conn()) + .await?; + if target.is_some_and(|(kind, _)| kind == 45010) { + return Err(crate::error::DbError::InvalidData( + "artifact revisions cannot be deleted by admin action; use op=delete or kind 9005 redaction" + .into(), + )); + } + // Canonical delete + thread_metadata counters, fenced by this transaction. // Counters move only when the row transitions to deleted, so a second // action against an already-deleted target leaves them unchanged. - crate::event::soft_delete_event_and_update_thread_in_tx( - &mut tx, - target_event_id, - parent_event_id, - root_event_id, - ) - .await?; + if let Some((_, created_at)) = target { + crate::event::soft_delete_event_and_update_thread_in_tx( + &mut tx, + target_event_id, + Some(created_at), + parent_event_id, + root_event_id, + ) + .await?; + } let marker = sqlx::query( r#" @@ -1705,7 +1732,7 @@ pub async fn deploy_kick_member( let result = sqlx::query( r#" UPDATE channel_members - SET removed_at = NOW(), removed_by = $1 + SET removed_at = clock_timestamp(), sync_modified_at = clock_timestamp(), removed_by = $1 WHERE community_id = $2 AND channel_id = $3 AND pubkey = $4 AND removed_at IS NULL "#, ) diff --git a/crates/buzz-db/src/store/relay_invite.rs b/crates/buzz-db/src/store/relay_invite.rs index 242fe42a841..327beb32ab3 100644 --- a/crates/buzz-db/src/store/relay_invite.rs +++ b/crates/buzz-db/src/store/relay_invite.rs @@ -30,6 +30,11 @@ use crate::error::Result; use crate::relay_members::{write_nip43_membership_snapshot, MembershipWrite}; use crate::{CommunityId, Db}; +mod claim_owner; +mod revocation; +pub use claim_owner::{claim_relay_membership_with_owner, MembershipClaimResult}; +pub(crate) use revocation::{revoke_banned_issuer_invites, revoke_restricted_agent_invites}; + /// Outcome of a v2 invite claim. Expected invalid/expired/exhausted states are /// typed variants so the relay layer can map them to distinct HTTP responses /// without inspecting database errors. @@ -56,6 +61,32 @@ pub enum ClaimOutcome { Exhausted, /// No invite row matches `(community_id, token_hash)`. Invalid, + /// The issuer's invitation was permanently revoked. + Revoked, + /// The issuer or its owner is currently banned or timed out. + IssuerRestricted, + /// The claimant or its verified owner is banned or timed out. + Restricted, +} + +/// A completed claim and whether its committed transaction first recorded an owner. +pub struct InviteClaimResult { + /// Membership or denial outcome. + pub outcome: ClaimOutcome, + /// Notify ownerless sockets only after a successful commit created the link. + pub owner_link_created: bool, + /// User rows first created by this successful transaction. + pub users_created: u64, +} + +impl From for InviteClaimResult { + fn from(outcome: ClaimOutcome) -> Self { + Self { + outcome, + owner_link_created: false, + users_created: 0, + } + } } /// A freshly minted v2 invite, including the plaintext code and metadata. @@ -93,6 +124,13 @@ fn validate_mint_inputs(ttl_secs: u64, max_uses: Option) -> Result<()> { Ok(()) } +fn is_canonical_invite_pubkey(pubkey: &str) -> bool { + pubkey.len() == 64 + && pubkey + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + /// Mint a v2 invite: generate a 32-byte random secret, hash it, persist the /// row, and return the plaintext code plus metadata. /// @@ -104,8 +142,40 @@ pub async fn mint_relay_invite( created_by: &str, ttl_secs: u64, max_uses: Option, +) -> Result { + mint(pool, community, created_by, ttl_secs, max_uses, false).await +} + +/// Like [`mint_relay_invite`], but refuses with +/// [`DbError::InviteIssuerNotAdmin`](crate::DbError::InviteIssuerNotAdmin) +/// unless `created_by` is an owner or admin inside the mint transaction. The +/// role row is held `FOR SHARE` through commit, so a concurrent demotion, +/// removal or ownership transfer either lands first and refuses this mint or +/// waits for it. +pub async fn mint_relay_invite_as_admin( + pool: &PgPool, + community: CommunityId, + created_by: &str, + ttl_secs: u64, + max_uses: Option, +) -> Result { + mint(pool, community, created_by, ttl_secs, max_uses, true).await +} + +async fn mint( + pool: &PgPool, + community: CommunityId, + created_by: &str, + ttl_secs: u64, + max_uses: Option, + require_admin: bool, ) -> Result { validate_mint_inputs(ttl_secs, max_uses)?; + if !is_canonical_invite_pubkey(created_by) { + return Err(crate::error::DbError::InvalidData( + "invalid invitation issuer".into(), + )); + } // Generate 32 random bytes and encode as base64url — this is the secret. let secret: [u8; V2_SECRET_LEN] = rand::random(); @@ -124,9 +194,27 @@ pub async fn mint_relay_invite( crate::observability::WriterOperation::Authorization, ) .await?; + lock_admission(tx.conn(), community).await?; + if require_admin { + let role: Option = sqlx::query_scalar( + "SELECT role FROM relay_members \ + WHERE community_id = $1 AND pubkey = $2 FOR SHARE", + ) + .bind(community.as_uuid()) + .bind(created_by) + .fetch_optional(tx.conn()) + .await?; + if !matches!(role.as_deref(), Some("owner" | "admin")) { + return Err(crate::DbError::InviteIssuerNotAdmin); + } + } + if principal_restricted(tx.conn(), community, created_by).await? { + return Err(crate::DbError::InviteRestricted); + } let row = sqlx::query( - "INSERT INTO relay_invites (community_id, token_hash, max_uses, expires_at, created_by) \ - VALUES ($1, $2, $3, $4, $5) \ + "INSERT INTO relay_invites \ + (community_id, token_hash, max_uses, expires_at, created_by, legacy_admission) \ + VALUES ($1, $2, $3, $4, $5, false) \ RETURNING id", ) .bind(community.as_uuid()) @@ -149,6 +237,95 @@ pub async fn mint_relay_invite( }) } +/// Lock invitation admission against community restriction and owner writes. +/// Call before reading restrictions or locking an invite row, and hold to commit. +/// A joined claim holds it through its NIP-43 membership snapshot, so mint, ban, +/// timeout and first owner link wait for that snapshot, which grows with the +/// member count. Claims reject unknown codes before taking it. +pub(crate) async fn lock_admission( + tx: &mut sqlx::PgConnection, + community: CommunityId, +) -> Result<()> { + sqlx::query( + "SELECT pg_advisory_xact_lock(\ + hashtextextended('invite-admission:' || $1::text, 0))", + ) + .bind(community.as_uuid()) + .execute(&mut *tx) + .await?; + Ok(()) +} + +/// Authoritative, transaction-local lookup; nonmembers need no user row. +pub(crate) async fn principal_restricted( + tx: &mut sqlx::PgConnection, + community: CommunityId, + pubkey: &str, +) -> Result { + if !is_canonical_invite_pubkey(pubkey) { + return Err(crate::DbError::InvalidData( + "invalid invitation principal".into(), + )); + } + let bytes = hex::decode(pubkey) + .map_err(|_| crate::DbError::InvalidData("invalid invitation principal".into()))?; + Ok(sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM community_bans \ + WHERE community_id = $1 AND pubkey IN (\ + SELECT $2::bytea UNION ALL \ + SELECT agent_owner_pubkey FROM users WHERE community_id = $1 AND pubkey = $2\ + ) AND ((banned AND (ban_expires_at IS NULL OR ban_expires_at > clock_timestamp())) \ + OR muted_until > clock_timestamp()))", + ) + .bind(community.as_uuid()) + .bind(bytes) + .fetch_one(&mut *tx) + .await?) +} + +/// Whether a restriction row permanently revokes an invite from this principal. +/// Unrepaired legacy rows treat every retained restriction as history; the +/// maintenance repair clears that marker after its historical decision. New +/// and repaired rows only treat a currently active ban as permanent revocation. +async fn has_revoking_restriction( + tx: &mut sqlx::PgConnection, + community: CommunityId, + pubkey: &[u8], + legacy_admission: bool, +) -> Result { + Ok(sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM community_bans restriction \ + WHERE restriction.community_id = $1 \ + AND (restriction.pubkey = $2 OR restriction.pubkey = ( \ + SELECT agent_owner_pubkey FROM users \ + WHERE community_id = $1 AND pubkey = $2)) \ + AND ($3 OR (restriction.banned \ + AND (restriction.ban_expires_at IS NULL \ + OR restriction.ban_expires_at > clock_timestamp()))))", + ) + .bind(community.as_uuid()) + .bind(pubkey) + .bind(legacy_admission) + .fetch_one(&mut *tx) + .await?) +} + +async fn persist_claim_revocation( + tx: &mut sqlx::PgConnection, + community: CommunityId, + invite_id: uuid::Uuid, +) -> Result<()> { + sqlx::query( + "UPDATE relay_invites SET revoked_at = clock_timestamp() \ + WHERE community_id = $1 AND id = $2 AND revoked_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(invite_id) + .execute(&mut *tx) + .await?; + Ok(()) +} + fn log_claim_outcome( community: CommunityId, invite_id: Option, @@ -258,6 +435,34 @@ pub async fn claim_relay_invite( policy_version: Option<&str>, relay_keypair: &nostr::Keys, ) -> Result> { + let write = claim_relay_invite_with_owner( + pool, + community, + token_hash, + claimer_pubkey, + policy_version, + None, + relay_keypair, + ) + .await?; + Ok(MembershipWrite { + outcome: write.outcome.outcome, + snapshot: write.snapshot, + }) +} + +/// Claim an invite with a caller-verified owner while keeping restriction checks, +/// owner persistence, membership, policy evidence, invite consumption, and the +/// NIP-43 membership snapshot in one admitted transaction. +pub async fn claim_relay_invite_with_owner( + pool: &PgPool, + community: CommunityId, + token_hash: &[u8; 32], + claimer_pubkey: &str, + policy_version: Option<&str>, + verified_owner: Option<&str>, + relay_keypair: &nostr::Keys, +) -> Result> { let mut tx = crate::begin_community_write_transaction( pool, community, @@ -265,9 +470,36 @@ pub async fn claim_relay_invite( ) .await?; - // 2. SELECT FOR UPDATE — lock the invite row for the duration of this txn. + // Unknown codes are free to forge, so reject them after the tenant fence + // but before the community-wide admission lock; the locked read below + // stays authoritative. + let known: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM relay_invites \ + WHERE community_id = $1 AND token_hash = $2)", + ) + .bind(community.as_uuid()) + .bind(token_hash) + .fetch_one(tx.conn()) + .await?; + if !known { + tx.rollback().await?; + log_claim_outcome(community, None, "invalid", None, None); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Invalid.into())); + } + + lock_admission(tx.conn(), community).await?; + if claim_owner::claimant_restricted(tx.conn(), community, claimer_pubkey, verified_owner) + .await? + { + tx.rollback().await?; + log_claim_outcome(community, None, "restricted", None, None); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Restricted.into())); + } + + // `FOR UPDATE` serializes concurrent claims so exactly one claimant wins + // the final slot, while admission serializes issuer/owner restriction changes. let row = sqlx::query( - "SELECT id, max_uses, use_count, expires_at \ + "SELECT id, max_uses, use_count, expires_at, created_by, revoked_at, legacy_admission \ FROM relay_invites \ WHERE community_id = $1 AND token_hash = $2 \ FOR UPDATE", @@ -277,21 +509,16 @@ pub async fn claim_relay_invite( .fetch_optional(tx.conn()) .await?; - // 3. No matching invite. let Some(invite) = row else { tx.rollback().await?; log_claim_outcome(community, None, "invalid", None, None); - return Ok(MembershipWrite::unchanged(ClaimOutcome::Invalid)); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Invalid.into())); }; let invite_id: uuid::Uuid = invite.try_get("id")?; let max_uses: Option = invite.try_get("max_uses")?; let use_count: i32 = invite.try_get("use_count")?; let expires_at: DateTime = invite.try_get("expires_at")?; - - // Expiry is checked before membership deliberately. An expired bearer must - // not authorize fresh policy-acceptance evidence, even for an existing - // member; exhausted-but-live invites remain valid for idempotent retries. if expires_at <= Utc::now() { tx.rollback().await?; log_claim_outcome( @@ -301,12 +528,76 @@ pub async fn claim_relay_invite( max_uses, Some(use_count), ); - return Ok(MembershipWrite::unchanged(ClaimOutcome::Expired)); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Expired.into())); } - let uses_remaining = || max_uses.map(|mu| mu - use_count); + let revoked_at: Option> = invite.try_get("revoked_at")?; + let issuer: String = invite.try_get("created_by")?; + let legacy_admission: bool = invite.try_get("legacy_admission")?; + if revoked_at.is_some() { + tx.rollback().await?; + log_claim_outcome( + community, + Some(invite_id), + "revoked", + max_uses, + Some(use_count), + ); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Revoked.into())); + } + if !is_canonical_invite_pubkey(&issuer) { + if legacy_admission { + persist_claim_revocation(tx.conn(), community, invite_id).await?; + tx.commit().await?; + log_claim_outcome( + community, + Some(invite_id), + "revoked", + max_uses, + Some(use_count), + ); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Revoked.into())); + } + tx.rollback().await?; + log_claim_outcome( + community, + Some(invite_id), + "invalid", + max_uses, + Some(use_count), + ); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Invalid.into())); + } + + let issuer_bytes = hex::decode(&issuer) + .map_err(|_| crate::DbError::InvalidData("invalid invitation issuer".into()))?; + if has_revoking_restriction(tx.conn(), community, &issuer_bytes, legacy_admission).await? { + persist_claim_revocation(tx.conn(), community, invite_id).await?; + tx.commit().await?; + log_claim_outcome( + community, + Some(invite_id), + "revoked", + max_uses, + Some(use_count), + ); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Revoked.into())); + } + if principal_restricted(tx.conn(), community, &issuer).await? { + tx.rollback().await?; + log_claim_outcome( + community, + Some(invite_id), + "issuer_restricted", + max_uses, + Some(use_count), + ); + return Ok(MembershipWrite::unchanged( + ClaimOutcome::IssuerRestricted.into(), + )); + } - // 5. Check existing membership. + let uses_remaining = || max_uses.map(|mu| mu - use_count); let existing = sqlx::query("SELECT 1 FROM relay_members WHERE community_id = $1 AND pubkey = $2") .bind(community.as_uuid()) @@ -315,7 +606,6 @@ pub async fn claim_relay_invite( .await?; if existing.is_some() { - // 6. Already a member — insert policy evidence but do NOT increment. if let Some(version) = policy_version { sqlx::query( "INSERT INTO join_policy_acceptances (community_id, pubkey, policy_version) \ @@ -327,6 +617,9 @@ pub async fn claim_relay_invite( .execute(tx.conn()) .await?; } + let owner = + claim_owner::persist_claim_owner(tx.conn(), community, claimer_pubkey, verified_owner) + .await?; tx.commit().await?; log_claim_outcome( community, @@ -335,33 +628,31 @@ pub async fn claim_relay_invite( max_uses, Some(use_count), ); - return Ok(MembershipWrite::unchanged(ClaimOutcome::AlreadyMember { - use_count, - uses_remaining: uses_remaining(), + return Ok(MembershipWrite::unchanged(InviteClaimResult { + outcome: ClaimOutcome::AlreadyMember { + use_count, + uses_remaining: uses_remaining(), + }, + owner_link_created: owner.link_created, + users_created: owner.users_created, })); } - // 7. Capacity check. - if let Some(mu) = max_uses { - if use_count >= mu { - tx.rollback().await?; - log_claim_outcome( - community, - Some(invite_id), - "exhausted", - max_uses, - Some(use_count), - ); - return Ok(MembershipWrite::unchanged(ClaimOutcome::Exhausted)); - } + if max_uses.is_some_and(|max_uses| use_count >= max_uses) { + tx.rollback().await?; + log_claim_outcome( + community, + Some(invite_id), + "exhausted", + max_uses, + Some(use_count), + ); + return Ok(MembershipWrite::unchanged(ClaimOutcome::Exhausted.into())); } - // 8. Insert relay member. The conflict branch covers a claimant admitted - // concurrently through a different invite: only the transaction that - // actually inserted membership may consume this invite. let inserted = sqlx::query( - "INSERT INTO relay_members (community_id, pubkey, role, added_by) \ - VALUES ($1, $2, 'member', 'invite') \ + "INSERT INTO relay_members (community_id, pubkey, role, added_by, auto_join_pending) \ + VALUES ($1, $2, 'member', 'invite', gen_random_uuid()) \ ON CONFLICT (community_id, pubkey) DO NOTHING", ) .bind(community.as_uuid()) @@ -371,8 +662,6 @@ pub async fn claim_relay_invite( .rows_affected() > 0; - // 9. Insert join-policy acceptance evidence. This is required for both a - // new member and a claimant whose concurrent membership insert won first. if let Some(version) = policy_version { sqlx::query( "INSERT INTO join_policy_acceptances (community_id, pubkey, policy_version) \ @@ -386,6 +675,9 @@ pub async fn claim_relay_invite( } if !inserted { + let owner = + claim_owner::persist_claim_owner(tx.conn(), community, claimer_pubkey, verified_owner) + .await?; tx.commit().await?; log_claim_outcome( community, @@ -394,13 +686,16 @@ pub async fn claim_relay_invite( max_uses, Some(use_count), ); - return Ok(MembershipWrite::unchanged(ClaimOutcome::AlreadyMember { - use_count, - uses_remaining: uses_remaining(), + return Ok(MembershipWrite::unchanged(InviteClaimResult { + outcome: ClaimOutcome::AlreadyMember { + use_count, + uses_remaining: uses_remaining(), + }, + owner_link_created: owner.link_created, + users_created: owner.users_created, })); } - // 10. Increment use_count (for every new member, even unlimited). let new_use_count = use_count + 1; sqlx::query("UPDATE relay_invites SET use_count = $1 WHERE community_id = $2 AND id = $3") .bind(new_use_count) @@ -409,12 +704,13 @@ pub async fn claim_relay_invite( .execute(tx.conn()) .await?; - // 11. Write the membership list and commit. + let owner = + claim_owner::persist_claim_owner(tx.conn(), community, claimer_pubkey, verified_owner) + .await?; let snapshot = write_nip43_membership_snapshot(&mut tx, relay_keypair).await?; tx.commit().await?; let new_uses_remaining = max_uses.map(|mu| mu - new_use_count); - log_claim_outcome( community, Some(invite_id), @@ -424,29 +720,57 @@ pub async fn claim_relay_invite( ); Ok(MembershipWrite { - outcome: ClaimOutcome::Joined { - use_count: new_use_count, - uses_remaining: new_uses_remaining, + outcome: InviteClaimResult { + outcome: ClaimOutcome::Joined { + use_count: new_use_count, + uses_remaining: new_uses_remaining, + }, + owner_link_created: owner.link_created, + users_created: owner.users_created, }, snapshot: Some(snapshot), }) } impl Db { - /// Mints a v2 use-limited relay invite. The plaintext code is returned - /// exactly once; only its SHA-256 hash is persisted. + /// Mints a v2 use-limited relay invite for an owner or admin; see + /// [`mint_relay_invite_as_admin`]. The plaintext code is returned exactly + /// once; only its SHA-256 hash is persisted. /// /// `max_uses` is `None` for unlimited or `Some(1..=10000)`. /// `ttl_secs` must be in the shared invite lifetime range. #[datastore_span(name = "mint_relay_invite", system = "postgresql")] - pub async fn mint_relay_invite( + pub async fn mint_relay_invite_as_admin( &self, community: CommunityId, created_by: &str, ttl_secs: u64, max_uses: Option, ) -> Result { - mint_relay_invite(&self.pool, community, created_by, ttl_secs, max_uses).await + mint_relay_invite_as_admin(&self.pool, community, created_by, ttl_secs, max_uses).await + } + + /// Claim an invite and persist caller-verified ownership atomically. + #[datastore_span(name = "claim_relay_invite_with_owner", system = "postgresql")] + pub async fn claim_relay_invite_with_owner( + &self, + community: CommunityId, + token_hash: &[u8; 32], + claimer_pubkey: &str, + policy_version: Option<&str>, + verified_owner: Option<&str>, + relay_keypair: &nostr::Keys, + ) -> Result> { + claim_relay_invite_with_owner( + &self.pool, + community, + token_hash, + claimer_pubkey, + policy_version, + verified_owner, + relay_keypair, + ) + .await } /// Delete one bounded batch of invites expired before `cutoff`. @@ -485,46 +809,18 @@ impl Db { mod postgres_tests { use super::*; use crate::relay_members::is_relay_member; + use crate::test_support::ScratchDb; use sha2::Digest; use sqlx::PgPool; use uuid::Uuid; - async fn setup_pool() -> PgPool { + pub(super) async fn setup_pool() -> PgPool { PgPool::connect(&crate::test_support::database_url()) .await .expect("connect to test DB") } - async fn create_scratch_database(prefix: &str) -> (PgPool, String, String) { - let admin_url = crate::test_support::database_url(); - let admin = PgPool::connect(&admin_url) - .await - .expect("connect to test database server"); - let name = format!("{}_{}", prefix, Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(&admin) - .await - .expect("create scratch database"); - let path_start = admin_url - .rfind('/') - .expect("database URL has a path segment"); - let scratch_url = format!("{}/{}", &admin_url[..path_start], name); - (admin, name, scratch_url) - } - - async fn drop_scratch_database(admin: PgPool, db: crate::Db, name: &str) { - db.pool.close().await; - drop(db); - sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(&admin) - .await - .expect("drop scratch database"); - admin.close().await; - } - - async fn make_test_community(pool: &PgPool) -> CommunityId { + pub(super) async fn make_test_community(pool: &PgPool) -> CommunityId { let id = Uuid::new_v4(); sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") .bind(id) @@ -561,11 +857,11 @@ mod postgres_tests { tx.commit().await.expect("commit test cleanup"); } - fn test_pubkey() -> String { + pub(super) fn test_pubkey() -> String { format!("{:064x}", Uuid::new_v4().as_u128()) } - async fn use_count(pool: &PgPool, community: CommunityId, invite_id: Uuid) -> i32 { + pub(super) async fn use_count(pool: &PgPool, community: CommunityId, invite_id: Uuid) -> i32 { sqlx::query_scalar( "SELECT use_count FROM relay_invites WHERE community_id = $1 AND id = $2", ) @@ -593,10 +889,10 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn mint_after_quiescing_returns_typed_fence_without_persisting() { - let (admin, database_name, database_url) = - create_scratch_database("relay_invite_fence").await; + let scratch = + ScratchDb::create(&crate::test_support::database_url(), "relay_invite_fence").await; let db = crate::Db::new(&crate::DbConfig { - database_url, + database_url: scratch.url().to_owned(), max_connections: 5, min_connections: 0, ..crate::DbConfig::default() @@ -613,7 +909,7 @@ mod postgres_tests { .expect("create fenced invite community") .id; let request = store - .submit(&host, "owner", None) + .submit(Some(&host), "owner", None, None) .await .expect("submit deletion request"); let empty_digest = hex::encode(sha2::Sha256::digest([])); @@ -661,7 +957,7 @@ mod postgres_tests { .await .expect("begin quiescing"); - let error = mint_relay_invite(&pool, community, "owner", 3600, Some(1)) + let error = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) .await .expect_err("quiescing must reject invite minting"); assert!(matches!(error, crate::error::DbError::AccessDenied(_))); @@ -673,10 +969,6 @@ mod postgres_tests { .await .expect("count relay invites"); assert_eq!(invite_count, 0, "rejected mint must not persist an invite"); - - drop(store); - drop(pool); - drop_scratch_database(admin, db, &database_name).await; } #[tokio::test] @@ -686,7 +978,7 @@ mod postgres_tests { let community = make_test_community(&pool).await; let first = test_pubkey(); let second = test_pubkey(); - let invite = mint_relay_invite(&pool, community, "owner", 3600, Some(1)) + let invite = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) .await .expect("mint bounded invite"); let hash = hash_v2_code(&invite.code); @@ -757,7 +1049,7 @@ mod postgres_tests { let community = make_test_community(&pool).await; let first = test_pubkey(); let second = test_pubkey(); - let invite = mint_relay_invite(&pool, community, "owner", 3600, Some(1)) + let invite = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) .await .expect("mint bounded invite"); let hash = hash_v2_code(&invite.code); @@ -806,7 +1098,7 @@ mod postgres_tests { let pool = setup_pool().await; let community_a = make_test_community(&pool).await; let community_b = make_test_community(&pool).await; - let invite = mint_relay_invite(&pool, community_a, "owner", 3600, Some(2)) + let invite = mint_relay_invite(&pool, community_a, &test_pubkey(), 3600, Some(2)) .await .expect("mint invite"); let hash = hash_v2_code(&invite.code); @@ -859,10 +1151,10 @@ mod postgres_tests { async fn retention_sweep_deletes_only_invites_older_than_cutoff() { let pool = setup_pool().await; let community = make_test_community(&pool).await; - let old = mint_relay_invite(&pool, community, "owner", 3600, Some(1)) + let old = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) .await .expect("mint old invite"); - let recent = mint_relay_invite(&pool, community, "owner", 3600, Some(1)) + let recent = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) .await .expect("mint recent invite"); let cutoff = Utc::now() - chrono::Duration::days(30); @@ -895,10 +1187,13 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn retention_sweep_skips_quiescing_tenant_while_active_bystanders_progress() { - let (admin, database_name, database_url) = - create_scratch_database("relay_invite_liveness").await; + let scratch = ScratchDb::create( + &crate::test_support::database_url(), + "relay_invite_liveness", + ) + .await; let db = crate::Db::new(&crate::DbConfig { - database_url, + database_url: scratch.url().to_owned(), max_connections: 5, min_connections: 0, ..crate::DbConfig::default() @@ -954,9 +1249,6 @@ mod postgres_tests { .await .expect("read remaining invite attribution"); assert_eq!(remaining, vec![*target.as_uuid()]); - - drop(pool); - drop_scratch_database(admin, db, &database_name).await; } #[tokio::test] @@ -964,7 +1256,7 @@ mod postgres_tests { async fn unlimited_invites_count_each_new_member() { let pool = setup_pool().await; let community = make_test_community(&pool).await; - let invite = mint_relay_invite(&pool, community, "owner", 3600, None) + let invite = mint_relay_invite(&pool, community, &test_pubkey(), 3600, None) .await .expect("mint unlimited invite"); let hash = hash_v2_code(&invite.code); @@ -998,7 +1290,7 @@ mod postgres_tests { let pool = setup_pool().await; let community = make_test_community(&pool).await; let pubkey = test_pubkey(); - let invite = mint_relay_invite(&pool, community, "owner", 3600, Some(1)) + let invite = mint_relay_invite(&pool, community, &test_pubkey(), 3600, Some(1)) .await .expect("mint bounded invite"); let hash = hash_v2_code(&invite.code); @@ -1037,3 +1329,16 @@ mod postgres_tests { delete_test_community(&pool, community).await; } } + +#[cfg(test)] +mod revocation_postgres_tests; + +#[cfg(test)] +#[path = "relay_invite/upgrade_postgres_tests.rs"] +mod upgrade_postgres_tests; + +#[cfg(test)] +mod owner_admission_postgres_tests; + +#[cfg(test)] +mod writer_protocol_postgres_tests; diff --git a/crates/buzz-db/src/store/relay_invite/claim_owner.rs b/crates/buzz-db/src/store/relay_invite/claim_owner.rs new file mode 100644 index 00000000000..a3106fc6bad --- /dev/null +++ b/crates/buzz-db/src/store/relay_invite/claim_owner.rs @@ -0,0 +1,158 @@ +use crate::error::Result; +use crate::{CommunityId, DbError}; +use sqlx::PgPool; + +/// Result of a committed legacy invitation claim. +pub struct MembershipClaimResult { + /// Whether this claim inserted membership. + pub inserted: bool, + /// Whether the same commit first recorded verified ownership. + pub owner_link_created: bool, + /// User rows first created by this successful transaction. + pub users_created: u64, +} + +/// Check existing and presented owner identities without creating a user row. +pub(super) async fn claimant_restricted( + tx: &mut sqlx::PgConnection, + community: CommunityId, + claimant: &str, + verified_owner: Option<&str>, +) -> Result { + if super::principal_restricted(tx, community, claimant).await? { + return Ok(true); + } + let Some(owner) = verified_owner else { + return Ok(false); + }; + if super::principal_restricted(tx, community, owner).await? { + return Ok(true); + } + let recorded: Option>> = sqlx::query_scalar( + "SELECT agent_owner_pubkey FROM users WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community.as_uuid()) + .bind( + hex::decode(claimant) + .map_err(|_| DbError::InvalidData("invalid invitation principal".into()))?, + ) + .fetch_optional(&mut *tx) + .await?; + let owner_bytes = + hex::decode(owner).map_err(|_| DbError::InvalidData("invalid invitation owner".into()))?; + if recorded + .flatten() + .is_some_and(|existing| existing != owner_bytes) + { + return Err(DbError::InviteOwnerMismatch); + } + Ok(false) +} + +#[derive(Default)] +pub(super) struct OwnerPersistence { + pub(super) link_created: bool, + pub(super) users_created: u64, +} + +/// Called only on an admitted claim, while the admission lock is still held. +pub(super) async fn persist_claim_owner( + tx: &mut sqlx::PgConnection, + community: CommunityId, + claimant: &str, + verified_owner: Option<&str>, +) -> Result { + let Some(owner) = verified_owner else { + return Ok(OwnerPersistence::default()); + }; + let owner_bytes = + hex::decode(owner).map_err(|_| DbError::InvalidData("invalid invitation owner".into()))?; + let claimant_bytes = hex::decode(claimant) + .map_err(|_| DbError::InvalidData("invalid invitation principal".into()))?; + let mut users_created = 0; + for key in [&owner_bytes, &claimant_bytes] { + users_created += sqlx::query( + "INSERT INTO users (community_id, pubkey) VALUES ($1, $2) ON CONFLICT DO NOTHING", + ) + .bind(community.as_uuid()) + .bind(key) + .execute(&mut *tx) + .await? + .rows_affected(); + } + let link_created = sqlx::query("UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2 AND agent_owner_pubkey IS NULL") + .bind(community.as_uuid()).bind(&claimant_bytes).bind(&owner_bytes).execute(&mut *tx).await?.rows_affected() > 0; + // Defense in depth: `claimant_restricted` already refused a banned owner + // under the same admission lock, so this finds nothing today. It keeps + // parity with every other owner writer if that check ever moves. + if link_created { + super::revoke_restricted_agent_invites(tx, community, &claimant_bytes, &owner_bytes) + .await?; + } + Ok(OwnerPersistence { + link_created, + users_created, + }) +} + +/// Atomically claim membership and caller-verified ownership after policy checks. +pub async fn claim_relay_membership_with_owner( + pool: &PgPool, + community: CommunityId, + pubkey: &str, + role: &str, + policy_version: Option<&str>, + verified_owner: Option<&str>, + relay_keypair: &nostr::Keys, +) -> Result> { + let mut tx = crate::begin_community_write_transaction( + pool, + community, + crate::observability::WriterOperation::Authorization, + ) + .await?; + super::lock_admission(tx.conn(), community).await?; + if claimant_restricted(tx.conn(), community, pubkey, verified_owner).await? { + return Err(DbError::InviteRestricted); + } + let inserted = sqlx::query( + "INSERT INTO relay_members (community_id, pubkey, role, added_by, auto_join_pending) \ + VALUES ($1, $2, $3, 'invite', gen_random_uuid()) \ + ON CONFLICT (community_id, pubkey) DO NOTHING", + ) + .bind(community.as_uuid()) + .bind(pubkey) + .bind(role) + .execute(tx.conn()) + .await? + .rows_affected() + > 0; + + if let Some(version) = policy_version { + sqlx::query( + "INSERT INTO join_policy_acceptances (community_id, pubkey, policy_version) \ + VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", + ) + .bind(community.as_uuid()) + .bind(pubkey) + .bind(version) + .execute(tx.conn()) + .await?; + } + + let owner = persist_claim_owner(tx.conn(), community, pubkey, verified_owner).await?; + let snapshot = if inserted { + Some(super::write_nip43_membership_snapshot(&mut tx, relay_keypair).await?) + } else { + None + }; + tx.commit().await?; + Ok(super::MembershipWrite { + outcome: MembershipClaimResult { + inserted, + owner_link_created: owner.link_created, + users_created: owner.users_created, + }, + snapshot, + }) +} diff --git a/crates/buzz-db/src/store/relay_invite/owner_admission_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/owner_admission_postgres_tests.rs new file mode 100644 index 00000000000..ead36ec4b0a --- /dev/null +++ b/crates/buzz-db/src/store/relay_invite/owner_admission_postgres_tests.rs @@ -0,0 +1,182 @@ +use super::revocation_postgres_tests::claim_relay_invite_outcome; +use super::*; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn failed_policy_evidence_rolls_back_verified_owner_and_membership() { + let pool = postgres_tests::setup_pool().await; + let community = postgres_tests::make_test_community(&pool).await; + let claimant = postgres_tests::test_pubkey(); + let owner = postgres_tests::test_pubkey(); + let invite = mint_relay_invite( + &pool, + community, + &postgres_tests::test_pubkey(), + 3600, + Some(1), + ) + .await + .unwrap(); + assert!(claim_relay_invite_with_owner( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + Some("too-short"), + Some(&owner), + &nostr::Keys::generate() + ) + .await + .is_err()); + assert!(claim_relay_membership_with_owner( + &pool, + community, + &claimant, + "member", + Some("too-short"), + Some(&owner), + &nostr::Keys::generate() + ) + .await + .is_err()); + let users: i64 = sqlx::query_scalar("SELECT count(*) FROM users WHERE community_id=$1") + .bind(community.as_uuid()) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(users, 0); + assert!( + !crate::relay_members::is_relay_member(&pool, community, &claimant) + .await + .unwrap() + ); + assert_eq!( + postgres_tests::use_count(&pool, community, invite.invite_id).await, + 0 + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn successful_claim_reports_only_committed_user_creation() { + let pool = postgres_tests::setup_pool().await; + let community = postgres_tests::make_test_community(&pool).await; + let claimant = postgres_tests::test_pubkey(); + let owner = postgres_tests::test_pubkey(); + let invite = mint_relay_invite( + &pool, + community, + &postgres_tests::test_pubkey(), + 3600, + Some(1), + ) + .await + .unwrap(); + let hash = hash_v2_code(&invite.code); + let first = claim_relay_invite_with_owner( + &pool, + community, + &hash, + &claimant, + None, + Some(&owner), + &nostr::Keys::generate(), + ) + .await + .unwrap(); + assert!(matches!(first.outcome.outcome, ClaimOutcome::Joined { .. })); + assert!(first.outcome.owner_link_created); + assert_eq!(first.outcome.users_created, 2); + let retry = claim_relay_invite_with_owner( + &pool, + community, + &hash, + &claimant, + None, + Some(&owner), + &nostr::Keys::generate(), + ) + .await + .unwrap(); + assert!(matches!( + retry.outcome.outcome, + ClaimOutcome::AlreadyMember { .. } + )); + assert!(!retry.outcome.owner_link_created); + assert_eq!(retry.outcome.users_created, 0); + let legacy_agent = postgres_tests::test_pubkey(); + let legacy = claim_relay_membership_with_owner( + &pool, + community, + &legacy_agent, + "member", + None, + Some(&owner), + &nostr::Keys::generate(), + ) + .await + .unwrap(); + assert!(legacy.outcome.inserted && legacy.outcome.owner_link_created); + assert_eq!(legacy.outcome.users_created, 1); + let retry = claim_relay_membership_with_owner( + &pool, + community, + &legacy_agent, + "member", + None, + Some(&owner), + &nostr::Keys::generate(), + ) + .await + .unwrap(); + assert!(!retry.outcome.inserted && !retry.outcome.owner_link_created); + assert_eq!(retry.outcome.users_created, 0); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn issuer_timeout_denies_temporarily_without_revoking_invite() { + let pool = postgres_tests::setup_pool().await; + let community = postgres_tests::make_test_community(&pool).await; + let issuer = postgres_tests::test_pubkey(); + let claimant = postgres_tests::test_pubkey(); + let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) + .await + .unwrap(); + sqlx::query("INSERT INTO community_bans (community_id,pubkey,muted_until,actor_pubkey) VALUES ($1,$2,clock_timestamp()+interval '1 hour',$2)") + .bind(community.as_uuid()).bind(hex::decode(&issuer).unwrap()).execute(&pool).await.unwrap(); + assert_eq!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::IssuerRestricted + ); + let revoked: Option> = + sqlx::query_scalar("SELECT revoked_at FROM relay_invites WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!(revoked.is_none()); + sqlx::query("UPDATE community_bans SET muted_until=clock_timestamp()-interval '1 second' WHERE community_id=$1") + .bind(community.as_uuid()).execute(&pool).await.unwrap(); + assert!(matches!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Joined { use_count: 1, .. } + )); +} diff --git a/crates/buzz-db/src/store/relay_invite/revocation.rs b/crates/buzz-db/src/store/relay_invite/revocation.rs new file mode 100644 index 00000000000..c9e17cb836a --- /dev/null +++ b/crates/buzz-db/src/store/relay_invite/revocation.rs @@ -0,0 +1,51 @@ +//! Application-owned revocation, under the admission lock and in the writer's commit. +use crate::{error::Result, CommunityId}; + +/// Durably revoke an active banned principal's invites and its verified agents' invites. +/// The caller holds the admission lock before writing restriction or invite rows. +pub(crate) async fn revoke_banned_issuer_invites( + tx: &mut sqlx::PgConnection, + community: CommunityId, + pubkey: &[u8], +) -> Result<()> { + sqlx::query( + "UPDATE relay_invites SET revoked_at = clock_timestamp() \ + WHERE community_id = $1 AND revoked_at IS NULL \ + AND (created_by = encode($2::bytea, 'hex') OR created_by IN (\ + SELECT encode(pubkey, 'hex') FROM users \ + WHERE community_id = $1 AND agent_owner_pubkey = $2\ + )) AND EXISTS (\ + SELECT 1 FROM community_bans WHERE community_id = $1 AND pubkey = $2 \ + AND banned AND (ban_expires_at IS NULL OR ban_expires_at > clock_timestamp())\ + )", + ) + .bind(community.as_uuid()) + .bind(pubkey) + .execute(&mut *tx) + .await?; + Ok(()) +} + +/// Durably revoke an agent's invites when its newly verified owner is actively banned. +/// Timeouts block admission temporarily but never durably revoke invites. +pub(crate) async fn revoke_restricted_agent_invites( + tx: &mut sqlx::PgConnection, + community: CommunityId, + agent_pubkey: &[u8], + owner_pubkey: &[u8], +) -> Result<()> { + sqlx::query( + "UPDATE relay_invites SET revoked_at = clock_timestamp() \ + WHERE community_id = $1 AND created_by = encode($2::bytea, 'hex') \ + AND revoked_at IS NULL AND EXISTS (\ + SELECT 1 FROM community_bans WHERE community_id = $1 AND pubkey = $3 \ + AND banned AND (ban_expires_at IS NULL OR ban_expires_at > clock_timestamp())\ + )", + ) + .bind(community.as_uuid()) + .bind(agent_pubkey) + .bind(owner_pubkey) + .execute(&mut *tx) + .await?; + Ok(()) +} diff --git a/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs new file mode 100644 index 00000000000..54da3cf1749 --- /dev/null +++ b/crates/buzz-db/src/store/relay_invite/revocation_postgres_tests.rs @@ -0,0 +1,645 @@ +use super::*; +use crate::moderation::{ban_member, unban_member}; +use uuid::Uuid; + +pub(super) async fn claim_relay_invite_outcome( + pool: &PgPool, + community: CommunityId, + token_hash: &[u8; 32], + claimer: &str, + policy_version: Option<&str>, +) -> Result { + super::claim_relay_invite( + pool, + community, + token_hash, + claimer, + policy_version, + &nostr::Keys::generate(), + ) + .await + .map(|write| write.outcome) +} + +pub(super) async fn fixture() -> (PgPool, CommunityId, String, String) { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let id = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(id) + .bind(format!("invite-{}.example", id.simple())) + .execute(&pool) + .await + .unwrap(); + ( + pool, + CommunityId::from_uuid(id), + hex::encode([1; 32]), + hex::encode([2; 32]), + ) +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn ban_permanently_revokes_issued_invites_but_not_another_tenant() { + let (pool, community, issuer, claimant) = fixture().await; + let other_id = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(other_id) + .bind(format!("other-{}.example", other_id.simple())) + .execute(&pool) + .await + .unwrap(); + let other = CommunityId::from_uuid(other_id); + let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + .await + .unwrap(); + let unaffected = mint_relay_invite(&pool, other, &issuer, 3600, None) + .await + .unwrap(); + ban_member(&pool, community, &[1; 32], &[3; 32], None, None) + .await + .unwrap(); + assert!(matches!( + mint_relay_invite(&pool, community, &issuer, 3600, None).await, + Err(crate::DbError::InviteRestricted) + )); + assert!(unban_member(&pool, community, &[1; 32], &[3; 32]) + .await + .unwrap()); + assert_eq!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Revoked + ); + assert!(matches!( + claim_relay_invite_outcome( + &pool, + other, + &hash_v2_code(&unaffected.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Joined { .. } + )); + let renewed = mint_relay_invite(&pool, community, &issuer, 3600, None) + .await + .unwrap(); + assert!(matches!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&renewed.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Joined { .. } + )); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn nonmember_restrictions_cover_both_claim_formats_and_owner() { + let (pool, community, issuer, claimant) = fixture().await; + let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) + .await + .unwrap(); + ban_member(&pool, community, &[2; 32], &[3; 32], None, None) + .await + .unwrap(); + assert_eq!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Restricted + ); + assert!(matches!( + crate::relay_members::claim_relay_membership( + &pool, + community, + &claimant, + "member", + None, + &nostr::Keys::generate() + ) + .await, + Err(crate::DbError::InviteRestricted) + )); + let agent = hex::encode([4; 32]); + sqlx::query("INSERT INTO users (community_id,pubkey) VALUES ($1,$2),($1,$3)") + .bind(community.as_uuid()) + .bind(&[2u8; 32][..]) + .bind(&[4u8; 32][..]) + .execute(&pool) + .await + .unwrap(); + crate::user::set_agent_owner(&pool, community, &[4; 32], &[2; 32]) + .await + .unwrap(); + assert_eq!( + claim_relay_invite_outcome(&pool, community, &hash_v2_code(&invite.code), &agent, None) + .await + .unwrap(), + ClaimOutcome::Restricted + ); + assert!( + !crate::relay_members::is_relay_member(&pool, community, &claimant) + .await + .unwrap() + ); + let count: i32 = + sqlx::query_scalar("SELECT use_count FROM relay_invites WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 0); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn issuer_agent_revocation_survives_owner_unban() { + let (pool, community, issuer, claimant) = fixture().await; + sqlx::query("INSERT INTO users (community_id,pubkey) VALUES ($1,$2),($1,$3)") + .bind(community.as_uuid()) + .bind(&[1u8; 32][..]) + .bind(&[4u8; 32][..]) + .execute(&pool) + .await + .unwrap(); + crate::user::set_agent_owner(&pool, community, &[1; 32], &[4; 32]) + .await + .unwrap(); + let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + .await + .unwrap(); + ban_member(&pool, community, &[4; 32], &[3; 32], None, None) + .await + .unwrap(); + unban_member(&pool, community, &[4; 32], &[3; 32]) + .await + .unwrap(); + assert_eq!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Revoked + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn stalled_production_mint_ignores_lifted_history_and_later_audit_touches() { + let (pool, community, issuer, claimant) = fixture().await; + let issuer_bytes = [1u8; 32]; + sqlx::query( + "INSERT INTO community_bans (community_id, pubkey, banned, actor_pubkey) \ + VALUES ($1, $2, false, $3)", + ) + .bind(community.as_uuid()) + .bind(issuer_bytes.as_slice()) + .bind([3u8; 32].as_slice()) + .execute(&pool) + .await + .unwrap(); + + let old_action = Uuid::new_v4(); + let old_action_time = Utc::now() - chrono::Duration::days(1); + sqlx::query( + "INSERT INTO relay_admin_actions \ + (id, report_community_id, request_id, actor_pubkey, actor_role, action, \ + state, step_marker, enforcement_target_pubkey, created_at, updated_at) \ + VALUES ($1, $2, $3, $4, 'operator', 'ban', 'succeeded', \ + 'mutation_committed', $5, $6, $6)", + ) + .bind(old_action) + .bind(community.as_uuid()) + .bind(Uuid::new_v4()) + .bind([3u8; 32].as_slice()) + .bind(issuer_bytes.as_slice()) + .bind(old_action_time) + .execute(&pool) + .await + .unwrap(); + + // Hold the production admission seam so mint starts its transaction and + // stalls before insert. Touching the old action while it waits creates the + // timestamp ordering that the retired audit predicate misread as proof. + let mut admission = pool.begin().await.unwrap(); + lock_admission(&mut admission, community).await.unwrap(); + let (mint_pool, mint_name) = named_pool().await; + let mint_issuer = issuer.clone(); + let mint = tokio::spawn(async move { + mint_relay_invite(&mint_pool, community, &mint_issuer, 3600, None).await + }); + wait_for_lock(&pool, &mint_name, "advisory", &mint).await; + + sqlx::query( + "UPDATE relay_admin_actions \ + SET updated_at=clock_timestamp()+interval '1 minute' WHERE id=$1", + ) + .bind(old_action) + .execute(&pool) + .await + .unwrap(); + admission.commit().await.unwrap(); + + let invite = tokio::time::timeout(std::time::Duration::from_secs(5), mint) + .await + .unwrap() + .unwrap() + .unwrap(); + let marker: bool = sqlx::query_scalar( + "SELECT legacy_admission FROM relay_invites WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!( + !marker, + "the production mint seam marks protocol-native rows" + ); + + let old_action_touched_after_mint_started: bool = sqlx::query_scalar( + "SELECT a.updated_at >= i.created_at \ + FROM relay_admin_actions a CROSS JOIN relay_invites i \ + WHERE a.id=$1 AND i.community_id=$2 AND i.id=$3", + ) + .bind(old_action) + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!( + old_action_touched_after_mint_started, + "the mint transaction began before the old action timestamp was touched" + ); + for action in ["ban", "resolve:ban"] { + sqlx::query( + "INSERT INTO moderation_actions \ + (community_id, actor_pubkey, action, target_pubkey, created_at) \ + VALUES ($1, $2, $3, $4, clock_timestamp()+interval '1 minute')", + ) + .bind(community.as_uuid()) + .bind([2u8; 32].as_slice()) + .bind(action) + .bind(issuer_bytes.as_slice()) + .execute(&pool) + .await + .unwrap(); + } + + let revoked: Option> = + sqlx::query_scalar("SELECT revoked_at FROM relay_invites WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!( + revoked.is_none(), + "lifted history and late audits spare new rows" + ); + assert!(matches!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Joined { .. } + )); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn active_ban_lazily_revokes_new_protocol_rows() { + let (pool, community, issuer, claimant) = fixture().await; + let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + .await + .unwrap(); + let legacy_admission: bool = sqlx::query_scalar( + "SELECT legacy_admission FROM relay_invites WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!(!legacy_admission); + sqlx::query( + "INSERT INTO community_bans (community_id, pubkey, banned, actor_pubkey) \ + VALUES ($1, $2, true, $3)", + ) + .bind(community.as_uuid()) + .bind([1u8; 32].as_slice()) + .bind([3u8; 32].as_slice()) + .execute(&pool) + .await + .unwrap(); + + assert_eq!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Revoked + ); + let revoked: bool = sqlx::query_scalar( + "SELECT revoked_at IS NOT NULL FROM relay_invites WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!(revoked, "active bans durably revoke new-protocol rows"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn malformed_legacy_issuers_return_a_typed_revoked_claim() { + let (pool, community, _, claimant) = fixture().await; + let issuers = [ + "not-a-pubkey".to_owned(), + hex::encode([0xabu8; 32]).to_ascii_uppercase(), + ]; + for (index, issuer) in issuers.iter().enumerate() { + let token_hash = [index as u8 + 10; 32]; + sqlx::query( + "INSERT INTO relay_invites (community_id, token_hash, created_by, expires_at) \ + VALUES ($1, $2, $3, clock_timestamp()+interval '1 day')", + ) + .bind(community.as_uuid()) + .bind(token_hash.as_slice()) + .bind(issuer) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + claim_relay_invite_outcome(&pool, community, &token_hash, &claimant, None) + .await + .unwrap(), + ClaimOutcome::Revoked, + "issuer {issuer} must fail closed without a database error" + ); + } + + let token_hash = [99u8; 32]; + sqlx::query( + "INSERT INTO relay_invites \ + (community_id, token_hash, created_by, expires_at, legacy_admission) \ + VALUES ($1, $2, 'not-a-pubkey', clock_timestamp()+interval '1 day', false)", + ) + .bind(community.as_uuid()) + .bind(token_hash.as_slice()) + .execute(&pool) + .await + .unwrap(); + assert_eq!( + claim_relay_invite_outcome(&pool, community, &token_hash, &claimant, None) + .await + .unwrap(), + ClaimOutcome::Invalid, + "a malformed non-legacy issuer returns a clean invalid outcome" + ); +} + +pub(super) async fn named_pool() -> (PgPool, String) { + let name = format!("invite-race-{}", Uuid::new_v4()); + let connection_name = name.clone(); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .after_connect(move |conn, _| { + let name = connection_name.clone(); + Box::pin(async move { + sqlx::query("SELECT set_config('application_name',$1,false)") + .bind(name) + .execute(conn) + .await?; + Ok(()) + }) + }) + .connect(&crate::test_support::database_url()) + .await + .unwrap(); + (pool, name) +} + +pub(super) async fn wait_for_lock( + pool: &PgPool, + name: &str, + kind: &str, + task: &tokio::task::JoinHandle, +) { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid \ + WHERE a.application_name=$1 AND l.locktype=$2 AND NOT l.granted)", + ) + .bind(name) + .bind(kind) + .fetch_one(pool) + .await + .unwrap(); + if waiting { + break; + } + assert!(!task.is_finished(), "writer bypassed expected {kind} lock"); + tokio::task::yield_now().await; + } + }) + .await + .expect("writer must observably wait on the expected lock"); +} + +async fn queued_claim( + pool: &PgPool, + community: CommunityId, + code: &str, + claimant: String, +) -> tokio::task::JoinHandle> { + let (claim_pool, name) = named_pool().await; + let hash = hash_v2_code(code); + let claim = tokio::spawn(async move { + claim_relay_invite_outcome(&claim_pool, community, &hash, &claimant, None).await + }); + wait_for_lock(pool, &name, "advisory", &claim).await; + claim +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn claimant_ban_and_timeout_commit_before_queued_claim_without_consuming_a_use() { + for timeout in [false, true] { + let (pool, community, issuer, claimant) = fixture().await; + let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) + .await + .unwrap(); + // Hold the existing restriction row so the production writer stops only + // after acquiring admission. The claim must queue behind that writer. + ban_member(&pool, community, &[2; 32], &[3; 32], None, None) + .await + .unwrap(); + unban_member(&pool, community, &[2; 32], &[3; 32]) + .await + .unwrap(); + let mut row_lock = pool.begin().await.unwrap(); + sqlx::query("SELECT pubkey FROM community_bans WHERE community_id=$1 FOR UPDATE") + .bind(community.as_uuid()) + .fetch_one(&mut *row_lock) + .await + .unwrap(); + let (writer_pool, name) = named_pool().await; + let restriction = tokio::spawn(async move { + if timeout { + crate::moderation::timeout_member( + &writer_pool, + community, + &[2; 32], + &[3; 32], + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + } else { + ban_member(&writer_pool, community, &[2; 32], &[3; 32], None, None).await + } + }); + wait_for_lock(&pool, &name, "transactionid", &restriction).await; + let claim = queued_claim(&pool, community, &invite.code, claimant.clone()).await; + row_lock.commit().await.unwrap(); + restriction.await.unwrap().unwrap(); + assert_eq!(claim.await.unwrap().unwrap(), ClaimOutcome::Restricted); + let uses: i32 = sqlx::query_scalar( + "SELECT use_count FROM relay_invites WHERE community_id=$1 AND id=$2", + ) + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(uses, 0); + assert!( + !crate::relay_members::is_relay_member(&pool, community, &claimant) + .await + .unwrap() + ); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn owner_materialization_commits_before_queued_agent_claim() { + let (pool, community, issuer, agent) = fixture().await; + let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + .await + .unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey) VALUES($1,$2),($1,$3)") + .bind(community.as_uuid()) + .bind(vec![2u8; 32]) + .bind(vec![4u8; 32]) + .execute(&pool) + .await + .unwrap(); + ban_member(&pool, community, &[4; 32], &[3; 32], None, None) + .await + .unwrap(); + let mut row_lock = pool.begin().await.unwrap(); + sqlx::query("SELECT pubkey FROM users WHERE community_id=$1 AND pubkey=$2 FOR UPDATE") + .bind(community.as_uuid()) + .bind(vec![2u8; 32]) + .fetch_one(&mut *row_lock) + .await + .unwrap(); + let (writer_pool, name) = named_pool().await; + let owner = tokio::spawn(async move { + crate::user::set_agent_owner(&writer_pool, community, &[2; 32], &[4; 32]).await + }); + wait_for_lock(&pool, &name, "transactionid", &owner).await; + let claim = queued_claim(&pool, community, &invite.code, agent).await; + row_lock.commit().await.unwrap(); + assert!(owner.await.unwrap().unwrap()); + assert_eq!(claim.await.unwrap().unwrap(), ClaimOutcome::Restricted); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn admission_first_then_ban_preserves_the_committed_use_and_denies_retries() { + let (pool, community, issuer, claimant) = fixture().await; + let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(2)) + .await + .unwrap(); + assert!(matches!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Joined { use_count: 1, .. } + )); + ban_member(&pool, community, &[2; 32], &[3; 32], None, None) + .await + .unwrap(); + assert_eq!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Restricted + ); + let uses: i32 = + sqlx::query_scalar("SELECT use_count FROM relay_invites WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(uses, 1); +} diff --git a/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs new file mode 100644 index 00000000000..b9cb3bce3e5 --- /dev/null +++ b/crates/buzz-db/src/store/relay_invite/upgrade_postgres_tests.rs @@ -0,0 +1,675 @@ +use super::*; +use chrono::{DateTime, Duration, Utc}; +use uuid::Uuid; + +struct LegacyInviteCase { + community: Uuid, +} + +struct RelayAdminActionFixture<'a> { + community: Uuid, + target_pubkey: &'a [u8; 32], + report_bound: bool, + state: &'a str, + step_marker: Option<&'a str>, + created_at: DateTime, + updated_at: DateTime, +} + +async fn insert_restriction( + pool: &PgPool, + community: Uuid, + pubkey: &[u8; 32], + banned: bool, + ban_expires_at: Option>, + muted_until: Option>, +) { + sqlx::query( + "INSERT INTO community_bans \ + (community_id, pubkey, banned, ban_expires_at, muted_until, actor_pubkey) \ + VALUES ($1, $2, $3, $4, $5, $6)", + ) + .bind(community) + .bind(pubkey.as_slice()) + .bind(banned) + .bind(ban_expires_at) + .bind(muted_until) + .bind([3u8; 32].as_slice()) + .execute(pool) + .await + .unwrap(); +} + +async fn insert_legacy_invite( + pool: &PgPool, + community: Uuid, + token_seed: u8, + created_by: &str, + created_at: DateTime, +) -> [u8; 32] { + let token_hash = [token_seed; 32]; + sqlx::query( + "INSERT INTO relay_invites \ + (community_id, token_hash, created_by, expires_at, created_at) \ + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(community) + .bind(token_hash.as_slice()) + .bind(created_by) + .bind(created_at + Duration::days(2)) + .bind(created_at) + .execute(pool) + .await + .unwrap(); + token_hash +} + +async fn insert_moderation_action( + pool: &PgPool, + community: Uuid, + action: &str, + target_pubkey: &[u8; 32], + created_at: DateTime, +) { + sqlx::query( + "INSERT INTO moderation_actions \ + (community_id, actor_pubkey, action, target_pubkey, created_at) \ + VALUES ($1, $2, $3, $4, $5)", + ) + .bind(community) + .bind([2u8; 32].as_slice()) + .bind(action) + .bind(target_pubkey.as_slice()) + .bind(created_at) + .execute(pool) + .await + .unwrap(); +} + +async fn insert_relay_admin_action(pool: &PgPool, fixture: RelayAdminActionFixture<'_>) -> Uuid { + let RelayAdminActionFixture { + community, + target_pubkey, + report_bound, + state, + step_marker, + created_at, + updated_at, + } = fixture; + let report_id = report_bound.then(Uuid::new_v4); + if let Some(report_id) = report_id { + let mut report_event_id = [0u8; 32]; + report_event_id[..16].copy_from_slice(report_id.as_bytes()); + report_event_id[16..].copy_from_slice(report_id.as_bytes()); + sqlx::query( + "INSERT INTO moderation_reports \ + (community_id, id, report_event_id, reporter_pubkey, target_kind, \ + target_pubkey, report_type) \ + VALUES ($1, $2, $3, $4, 'pubkey', $5, 'spam')", + ) + .bind(community) + .bind(report_id) + .bind(report_event_id.as_slice()) + .bind([4u8; 32].as_slice()) + .bind(target_pubkey.as_slice()) + .execute(pool) + .await + .unwrap(); + } + + let id = Uuid::new_v4(); + let actor_pubkey = [3u8; 32]; + let cancelled_by = (state == "cancelled").then_some(actor_pubkey.as_slice()); + sqlx::query( + "INSERT INTO relay_admin_actions \ + (id, report_id, report_community_id, request_id, actor_pubkey, actor_role, \ + action, state, step_marker, cancelled_by, enforcement_target_pubkey, \ + created_at, updated_at) \ + VALUES ($1, $2, $3, $4, $5, 'operator', 'ban', $6, $7, $8, $9, $10, $11)", + ) + .bind(id) + .bind(report_id) + .bind(community) + .bind(Uuid::new_v4()) + .bind(actor_pubkey.as_slice()) + .bind(state) + .bind(step_marker) + .bind(cancelled_by) + .bind(target_pubkey.as_slice()) + .bind(created_at) + .bind(updated_at) + .execute(pool) + .await + .unwrap(); + id +} + +async fn set_deletion_state(pool: &PgPool, community: Uuid, state: &str) { + let mut tx = pool.begin().await.unwrap(); + sqlx::query( + "SELECT set_config('buzz.deletion_executor_community', $1, true), \ + set_config('buzz.deletion_fence_generation', '7', true)", + ) + .bind(community.to_string()) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query( + "UPDATE communities \ + SET deletion_state = $2, deletion_fence_generation = 7 WHERE id = $1", + ) + .bind(community) + .bind(state) + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); +} + +async fn legacy_fixture() -> (PgPool, Vec) { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + // Pinned main includes the user deletion target in 0072-0073 and its fences in + // 0074; invitations expand in 0075. + crate::migration::run_migrations_through(&pool, 74) + .await + .unwrap(); + let last_migration: i64 = + sqlx::query_scalar("SELECT max(version) FROM _sqlx_migrations WHERE success") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + last_migration, 74, + "fixtures start at the complete pinned-main schema" + ); + + let issuer = [1u8; 32]; + let mut cases = Vec::new(); + for index in 0u8..12 { + let community = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("upgrade-{index}-{community}.example")) + .execute(&pool) + .await + .unwrap(); + + let created_by = match index { + 5 => { + let agent = [4u8; 32]; + let owner = [5u8; 32]; + sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2), ($1, $3)") + .bind(community) + .bind(agent.as_slice()) + .bind(owner.as_slice()) + .execute(&pool) + .await + .unwrap(); + // Seed the owner link before testing the writer-side admission lock. + sqlx::query( + "UPDATE users SET agent_owner_pubkey = $1 \ + WHERE community_id = $2 AND pubkey = $3", + ) + .bind(owner.as_slice()) + .bind(community) + .bind(agent.as_slice()) + .execute(&pool) + .await + .unwrap(); + insert_restriction(&pool, community, &owner, false, None, None).await; + hex::encode(agent) + } + 6 => "not-a-pubkey".to_owned(), + 7 => hex::encode([0xabu8; 32]).to_ascii_uppercase(), + _ => hex::encode(issuer), + }; + + match index { + 0 => insert_restriction(&pool, community, &issuer, true, None, None).await, + 1 => { + insert_restriction( + &pool, + community, + &issuer, + true, + Some(Utc::now() - Duration::hours(1)), + None, + ) + .await; + } + 2 | 4 => insert_restriction(&pool, community, &issuer, false, None, None).await, + 3 => { + insert_restriction( + &pool, + community, + &issuer, + false, + None, + Some(Utc::now() - Duration::hours(1)), + ) + .await; + } + _ => {} + } + + let old_action = if index == 10 { + Some( + insert_relay_admin_action( + &pool, + RelayAdminActionFixture { + community, + target_pubkey: &issuer, + report_bound: false, + state: "succeeded", + step_marker: Some("mutation_committed"), + created_at: Utc::now() - Duration::days(1), + updated_at: Utc::now() - Duration::days(1), + }, + ) + .await, + ) + } else { + None + }; + let created_at = if index == 4 { + Utc::now() + Duration::hours(1) + } else { + Utc::now() - Duration::hours(1) + }; + insert_legacy_invite(&pool, community, index + 1, &created_by, created_at).await; + + if index == 9 { + insert_moderation_action( + &pool, + community, + "resolve:ban", + &issuer, + Utc::now() + Duration::minutes(1), + ) + .await; + } + if index == 10 { + let after = Utc::now() + Duration::minutes(1); + insert_moderation_action(&pool, community, "ban", &issuer, after).await; + for state in ["pending", "enforcing", "failed", "cancelled"] { + let marker = + matches!(state, "enforcing" | "failed").then_some("mutation_committed"); + for report_bound in [true, false] { + insert_relay_admin_action( + &pool, + RelayAdminActionFixture { + community, + target_pubkey: &issuer, + report_bound, + state, + step_marker: marker, + created_at: after, + updated_at: after, + }, + ) + .await; + } + } + sqlx::query("UPDATE relay_admin_actions SET updated_at = $2 WHERE id = $1") + .bind(old_action.unwrap()) + .bind(Utc::now() + Duration::minutes(2)) + .execute(&pool) + .await + .unwrap(); + } + if index == 11 { + let bystander = Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(bystander) + .bind(format!("upgrade-bystander-{bystander}.example")) + .execute(&pool) + .await + .unwrap(); + insert_restriction(&pool, bystander, &issuer, true, None, None).await; + } + if index == 1 { + set_deletion_state(&pool, community, "quiescing").await; + } else if index == 2 { + set_deletion_state(&pool, community, "tombstone").await; + } + + cases.push(LegacyInviteCase { community }); + } + // Preserve a populated, non-default join role across both upgrade paths. + sqlx::query( + "INSERT INTO channels (community_id, name, created_by, join_role) \ + VALUES ($1, 'upgrade-guest', $2, 'guest')", + ) + .bind(cases[0].community) + .bind(issuer.as_slice()) + .execute(&pool) + .await + .unwrap(); + assert_join_role_preserved(&pool, cases[0].community).await; + (pool, cases) +} + +async fn assert_join_role_preserved(pool: &PgPool, community: Uuid) { + let column: (String, String, Option) = sqlx::query_as( + "SELECT data_type, is_nullable, column_default \ + FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = 'channels' \ + AND column_name = 'join_role'", + ) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!( + column, + ("text".into(), "NO".into(), Some("'member'::text".into())) + ); + let join_role: String = sqlx::query_scalar( + "SELECT join_role FROM channels WHERE community_id = $1 AND name = 'upgrade-guest'", + ) + .bind(community) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!( + join_role, "guest", + "upgrading must preserve channel admission policy" + ); +} + +async fn invite_revocation_state(pool: &PgPool) -> Vec<(Uuid, Option>, bool)> { + sqlx::query_as( + "SELECT community_id, revoked_at, legacy_admission \ + FROM relay_invites ORDER BY community_id", + ) + .fetch_all(pool) + .await + .unwrap() +} + +async fn assert_admission_column(pool: &PgPool) { + let column: Option<(String, String, Option)> = sqlx::query_as( + "SELECT data_type, is_nullable, column_default \ + FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = 'relay_invites' \ + AND column_name = 'legacy_admission'", + ) + .fetch_optional(pool) + .await + .unwrap(); + assert_eq!( + column, + Some(("boolean".into(), "NO".into(), Some("true".into()))) + ); + let revoked: Option<(String, String, Option)> = sqlx::query_as( + "SELECT data_type, is_nullable, column_default \ + FROM information_schema.columns \ + WHERE table_schema = 'public' AND table_name = 'relay_invites' \ + AND column_name = 'revoked_at'", + ) + .fetch_optional(pool) + .await + .unwrap(); + assert_eq!( + revoked, + Some(("timestamp with time zone".into(), "YES".into(), None)) + ); +} + +async fn apply_pgschema_to_existing_database(pool: &PgPool) { + // The pinned migration history has retired triggers on the partitioned + // events parent and auto-named deletion-request checks that the desired + // schema replaces. pgschema orders child-trigger drops before their parent + // and schedules a replacement check before dropping its same-named copy. + // Remove only those stale objects in this disposable fixture; pgschema + // still applies desired state; historical repair is a separate reviewed + // operation after deployment. + sqlx::raw_sql( + "DROP TRIGGER IF EXISTS trg_events_guard_nip_rs_hard_delete ON events; \ + DROP TRIGGER IF EXISTS trg_events_nip_rs_watermark ON events; \ + DROP TRIGGER IF EXISTS trg_events_purge_soft_deleted_nip_rs ON events; \ + DROP TRIGGER IF EXISTS trg_events_purge_soft_deleted_buzz_mesh_status ON events; \ + ALTER TABLE community_deletion_requests \ + DROP CONSTRAINT IF EXISTS community_deletion_requests_check1; \ + ALTER TABLE community_deletion_requests \ + DROP CONSTRAINT IF EXISTS community_deletion_requests_check2; \ + ALTER TABLE community_deletion_requests \ + DROP CONSTRAINT IF EXISTS community_deletion_requests_check3; \ + ALTER TABLE community_deletion_requests \ + DROP CONSTRAINT IF EXISTS community_deletion_requests_check4;", + ) + .execute(pool) + .await + .unwrap(); + + let database_url = crate::test_support::database_url(); + let options: sqlx::postgres::PgConnectOptions = database_url.parse().unwrap(); + let host = options.get_host().to_owned(); + let port = options.get_port().to_string(); + let user = options.get_username().to_owned(); + let password = database_url + .split_once("://") + .and_then(|(_, rest)| rest.split_once('@')) + .and_then(|(authority, _)| authority.split_once(':')) + .map(|(_, password)| password.to_owned()) + .or_else(|| std::env::var("PGPASSWORD").ok()) + .unwrap_or_default(); + let database: String = sqlx::query_scalar("SELECT current_database()") + .fetch_one(pool) + .await + .unwrap(); + // Run from the repository root, like every pgschema caller, so + // `.pgschemaignore` applies. + let repo_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let schema_file = repo_root.join("schema/schema.sql"); + let output = std::process::Command::new(repo_root.join("bin/pgschema")) + .current_dir(&repo_root) + .args([ + "apply", + "--auto-approve", + "--file", + schema_file.to_str().unwrap(), + "--host", + &host, + "--port", + &port, + "--user", + &user, + "--password", + &password, + "--db", + &database, + "--plan-host", + &host, + "--plan-port", + &port, + "--plan-user", + &user, + "--plan-password", + &password, + "--plan-db", + &database, + ]) + .output() + .unwrap(); + assert!( + output.status.success(), + "pgschema apply failed:\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_0075_adds_invite_columns_without_rewriting_history() { + let (pool, cases) = legacy_fixture().await; + crate::migration::run_migrations(&pool).await.unwrap(); + assert!(sqlx::query_scalar::<_, bool>( + "SELECT EXISTS(SELECT 1 FROM _sqlx_migrations WHERE version=75 AND success)" + ) + .fetch_one(&pool) + .await + .unwrap()); + assert_admission_column(&pool).await; + assert_join_role_preserved(&pool, cases[0].community).await; + assert_eq!( + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM relay_invites WHERE revoked_at IS NOT NULL" + ) + .fetch_one(&pool) + .await + .unwrap(), + 0, + "schema migration must not rewrite historical rows" + ); + assert_eq!( + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM relay_invites WHERE legacy_admission IS DISTINCT FROM true" + ) + .fetch_one(&pool) + .await + .unwrap(), + 0, + "pre-migration rows remain legacy-admitted" + ); + + insert_legacy_invite( + &pool, + cases[8].community, + 100, + &hex::encode([1u8; 32]), + Utc::now(), + ) + .await; + let old_code_insert_default: bool = sqlx::query_scalar( + "SELECT legacy_admission FROM relay_invites \ + WHERE community_id=$1 AND token_hash=$2", + ) + .bind(cases[8].community) + .bind([100u8; 32].as_slice()) + .fetch_one(&pool) + .await + .unwrap(); + assert!(old_code_insert_default); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_legacy_claim_lazily_revokes_history_after_a_fenced_community_reactivates() +{ + let (pool, cases) = legacy_fixture().await; + crate::migration::run_migrations(&pool).await.unwrap(); + + let community = cases[1].community; + let token_hash = [2u8; 32]; + let fenced = claim_relay_invite( + &pool, + CommunityId::from_uuid(community), + &token_hash, + &format!("{:064x}", 9), + None, + &nostr::Keys::generate(), + ) + .await + .unwrap_err(); + assert!( + matches!(fenced, crate::DbError::AccessDenied(_)), + "{fenced:?}" + ); + let revoked: bool = sqlx::query_scalar( + "SELECT revoked_at IS NOT NULL FROM relay_invites WHERE community_id = $1", + ) + .bind(community) + .fetch_one(&pool) + .await + .unwrap(); + assert!(!revoked, "quiescing tenants stay fenced and untouched"); + + set_deletion_state(&pool, community, "active").await; + assert_eq!( + claim_relay_invite( + &pool, + CommunityId::from_uuid(community), + &token_hash, + &format!("{:064x}", 9), + None, + &nostr::Keys::generate(), + ) + .await + .map(|write| write.outcome) + .unwrap(), + ClaimOutcome::Revoked + ); + let revoked: bool = sqlx::query_scalar( + "SELECT revoked_at IS NOT NULL FROM relay_invites WHERE community_id = $1", + ) + .bind(community) + .fetch_one(&pool) + .await + .unwrap(); + assert!( + revoked, + "reactivated legacy history is durably revoked on claim" + ); + let legacy_admission: bool = + sqlx::query_scalar("SELECT legacy_admission FROM relay_invites WHERE community_id = $1") + .bind(community) + .fetch_one(&pool) + .await + .unwrap(); + assert!( + legacy_admission, + "claim does not stand in for maintenance repair" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_desired_pgschema_reconcile_matches_populated_upgrade() { + let (pool, cases) = legacy_fixture().await; + let before: i64 = sqlx::query_scalar("SELECT count(*) FROM relay_invites") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(before, cases.len() as i64); + + // Exercise the deployment path against populated data at the complete + // pinned-main schema through 0074, rather than reproducing its DDL by hand. + // Existing partitioned tables require the operator prebuild before pgschema, + // which otherwise tries unsupported CREATE INDEX CONCURRENTLY on the parent. + crate::test_support::prebuild_media_edit_index(&pool).await; + apply_pgschema_to_existing_database(&pool).await; + assert_admission_column(&pool).await; + assert_join_role_preserved(&pool, cases[0].community).await; + let before_reconcile: i64 = + sqlx::query_scalar("SELECT count(*) FROM relay_invites WHERE revoked_at IS NOT NULL") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + before_reconcile, 0, + "pgschema does not execute historical DML" + ); + + let before_reconcile = invite_revocation_state(&pool).await; + let reconcile = include_str!("../../../../../scripts/reconcile-schema-after-pgschema.sql"); + sqlx::raw_sql(reconcile).execute(&pool).await.unwrap(); + assert_eq!(invite_revocation_state(&pool).await, before_reconcile); + // Reconciliation is schema-only and idempotent; no historical data is + // rewritten by the desired-state path. + sqlx::raw_sql(reconcile).execute(&pool).await.unwrap(); + assert_eq!(invite_revocation_state(&pool).await, before_reconcile); + assert_join_role_preserved(&pool, cases[0].community).await; + assert_eq!( + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM relay_invites WHERE legacy_admission IS DISTINCT FROM true" + ) + .fetch_one(&pool) + .await + .unwrap(), + 0, + "pgschema preserves the legacy default for populated rows" + ); +} diff --git a/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs b/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs new file mode 100644 index 00000000000..7157267ec92 --- /dev/null +++ b/crates/buzz-db/src/store/relay_invite/writer_protocol_postgres_tests.rs @@ -0,0 +1,378 @@ +use super::revocation_postgres_tests::{ + claim_relay_invite_outcome, fixture, named_pool, wait_for_lock, +}; +use super::*; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn authorization_owner_writer_waits_before_claim_owner_row_and_links_once() { + let (pool, community, _, claimant) = fixture().await; + let owner = hex::encode([4; 32]); + for key in [[2; 32], [4; 32]] { + crate::user::ensure_user(&pool, community, &key) + .await + .unwrap(); + } + let mut claim = pool.begin().await.unwrap(); + lock_admission(&mut claim, community).await.unwrap(); + let (writer_pool, name) = named_pool().await; + let setter = tokio::spawn(async move { + Db::from_pool(writer_pool) + .set_agent_owner_for_authorization(community, &[2; 32], &[4; 32]) + .await + }); + wait_for_lock(&pool, &name, "advisory", &setter).await; + // Exercise the production claim persistence while the setter is queued. + // If the setter locks the user first, this bounded operation cannot finish. + let written = tokio::time::timeout( + std::time::Duration::from_secs(5), + super::claim_owner::persist_claim_owner(&mut claim, community, &claimant, Some(&owner)), + ) + .await + .unwrap() + .unwrap(); + assert!(written.link_created); + claim.commit().await.unwrap(); + assert!( + !tokio::time::timeout(std::time::Duration::from_secs(5), setter) + .await + .unwrap() + .unwrap() + .unwrap() + ); + assert_eq!( + crate::user::get_agent_channel_policy(&pool, community, &[2; 32]) + .await + .unwrap() + .unwrap() + .1, + Some(vec![4; 32]) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn ensure_user_insert_and_conflict_do_not_take_admission_lock() { + let (pool, community, _, _) = fixture().await; + let mut claim = pool.begin().await.unwrap(); + lock_admission(&mut claim, community).await.unwrap(); + let (writer_pool, name) = named_pool().await; + for expected in [true, false] { + let mut table_lock = pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE users IN ACCESS EXCLUSIVE MODE") + .execute(&mut *table_lock) + .await + .unwrap(); + let insert_pool = writer_pool.clone(); + let insert = tokio::spawn(async move { + crate::user::ensure_user(&insert_pool, community, &[5; 32]).await + }); + // Inspect the writer while its INSERT is in flight, not after its + // autocommit releases locks. It must reach the table behind admission. + wait_for_lock(&pool, &name, "relation", &insert).await; + let locks: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid \ + WHERE a.application_name=$1 AND l.locktype='advisory'", + ) + .bind(&name) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + locks, 0, + "user insert must not hold or wait on advisory locks" + ); + table_lock.commit().await.unwrap(); + assert_eq!( + tokio::time::timeout(std::time::Duration::from_secs(5), insert) + .await + .unwrap() + .unwrap() + .unwrap(), + expected + ); + } + claim.rollback().await.unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn linking_banned_owner_revokes_agent_invites_but_timeout_does_not() { + for banned in [true, false] { + let (pool, community, issuer, claimant) = fixture().await; + for key in [[1; 32], [4; 32]] { + crate::user::ensure_user(&pool, community, &key) + .await + .unwrap(); + } + let invite = mint_relay_invite(&pool, community, &issuer, 3600, Some(1)) + .await + .unwrap(); + if banned { + crate::moderation::ban_member(&pool, community, &[4; 32], &[3; 32], None, None) + .await + .unwrap(); + } else { + crate::moderation::timeout_member( + &pool, + community, + &[4; 32], + &[3; 32], + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + .unwrap(); + } + assert!( + crate::user::set_agent_owner(&pool, community, &[1; 32], &[4; 32]) + .await + .unwrap() + ); + let revoked: bool = + sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM relay_invites WHERE id=$1") + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(revoked, banned); + if banned { + crate::moderation::unban_member(&pool, community, &[4; 32], &[3; 32]) + .await + .unwrap(); + assert_eq!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Revoked + ); + } else { + assert_eq!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::IssuerRestricted + ); + crate::moderation::untimeout_member(&pool, community, &[4; 32], &[3; 32]) + .await + .unwrap(); + assert!(matches!( + claim_relay_invite_outcome( + &pool, + community, + &hash_v2_code(&invite.code), + &claimant, + None + ) + .await + .unwrap(), + ClaimOutcome::Joined { .. } + )); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn marker_writers_serialize_before_rows_and_commit_revocation_with_marker() { + for timeout in [false, true] { + let (pool, community, issuer, _) = fixture().await; + let invite = mint_relay_invite(&pool, community, &issuer, 3600, None) + .await + .unwrap(); + for key in [[1; 32], [4; 32]] { + crate::user::ensure_user(&pool, community, &key) + .await + .unwrap(); + } + crate::user::set_agent_owner(&pool, community, &[4; 32], &[1; 32]) + .await + .unwrap(); + let agent_invite = mint_relay_invite(&pool, community, &hex::encode([4; 32]), 3600, None) + .await + .unwrap(); + if timeout { + // A timeout must also repair revocation for an existing active ban, + // rather than revoking invites for timeout-only principals. + crate::moderation::ban_member(&pool, community, &[1; 32], &[3; 32], None, None) + .await + .unwrap(); + sqlx::query("UPDATE relay_invites SET revoked_at=NULL WHERE id IN ($1,$2)") + .bind(invite.invite_id) + .bind(agent_invite.invite_id) + .execute(&pool) + .await + .unwrap(); + } + let action = uuid::Uuid::new_v4(); + let lease = uuid::Uuid::new_v4(); + sqlx::query("INSERT INTO relay_admin_actions \ + (id, report_community_id, request_id, actor_pubkey, actor_role, action, state, \ + enforcement_target_pubkey, timeout_secs, timeout_until, action_lease_token, action_lease_expires_at) \ + VALUES ($1,$2,$1,$3,'operator',$4,'enforcing',$5, \ + CASE WHEN $6 THEN 3600 END, CASE WHEN $6 THEN clock_timestamp()+interval '1 hour' END, \ + $7,clock_timestamp()+interval '1 hour')") + .bind(action).bind(community.as_uuid()).bind(vec![3u8;32]) + .bind(if timeout {"timeout"} else {"ban"}).bind(vec![1u8;32]).bind(timeout).bind(lease) + .execute(&pool).await.unwrap(); + let mut admission = pool.begin().await.unwrap(); + lock_admission(&mut admission, community).await.unwrap(); + let (writer_pool, name) = named_pool().await; + let writer = tokio::spawn(async move { + if timeout { + crate::relay_admin_actions::execute_timeout_with_marker( + &writer_pool, + action, + lease, + community, + &[1; 32], + &[3; 32], + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + } else { + crate::relay_admin_actions::execute_ban_with_marker( + &writer_pool, + action, + lease, + community, + &[1; 32], + &[3; 32], + None, + ) + .await + } + }); + wait_for_lock(&pool, &name, "advisory", &writer).await; + // The action row must still be free while admission is held. This also + // prevents future inversion with action-row locking. + sqlx::query("SELECT id FROM relay_admin_actions WHERE id=$1 FOR UPDATE NOWAIT") + .bind(action) + .fetch_one(&mut *admission) + .await + .unwrap(); + admission.commit().await.unwrap(); + assert!(writer.await.unwrap().unwrap()); + let state: (bool, Option) = sqlx::query_as( + "SELECT i.revoked_at IS NOT NULL, a.step_marker FROM relay_invites i \ + JOIN relay_admin_actions a ON a.id=$2 WHERE i.id=$1", + ) + .bind(invite.invite_id) + .bind(action) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(state, (true, Some("mutation_committed".into()))); + let agent_revoked: bool = + sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM relay_invites WHERE id=$1") + .bind(agent_invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!(agent_revoked, "marker ban also revokes owned-agent invites"); + // Already marked: revocation and domain mutations must roll back too. + sqlx::query("UPDATE relay_invites SET revoked_at=NULL WHERE id IN ($1,$2)") + .bind(invite.invite_id) + .bind(agent_invite.invite_id) + .execute(&pool) + .await + .unwrap(); + let repeated = if timeout { + crate::relay_admin_actions::execute_timeout_with_marker( + &pool, + action, + lease, + community, + &[1; 32], + &[3; 32], + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + } else { + crate::relay_admin_actions::execute_ban_with_marker( + &pool, action, lease, community, &[1; 32], &[3; 32], None, + ) + .await + } + .unwrap(); + assert!(!repeated); + let revoked: bool = + sqlx::query_scalar("SELECT revoked_at IS NOT NULL FROM relay_invites WHERE id=$1") + .bind(invite.invite_id) + .fetch_one(&pool) + .await + .unwrap(); + assert!(!revoked, "failed marker must not commit revocation"); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn linked_authorization_owner_and_missing_agent_do_not_wait_on_admission() { + let (pool, community, _, _) = fixture().await; + for key in [[2; 32], [4; 32]] { + crate::user::ensure_user(&pool, community, &key) + .await + .unwrap(); + } + assert!( + crate::user::set_agent_owner(&pool, community, &[2; 32], &[4; 32]) + .await + .unwrap() + ); + let mut claim = pool.begin().await.unwrap(); + lock_admission(&mut claim, community).await.unwrap(); + let db = Db::from_pool(pool.clone()); + for owner in [[4; 32], [6; 32]] { + assert!(!tokio::time::timeout( + std::time::Duration::from_secs(5), + db.set_agent_owner_for_authorization(community, &[2; 32], &owner) + ) + .await + .unwrap() + .unwrap()); + } + assert!(matches!( + tokio::time::timeout( + std::time::Duration::from_secs(5), + db.set_agent_owner_for_authorization(community, &[7; 32], &[4; 32]) + ) + .await + .unwrap(), + Err(crate::DbError::NotFound(_)) + )); + claim.rollback().await.unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn unknown_claim_code_is_rejected_without_waiting_on_admission() { + let (pool, community, _, claimant) = fixture().await; + let mut held = pool.begin().await.unwrap(); + lock_admission(&mut held, community).await.unwrap(); + // A forged code must not queue behind admission; if the claim takes the + // lock before looking the code up, this bounded call cannot finish. + let outcome = tokio::time::timeout( + std::time::Duration::from_secs(5), + claim_relay_invite_outcome(&pool, community, &[0xAB; 32], &claimant, None), + ) + .await + .expect("unknown code waited on the admission lock") + .unwrap(); + assert_eq!(outcome, ClaimOutcome::Invalid); + held.rollback().await.unwrap(); +} diff --git a/crates/buzz-db/src/store/relay_members.rs b/crates/buzz-db/src/store/relay_members.rs index 6bc4de1a959..f21d436a8f3 100644 --- a/crates/buzz-db/src/store/relay_members.rs +++ b/crates/buzz-db/src/store/relay_members.rs @@ -150,6 +150,19 @@ pub async fn add_relay_member( role: &str, added_by: Option<&str>, relay_keypair: &nostr::Keys, +) -> Result> { + add_relay_member_with_pending(pool, community, pubkey, role, added_by, None, relay_keypair) + .await +} + +async fn add_relay_member_with_pending( + pool: &PgPool, + community: CommunityId, + pubkey: &str, + role: &str, + added_by: Option<&str>, + pending: Option, + relay_keypair: &nostr::Keys, ) -> Result> { let mut tx = crate::begin_community_write_transaction( pool, @@ -158,13 +171,14 @@ pub async fn add_relay_member( ) .await?; let result = sqlx::query( - "INSERT INTO relay_members (community_id, pubkey, role, added_by) \ - VALUES ($1, $2, $3, $4) ON CONFLICT (community_id, pubkey) DO NOTHING", + "INSERT INTO relay_members (community_id, pubkey, role, added_by, auto_join_pending) \ + VALUES ($1, $2, $3, $4, $5) ON CONFLICT (community_id, pubkey) DO NOTHING", ) .bind(community.as_uuid()) .bind(pubkey) .bind(role) .bind(added_by) + .bind(pending) .execute(tx.conn()) .await?; let added = result.rows_affected() > 0; @@ -201,38 +215,20 @@ pub async fn claim_relay_membership( policy_version: Option<&str>, relay_keypair: &nostr::Keys, ) -> Result> { - let mut tx = crate::begin_community_write_transaction( + let write = super::relay_invite::claim_relay_membership_with_owner( pool, community, - observability::WriterOperation::Authorization, + pubkey, + role, + policy_version, + None, + relay_keypair, ) .await?; - let inserted = sqlx::query( - "INSERT INTO relay_members (community_id, pubkey, role, added_by) \ - VALUES ($1, $2, $3, 'invite') \ - ON CONFLICT (community_id, pubkey) DO NOTHING", - ) - .bind(community.as_uuid()) - .bind(pubkey) - .bind(role) - .execute(tx.conn()) - .await? - .rows_affected() - > 0; - - if let Some(version) = policy_version { - sqlx::query( - "INSERT INTO join_policy_acceptances (community_id, pubkey, policy_version) \ - VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", - ) - .bind(community.as_uuid()) - .bind(pubkey) - .bind(version) - .execute(tx.conn()) - .await?; - } - - commit_membership_write(tx, inserted, inserted, relay_keypair).await + Ok(MembershipWrite { + outcome: write.outcome.inserted, + snapshot: write.snapshot, + }) } /// Returns whether a member has persisted acceptance evidence for a policy version. @@ -1086,8 +1082,9 @@ pub(crate) async fn write_nip43_membership_snapshot( pubkey_bytes.as_slice(), None, ); - observability::observe_advisory_lock( + observability::observe_event_lock( observability::LockType::Membership, + kind_i32, sqlx::query("SELECT pg_advisory_xact_lock($1)") .bind(lock_key) .execute(tx.conn()), @@ -1155,7 +1152,7 @@ pub(crate) async fn write_nip43_membership_snapshot( .await?; sqlx::query( "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) \ - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)", + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10)", ) .bind(community_id.as_uuid()) .bind(event.id.as_bytes().as_slice()) @@ -1166,13 +1163,13 @@ pub(crate) async fn write_nip43_membership_snapshot( .bind(&event.content) .bind(event.sig.serialize().as_slice()) .bind(received_at) - .bind::>(None) .bind(d_tag.as_deref()) .execute(tx.conn()) .await?; crate::store::event_follow_up::after_admitted_insert( tx, event.id.as_bytes().as_slice(), + created_at, kind_i32, None, ) @@ -1206,15 +1203,129 @@ pub async fn rewrite_nip43_membership_list( commit_membership_write(tx, (), true, relay_keypair).await } +/// Durable default-channel work for one roster admission. +#[derive(Debug, sqlx::FromRow)] +pub struct PendingDefaultChannelJoin { + /// Generation checked before writing or completing this work. + pub token: Uuid, + /// Original actor; `invite` denotes a self-claim. + pub added_by: Option, +} + +async fn pending_default_channel_join( + pool: &PgPool, + community: CommunityId, + pubkey: &str, +) -> Result> { + let mut conn = + observability::acquire_writer(pool, observability::WriterOperation::Authorization).await?; + pending_default_channel_join_on(&mut conn, community, pubkey).await +} + +async fn pending_default_channel_join_on( + conn: &mut sqlx::PgConnection, + community: CommunityId, + pubkey: &str, +) -> Result> { + Ok(sqlx::query_as( + "SELECT auto_join_pending AS token, added_by FROM relay_members \ + WHERE community_id = $1 AND pubkey = $2 AND auto_join_pending IS NOT NULL", + ) + .bind(community.as_uuid()) + .bind(pubkey) + .fetch_optional(conn) + .await?) +} + impl Db { + /// Read unfinished default-channel work and its original adding actor. + #[datastore_span(name = "pending_default_channel_join", system = "postgresql")] + pub async fn pending_default_channel_join( + &self, + community: CommunityId, + pubkey: &str, + ) -> Result> { + pending_default_channel_join(&self.pool, community, pubkey).await + } + + /// [`Db::pending_default_channel_join`] on the bounded replica arm, for + /// the retry that runs on every AUTH. A stale answer is safe: it can only + /// defer the work to a later admission or carry an old token, and every + /// write re-checks the token on the writer. Falls back to the writer as + /// [`Db::is_relay_member`] does. + #[datastore_span(name = "pending_default_channel_join_routed", system = "postgresql")] + pub async fn pending_default_channel_join_routed( + &self, + community: CommunityId, + pubkey: &str, + ) -> Result> { + let path = "pending_default_channel_join"; + match self + .route_read( + path, + RoutePredicate::Bounded, + crate::observability::ReaderOperation::Authorization, + ) + .await? + { + RouteDecision::Replica(mut tx, _entry, reason) => { + match pending_default_channel_join_on(&mut tx, community, pubkey).await { + Ok(pending) => { + Self::record_route(path, "replica", reason); + Ok(pending) + } + Err(e) if e.is_statement_cancelled() => { + Self::record_route(path, "replica", "statement_cancelled"); + Err(e) + } + Err(e) => { + tracing::warn!(path, "replica read failed; re-running on writer: {e}"); + Self::record_route(path, "writer", "replica_error"); + pending_default_channel_join(&self.pool, community, pubkey).await + } + } + } + RouteDecision::Writer => { + pending_default_channel_join(&self.pool, community, pubkey).await + } + } + } + + /// Finish only the admission generation that was actually processed. + #[datastore_span(name = "finish_default_channel_join", system = "postgresql")] + pub async fn finish_default_channel_join( + &self, + community: CommunityId, + pubkey: &str, + pending: Uuid, + ) -> Result<()> { + let mut tx = crate::begin_community_write_transaction( + &self.pool, + community, + observability::WriterOperation::Authorization, + ) + .await?; + sqlx::query( + "UPDATE relay_members SET auto_join_pending = NULL \ + WHERE community_id = $1 AND pubkey = $2 AND auto_join_pending = $3", + ) + .bind(community.as_uuid()) + .bind(pubkey) + .bind(pending) + .execute(tx.conn()) + .await?; + tx.commit().await?; + Ok(()) + } + /// Returns `true` if `pubkey` (64-char hex) is a member of `community`. /// /// Replica-routed on the bounded arm — the one PERMISSION read routed by /// explicit product decision (bounded-stale membership beats the 10s /// cache it replaced). Admits and revokes may lag by at most the budget - /// `B`; everything else fails closed to the writer, exactly like - /// [`Db::query_events_routed_bounded`]. Not precedent for routing other - /// permission reads. + /// `B`; everything else fails closed to the writer, including a busy + /// reader that history reads would be rejected for (see + /// [`Db::route_read`]). Not precedent for routing other permission reads. #[datastore_span(name = "is_relay_member", system = "postgresql")] pub async fn is_relay_member(&self, community: CommunityId, pubkey: &str) -> Result { let path = "relay_membership"; @@ -1224,7 +1335,7 @@ impl Db { RoutePredicate::Bounded, crate::observability::ReaderOperation::Authorization, ) - .await + .await? { RouteDecision::Replica(mut tx, _entry, reason) => { match is_relay_member_on(&mut tx, community, pubkey).await { @@ -1293,6 +1404,29 @@ impl Db { add_relay_member(&self.pool, community, pubkey, role, added_by, relay_keypair).await } + /// Adds a roster member and records default-channel work atomically. + /// Unlike the roster-only `add_relay_member`, this opts into auto-join. + #[datastore_span(name = "add_relay_member_with_default_channels", system = "postgresql")] + pub async fn add_relay_member_with_default_channels( + &self, + community: CommunityId, + pubkey: &str, + role: &str, + added_by: &str, + relay_keypair: &nostr::Keys, + ) -> Result> { + add_relay_member_with_pending( + &self.pool, + community, + pubkey, + role, + Some(added_by), + Some(Uuid::new_v4()), + relay_keypair, + ) + .await + } + /// Claims relay membership via an invite and atomically persists the /// accepted policy version when a policy is configured. #[datastore_span(name = "claim_relay_membership", system = "postgresql")] @@ -1315,6 +1449,29 @@ impl Db { .await } + /// Claim legacy membership and verified ownership in one admission transaction. + #[datastore_span(name = "claim_relay_membership_with_owner", system = "postgresql")] + pub async fn claim_relay_membership_with_owner( + &self, + community: CommunityId, + pubkey: &str, + role: &str, + policy_version: Option<&str>, + verified_owner: Option<&str>, + relay_keypair: &nostr::Keys, + ) -> Result> { + super::relay_invite::claim_relay_membership_with_owner( + &self.pool, + community, + pubkey, + role, + policy_version, + verified_owner, + relay_keypair, + ) + .await + } + /// Returns whether a member has persisted acceptance evidence for a policy version. #[datastore_span(name = "has_join_policy_acceptance", system = "postgresql")] pub async fn has_join_policy_acceptance( @@ -1567,6 +1724,57 @@ mod postgres_tests { format!("{:064x}", Uuid::new_v4().as_u128()) } + /// The roster write records its list lock under `membership` with the + /// roster's kind. Mutation: observe the list lock without its kind → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn membership_list_lock_records_the_roster_kind() { + use metrics_util::debugging::{DebugValue, DebuggingRecorder}; + + let pool = setup_pool().await; + let keys = nostr::Keys::generate(); + let community = make_test_community(&pool).await; + let recorder = DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _guard = metrics::set_default_local_recorder(&recorder); + + let mut tx = crate::begin_community_write_transaction( + &pool, + community, + observability::WriterOperation::Authorization, + ) + .await + .expect("begin roster write"); + write_nip43_membership_snapshot(&mut tx, &keys) + .await + .expect("write roster"); + tx.commit().await.expect("commit roster"); + + let roster_kind = buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST.to_string(); + let acquisitions = snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, _, _, _)| { + let label = |name: &str| { + key.key() + .labels() + .find(|label| label.key() == name) + .map(|label| label.value().to_owned()) + }; + key.key().name() == "buzz_db_advisory_lock_acquisitions_total" + && label("lock_type").as_deref() + == Some(observability::LockType::Membership.as_str()) + && label("kind") == Some(roster_kind.clone()) + }) + .map(|(_, _, _, value)| match value { + DebugValue::Counter(count) => count, + other => panic!("acquisitions are a counter, got {other:?}"), + }) + .sum::(); + assert_eq!(acquisitions, 1, "one roster list lock per write"); + } + async fn assert_role(pool: &PgPool, community: CommunityId, pubkey: &str, role: &str) { assert_eq!( get_relay_member(pool, community, pubkey) diff --git a/crates/buzz-db/src/store/replaceable.rs b/crates/buzz-db/src/store/replaceable.rs index 1ccee163320..36cc4a5d7aa 100644 --- a/crates/buzz-db/src/store/replaceable.rs +++ b/crates/buzz-db/src/store/replaceable.rs @@ -123,8 +123,9 @@ async fn replace_parameterized_event_in_transaction_impl( pubkey_bytes.as_slice(), Some(d_tag.as_bytes()), ); - observability::observe_advisory_lock( + observability::observe_event_lock( LockType::Replacement, + kind_i32, sqlx::query("SELECT pg_advisory_xact_lock($1)") .bind(lock_key) .execute(tx.conn()), @@ -278,11 +279,15 @@ async fn replace_parameterized_event_in_transaction_impl( .await?; } let statement = if hard_delete_superseded { - "DELETE FROM events \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" + superseded_with_mentions_sql!( + "DELETE FROM events \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" + ) } else { - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" + superseded_with_mentions_sql!( + "UPDATE events SET deleted_at = NOW() \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" + ) }; sqlx::query(statement) .bind(community_id.as_uuid()) @@ -299,16 +304,6 @@ async fn replace_parameterized_event_in_transaction_impl( .execute(tx.conn()) .await?; } - - if hard_delete_superseded { - if let Some((_, existing_id)) = &existing { - sqlx::query("DELETE FROM event_mentions WHERE community_id = $1 AND event_id = $2") - .bind(community_id.as_uuid()) - .bind(existing_id) - .execute(tx.conn()) - .await?; - } - } } let sig_bytes = event.sig.serialize(); @@ -335,6 +330,10 @@ async fn replace_parameterized_event_in_transaction_impl( if insert_result.rows_affected() == 0 { return Ok(false); } + // After the replay exit: a stored id (even soft-deleted) is a + // duplicate, not a floor rejection. Failure rolls back to the + // savepoint, restoring the previous live head. + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id).await?; if is_nip_rs { sqlx::query( @@ -383,8 +382,14 @@ async fn replace_parameterized_event_in_transaction_impl( .execute(tx.conn()) .await?; if status == ParameterizedReplaceStatus::Inserted { - crate::store::event_follow_up::after_admitted_insert(tx, incoming_id, kind_i32, channel_id) - .await?; + crate::store::event_follow_up::after_admitted_insert( + tx, + incoming_id, + created_at, + kind_i32, + channel_id, + ) + .await?; } Ok(ParameterizedReplaceResult::new( @@ -395,9 +400,203 @@ async fn replace_parameterized_event_in_transaction_impl( )) } +/// The `WHERE` scope of one replaceable coordinate's head read and supersede. +/// `in_channel` binds the channel as `$4`; `global` binds three parameters. +/// +/// The channel predicate is spelled per case, never `IS NOT DISTINCT FROM $4`: +/// a btree cannot use that as an index condition, so the read would filter +/// every live row of the (kind, pubkey) across all of its channels. The relay +/// signs every channel's state events with one key, so each channel-state +/// write would scan the whole community's. +macro_rules! replacement_scope { + (in_channel) => { + "WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ + AND channel_id = $4 AND deleted_at IS NULL" + }; + (global) => { + "WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ + AND channel_id IS NULL AND deleted_at IS NULL" + }; +} + +/// The newest live row of one replaceable coordinate. +macro_rules! replacement_head_sql { + ($scope:tt) => { + concat!( + "SELECT created_at, id FROM events ", + replacement_scope!($scope), + " ORDER BY created_at DESC, id ASC LIMIT 1" + ) + }; +} + +/// Take the replacement lock of the `(kind, pubkey, channel_id)` coordinate +/// on `tx`, serializing every writer of that coordinate until the transaction +/// ends. Key collisions only cause extra serialization; they cannot change +/// behavior. Taken once per write: it is reentrant, but each take records an +/// acquisition and a wait sample. +pub(crate) async fn take_replacement_lock( + tx: &mut AdmittedTx, + kind: i32, + pubkey: &[u8], + channel_id: Option, +) -> Result<()> { + let lock_key = event_replacement_lock_key( + tx.community(), + kind, + pubkey, + channel_id.as_ref().map(|id| id.as_bytes().as_slice()), + ); + observability::observe_event_lock( + LockType::Replacement, + kind, + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(lock_key) + .execute(tx.conn()), + ) + .await?; + Ok(()) +} + +/// Replace a replaceable event on a caller-owned transaction that already +/// holds the coordinate's replacement lock ([`take_replacement_lock`]): the +/// body of [`Db::replace_addressable_event`], shared with the relay's locked +/// group-state snapshots. +/// +/// Returns `(event, false)` for a stale write or a duplicate ID. The caller +/// commits only when the event was inserted and rolls back otherwise: a +/// duplicate leaves the previous event soft-deleted on the transaction. +pub(crate) async fn replace_addressable_event_under_lock( + tx: &mut AdmittedTx, + event: &nostr::Event, + channel_id: Option, +) -> Result<(StoredEvent, bool)> { + let community_id = tx.community(); + let kind_i32 = buzz_core::kind::event_kind_i32(event); + let pubkey_bytes = event.pubkey.to_bytes(); + let created_at_secs = event.created_at.as_secs() as i64; + let created_at = chrono::DateTime::from_timestamp(created_at_secs, 0) + .ok_or(DbError::InvalidTimestamp(created_at_secs))?; + + // Check for the newest existing event. ORDER BY + LIMIT 1 is defensive against + // historical data where prior bugs may have left multiple live rows. + let (head_sql, supersede_sql) = if channel_id.is_some() { + ( + replacement_head_sql!(in_channel), + superseded_with_mentions_sql!(concat!( + "UPDATE events SET deleted_at = NOW() ", + replacement_scope!(in_channel) + )), + ) + } else { + ( + replacement_head_sql!(global), + superseded_with_mentions_sql!(concat!( + "UPDATE events SET deleted_at = NOW() ", + replacement_scope!(global) + )), + ) + }; + let mut head = sqlx::query_as(head_sql) + .bind(community_id.as_uuid()) + .bind(kind_i32) + .bind(pubkey_bytes.as_slice()); + if let Some(channel_id) = channel_id { + head = head.bind(channel_id); + } + let existing: Option<(chrono::DateTime, Vec)> = + head.fetch_optional(tx.conn()).await?; + + // Stale-write protection: reject if incoming is not newer. + // NIP-16: created_at is second-resolution. On same-second tie, lowest + // event id (lexicographic) wins — deterministic across relays. + let incoming_id = event.id.as_bytes().as_slice(); + if let Some((existing_ts, existing_id)) = existing { + let dominated = created_at < existing_ts + || (created_at == existing_ts && incoming_id >= existing_id.as_slice()); + if dominated { + let received_at = chrono::Utc::now(); + return Ok(( + StoredEvent::with_received_at(event.clone(), received_at, channel_id, false), + false, + )); + } + } + + let tags_json = serde_json::to_value(&event.tags)?; + crate::channel_members::guard_channel_roster_event(tx, kind_i32, channel_id, &tags_json) + .await?; + + // Soft-delete the old event (if any). + let mut supersede = sqlx::query(supersede_sql) + .bind(community_id.as_uuid()) + .bind(kind_i32) + .bind(pubkey_bytes.as_slice()); + if let Some(channel_id) = channel_id { + supersede = supersede.bind(channel_id); + } + supersede.execute(tx.conn()).await?; + + // Insert the new event inside the same transaction. + let sig_bytes = event.sig.serialize(); + let received_at = chrono::Utc::now(); + let d_tag = crate::event::extract_d_tag(event); + + let insert_result = sqlx::query( + "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) \ + ON CONFLICT DO NOTHING", + ) + .bind(community_id.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .bind(pubkey_bytes.as_slice()) + .bind(created_at) + .bind(kind_i32) + .bind(&tags_json) + .bind(&event.content) + .bind(sig_bytes.as_slice()) + .bind(received_at) + .bind(channel_id) + .bind(d_tag.as_deref()) + .execute(tx.conn()) + .await?; + + if insert_result.rows_affected() == 0 { + // ON CONFLICT fired — the event ID already exists. The caller's + // rollback restores the previous replaceable event. + return Ok(( + StoredEvent::with_received_at(event.clone(), received_at, channel_id, false), + false, + )); + } + // After the replay exit, as in the parameterized path; the caller's + // rollback restores the previous head on failure. + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id).await?; + + crate::store::event_follow_up::after_admitted_insert( + tx, + event.id.as_bytes().as_slice(), + created_at, + kind_i32, + channel_id, + ) + .await?; + + // The replaceable event and its denormalized mention index are one + // authoritative discovery write. An indexing error must roll back the + // new event and restore the previously-live event. + crate::insert_mentions_in_transaction(tx, event, channel_id).await?; + + Ok(( + StoredEvent::with_received_at(event.clone(), received_at, channel_id, true), + true, + )) +} + impl Db { /// Atomically replace a replaceable event: NIP-16 kinds (0, 3, 41, 10000–19999) - /// and NIP-29 discovery state (39000–39002, called from side_effects.rs). + /// and NIP-29 discovery state (39000–39002) written outside the relay's + /// locked group-state snapshots, e.g. by `buzz-admin`. /// /// Keeps only the event with the highest `created_at` per (kind, pubkey, channel_id). /// Same-second ties are broken by lowest event `id` (NIP-16 deterministic ordering). @@ -410,20 +609,6 @@ impl Db { event: &nostr::Event, channel_id: Option, ) -> Result<(StoredEvent, bool)> { - let kind_i32 = buzz_core::kind::event_kind_i32(event); - let pubkey_bytes = event.pubkey.to_bytes(); - let created_at_secs = event.created_at.as_secs() as i64; - let created_at = chrono::DateTime::from_timestamp(created_at_secs, 0) - .ok_or(DbError::InvalidTimestamp(created_at_secs))?; - - // Collisions only cause extra serialization; they cannot change behavior. - let lock_key = event_replacement_lock_key( - community_id, - kind_i32, - pubkey_bytes.as_slice(), - channel_id.as_ref().map(|id| id.as_bytes().as_slice()), - ); - let mut tx = crate::begin_community_event_write_transaction_with_legacy_metrics( &self.pool, community_id, @@ -437,136 +622,84 @@ impl Db { transaction_timer .observe(async { - // Serialize all writers for the same (kind, pubkey, channel_id) tuple. - // Advisory lock is transaction-scoped — released on commit/rollback. - observability::observe_advisory_lock( - observability::LockType::Replacement, - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(lock_key) - .execute(tx.conn()), + take_replacement_lock( + &mut tx, + buzz_core::kind::event_kind_i32(event), + &event.pubkey.to_bytes(), + channel_id, ) .await?; - - // Check for the newest existing event. ORDER BY + LIMIT 1 is defensive against - // historical data where prior bugs may have left multiple live rows. - let existing: Option<(chrono::DateTime, Vec)> = - sqlx::query_as( - "SELECT created_at, id FROM events \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ - AND channel_id IS NOT DISTINCT FROM $4 \ - AND deleted_at IS NULL \ - ORDER BY created_at DESC, id ASC LIMIT 1", - ) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(channel_id) - .fetch_optional(tx.conn()) - .await?; - - // Stale-write protection: reject if incoming is not newer. - // NIP-16: created_at is second-resolution. On same-second tie, lowest - // event id (lexicographic) wins — deterministic across relays. - let incoming_id = event.id.as_bytes().as_slice(); - if let Some((existing_ts, existing_id)) = existing { - let dominated = created_at < existing_ts - || (created_at == existing_ts - && incoming_id >= existing_id.as_slice()); - if dominated { - tx.rollback().await?; - let received_at = chrono::Utc::now(); - return Ok(( - StoredEvent::with_received_at( - event.clone(), - received_at, - channel_id, - false, - ), - false, - )); - } + let (stored, was_inserted) = + replace_addressable_event_under_lock(&mut tx, event, channel_id).await?; + if was_inserted { + tx.commit().await?; + } else { + tx.rollback().await?; } + Ok((stored, was_inserted)) + }) + .await + } - let tags_json = serde_json::to_value(&event.tags)?; - crate::channel_members::guard_channel_roster_event( - &mut tx, kind_i32, channel_id, &tags_json, - ) - .await?; - - // Soft-delete the old event (if any). IS NOT DISTINCT FROM for NULL safety. - sqlx::query( - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 \ - AND channel_id IS NOT DISTINCT FROM $4 \ - AND deleted_at IS NULL", - ) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(channel_id) - .execute(tx.conn()) - .await?; - - // Insert the new event inside the same transaction. - let sig_bytes = event.sig.serialize(); - let received_at = chrono::Utc::now(); - let d_tag = crate::event::extract_d_tag(event); - - let insert_result = sqlx::query( - "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) \ - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) \ - ON CONFLICT DO NOTHING", - ) - .bind(community_id.as_uuid()) - .bind(event.id.as_bytes().as_slice()) - .bind(pubkey_bytes.as_slice()) - .bind(created_at) - .bind(kind_i32) - .bind(&tags_json) - .bind(&event.content) - .bind(sig_bytes.as_slice()) - .bind(received_at) - .bind(channel_id) - .bind(d_tag.as_deref()) - .execute(tx.conn()) - .await?; + /// Replace a relay-built replaceable event whose `created_at` depends on + /// the live head: `build` receives the head's `created_at` (or `None`) + /// read behind the coordinate's replacement lock, so concurrent writers + /// of one coordinate each see the previous writer's event and can stamp + /// theirs strictly later. The built event must be signed by `pubkey` and + /// have `kind`. Otherwise as [`Db::replace_addressable_event`]. + #[datastore_span(name = "replace_addressable_event_after_head", system = "postgresql")] + pub async fn replace_addressable_event_after_head( + &self, + community_id: CommunityId, + kind: i32, + pubkey: &[u8], + channel_id: Option, + build: impl FnOnce(Option) -> Result + Send, + ) -> Result<(StoredEvent, bool)> { + let mut tx = crate::begin_community_event_write_transaction_with_legacy_metrics( + &self.pool, + community_id, + observability::WriterOperation::EventWrite, + ) + .await?; + tx.set_push_enqueue(self.push_enqueue.clone()); + let transaction_timer = observability::TransactionTimer::start( + observability::TransactionOperation::ReplaceAddressableEvent, + ); - let was_inserted = insert_result.rows_affected() > 0; - if !was_inserted { - // ON CONFLICT fired — the event ID already exists. Rollback the - // soft-delete so we don't lose the previous replaceable event. - tx.rollback().await?; - return Ok(( - StoredEvent::with_received_at( - event.clone(), - received_at, - channel_id, - false, - ), - false, + transaction_timer + .observe(async { + take_replacement_lock(&mut tx, kind, pubkey, channel_id).await?; + let head_sql = if channel_id.is_some() { + replacement_head_sql!(in_channel) + } else { + replacement_head_sql!(global) + }; + let mut head = sqlx::query_as(head_sql) + .bind(community_id.as_uuid()) + .bind(kind) + .bind(pubkey); + if let Some(channel_id) = channel_id { + head = head.bind(channel_id); + } + let existing: Option<(chrono::DateTime, Vec)> = + head.fetch_optional(tx.conn()).await?; + let event = build(existing.map(|(created_at, _)| created_at.timestamp() as u64))?; + if buzz_core::kind::event_kind_i32(&event) != kind + || event.pubkey.to_bytes().as_slice() != pubkey + { + return Err(DbError::InvalidData( + "replacement does not match its locked coordinate".into(), )); } - - crate::store::event_follow_up::after_admitted_insert( - &mut tx, - event.id.as_bytes().as_slice(), - kind_i32, - channel_id, - ) - .await?; - - // The replaceable event and its denormalized mention index are one - // authoritative discovery write. An indexing error must roll back the - // new event and restore the previously-live event. - crate::insert_mentions_in_transaction(&mut tx, event, channel_id) - .await?; - - tx.commit().await?; - - Ok(( - StoredEvent::with_received_at(event.clone(), received_at, channel_id, true), - true, - )) + let (stored, was_inserted) = + replace_addressable_event_under_lock(&mut tx, &event, channel_id).await?; + if was_inserted { + tx.commit().await?; + } else { + tx.rollback().await?; + } + Ok((stored, was_inserted)) }) .await } @@ -639,6 +772,7 @@ impl Db { #[cfg(test)] mod postgres_tests { use super::*; + use crate::test_support::ScratchDb; use crate::{event, migration, replaceable}; use sqlx::postgres::PgPoolOptions; use sqlx::{Acquire, PgPool}; @@ -676,52 +810,6 @@ mod postgres_tests { std::env::var("TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.into()) } - /// Create a fresh scratch database on the same server and optionally run migrations. - async fn create_scratch_db_through( - admin: &PgPool, - prefix: &str, - target: Option, - ) -> (PgPool, String) { - let name = format!("{}_{}", prefix, Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(admin) - .await - .expect("create scratch db"); - let base = admin_url().await; - // Swap the database path segment of the admin URL for the scratch name. - let scratch_url = { - let idx = base.rfind('/').expect("db url has a path segment"); - format!("{}/{}", &base[..idx], name) - }; - let pool = PgPool::connect(&scratch_url) - .await - .expect("connect scratch db"); - match target { - Some(target) => migration::run_migrations_through(&pool, target) - .await - .expect("migrate scratch db through target"), - None => migration::run_migrations(&pool) - .await - .expect("migrate scratch db"), - } - (pool, name) - } - - /// Create a fresh scratch database on the same server and run all migrations. - /// Returns (pool, db_name); callers should `drop_scratch_db` when done. - async fn create_scratch_db(admin: &PgPool, prefix: &str) -> (PgPool, String) { - create_scratch_db_through(admin, prefix, None).await - } - - async fn drop_scratch_db(admin: &PgPool, pool: PgPool, name: &str) { - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(admin) - .await; - } - /// Insert identical community + channel rows into a database so the same /// (community, channel) ids resolve in both writer and replica. async fn seed_community_channel( @@ -757,10 +845,7 @@ mod postgres_tests { async fn addressable_replacement_rolls_back_when_mention_indexing_fails() { use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (pool, scratch_name) = create_scratch_db(&admin, "atomic_addressable").await; + let (pool, _scratch) = ScratchDb::migrated(&admin_url().await, "atomic_addressable").await; let db = Db::from_pool(pool.clone()); let community_uuid = Uuid::new_v4(); let channel = Uuid::new_v4(); @@ -830,26 +915,446 @@ mod postgres_tests { .await .expect("count rolled-back event"); assert_eq!(new_rows, 0, "new roster must roll back with its index"); + } + + /// A replaceable write supersedes only its own channel's head, and a + /// channel-less (global) write only the global head. Each case reads and + /// supersedes through its own `channel_id` predicate, so this pins that + /// neither spelling reaches the other's rows. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn addressable_replacement_supersedes_only_its_own_channel_scope() { + use nostr::{EventBuilder, Keys, Kind, Timestamp}; + + let (pool, _scratch) = ScratchDb::migrated(&admin_url().await, "addressable_scope").await; + let db = Db::from_pool(pool.clone()); + let community_uuid = Uuid::new_v4(); + let owner_keys = Keys::generate(); + let channel_a = Uuid::new_v4(); + let channel_b = Uuid::new_v4(); + seed_community_channel(&pool, community_uuid, channel_a, &owner_keys).await; + crate::channel::create_channel_with_id( + &pool, + CommunityId::from_uuid(community_uuid), + channel_b, + &format!("replica-routing-{channel_b}"), + crate::channel::ChannelType::Stream, + crate::channel::ChannelVisibility::Open, + None, + owner_keys.public_key().to_bytes().as_slice(), + None, + &[], + ) + .await + .expect("create second channel"); + let community = CommunityId::from_uuid(community_uuid); + let keys = Keys::generate(); + let base = Timestamp::now().as_secs(); + let version = |offset: u64, content: &str| { + EventBuilder::new(Kind::Custom(10_050), content) + .custom_created_at(Timestamp::from(base + offset)) + .sign_with_keys(&keys) + .expect("sign version") + }; + let live = |event: &nostr::Event| { + let pool = pool.clone(); + let id = event.id.as_bytes().to_vec(); + async move { + sqlx::query_scalar::<_, bool>( + "SELECT deleted_at IS NULL FROM events WHERE community_id = $1 AND id = $2", + ) + .bind(community_uuid) + .bind(id) + .fetch_one(&pool) + .await + .expect("read head") + } + }; + + let global = version(0, "global"); + let in_a = version(1, "a"); + let in_b = version(2, "b"); + for (event, channel) in [ + (&global, None), + (&in_a, Some(channel_a)), + (&in_b, Some(channel_b)), + ] { + assert!( + db.replace_addressable_event(community, event, channel) + .await + .expect("insert head") + .1, + "each scope starts with its own head" + ); + } + assert!(live(&global).await && live(&in_a).await && live(&in_b).await); - drop_scratch_db(&admin, pool, &scratch_name).await; + let newer_a = version(3, "a2"); + db.replace_addressable_event(community, &newer_a, Some(channel_a)) + .await + .expect("replace in channel a"); + assert!(!live(&in_a).await, "channel a's old head is superseded"); + assert!(live(&newer_a).await); + assert!(live(&in_b).await, "channel b's head is untouched"); + assert!(live(&global).await, "the global head is untouched"); + + // An older write is judged against its own scope's head only: channel + // b's newest head (offset 2) must not make this channel-less write stale. + let newer_global = version(1, "global2"); + assert!( + db.replace_addressable_event(community, &newer_global, None) + .await + .expect("replace global") + .1, + "a global write is ordered against the global head only" + ); + assert!(!live(&global).await, "the old global head is superseded"); + assert!( + live(&newer_a).await && live(&in_b).await, + "channel heads are untouched" + ); } + /// Both channel spellings of the head read and the supersede must reach a + /// btree as an index condition. `channel_id IS NOT DISTINCT FROM $4` cannot, + /// so a relay channel-state write would filter every live row of its kind + /// across the community instead of seeking to one channel. + /// + /// The fixture is that shape: one relay key with a live head of one kind in + /// each of many channels, plus one channel-less head, with fresh + /// statistics. On an empty table the planner prefers the newest-first + /// `(pubkey, kind)` index for `LIMIT 1` and filters the channel, which is + /// exactly the walk this guards against once the rows exist. `events` is + /// partitioned, so the check reads the JSON plan and holds every populated + /// partition's scan to it, not just one node. #[tokio::test] #[ignore = "requires Postgres"] - async fn stale_legacy_roster_cannot_replace_new_locked_snapshot() { + async fn replacement_channel_predicate_is_an_index_condition() { + const CHANNELS: i32 = 4_000; + let (pool, _scratch) = + ScratchDb::migrated(&admin_url().await, "replacement_channel_seek").await; + let community = make_community(&pool).await; + let relay = [7_u8; 32]; + sqlx::query( + "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, \ + channel_id) \ + SELECT $1, sha256(int4send(g)), $2, now() - make_interval(secs => g), 39000, \ + '[]'::jsonb, '', sha256(int4send(g)) || sha256(int4send(g)), \ + CASE WHEN g = 0 THEN NULL ELSE gen_random_uuid() END \ + FROM generate_series(0, $3) g", + ) + .bind(community) + .bind(relay.as_slice()) + .bind(CHANNELS) + .execute(&pool) + .await + .expect("seed one head per channel"); + sqlx::query("ANALYZE events") + .execute(&pool) + .await + .expect("analyze events"); + let channel: Uuid = sqlx::query_scalar( + "SELECT channel_id FROM events WHERE community_id = $1 AND channel_id IS NOT NULL \ + LIMIT 1", + ) + .bind(community) + .fetch_one(&pool) + .await + .expect("pick a channel"); + // Seeded rows span a partition boundary only near a month's start, so + // this is one partition or two. + let mut populated: Vec = sqlx::query_scalar( + "SELECT DISTINCT c.relname::text FROM events e \ + JOIN pg_class c ON c.oid = e.tableoid WHERE e.community_id = $1", + ) + .bind(community) + .fetch_all(&pool) + .await + .expect("populated partitions"); + populated.sort(); + + let statements = [ + ( + true, + replacement_head_sql!(in_channel), + superseded_with_mentions_sql!(concat!( + "UPDATE events SET deleted_at = NOW() ", + replacement_scope!(in_channel) + )), + ), + ( + false, + replacement_head_sql!(global), + superseded_with_mentions_sql!(concat!( + "UPDATE events SET deleted_at = NOW() ", + replacement_scope!(global) + )), + ), + ]; + for (in_channel, head_sql, supersede_sql) in statements { + for sql in [head_sql, supersede_sql] { + let explain = format!("EXPLAIN (FORMAT JSON) {sql}"); + let mut query = + sqlx::query_scalar::<_, serde_json::Value>(sqlx::AssertSqlSafe(explain)) + .bind(community) + .bind(39_000_i32) + .bind(relay.as_slice()); + if in_channel { + query = query.bind(channel); + } + let plan = query.fetch_one(&pool).await.expect("explain"); + let mut scanned = Vec::new(); + partition_scans_seeking_channel( + &plan[0]["Plan"], + &populated, + &mut scanned, + &format!("in_channel={in_channel}"), + ); + scanned.sort(); + assert_eq!( + scanned, populated, + "in_channel={in_channel}: every populated partition is scanned once:\n{plan:#}" + ); + } + } + } + + /// Walk `node` and assert that each scan of a `populated` partition seeks + /// by `channel_id`: an index scan's own `Index Cond`, or a bitmap heap + /// scan's index child. Records each partition scan it checked. + fn partition_scans_seeking_channel( + node: &serde_json::Value, + populated: &[String], + scanned: &mut Vec, + context: &str, + ) { + fn index_cond_names_channel(node: &serde_json::Value) -> bool { + node["Index Cond"] + .as_str() + .is_some_and(|cond| cond.contains("channel_id")) + || node["Plans"] + .as_array() + .is_some_and(|plans| plans.iter().any(index_cond_names_channel)) + } + + if let Some(relation) = node["Relation Name"] + .as_str() + .filter(|relation| populated.iter().any(|p| p == relation)) + { + assert!( + index_cond_names_channel(node), + "{context}: the {} on {relation} must seek by channel_id:\n{node:#}", + node["Node Type"] + ); + scanned.push(relation.to_owned()); + } + for child in node["Plans"].as_array().into_iter().flatten() { + partition_scans_seeking_channel(child, populated, scanned, context); + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn superseded_heads_drop_their_mention_rows() { use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; - let admin = PgPool::connect(&admin_url().await) + let (pool, _scratch) = ScratchDb::migrated(&admin_url().await, "superseded_mentions").await; + let db = Db::from_pool(pool.clone()); + let community_uuid = Uuid::new_v4(); + let channel = Uuid::new_v4(); + // The signer must differ from every p-tagged key: the builder drops + // self-references. + let keys = Keys::generate(); + let owner_keys = Keys::generate(); + seed_community_channel(&pool, community_uuid, channel, &owner_keys).await; + let community = CommunityId::from_uuid(community_uuid); + let owner = owner_keys.public_key().to_hex(); + let mentioned: Vec = (0..3) + .map(|_| Keys::generate().public_key().to_hex()) + .collect(); + let mention_rows = |event: &nostr::Event| { + let id = event.id.as_bytes().to_vec(); + let pool = pool.clone(); + async move { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM event_mentions WHERE community_id = $1 AND event_id = $2", + ) + .bind(community_uuid) + .bind(id) + .fetch_one(&pool) + .await + .expect("count mention rows") + } + }; + let base = Timestamp::now().as_secs(); + + // Every supersede path retires the old head with a soft delete, except + // NIP-RS read state and mesh status, which the NIP-33 path hard-deletes. + // The relay roster writer is the production kind:39002 path; its p tags + // must match the channel's members. The relay-signed kind:13535 list + // goes through the addressable path. + enum Path { + MemberSnapshot, + Addressable, + Parameterized, + } + let roster_p = vec![vec![owner.as_str(), "", "owner"]]; + let people_p = + || -> Vec> { mentioned.iter().map(|pk| vec![pk.as_str()]).collect() }; + let relay_pubkey = keys.public_key().to_bytes(); + for (case, path, kind, d_tag, extra_tags, p_tags, hard_delete) in [ + ( + "member snapshot", + Path::MemberSnapshot, + 39002_u16, + Some(channel.to_string()), + vec![], + roster_p, + false, + ), + ( + "addressable", + Path::Addressable, + 13535_u16, + None, + vec![], + people_p(), + false, + ), + ( + "parameterized", + Path::Parameterized, + 30000_u16, + Some("people".to_owned()), + vec![], + people_p(), + false, + ), + ( + "NIP-RS read state", + Path::Parameterized, + buzz_core::kind::KIND_READ_STATE as u16, + Some(format!("read-state:{}", "a".repeat(32))), + vec![["t", "read-state"]], + people_p(), + true, + ), + ( + "mesh status", + Path::Parameterized, + buzz_core::kind::KIND_BOOKMARK_SET as u16, + Some("buzz-mesh-member-status:owner-test".to_owned()), + vec![["k", "buzz-mesh-status"]], + people_p(), + true, + ), + ] { + let indexed = p_tags.len() as i64; + let version = |offset: u64, content: &str| { + let mut tags: Vec = d_tag + .iter() + .map(|d| Tag::parse(["d", d.as_str()]).expect("d tag")) + .collect(); + tags.extend( + extra_tags + .iter() + .map(|t| Tag::parse(*t).expect("extra tag")), + ); + tags.extend(p_tags.iter().map(|p| { + let mut parts = vec!["p"]; + parts.extend(p.iter().copied()); + Tag::parse(parts).expect("p tag") + })); + EventBuilder::new(Kind::Custom(kind), content) + .tags(tags) + .custom_created_at(Timestamp::from(base + offset)) + .sign_with_keys(&keys) + .expect("sign version") + }; + let replace = |event: nostr::Event| { + let db = &db; + let d_tag = d_tag.clone(); + let path = &path; + async move { + let inserted = match path { + Path::MemberSnapshot => { + let mut snapshot = db + .lock_member_snapshot(community, channel, &relay_pubkey) + .await + .expect("lock member snapshot"); + let inserted = snapshot + .replace_member_event(&event) + .await + .expect("replace roster") + .1; + snapshot.release().await.expect("commit roster"); + inserted + } + Path::Addressable => { + db.replace_addressable_event(community, &event, None) + .await + .expect("replace addressable") + .1 + } + Path::Parameterized => { + let d_tag = d_tag.expect("parameterized d tag"); + db.replace_parameterized_event(community, &event, &d_tag, None) + .await + .expect("replace parameterized") + .1 + } + }; + assert!(inserted, "{case}: newer version must be inserted"); + } + }; + + let old = version(0, "old"); + replace(old.clone()).await; + assert_eq!(mention_rows(&old).await, indexed, "{case}: head is indexed"); + + let new = version(1, "new"); + replace(new.clone()).await; + assert_eq!( + mention_rows(&old).await, + 0, + "{case}: retired head keeps no mention rows" + ); + assert_eq!( + mention_rows(&new).await, + indexed, + "{case}: new head is indexed" + ); + let retired: Option = sqlx::query_scalar( + "SELECT deleted_at IS NOT NULL FROM events WHERE community_id = $1 AND id = $2", + ) + .bind(community_uuid) + .bind(old.id.as_bytes().as_slice()) + .fetch_optional(&pool) .await - .expect("connect admin"); - let (setup_pool, scratch_name) = create_scratch_db(&admin, "mixed_roster_writer").await; - let base_url = admin_url().await; - let slash = base_url.rfind('/').expect("database URL has path segment"); - let scratch_url = format!("{}/{}", &base_url[..slash], scratch_name); + .expect("read retired head"); + if hard_delete { + assert_eq!(retired, None, "{case}: the old head is removed"); + } else { + assert_eq!( + retired, + Some(true), + "{case}: the old head is soft-deleted, not removed" + ); + } + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn stale_legacy_roster_cannot_replace_new_locked_snapshot() { + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + + let (setup_pool, scratch) = + ScratchDb::migrated(&admin_url().await, "mixed_roster_writer").await; let pool = PgPoolOptions::new() .max_connections(1) .acquire_timeout(Duration::from_secs(1)) - .connect(&scratch_url) + .connect(scratch.url()) .await .expect("connect one-connection scratch pool"); setup_pool.close().await; @@ -1004,8 +1509,6 @@ mod postgres_tests { .await .expect("count rejected stale roster"); assert_eq!(stale_rows, 0, "stale roster insert must roll back"); - - drop_scratch_db(&admin, pool, &scratch_name).await; } #[tokio::test] @@ -1099,7 +1602,12 @@ mod postgres_tests { .await .expect("load community host"); let submitted = store - .submit(&host, "test-operator", Some("replaceable fence regression")) + .submit( + Some(&host), + "test-operator", + Some("replaceable fence regression"), + None, + ) .await .expect("submit deletion request"); let empty_digest = crate::deletion::KeyStreamDigest::new().finish().0; @@ -1397,10 +1905,8 @@ mod postgres_tests { async fn parameterized_replacement_rolls_back_when_mention_indexing_fails() { use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; - let admin = PgPool::connect(&admin_url().await) - .await - .expect("connect admin"); - let (pool, scratch_name) = create_scratch_db(&admin, "atomic_parameterized").await; + let (pool, _scratch) = + ScratchDb::migrated(&admin_url().await, "atomic_parameterized").await; let db = Db::from_pool(pool.clone()); let community = CommunityId::from_uuid(make_community(&pool).await); let keys = Keys::generate(); @@ -1489,8 +1995,6 @@ mod postgres_tests { .expect("count rolled-back project"); assert_eq!(new_rows, 0); tx.commit().await.expect("commit usable caller transaction"); - - drop_scratch_db(&admin, pool, &scratch_name).await; } #[tokio::test] diff --git a/crates/buzz-db/src/store/storage_accounting.rs b/crates/buzz-db/src/store/storage_accounting.rs index 73c39bea39c..72e9356e0df 100644 --- a/crates/buzz-db/src/store/storage_accounting.rs +++ b/crates/buzz-db/src/store/storage_accounting.rs @@ -2,9 +2,10 @@ use buzz_datastore_tracing::datastore_span; use chrono::{DateTime, Utc}; -use sqlx::postgres::PgConnection; +use sqlx::{postgres::PgConnection, Connection}; +use uuid::Uuid; -use crate::{observability, Db, Result}; +use crate::{observability, Db, DbError, Result}; /// Deployment-global advisory lock for the run-once storage worker. pub const STORAGE_ACCOUNTING_LOCK_KEY: i64 = 0x4255_5a5a_5354_4f52; @@ -14,6 +15,17 @@ pub struct StorageAccountingLeader { connection: PgConnection, } +/// A community that storage-usage delivery reports on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StorageUsageCommunity { + /// The community UUID used by the snapshot's per-community map. + pub id: Uuid, + /// The canonical host stored on the community row. + pub host: String, + /// Whether the community is serving: not archived and not being deleted. + pub active: bool, +} + /// The newest complete snapshot stored by the worker. #[derive(Debug, Clone)] pub struct StoredStorageSnapshot { @@ -58,6 +70,31 @@ impl StorageAccountingLeader { .await?; Ok(()) } + + /// Unlock the lease on its own session, then close that session. + /// + /// Dropping the leader frees the lease only once PostgreSQL notices the + /// closed socket and ends the old backend, which can lag on a loaded + /// server. When this returns `Ok`, the unlock has run on the lease's own + /// session, so the lease is already free for a successor's + /// [`Db::try_lock_storage_accounting`], even if the close then failed. + /// An error means the unlock failed or this session no longer held the + /// lease. + #[datastore_span(name = "release_storage_accounting", system = "postgresql")] + pub async fn release(mut self) -> Result<()> { + let unlocked = sqlx::query_scalar::<_, bool>("SELECT pg_advisory_unlock($1)") + .bind(STORAGE_ACCOUNTING_LOCK_KEY) + .fetch_one(&mut self.connection) + .await; + let _ = self.connection.close().await; + if unlocked? { + Ok(()) + } else { + Err(DbError::InvalidData( + "storage-accounting session did not hold its lease".into(), + )) + } + } } impl Db { @@ -100,41 +137,52 @@ impl Db { }, )) } + + /// Load only the newest snapshot's commit time, so a poller can detect a + /// new snapshot without decoding the full per-community payload. + #[datastore_span(name = "load_storage_accounting_completed_at", system = "postgresql")] + pub async fn load_storage_accounting_completed_at(&self) -> Result>> { + let mut connection = + observability::acquire_writer(&self.pool, observability::WriterOperation::Maintenance) + .await?; + Ok(sqlx::query_scalar::<_, DateTime>( + "SELECT completed_at FROM storage_accounting_snapshots WHERE singleton = TRUE", + ) + .fetch_optional(&mut *connection) + .await?) + } + + /// List every community with its host and whether it is still serving. + #[datastore_span(name = "storage_usage_communities", system = "postgresql")] + pub async fn storage_usage_communities(&self) -> Result> { + let mut connection = + observability::acquire_writer(&self.pool, observability::WriterOperation::Maintenance) + .await?; + let rows = sqlx::query_as::<_, (Uuid, String, bool)>( + "SELECT id, host, \ + (archived_at IS NULL AND deleted_at IS NULL AND deletion_state = 'active') \ + FROM communities", + ) + .fetch_all(&mut *connection) + .await?; + Ok(rows + .into_iter() + .map(|(id, host, active)| StorageUsageCommunity { id, host, active }) + .collect()) + } } #[cfg(test)] mod postgres_tests { use super::*; + use crate::test_support::ScratchDb; use sqlx::postgres::PgPoolOptions; - use sqlx::PgPool; - use uuid::Uuid; - - async fn create_scratch_db(admin: &PgPool) -> (PgPool, String) { - let name = format!("storage_accounting_{}", Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(admin) - .await - .expect("create scratch db"); - let base = crate::test_support::database_url(); - let idx = base.rfind('/').expect("db url has path"); - let pool = PgPool::connect(&format!("{}/{name}", &base[..idx])) - .await - .expect("connect scratch db"); - crate::migration::run_migrations(&pool) - .await - .expect("migrate scratch db"); - (pool, name) - } #[tokio::test] #[ignore = "requires Postgres"] async fn complete_snapshot_replaces_atomically_and_worker_lock_excludes_overlap() { - let admin = PgPoolOptions::new() - .max_connections(1) - .connect(&crate::test_support::database_url()) - .await - .expect("connect admin"); - let (pool, name) = create_scratch_db(&admin).await; + let (pool, _scratch) = + ScratchDb::migrated(&crate::test_support::database_url(), "storage_accounting").await; let first = Db::from_pool(pool.clone()); let second = Db::from_pool(pool.clone()); @@ -169,16 +217,6 @@ mod postgres_tests { assert_eq!(stored.duration_ms, 20); assert_eq!(stored.max_objects, 200); assert_eq!(stored.code_sha, "b"); - - drop(leader); - drop(first); - drop(second); - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(&admin) - .await; } #[tokio::test] @@ -189,7 +227,8 @@ mod postgres_tests { .connect(&crate::test_support::database_url()) .await .expect("connect admin"); - let (pool, name) = create_scratch_db(&admin).await; + let (pool, _scratch) = + ScratchDb::migrated(&crate::test_support::database_url(), "storage_accounting").await; let first = Db::from_pool(pool.clone()); let second = Db::from_pool(pool.clone()); @@ -242,16 +281,136 @@ mod postgres_tests { assert_eq!(stored.duration_ms, 20); assert_eq!(stored.max_objects, 200); assert_eq!(stored.code_sha, "b"); + } - drop(stale_leader); - drop(fresh_leader); - drop(first); - drop(second); - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" + #[tokio::test] + #[ignore = "requires Postgres"] + async fn released_lease_admits_successor_before_old_session_exits() { + let (pool, _scratch) = + ScratchDb::migrated(&crate::test_support::database_url(), "storage_accounting").await; + let db = Db::from_pool(pool.clone()); + + let mut leader = db + .try_lock_storage_accounting() + .await + .expect("first lock") + .expect("first worker owns lock"); + // A closing backend drops its temp tables before it frees session + // locks. Locking the leader's temp table keeps that backend alive + // after release, so only an explicit unlock can admit a successor. + sqlx::query("CREATE TEMP TABLE exit_fence ()") + .execute(&mut leader.connection) + .await + .expect("create leader temp table"); + let (temp_schema, leader_pid) = sqlx::query_as::<_, (String, i32)>( + "SELECT pg_my_temp_schema()::regnamespace::text, pg_backend_pid()", + ) + .fetch_one(&mut leader.connection) + .await + .expect("load leader session"); + let mut exit_fence = pool.begin().await.expect("begin exit fence"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "LOCK TABLE {temp_schema}.exit_fence IN ACCESS SHARE MODE" ))) - .execute(&admin) - .await; + .execute(&mut *exit_fence) + .await + .expect("hold the leader's temp-table cleanup"); + + leader.release().await.expect("release lease"); + let mut successor = db + .try_lock_storage_accounting() + .await + .expect("successor lock attempt") + .expect("a released lease must admit a successor at once"); + let leader_alive = sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = $1)", + ) + .bind(leader_pid) + .fetch_one(&pool) + .await + .expect("load leader backend"); + assert!(leader_alive, "the old backend must not have exited yet"); + exit_fence + .rollback() + .await + .expect("let the old backend exit"); + + // A session that no longer holds the lease must not report it freed. + sqlx::query("SELECT pg_advisory_unlock($1)") + .bind(STORAGE_ACCOUNTING_LOCK_KEY) + .execute(&mut successor.connection) + .await + .expect("unlock out from under the successor"); + successor + .release() + .await + .expect_err("releasing a lease the session lost must fail"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn usage_delivery_reads_snapshot_time_and_community_states() { + let (pool, _scratch) = + ScratchDb::migrated(&crate::test_support::database_url(), "storage_accounting").await; + let db = Db::from_pool(pool.clone()); + + assert_eq!( + db.load_storage_accounting_completed_at() + .await + .expect("load absent completed_at"), + None + ); + let mut leader = db + .try_lock_storage_accounting() + .await + .expect("lock") + .expect("worker owns lock"); + leader + .save_snapshot(&serde_json::json!({"version": 1}), 10, 100, "a") + .await + .expect("save snapshot"); + let stored = db + .load_storage_accounting_snapshot() + .await + .expect("load snapshot") + .expect("snapshot exists"); + assert_eq!( + db.load_storage_accounting_completed_at() + .await + .expect("load completed_at"), + Some(stored.completed_at) + ); + + let mut expected = Vec::new(); + for (host, archived, state, active) in [ + ("active.example", false, "active", true), + ("archived.example", true, "active", false), + ("quiescing.example", false, "quiescing", false), + ("tombstone.example", false, "tombstone", false), + ] { + let id = sqlx::query_scalar::<_, Uuid>( + "INSERT INTO communities (host, archived_at, deletion_state) \ + VALUES ($1, CASE WHEN $2 THEN now() END, $3) RETURNING id", + ) + .bind(host) + .bind(archived) + .bind(state) + .fetch_one(&pool) + .await + .expect("insert community"); + expected.push(StorageUsageCommunity { + id, + host: host.to_string(), + active, + }); + } + let mut communities = db + .storage_usage_communities() + .await + .expect("list communities"); + communities.retain(|community| expected.iter().any(|e| e.id == community.id)); + communities.sort_by(|a, b| a.host.cmp(&b.host)); + expected.sort_by(|a, b| a.host.cmp(&b.host)); + assert_eq!(communities, expected); } } diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 0e4c9d93757..a452f2136f8 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -9,6 +9,8 @@ use chrono::{DateTime, Utc}; use sqlx::{PgPool, Row}; use uuid::Uuid; +use crate::store::recent_pass::Range; + use buzz_datastore_tracing::datastore_span; use buzz_core::CommunityId; @@ -18,6 +20,60 @@ use crate::{ ReadSessionInner, RouteDecision, RoutePredicate, }; +/// [`THREAD_PARTICIPANT_SCAN_LIMIT`] as a literal, so SQL can `concat!` it. +macro_rules! thread_participant_scan_limit { + () => { + 1000 + }; +} + +/// How many of a thread's newest replies a participant summary reads. +/// +/// Participants are the thread's most recently active distinct authors, so +/// the newest replies decide them. Aggregating the whole thread instead made +/// every summary cost O(thread), recomputed after every reply, so one very +/// large thread could saturate the writer. An author silent for this many +/// replies drops out of the facepile, which shows at most 10. +pub const THREAD_PARTICIPANT_SCAN_LIMIT: i64 = thread_participant_scan_limit!(); + +/// Correlated `ARRAY(...)` of up to 10 participant pubkeys, most recent +/// first, for the thread rooted at `root.event_id` in community `$1`. +/// +/// Walks `idx_thread_metadata_window` newest-first and stops after +/// [`THREAD_PARTICIPANT_SCAN_LIMIT`] rows, so cost is bounded by the window, +/// not the thread. The one argument is an extra (possibly empty) predicate on +/// the window's `tm` rows. A macro so callers stay `&'static str` via +/// `concat!`. +macro_rules! recent_thread_participants_sql { + ($extra:literal) => { + concat!( + r#"ARRAY( + SELECT e.pubkey + FROM ( + SELECT tm.event_created_at, tm.event_id + FROM thread_metadata tm + WHERE tm.community_id = $1 + AND tm.root_event_id = root.event_id "#, + $extra, + r#" + ORDER BY tm.event_created_at DESC, tm.event_id ASC + LIMIT "#, + thread_participant_scan_limit!(), + r#" + ) recent + JOIN events e + ON e.community_id = $1 + AND e.created_at = recent.event_created_at + AND e.id = recent.event_id + WHERE e.deleted_at IS NULL + GROUP BY e.pubkey + ORDER BY MAX(e.created_at) DESC, e.pubkey ASC + LIMIT 10 + )"# + ) + }; +} + // -- Structs ------------------------------------------------------------------ /// A single reply within a thread, joined with event content. @@ -56,7 +112,9 @@ pub struct ThreadSummary { pub descendant_count: i32, /// Timestamp of the most recent reply in the thread. pub last_reply_at: Option>, - /// Compressed public keys of all participants who have replied. + /// Up to 10 distinct reply authors, most recently active first, drawn + /// from the newest [`THREAD_PARTICIPANT_SCAN_LIMIT`] replies. Deleted + /// replies count toward that window but contribute no author. pub participants: Vec>, } @@ -467,63 +525,29 @@ pub async fn get_thread_summary( crate::observability::WriterOperation::EventWrite, ) .await?; - let row = sqlx::query( - r#" - SELECT reply_count, descendant_count, last_reply_at - FROM thread_metadata - WHERE community_id = $1 AND event_id = $2 + let row = sqlx::query(concat!( + "SELECT root.reply_count, root.descendant_count, root.last_reply_at, ", + recent_thread_participants_sql!(""), + r#" AS participants + FROM thread_metadata root + WHERE root.community_id = $1 AND root.event_id = $2 LIMIT 1 "#, - ) + )) .bind(community_id.as_uuid()) .bind(event_id) .fetch_optional(&mut *connection) .await?; - let row = match row { - Some(r) => r, - None => return Ok(None), - }; - - let reply_count: i32 = row.try_get("reply_count")?; - let descendant_count: i32 = row.try_get("descendant_count")?; - let last_reply_at: Option> = row.try_get("last_reply_at")?; - - // Collect distinct participant pubkeys from the thread, most recent first. - let participant_rows = sqlx::query( - r#" - SELECT pubkey FROM ( - SELECT DISTINCT e.pubkey, MAX(e.created_at) AS last_seen - FROM thread_metadata tm - JOIN events e - ON e.community_id = tm.community_id - AND e.created_at = tm.event_created_at - AND e.id = tm.event_id - WHERE tm.community_id = $1 - AND tm.root_event_id = $2 - AND e.deleted_at IS NULL - GROUP BY e.pubkey - ) sub - ORDER BY last_seen DESC - LIMIT 10 - "#, - ) - .bind(community_id.as_uuid()) - .bind(event_id) - .fetch_all(&mut *connection) - .await?; - - let participants: Vec> = participant_rows - .into_iter() - .map(|r| r.try_get::, _>("pubkey")) - .collect::>()?; - - Ok(Some(ThreadSummary { - reply_count, - descendant_count, - last_reply_at, - participants, - })) + row.map(|row| { + Ok(ThreadSummary { + reply_count: row.try_get("reply_count")?, + descendant_count: row.try_get("descendant_count")?, + last_reply_at: row.try_get("last_reply_at")?, + participants: row.try_get("participants")?, + }) + }) + .transpose() } /// Fetch one channel window: top-level rows (depth = 0, missing metadata, or @@ -558,6 +582,7 @@ pub async fn get_channel_window( limit, cursor, kind_filter, + crate::event::ReadDeadline::PerRead, ) .await } @@ -566,7 +591,8 @@ pub async fn get_channel_window( /// runs the page (and its participants batch) on the exact reader connection /// whose heartbeat observation proved coverage (the proof is /// connection-local; a different pooled session may sit at a different -/// replay position). +/// replay position). The page runs under the event read deadline, shared by +/// its passes (see `ReadTransaction`). pub(crate) async fn get_channel_window_on( conn: &mut sqlx::PgConnection, community_id: CommunityId, @@ -574,6 +600,7 @@ pub(crate) async fn get_channel_window_on( limit: u32, cursor: Option<(DateTime, Vec)>, kind_filter: Option<&[u32]>, + deadline: crate::event::ReadDeadline, ) -> Result { let mut param_idx = 3u32; // $1 is community_id, $2 is channel_id let mut sql = String::from( @@ -629,20 +656,58 @@ pub(crate) async fn get_channel_window_on( } } - sql.push_str(&format!( - " ORDER BY e.created_at DESC, e.id ASC LIMIT ${param_idx}" - )); - - let mut q = sqlx::query(sqlx::AssertSqlSafe(sql)) - .bind(community_id.as_uuid()) - .bind(channel_id); - if let Some((ts, id)) = &cursor { - q = q.bind(*ts).bind(id.clone()); - } + // Recent-first (see `recent_pass`): the newest partitions answer a window + // that fills there (with its +1 probe row); older rows are read only for + // what is still missing. + let kinds: Option> = + kind_filter.map(|ks| ks.iter().filter_map(|&k| i32::try_from(k).ok()).collect()); + let split = crate::store::recent_pass::split_for( + Utc::now(), + kinds.as_deref(), + None, + cursor.as_ref().map(|(ts, _)| *ts), + ); // The +1 probe row is the server-internal has_more evidence. - q = q.bind(limit as i64 + 1); - - let mut db_rows = q.fetch_all(&mut *conn).await?; + let probe_limit = i64::from(limit) + 1; + let pass_query = |range: Range, pass_limit: i64| { + let mut pass_sql = sql.clone(); + if let Some(bound) = range.predicate("e.created_at") { + pass_sql.push_str(&bound); + } + pass_sql.push_str(&format!( + " ORDER BY e.created_at DESC, e.id ASC LIMIT ${param_idx}" + )); + let mut q = sqlx::query(sqlx::AssertSqlSafe(pass_sql)) + .bind(community_id.as_uuid()) + .bind(channel_id); + if let Some((ts, id)) = &cursor { + q = q.bind(*ts).bind(id.clone()); + } + q.bind(pass_limit) + }; + let mut db_rows = match split { + None => { + crate::event::fetch_with_read_deadline( + &mut *conn, + pass_query(Range::All, probe_limit), + deadline, + ) + .await? + } + Some(split) => { + // One snapshot and one deadline for both passes (see + // `ReadTransaction`). + let mut read = crate::event::ReadTransaction::begin(conn, deadline).await?; + let mut rows = Vec::new(); + let mut pass = Some((Range::Recent(split), probe_limit)); + while let Some((range, pass_limit)) = pass { + rows.extend(read.fetch(pass_query(range, pass_limit)).await?); + pass = crate::store::recent_pass::next(range, rows.len(), probe_limit); + } + read.finish().await?; + rows + } + }; let has_more = db_rows.len() > limit as usize; db_rows.truncate(limit as usize); @@ -692,39 +757,21 @@ pub(crate) async fn get_channel_window_on( } // Batch participants for every row with thread activity — one query for - // the whole window instead of a per-root fan-out. Same shape and 10-cap - // as get_thread_summary. + // the whole window instead of a per-root fan-out, each root bounded the + // same way as get_thread_summary. let roots: Vec> = rows .iter() .filter(|r| r.thread_summary.is_some()) .map(|r| r.stored_event.event.id.as_bytes().to_vec()) .collect(); if !roots.is_empty() { - let participant_rows = sqlx::query( - r#" - SELECT root_event_id, pubkey FROM ( - SELECT - tm.root_event_id, - e.pubkey, - MAX(e.created_at) AS last_seen, - ROW_NUMBER() OVER ( - PARTITION BY tm.root_event_id - ORDER BY MAX(e.created_at) DESC - ) AS rn - FROM thread_metadata tm - JOIN events e - ON e.community_id = tm.community_id - AND e.created_at = tm.event_created_at - AND e.id = tm.event_id - WHERE tm.community_id = $1 - AND tm.root_event_id = ANY($2) - AND e.deleted_at IS NULL - GROUP BY tm.root_event_id, e.pubkey - ) sub - WHERE rn <= 10 - ORDER BY root_event_id, rn + let participant_rows = sqlx::query(concat!( + "SELECT root.event_id, ", + recent_thread_participants_sql!(""), + r#" AS participants + FROM unnest($2::bytea[]) AS root(event_id) "#, - ) + )) .bind(community_id.as_uuid()) .bind(&roots) .fetch_all(&mut *conn) @@ -733,9 +780,7 @@ pub(crate) async fn get_channel_window_on( let mut by_root: std::collections::HashMap, Vec>> = std::collections::HashMap::new(); for row in participant_rows { - let root: Vec = row.try_get("root_event_id")?; - let pubkey: Vec = row.try_get("pubkey")?; - by_root.entry(root).or_default().push(pubkey); + by_root.insert(row.try_get("event_id")?, row.try_get("participants")?); } for row in &mut rows { if let Some(summary) = &mut row.thread_summary { @@ -897,7 +942,7 @@ impl Db { predicate, crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { match crate::thread::get_thread_replies_on( &mut tx, @@ -982,18 +1027,10 @@ impl Db { crate::observability::WriterOperation::SubscriptionHistory, ) .await?; - let rows = sqlx::query( - r#" - SELECT root.event_id, root.reply_count, root.descendant_count, root.last_reply_at, - ARRAY( - SELECT e.pubkey - FROM thread_metadata tm - JOIN events e ON e.community_id = tm.community_id - AND e.created_at = tm.event_created_at AND e.id = tm.event_id - WHERE tm.community_id = root.community_id AND tm.root_event_id = root.event_id - AND tm.channel_id = root.channel_id AND e.deleted_at IS NULL - GROUP BY e.pubkey ORDER BY MAX(e.created_at) DESC LIMIT 10 - ) AS participants + let rows = sqlx::query(concat!( + "SELECT root.event_id, root.reply_count, root.descendant_count, root.last_reply_at, ", + recent_thread_participants_sql!("AND tm.channel_id = root.channel_id"), + r#" AS participants FROM thread_metadata root WHERE root.community_id = $1 AND root.channel_id = $2 AND root.event_id IN ( @@ -1003,7 +1040,7 @@ impl Db { AND target.event_id = ANY($3) AND target.parent_event_id IS NOT NULL ) "#, - ) + )) .bind(community_id.as_uuid()) .bind(channel_id) .bind(target_ids) @@ -1067,7 +1104,8 @@ impl Db { /// /// Every replica failure except a cancelled statement (57014, which the /// writer would only repeat) fails closed to the writer and is recorded - /// in `buzz_db_route_decision`. + /// in `buzz_db_route_decision`. A busy reader rejects the read as + /// retryable instead (see [`Db::route_read`]). #[datastore_span(name = "get_channel_window", system = "postgresql")] pub async fn get_channel_window_with_session( &self, @@ -1088,7 +1126,7 @@ impl Db { RoutePredicate::from_channel_cursor(channel_id, &cursor), crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { RouteDecision::Replica(mut tx, _entry, reason) => { match crate::thread::get_channel_window_on( @@ -1098,6 +1136,7 @@ impl Db { limit, cursor.clone(), kind_filter, + crate::event::ReadDeadline::Session, ) .await { @@ -1170,7 +1209,7 @@ mod postgres_tests { use super::*; use crate::{ channel::{ChannelType, ChannelVisibility}, - event::{insert_event_with_thread_metadata, ThreadMetadataParams}, + event::{insert_event_with_thread_metadata, ReadDeadline, ThreadMetadataParams}, }; use nostr::{EventBuilder, Keys, Kind}; @@ -2058,6 +2097,34 @@ mod postgres_tests { .expect("insert top-level event"); } + /// [`insert_root`] for a row already in storage: the serving writer + /// rejects an event older than the `created_at` floor. + async fn insert_historical_root( + pool: &PgPool, + community: CommunityId, + channel_id: Uuid, + event: &nostr::Event, + ) { + crate::test_support::insert_historical_event_with_thread_metadata( + pool, + community, + event, + channel_id, + ThreadMetadataParams { + event_id: event.id.as_bytes(), + event_created_at: event_created_at(event), + channel_id, + parent_event_id: None, + parent_event_created_at: None, + root_event_id: None, + root_event_created_at: None, + depth: 0, + broadcast: true, + }, + ) + .await; + } + /// Insert a depth-1 reply under `root`, with the given broadcast flag. async fn insert_reply( pool: &PgPool, @@ -2258,6 +2325,384 @@ mod postgres_tests { assert!(page2.next_cursor.is_none(), "no cursor past the last row"); } + /// The window is split at the floor: a recent pass that fills the page + /// and its +1 probe row answers alone; otherwise the older pass reads the + /// missing rows, so `has_more` still sees rows before the floor. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_split_matches_the_unsplit_read() { + use nostr::Timestamp; + + let pool = setup_pool().await; + let author = Keys::generate(); + let (channel, community) = create_test_channel( + &pool, + &format!("window-recent-{}", Uuid::new_v4()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + author.public_key().to_bytes().as_slice(), + None, + ) + .await + .expect("create channel"); + let now = Utc::now().timestamp() as u64; + let floor = crate::store::recent_pass::floor_at(Utc::now()).timestamp() as u64; + // Two rows inside the recent window and two before it, newest first. + let mut newest_first = Vec::new(); + for at in [now - 10, now - 20, floor - 86_400, floor - 2 * 86_400] { + let event = EventBuilder::new(Kind::Custom(9), format!("at {at}")) + .custom_created_at(Timestamp::from(at)) + .sign_with_keys(&author) + .expect("sign"); + insert_historical_root(&pool, community, channel.id, &event).await; + newest_first.push(event.id); + } + + let mut conn = pool.acquire().await.expect("acquire"); + sqlx::Connection::clear_cached_statements(&mut *conn) + .await + .expect("clear prepared statements"); + let prepared = |like: &'static str| { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM pg_prepared_statements WHERE statement LIKE $1", + ) + .bind(like) + }; + let recent = "%FROM events e%created_at >= '%::timestamptz%"; + let older = "%FROM events e%created_at < '%::timestamptz%"; + let all = "%FROM events e%"; + let ids = |w: &ChannelWindow| { + w.rows + .iter() + .map(|r| r.stored_event.event.id) + .collect::>() + }; + + // Limit 1: two recent rows fill the page and its probe row. + let window = get_channel_window_on( + &mut conn, + community, + channel.id, + 1, + None, + None, + ReadDeadline::PerRead, + ) + .await + .expect("recent window"); + assert_eq!(ids(&window), newest_first[..1]); + assert!(window.has_more); + let recent_count = prepared(recent).fetch_one(&mut *conn).await.expect("count"); + let all_count = prepared(all).fetch_one(&mut *conn).await.expect("count"); + assert_eq!((recent_count, all_count), (1, 1), "recent pass alone"); + + // Limit 2: the recent pass has no probe row, so the older pass reads + // it and `has_more` sees the rows before the floor. + let window = get_channel_window_on( + &mut conn, + community, + channel.id, + 2, + None, + None, + ReadDeadline::PerRead, + ) + .await + .expect("split window"); + assert_eq!(ids(&window), newest_first[..2]); + assert!(window.has_more, "older rows lie before the floor"); + let older_count = prepared(older).fetch_one(&mut *conn).await.expect("count"); + let all_count = prepared(all).fetch_one(&mut *conn).await.expect("count"); + assert_eq!((older_count, all_count), (1, 2), "older pass ran"); + + // The whole channel, then a cursor page below the floor. + let window = get_channel_window_on( + &mut conn, + community, + channel.id, + 4, + None, + None, + ReadDeadline::PerRead, + ) + .await + .expect("whole window"); + assert_eq!(ids(&window), newest_first); + assert!(!window.has_more); + let cursor = get_channel_window_on( + &mut conn, + community, + channel.id, + 2, + None, + None, + ReadDeadline::PerRead, + ) + .await + .expect("first page") + .next_cursor + .expect("cursor"); + let window = get_channel_window_on( + &mut conn, + community, + channel.id, + 2, + Some(cursor), + None, + ReadDeadline::PerRead, + ) + .await + .expect("older page"); + assert_eq!(ids(&window), newest_first[2..]); + assert!(!window.has_more); + + // A failed older pass fails the window; it never reports the recent + // rows as the whole channel. Another session locks the partition of a + // root from before every dated monthly, which only the older pass + // plans (the recent rows' partition can hold rows below the floor too). + let ancient = EventBuilder::new(Kind::Custom(9), "ancient") + .custom_created_at(Timestamp::from(1_748_736_000)) // 2025-06-01 + .sign_with_keys(&author) + .expect("sign"); + insert_historical_root(&pool, community, channel.id, &ancient).await; + let partition_of = |id: nostr::EventId| { + let pool = pool.clone(); + async move { + sqlx::query_scalar::<_, String>( + "SELECT tableoid::regclass::text FROM events WHERE id = $1", + ) + .bind(id.as_bytes().to_vec()) + .fetch_one(&pool) + .await + .expect("partition") + } + }; + let old_partition = partition_of(ancient.id).await; + assert_ne!(old_partition, partition_of(newest_first[0]).await); + let mut locker = pool.begin().await.expect("begin locker"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "LOCK TABLE {old_partition} IN ACCESS EXCLUSIVE MODE" + ))) + .execute(&mut *locker) + .await + .expect("lock old partition"); + sqlx::query("SET lock_timeout = '200ms'") + .execute(&mut *conn) + .await + .expect("set lock_timeout"); + let window = get_channel_window_on( + &mut conn, + community, + channel.id, + 1, + None, + None, + ReadDeadline::PerRead, + ) + .await + .expect("a full recent window never touches the old partition"); + assert_eq!(ids(&window), newest_first[..1]); + let failed = get_channel_window_on( + &mut conn, + community, + channel.id, + 2, + None, + None, + ReadDeadline::PerRead, + ) + .await; + assert!( + failed.is_err(), + "a failed older pass must fail the window, got {:?}", + failed.map(|w| (w.rows.len(), w.has_more)) + ); + locker.rollback().await.expect("release lock"); + sqlx::query("RESET lock_timeout") + .execute(&mut *conn) + .await + .expect("reset lock_timeout"); + } + + /// The window's passes share one snapshot: a replacement that commits + /// between them neither drops the row it replaces nor shows the row it + /// adds. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_passes_share_one_snapshot() { + let pool = setup_pool().await; + let author = Keys::generate(); + let (channel, community) = create_test_channel( + &pool, + &format!("window-snapshot-{}", Uuid::new_v4()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + author.public_key().to_bytes().as_slice(), + None, + ) + .await + .expect("create channel"); + let channel_id = channel.id; + let (window, expected) = crate::test_support::replace_between_passes( + &pool, + community, + channel_id, + move |mut conn| async move { + get_channel_window_on( + &mut conn, + community, + channel_id, + 10, + None, + None, + ReadDeadline::PerRead, + ) + .await + .expect("split window") + .rows + .iter() + .map(|row| row.stored_event.event.id) + .collect::>() + }, + ) + .await; + assert_eq!(window, expected); + } + + /// A split window's passes share one read deadline. Another session holds + /// the newest partition for a while, so the recent pass spends part of + /// the deadline waiting, and holds the oldest partition, which only the + /// older pass plans, for good. The window must be cancelled once the whole + /// deadline has passed, not a full deadline after its older pass starts. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_passes_share_one_deadline() { + window_cancelled_within_the_read_deadline(Some(std::time::Duration::from_secs(8))).await; + } + + /// A writer window's first pass already runs under the read deadline, not + /// the writer session's longer timeout: with the newest partition held + /// for good, the window is cancelled in its recent pass. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn writer_window_first_pass_runs_under_the_read_deadline() { + window_cancelled_within_the_read_deadline(None).await; + } + + /// Read a split window through the production writer entry, whose own + /// session timeout is longer than the read deadline, while other sessions + /// lock the newest partition (released after `hold`, or never) and the + /// oldest one, which only the older pass plans (never released). The + /// window must be cancelled within the read deadline of its start. + async fn window_cancelled_within_the_read_deadline(hold: Option) { + let pool = setup_pool().await; + let author = Keys::generate(); + let (channel, community) = create_test_channel( + &pool, + &format!("window-deadline-{}", Uuid::new_v4()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + author.public_key().to_bytes().as_slice(), + None, + ) + .await + .expect("create channel"); + let mut partitions = Vec::new(); + for at in [Utc::now().timestamp() as u64 - 10, 1_748_736_000] { + let event = EventBuilder::new(Kind::Custom(9), format!("at {at}")) + .custom_created_at(nostr::Timestamp::from(at)) + .sign_with_keys(&author) + .expect("sign"); + crate::test_support::insert_historical_event(&pool, community, &event, channel.id) + .await; + partitions.push( + sqlx::query_scalar::<_, String>( + "SELECT tableoid::regclass::text FROM events WHERE id = $1", + ) + .bind(event.id.as_bytes().to_vec()) + .fetch_one(&pool) + .await + .expect("partition"), + ); + } + let [newest, oldest] = <[String; 2]>::try_from(partitions).expect("two partitions"); + assert_ne!(newest, oldest); + let lock = |partition: String| { + let pool = pool.clone(); + async move { + let mut tx = pool.begin().await.expect("begin locker"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "LOCK TABLE {partition} IN ACCESS EXCLUSIVE MODE" + ))) + .execute(&mut *tx) + .await + .expect("lock"); + tx + } + }; + let mut newest_lock = lock(newest.clone()).await; + let oldest_lock = lock(oldest).await; + + let started = std::time::Instant::now(); + let window_pool = pool.clone(); + let mut task = tokio::spawn(async move { + get_channel_window(&window_pool, community, channel.id, 10, None, None).await + }); + let waiting = tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + let blocked: bool = sqlx::query_scalar( + // `pg_locks` spans every database, and the per-test + // databases are clones that share relation OIDs. + "SELECT EXISTS(SELECT 1 FROM pg_locks \ + WHERE relation = $1::text::regclass AND NOT granted \ + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()))", + ) + .bind(&newest) + .fetch_one(&mut *newest_lock) + .await + .expect("inspect the recent pass"); + if blocked { + break; + } + tokio::task::yield_now().await; + } + }) + .await; + assert!(waiting.is_ok(), "the recent pass never waited on the lock"); + // Spend part of the deadline in the recent pass, then let it finish. + if let Some(hold) = hold { + tokio::time::sleep(hold).await; + newest_lock + .rollback() + .await + .expect("release the newest partition"); + } + + let margin = std::time::Duration::from_secs(4); + let result = + tokio::time::timeout(crate::event::READ_DEADLINE + margin * 4, &mut task).await; + let elapsed = started.elapsed(); + drop(oldest_lock); + let Ok(result) = result else { + task.abort(); + panic!("the window was never cancelled"); + }; + let err = result + .expect("window task") + .expect_err("the window must be cancelled"); + assert!( + err.is_statement_cancelled(), + "cancelled by the deadline: {err}" + ); + assert!( + elapsed < crate::event::READ_DEADLINE + margin, + "the window got more than one read deadline; took {elapsed:?}" + ); + } + /// Rows with replies carry a thread summary (counts + batched /// participants); rows without replies carry none. This is the join that /// lets the GUI render thread affordances without a per-root fan-out. @@ -2320,4 +2765,101 @@ mod postgres_tests { "reply-less row carries no summary" ); } + + /// Every participant reader (live summary, channel window, deleted-reply + /// root resolution) aggregates only the newest + /// [`THREAD_PARTICIPANT_SCAN_LIMIT`] replies, most recent author first, + /// skipping deleted replies. An author who last posted before that window + /// drops out; a whole-thread aggregate would still return them. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn participant_summaries_read_only_the_newest_replies() { + let pool = setup_pool().await; + let db = Db::from_pool(pool.clone()); + let early = Keys::generate(); + let steady = Keys::generate(); + let deleted_author = Keys::generate(); + let latest = Keys::generate(); + let (channel, community) = create_test_channel( + &pool, + &format!("participant-window-{}", Uuid::new_v4()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + steady.public_key().to_bytes().as_slice(), + None, + ) + .await + .expect("create channel"); + + let root = make_stream_event(&steady, "root"); + insert_root(&pool, community, channel.id, &root).await; + let base = root.created_at.as_secs(); + let reply_at = |keys: &Keys, offset: u64| { + EventBuilder::new(Kind::Custom(9), format!("reply-{offset}")) + .custom_created_at(nostr::Timestamp::from(base + offset)) + .sign_with_keys(keys) + .expect("sign reply") + }; + + // `early` posts first, then `steady` fills the whole window after it. + let early_reply = reply_at(&early, 1); + insert_reply(&pool, community, channel.id, &root, &early_reply, false).await; + let window = THREAD_PARTICIPANT_SCAN_LIMIT as u64; + for offset in 2..window { + let reply = reply_at(&steady, offset); + insert_reply(&pool, community, channel.id, &root, &reply, false).await; + } + let deleted_reply = reply_at(&deleted_author, window); + insert_reply(&pool, community, channel.id, &root, &deleted_reply, false).await; + let latest_reply = reply_at(&latest, window + 1); + insert_reply(&pool, community, channel.id, &root, &latest_reply, false).await; + db.soft_delete_event_and_update_thread( + community, + deleted_reply.id.as_bytes(), + Some(root.id.as_bytes()), + Some(root.id.as_bytes()), + ) + .await + .expect("delete reply"); + + let expected = vec![ + latest.public_key().to_bytes().to_vec(), + steady.public_key().to_bytes().to_vec(), + ]; + + let summary = get_thread_summary(&pool, community, root.id.as_bytes()) + .await + .expect("thread summary") + .expect("root has thread metadata"); + assert_eq!(summary.participants, expected, "live summary"); + + let window = get_channel_window(&pool, community, channel.id, 50, None, None) + .await + .expect("fetch window"); + let row = window + .rows + .iter() + .find(|r| r.stored_event.event.id == root.id) + .expect("root row present"); + assert_eq!( + row.thread_summary + .as_ref() + .expect("root has a summary") + .participants, + expected, + "channel window" + ); + + let resolved = db + .resolve_thread_root_summaries( + community, + channel.id, + &[deleted_reply.id.as_bytes().to_vec()], + ) + .await + .expect("resolve root"); + assert_eq!(resolved.len(), 1); + assert_eq!(resolved[0].1.participants, expected, "resolved root"); + } } diff --git a/crates/buzz-db/src/store/thread_window.rs b/crates/buzz-db/src/store/thread_window.rs index 926ffae8df0..daf37f7e941 100644 --- a/crates/buzz-db/src/store/thread_window.rs +++ b/crates/buzz-db/src/store/thread_window.rs @@ -223,7 +223,7 @@ impl Db { RoutePredicate::from_channel_cursor(request.channel, &cursor), crate::observability::ReaderOperation::SubscriptionHistory, ) - .await + .await? { let result = async { set_deadline(&mut tx).await?; diff --git a/crates/buzz-db/src/store/usage.rs b/crates/buzz-db/src/store/usage.rs deleted file mode 100644 index a1532144b30..00000000000 --- a/crates/buzz-db/src/store/usage.rs +++ /dev/null @@ -1,1786 +0,0 @@ -//! Per-community usage rollup queries for Prometheus gauges. -//! -//! Stock queries (`user_counts`, `channel_counts`, `relay_member_counts`, -//! `workflow_counts`, `git_repo_counts`) use `GROUP BY community_id` against -//! indexed columns — no per-community loops, no full-table scans. -//! -//! Event-derived queries (`message_counts`, `active_user_counts`, -//! `active_channel_counts`) are exact aggregates over the `events` table. -//! At scale these can become recurring partition scans; if that becomes a -//! problem, move them to a maintained rollup table and drop the interval. -//! -//! Returned structs are plain data; the caller (relay poller) maps them -//! to Prometheus labels and calls `metrics::gauge!(...).set(...)`. - -use buzz_datastore_tracing::datastore_span; -use chrono::{DateTime, Duration, Utc}; -use sqlx::postgres::PgConnection; -use sqlx::{Connection as _, Executor, PgPool, Postgres}; -use uuid::Uuid; - -use crate::error::Result; -use crate::{observability, Db}; - -/// Fixed-row fleet adoption snapshot used when per-community telemetry is disabled. -#[derive(Debug, Clone, Copy, Default, sqlx::FromRow)] -pub struct FleetStockSnapshot { - /// Planner estimate for the number of communities. - pub communities_estimated: i64, - /// Active human users. - pub users_human: i64, - /// Active agent users. - pub users_agent: i64, - /// Non-deleted stream channels. - pub channels_stream: i64, - /// Non-deleted forum channels. - pub channels_forum: i64, - /// Non-deleted direct-message channels. - pub channels_dm: i64, - /// Non-deleted workflow channels. - pub channels_workflow: i64, - /// Non-deleted system channels. - pub channels_system: i64, - /// Relay owners. - pub members_owner: i64, - /// Relay administrators. - pub members_admin: i64, - /// Relay members. - pub members_member: i64, - /// Active workflows. - pub workflows_active: i64, - /// Disabled workflows. - pub workflows_disabled: i64, - /// Archived workflows. - pub workflows_archived: i64, - /// Registered Git repositories. - pub git_repos: i64, -} - -/// Fixed-row 1d/7d/30d active-user snapshot derived from one 30-day scan. -#[derive(Debug, Clone, Copy, Default, sqlx::FromRow)] -pub struct FleetActiveUsersSnapshot { - /// Human publishers active in the last day. - pub human_1d: i64, - /// Agent publishers active in the last day. - pub agent_1d: i64, - /// Unclassified publishers active in the last day. - pub unknown_1d: i64, - /// Human publishers active in the last seven days. - pub human_7d: i64, - /// Agent publishers active in the last seven days. - pub agent_7d: i64, - /// Unclassified publishers active in the last seven days. - pub unknown_7d: i64, - /// Human publishers active in the last thirty days. - pub human_30d: i64, - /// Agent publishers active in the last thirty days. - pub agent_30d: i64, - /// Unclassified publishers active in the last thirty days. - pub unknown_30d: i64, -} - -/// Collect one fixed-row fleet adoption snapshot on the supplied executor. -pub async fn fleet_stock_snapshot_on<'e, E>(executor: E) -> Result -where - E: Executor<'e, Database = Postgres>, -{ - Ok(sqlx::query_as::<_, FleetStockSnapshot>( - r#" - WITH user_counts AS ( - SELECT - COUNT(*) FILTER (WHERE agent_owner_pubkey IS NULL) AS human, - COUNT(*) FILTER (WHERE agent_owner_pubkey IS NOT NULL) AS agent - FROM users - WHERE deactivated_at IS NULL - ), - channel_counts AS ( - SELECT - COUNT(*) FILTER (WHERE channel_type = 'stream') AS stream, - COUNT(*) FILTER (WHERE channel_type = 'forum') AS forum, - COUNT(*) FILTER (WHERE channel_type = 'dm') AS dm, - COUNT(*) FILTER (WHERE channel_type = 'workflow') AS workflow, - COUNT(*) FILTER (WHERE channel_type = 'system') AS system - FROM channels - WHERE deleted_at IS NULL - ), - member_counts AS ( - SELECT - COUNT(*) FILTER (WHERE role = 'owner') AS owner, - COUNT(*) FILTER (WHERE role = 'admin') AS admin, - COUNT(*) FILTER (WHERE role = 'member') AS member - FROM relay_members - ), - workflow_counts AS ( - SELECT - COUNT(*) FILTER (WHERE status = 'active') AS active, - COUNT(*) FILTER (WHERE status = 'disabled') AS disabled, - COUNT(*) FILTER (WHERE status = 'archived') AS archived - FROM workflows - ) - SELECT - COALESCE((SELECT GREATEST(reltuples, 0)::bigint FROM pg_class WHERE oid = 'communities'::regclass), 0) AS communities_estimated, - users.human AS users_human, - users.agent AS users_agent, - channels.stream AS channels_stream, - channels.forum AS channels_forum, - channels.dm AS channels_dm, - channels.workflow AS channels_workflow, - channels.system AS channels_system, - members.owner AS members_owner, - members.admin AS members_admin, - members.member AS members_member, - workflows.active AS workflows_active, - workflows.disabled AS workflows_disabled, - workflows.archived AS workflows_archived, - (SELECT COUNT(*) FROM git_repo_names) AS git_repos - FROM user_counts users - CROSS JOIN channel_counts channels - CROSS JOIN member_counts members - CROSS JOIN workflow_counts workflows - "#, - ) - .fetch_one(executor) - .await?) -} - -/// Collect all fleet active-user windows with one bounded 30-day event scan. -pub async fn fleet_active_users_on<'e, E>( - executor: E, - observed_at: DateTime, -) -> Result -where - E: Executor<'e, Database = Postgres>, -{ - let start_30d = observed_at - Duration::days(30); - let start_7d = observed_at - Duration::days(7); - let start_1d = observed_at - Duration::days(1); - Ok(sqlx::query_as::<_, FleetActiveUsersSnapshot>( - r#" - WITH publishers AS ( - SELECT - e.community_id, - e.pubkey, - MAX(e.created_at) AS last_active_at, - CASE - WHEN u.pubkey IS NULL THEN 'unknown' - WHEN u.agent_owner_pubkey IS NULL THEN 'human' - ELSE 'agent' - END AS author_type - FROM events e - LEFT JOIN users u - ON u.community_id = e.community_id AND u.pubkey = e.pubkey - WHERE e.created_at >= $1 - AND e.created_at < $2 - AND e.deleted_at IS NULL - GROUP BY e.community_id, e.pubkey, u.pubkey, u.agent_owner_pubkey - ) - SELECT - COUNT(*) FILTER (WHERE last_active_at >= $4 AND author_type = 'human') AS human_1d, - COUNT(*) FILTER (WHERE last_active_at >= $4 AND author_type = 'agent') AS agent_1d, - COUNT(*) FILTER (WHERE last_active_at >= $4 AND author_type = 'unknown') AS unknown_1d, - COUNT(*) FILTER (WHERE last_active_at >= $3 AND author_type = 'human') AS human_7d, - COUNT(*) FILTER (WHERE last_active_at >= $3 AND author_type = 'agent') AS agent_7d, - COUNT(*) FILTER (WHERE last_active_at >= $3 AND author_type = 'unknown') AS unknown_7d, - COUNT(*) FILTER (WHERE author_type = 'human') AS human_30d, - COUNT(*) FILTER (WHERE author_type = 'agent') AS agent_30d, - COUNT(*) FILTER (WHERE author_type = 'unknown') AS unknown_30d - FROM publishers - "#, - ) - .bind(start_30d) - .bind(observed_at) - .bind(start_7d) - .bind(start_1d) - .fetch_one(executor) - .await?) -} - -/// Owns the detached Postgres session holding a deployment-wide leader advisory lock. -/// -/// The connection deliberately does not return to the main pool: session advisory -/// locks must remain bound to this exact physical connection, and each leader-only -/// loop (usage metrics, NIP-43 snapshot reconciliation) pings it before working. -pub struct SessionLeader { - connection: PgConnection, -} - -impl SessionLeader { - /// Returns whether the lock-owning session is still reachable. - /// - /// Bounded to 5 seconds — a blackholed connection (no RST) would otherwise - /// stall the entire poller tick until the OS TCP timeout. - pub async fn is_live(&mut self) -> bool { - tokio::time::timeout(std::time::Duration::from_secs(5), self.connection.ping()) - .await - .is_ok_and(|r| r.is_ok()) - } -} - -/// Total number of communities registered on this relay. -pub async fn community_count(pool: &PgPool) -> Result { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - let row = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM communities") - .fetch_one(&mut *connection) - .await?; - Ok(row) -} - -/// Per-community user counts split by human/agent. -#[derive(Debug)] -pub struct CommunityUserCounts { - /// The UUID of the community. - pub community_id: Uuid, - /// Number of active human users (no `agent_owner_pubkey`). - pub human: i64, - /// Number of active agent users (`agent_owner_pubkey IS NOT NULL`). - pub agent: i64, -} - -/// Return active (non-deactivated) user counts per community, split by type. -/// -/// Agent discriminator: `agent_owner_pubkey IS NOT NULL`. -pub async fn user_counts(pool: &PgPool) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - // Single GROUP BY query; two conditional SUMs avoid two round-trips. - let rows = sqlx::query_as::<_, (Uuid, i64, i64)>( - r#" - SELECT - community_id, - COUNT(*) FILTER (WHERE agent_owner_pubkey IS NULL) AS human, - COUNT(*) FILTER (WHERE agent_owner_pubkey IS NOT NULL) AS agent - FROM users - WHERE deactivated_at IS NULL - GROUP BY community_id - "#, - ) - .fetch_all(&mut *connection) - .await?; - - Ok(rows - .into_iter() - .map(|(community_id, human, agent)| CommunityUserCounts { - community_id, - human, - agent, - }) - .collect()) -} - -/// Per-community channel counts by type. -#[derive(Debug)] -pub struct CommunityChannelCount { - /// The UUID of the community. - pub community_id: Uuid, - /// Channel type string (e.g. `"stream"`, `"dm"`, `"forum"`, `"workflow"`). - pub channel_type: String, - /// Number of non-deleted channels of this type. - pub count: i64, -} - -/// Return non-deleted channel counts per community per type. -pub async fn channel_counts(pool: &PgPool) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - let rows = sqlx::query_as::<_, (Uuid, String, i64)>( - r#" - SELECT community_id, channel_type::text, COUNT(*) AS count - FROM channels - WHERE deleted_at IS NULL - GROUP BY community_id, channel_type - "#, - ) - .fetch_all(&mut *connection) - .await?; - - Ok(rows - .into_iter() - .map( - |(community_id, channel_type, count)| CommunityChannelCount { - community_id, - channel_type, - count, - }, - ) - .collect()) -} - -/// Per-community message (kind=9) count. -#[derive(Debug)] -pub struct CommunityMessageCount { - /// The UUID of the community. - pub community_id: Uuid, - /// Number of stored non-deleted kind=9 events. - pub count: i64, -} - -/// Return non-deleted kind=9 event counts per community. -pub async fn message_counts(pool: &PgPool) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - let rows = sqlx::query_as::<_, (Uuid, i64)>( - r#" - SELECT community_id, COUNT(*) AS count - FROM events - WHERE kind = 9 AND deleted_at IS NULL - GROUP BY community_id - "#, - ) - .fetch_all(&mut *connection) - .await?; - - Ok(rows - .into_iter() - .map(|(community_id, count)| CommunityMessageCount { - community_id, - count, - }) - .collect()) -} - -/// Per-community relay-member counts by role. -#[derive(Debug)] -pub struct CommunityMemberCount { - /// The UUID of the community. - pub community_id: Uuid, - /// Role string (e.g. `"owner"`, `"admin"`, `"member"`). - pub role: String, - /// Number of members with this role. - pub count: i64, -} - -/// Return relay-member counts per community per role. -pub async fn relay_member_counts(pool: &PgPool) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - let rows = sqlx::query_as::<_, (Uuid, String, i64)>( - r#" - SELECT community_id, role::text, COUNT(*) AS count - FROM relay_members - GROUP BY community_id, role - "#, - ) - .fetch_all(&mut *connection) - .await?; - - Ok(rows - .into_iter() - .map(|(community_id, role, count)| CommunityMemberCount { - community_id, - role, - count, - }) - .collect()) -} - -/// Per-community workflow counts by status. -#[derive(Debug)] -pub struct CommunityWorkflowCount { - /// The UUID of the community. - pub community_id: Uuid, - /// Workflow status string (e.g. `"active"`, `"inactive"`). - pub status: String, - /// Number of workflows in this status. - pub count: i64, -} - -/// Return workflow counts per community per status. -pub async fn workflow_counts(pool: &PgPool) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - let rows = sqlx::query_as::<_, (Uuid, String, i64)>( - r#" - SELECT community_id, status::text, COUNT(*) AS count - FROM workflows - GROUP BY community_id, status - "#, - ) - .fetch_all(&mut *connection) - .await?; - - Ok(rows - .into_iter() - .map(|(community_id, status, count)| CommunityWorkflowCount { - community_id, - status, - count, - }) - .collect()) -} - -/// Per-community git-repo count. -#[derive(Debug)] -pub struct CommunityGitRepoCount { - /// The UUID of the community. - pub community_id: Uuid, - /// Number of git repos registered for this community. - pub count: i64, -} - -/// Return git repo counts per community. -pub async fn git_repo_counts(pool: &PgPool) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - let rows = sqlx::query_as::<_, (Uuid, i64)>( - r#" - SELECT community_id, COUNT(*) AS count - FROM git_repo_names - GROUP BY community_id - "#, - ) - .fetch_all(&mut *connection) - .await?; - - Ok(rows - .into_iter() - .map(|(community_id, count)| CommunityGitRepoCount { - community_id, - count, - }) - .collect()) -} - -/// Per-community active-user counts for a given window (e.g. 1d, 7d, 30d), -/// split by human/agent. -#[derive(Debug)] -pub struct CommunityActiveUsers { - /// The UUID of the community. - pub community_id: Uuid, - /// Distinct human pubkeys that published at least one event in the window. - /// A pubkey is human when its `users` row exists and `agent_owner_pubkey IS NULL`. - pub human: i64, - /// Distinct agent pubkeys that published at least one event in the window. - /// A pubkey is an agent when its `users` row exists and `agent_owner_pubkey IS NOT NULL`. - pub agent: i64, - /// Distinct pubkeys that published at least one event but have no `users` row. - /// Ingest does not guarantee a `users` row for every pubkey (profileless posters, - /// agents with missing rows). These are not classified and must not be folded into - /// `human` to avoid inflating the human count. - pub unknown: i64, -} - -/// Return distinct-publisher counts for events in `[now - interval, now]` -/// per community, split by human/agent/unknown. -/// -/// `interval_sql` must be a trusted literal (e.g. `"1 day"`, `"7 days"`) — -/// it is not user-controlled; callers are in the relay process. -pub async fn active_user_counts( - pool: &PgPool, - interval_sql: &'static str, -) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - // LEFT JOIN users: pubkeys with no row have u.* = NULL. - // Three-way classification: - // human — row exists (u.pubkey IS NOT NULL) and agent_owner_pubkey IS NULL - // agent — row exists and agent_owner_pubkey IS NOT NULL - // unknown — no row (u.pubkey IS NULL); not classified, reported separately - let sql = format!( - r#" - SELECT - e.community_id, - COUNT(DISTINCT e.pubkey) - FILTER (WHERE u.pubkey IS NOT NULL AND u.agent_owner_pubkey IS NULL) AS human, - COUNT(DISTINCT e.pubkey) - FILTER (WHERE u.pubkey IS NOT NULL AND u.agent_owner_pubkey IS NOT NULL) AS agent, - COUNT(DISTINCT e.pubkey) - FILTER (WHERE u.pubkey IS NULL) AS unknown - FROM events e - LEFT JOIN users u - ON u.community_id = e.community_id AND u.pubkey = e.pubkey - WHERE e.created_at >= NOW() - INTERVAL '{interval_sql}' - AND e.deleted_at IS NULL - GROUP BY e.community_id - "# - ); - let rows = sqlx::query_as::<_, (Uuid, i64, i64, i64)>(sqlx::AssertSqlSafe(sql)) - .fetch_all(&mut *connection) - .await?; - - Ok(rows - .into_iter() - .map( - |(community_id, human, agent, unknown)| CommunityActiveUsers { - community_id, - human, - agent, - unknown, - }, - ) - .collect()) -} - -/// Per-community active-channel counts for a given window. -#[derive(Debug)] -pub struct CommunityActiveChannels { - /// The UUID of the community. - pub community_id: Uuid, - /// Distinct channel IDs with ≥1 kind=9 message in the window. - pub count: i64, -} - -/// Return distinct channel IDs with ≥1 kind=9 message in `[now - interval, now]`. -pub async fn active_channel_counts( - pool: &PgPool, - interval_sql: &'static str, -) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - let sql = format!( - r#" - SELECT community_id, COUNT(DISTINCT channel_id) AS count - FROM events - WHERE kind = 9 - AND channel_id IS NOT NULL - AND created_at >= NOW() - INTERVAL '{interval_sql}' - AND deleted_at IS NULL - GROUP BY community_id - "# - ); - let rows = sqlx::query_as::<_, (Uuid, i64)>(sqlx::AssertSqlSafe(sql)) - .fetch_all(&mut *connection) - .await?; - - Ok(rows - .into_iter() - .map(|(community_id, count)| CommunityActiveChannels { - community_id, - count, - }) - .collect()) -} - -/// Mapping from community UUID to host string, used by the poller to resolve -/// Prometheus label values. -#[derive(Debug)] -pub struct CommunityHost { - /// The UUID of the community. - pub id: Uuid, - /// The canonical host string for this community (used as the Prometheus label value). - pub host: String, -} - -/// Fetch every community id → host mapping in one query, including archived, -/// deleting, and tombstoned communities. -/// -/// Usage metrics label per-community series and attribute storage with this -/// map, so it must cover the same rows as the unfiltered usage count queries. -pub async fn community_hosts(pool: &PgPool) -> Result> { - let mut connection = - observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?; - let rows = sqlx::query_as::<_, (Uuid, String)>("SELECT id, host FROM communities") - .fetch_all(&mut *connection) - .await?; - Ok(into_community_hosts(rows)) -} - -/// Fetch the id → host mapping for every active community in one query. -/// -/// Archived communities are unreachable through host resolution, and -/// communities anywhere in the deletion lifecycle (`quiescing`, `fenced`, -/// `tombstone`) have their writes DB-fenced, so background workers that write -/// per community must skip them. Tombstone rows stay in place for retention. -async fn active_community_hosts( - pool: &PgPool, - operation: observability::WriterOperation, -) -> Result> { - let mut connection = observability::acquire_writer(pool, operation).await?; - let rows = sqlx::query_as::<_, (Uuid, String)>( - "SELECT id, host FROM communities \ - WHERE archived_at IS NULL \ - AND deleted_at IS NULL \ - AND deletion_state = 'active'", - ) - .fetch_all(&mut *connection) - .await?; - Ok(into_community_hosts(rows)) -} - -fn into_community_hosts(rows: Vec<(Uuid, String)>) -> Vec { - rows.into_iter() - .map(|(id, host)| CommunityHost { id, host }) - .collect() -} - -impl Db { - /// Try to acquire the detached session advisory lock `lock_key`, making this - /// replica the leader for the job that key names. - /// - /// The returned guard owns the exact connection that acquired the lock. It is - /// detached from the shared pool so a stable leader neither returns a locked - /// session to other callers nor permanently consumes a pool slot. Dropping the - /// guard closes the connection and releases the session-scoped lock. - #[datastore_span(name = "try_lock_session_leader", system = "postgresql")] - pub async fn try_lock_session_leader(&self, lock_key: i64) -> Result> { - let mut connection = observability::acquire_writer_with_legacy_metrics( - &self.pool, - observability::WriterOperation::Maintenance, - ) - .await?; - let acquired = sqlx::query_scalar::<_, bool>("SELECT pg_try_advisory_lock($1)") - .bind(lock_key) - .fetch_one(&mut *connection) - .await?; - if acquired { - Ok(Some(SessionLeader { - connection: connection.detach(), - })) - } else { - Ok(None) - } - } - - /// Collect fleet adoption stocks from a proved read-replica snapshot. - /// - /// Returns `None` instead of falling back to the writer when a proved - /// reader is unavailable. Usage telemetry is allowed to be stale or - /// skipped and must not add load to the serving database. - #[datastore_span(name = "usage_fleet_stock_snapshot", system = "postgresql")] - pub async fn usage_fleet_stock_snapshot(&self) -> Result> { - let path = "usage_fleet_stock"; - let Some((mut tx, reason)) = self.route_usage_read(path).await else { - return Ok(None); - }; - let collected = async { - sqlx::query("SET LOCAL statement_timeout = '5s'") - .execute(&mut *tx) - .await?; - fleet_stock_snapshot_on(&mut *tx).await - } - .await; - Self::finish_usage_read(path, reason, collected) - } - - /// Collect all fleet active-user windows from a proved read-replica snapshot. - /// - /// Returns `None` instead of falling back to the writer when a proved - /// reader is unavailable. - #[datastore_span(name = "usage_fleet_active_users", system = "postgresql")] - pub async fn usage_fleet_active_users( - &self, - observed_at: DateTime, - ) -> Result> { - let path = "usage_fleet_active_users"; - let Some((mut tx, reason)) = self.route_usage_read(path).await else { - return Ok(None); - }; - let collected = async { - sqlx::query("SET LOCAL statement_timeout = '15s'") - .execute(&mut *tx) - .await?; - fleet_active_users_on(&mut *tx, observed_at).await - } - .await; - Self::finish_usage_read(path, reason, collected) - } - - /// Record the route outcome of a proved-reader telemetry query. A query - /// error is a skipped attempt (`replica_error`), never a writer fallback, - /// so every attempt that completes appears in `buzz_db_route_decision`. - fn finish_usage_read( - path: &'static str, - reason: &'static str, - collected: Result, - ) -> Result> { - match collected { - Ok(snapshot) => { - Self::record_route(path, "replica", reason); - Ok(Some(snapshot)) - } - Err(error) => { - Self::record_route(path, "skipped", "replica_error"); - Err(error) - } - } - } - - /// Return total number of communities on this relay. - #[datastore_span(name = "usage_community_count", system = "postgresql")] - pub async fn usage_community_count(&self) -> Result { - community_count(&self.pool).await - } - - /// Return per-community user counts split by human/agent. - #[datastore_span(name = "usage_user_counts", system = "postgresql")] - pub async fn usage_user_counts(&self) -> Result> { - user_counts(&self.pool).await - } - - /// Return per-community channel counts by type. - #[datastore_span(name = "usage_channel_counts", system = "postgresql")] - pub async fn usage_channel_counts(&self) -> Result> { - channel_counts(&self.pool).await - } - - /// Return per-community kind=9 message counts. - #[datastore_span(name = "usage_message_counts", system = "postgresql")] - pub async fn usage_message_counts(&self) -> Result> { - message_counts(&self.pool).await - } - - /// Return per-community relay-member counts by role. - #[datastore_span(name = "usage_relay_member_counts", system = "postgresql")] - pub async fn usage_relay_member_counts(&self) -> Result> { - relay_member_counts(&self.pool).await - } - - /// Return per-community workflow counts by status. - #[datastore_span(name = "usage_workflow_counts", system = "postgresql")] - pub async fn usage_workflow_counts(&self) -> Result> { - workflow_counts(&self.pool).await - } - - /// Return per-community git-repo counts. - #[datastore_span(name = "usage_git_repo_counts", system = "postgresql")] - pub async fn usage_git_repo_counts(&self) -> Result> { - git_repo_counts(&self.pool).await - } - - /// Return per-community distinct active-user counts for a given SQL interval. - /// - /// `interval_sql` must be a trusted literal such as `"1 day"` or `"7 days"`. - #[datastore_span(name = "usage_active_user_counts", system = "postgresql")] - pub async fn usage_active_user_counts( - &self, - interval_sql: &'static str, - ) -> Result> { - active_user_counts(&self.pool, interval_sql).await - } - - /// Return per-community active-channel counts for a given SQL interval. - #[datastore_span(name = "usage_active_channel_counts", system = "postgresql")] - pub async fn usage_active_channel_counts( - &self, - interval_sql: &'static str, - ) -> Result> { - active_channel_counts(&self.pool, interval_sql).await - } - - /// Return all community id → host mappings, for usage-metrics labels. - #[datastore_span(name = "usage_community_hosts", system = "postgresql")] - pub async fn usage_community_hosts(&self) -> Result> { - community_hosts(&self.pool).await - } - - /// Return active community host mappings for background maintenance writers. - #[datastore_span(name = "active_community_hosts", system = "postgresql")] - pub async fn active_community_hosts(&self) -> Result> { - active_community_hosts(&self.pool, observability::WriterOperation::Maintenance).await - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::error::DbError; - use metrics_util::debugging::{DebugValue, DebuggingRecorder}; - - fn route_decisions(recorder: &DebuggingRecorder) -> Vec<(String, String, String, u64)> { - let mut decisions: Vec<_> = recorder - .snapshotter() - .snapshot() - .into_vec() - .into_iter() - .filter_map(|(key, _, _, value)| { - if key.key().name() != "buzz_db_route_decision" { - return None; - } - let label = |name: &str| { - key.key() - .labels() - .find(|label| label.key() == name) - .map(|label| label.value().to_owned()) - .unwrap_or_default() - }; - let DebugValue::Counter(count) = value else { - return None; - }; - Some((label("path"), label("decision"), label("reason"), count)) - }) - .collect(); - decisions.sort(); - decisions - } - - /// Every telemetry attempt on a proved reader lands in the route counter: - /// a completed query as `replica/`, a failed one as - /// `skipped/replica_error` with the error propagated (never a writer - /// fallback). - #[test] - fn finish_usage_read_records_every_attempt_in_route_decisions() { - let recorder = DebuggingRecorder::new(); - let (ok, err) = metrics::with_local_recorder(&recorder, || { - ( - Db::finish_usage_read("usage_fleet_stock", "fresh", Ok(7_u8)), - Db::finish_usage_read::( - "usage_fleet_active_users", - "fresh", - Err(DbError::AuthEventRejected), - ), - ) - }); - - assert!(matches!(ok, Ok(Some(7)))); - assert!(matches!(err, Err(DbError::AuthEventRejected))); - assert_eq!( - route_decisions(&recorder), - vec![ - ( - "usage_fleet_active_users".to_owned(), - "skipped".to_owned(), - "replica_error".to_owned(), - 1 - ), - ( - "usage_fleet_stock".to_owned(), - "replica".to_owned(), - "fresh".to_owned(), - 1 - ), - ] - ); - } -} - -#[cfg(test)] -mod postgres_tests { - use super::*; - use buzz_core::CommunityId; - use nostr::Keys; - use sqlx::postgres::PgPoolOptions; - use sqlx::PgPool; - - async fn get_pool() -> PgPool { - PgPool::connect(&crate::test_support::database_url()) - .await - .expect("connect to test DB") - } - - async fn create_scratch_db(admin: &PgPool, prefix: &str) -> (PgPool, String) { - let name = format!("{}_{}", prefix, Uuid::new_v4().simple()); - sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) - .execute(admin) - .await - .expect("create scratch db"); - let base = crate::test_support::database_url(); - let idx = base.rfind('/').expect("db url has a path segment"); - let scratch_url = format!("{}/{}", &base[..idx], name); - let pool = PgPool::connect(&scratch_url) - .await - .expect("connect scratch db"); - crate::migration::run_migrations(&pool) - .await - .expect("migrate scratch db"); - (pool, name) - } - - async fn drop_scratch_db(admin: &PgPool, pool: PgPool, name: &str) { - pool.close().await; - let _ = sqlx::query(sqlx::AssertSqlSafe(format!( - "DROP DATABASE IF EXISTS {name} WITH (FORCE)" - ))) - .execute(admin) - .await; - } - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_usage_metrics_lock_has_single_owner_and_releases_on_drop() { - // Use a private scratch database — not the shared TEST_DATABASE_URL. - // Postgres advisory locks are per-database; hardcoding the production - // USAGE_METRICS_LOCK_KEY (0x4255_5A5A_4D45_5452) on the shared test DB - // races any live buzz-relay on the same database (see #3619). - let admin_url = crate::test_support::database_url(); - let admin = PgPoolOptions::new() - .max_connections(1) - .connect(&admin_url) - .await - .expect("connect admin to create scratch db"); - let (pool, scratch_name) = create_scratch_db(&admin, "usage_metrics_lock").await; - let first = Db::from_pool(pool.clone()); - let second = Db::from_pool(pool.clone()); - // Same key as production (`buzz-relay` USAGE_METRICS_LOCK_KEY) — safe here - // because the scratch DB is empty of other holders. - let key = 0x4255_5A5A_4D45_5452; - - let mut leader = first - .try_lock_session_leader(key) - .await - .expect("first lock attempt") - .expect("first database handle becomes leader"); - assert!(leader.is_live().await, "lock owner remains reachable"); - assert!( - second - .try_lock_session_leader(key) - .await - .expect("second lock attempt") - .is_none(), - "another session cannot become leader while the guard exists" - ); - - drop(leader); - // Dropping closes the socket; the server releases the session lock only - // once its backend observes the disconnect, so poll briefly. - let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); - let successor = loop { - let attempt = second - .try_lock_session_leader(key) - .await - .expect("lock attempt after leader drop"); - if attempt.is_some() || tokio::time::Instant::now() >= deadline { - break attempt; - } - tokio::time::sleep(std::time::Duration::from_millis(20)).await; - }; - assert!( - successor.is_some(), - "dropping the detached session releases its advisory lock" - ); - drop(successor); - - // Release any remaining session state before DROP DATABASE. - drop(first); - drop(second); - drop_scratch_db(&admin, pool, &scratch_name).await; - } - - fn random_pubkey() -> Vec { - Keys::generate().public_key().to_bytes().to_vec() - } - - async fn make_community(pool: &PgPool) -> (Uuid, CommunityId, String) { - let id = uuid::Uuid::new_v4(); - let host = format!("usage-test-{}.example", id.simple()); - sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") - .bind(id) - .bind(&host) - .execute(pool) - .await - .expect("insert test community"); - (id, CommunityId::from_uuid(id), host) - } - - async fn insert_user(pool: &PgPool, community_id: Uuid, pubkey: &[u8], is_agent: bool) { - if is_agent { - let owner = random_pubkey(); - // Insert owner first (FK constraint). - sqlx::query( - "INSERT INTO users (community_id, pubkey) VALUES ($1, $2) ON CONFLICT DO NOTHING", - ) - .bind(community_id) - .bind(&owner) - .execute(pool) - .await - .expect("insert owner"); - sqlx::query( - "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", - ) - .bind(community_id) - .bind(pubkey) - .bind(&owner) - .execute(pool) - .await - .expect("insert agent user"); - } else { - sqlx::query( - "INSERT INTO users (community_id, pubkey) VALUES ($1, $2) ON CONFLICT DO NOTHING", - ) - .bind(community_id) - .bind(pubkey) - .execute(pool) - .await - .expect("insert human user"); - } - } - - /// user_counts returns correct human/agent split and is scoped per community. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_user_counts_scoped_per_community() { - let pool = get_pool().await; - let (comm_a_uuid, _, _) = make_community(&pool).await; - let (comm_b_uuid, _, _) = make_community(&pool).await; - - // Community A: insert 2 humans first, then 1 agent whose owner is one - // of those humans (reuses existing pubkey — no extra human row). - let human1 = random_pubkey(); - let human2 = random_pubkey(); - let agent_pk = random_pubkey(); - insert_user(&pool, comm_a_uuid, &human1, false).await; - insert_user(&pool, comm_a_uuid, &human2, false).await; - // Insert agent with human1 as owner (human1 is already in users). - sqlx::query( - "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) - VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", - ) - .bind(comm_a_uuid) - .bind(&agent_pk) - .bind(&human1) - .execute(&pool) - .await - .expect("insert agent user"); - - // Community B: 0 human, 1 agent (owner is a fresh human in comm_b). - let owner_b = random_pubkey(); - insert_user(&pool, comm_b_uuid, &owner_b, false).await; - let agent_b = random_pubkey(); - sqlx::query( - "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) - VALUES ($1, $2, $3) ON CONFLICT DO NOTHING", - ) - .bind(comm_b_uuid) - .bind(&agent_b) - .bind(&owner_b) - .execute(&pool) - .await - .expect("insert agent user b"); - - let counts = user_counts(&pool).await.expect("user_counts"); - - let a = counts.iter().find(|r| r.community_id == comm_a_uuid); - let b = counts.iter().find(|r| r.community_id == comm_b_uuid); - - let a = a.expect("community A row"); - assert_eq!(a.human, 2, "community A: 2 humans"); - assert_eq!(a.agent, 1, "community A: 1 agent"); - - let b = b.expect("community B row"); - assert_eq!(b.human, 1, "community B: 1 human (the agent owner)"); - assert_eq!(b.agent, 1, "community B: 1 agent"); - } - - /// Deactivated users are excluded from user_counts. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_user_counts_excludes_deactivated() { - let pool = get_pool().await; - let (comm_uuid, _, _) = make_community(&pool).await; - - let active_pk = random_pubkey(); - let deactivated_pk = random_pubkey(); - - insert_user(&pool, comm_uuid, &active_pk, false).await; - insert_user(&pool, comm_uuid, &deactivated_pk, false).await; - // Deactivate the second user. - sqlx::query( - "UPDATE users SET deactivated_at = NOW() WHERE community_id = $1 AND pubkey = $2", - ) - .bind(comm_uuid) - .bind(&deactivated_pk) - .execute(&pool) - .await - .expect("deactivate user"); - - let counts = user_counts(&pool).await.expect("user_counts"); - let row = counts - .iter() - .find(|r| r.community_id == comm_uuid) - .expect("row"); - assert_eq!(row.human, 1, "only active user counted"); - } - - /// channel_counts is scoped per community and excludes deleted channels. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_channel_counts_scoped_and_excludes_deleted() { - let pool = get_pool().await; - let (comm_uuid, comm_id, _) = make_community(&pool).await; - let owner = random_pubkey(); - insert_user(&pool, comm_uuid, &owner, false).await; - - // Insert a stream and a DM channel. - sqlx::query( - "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) - VALUES ($1, $2, 'test-stream', 'stream', 'open', $3)", - ) - .bind(uuid::Uuid::new_v4()) - .bind(comm_uuid) - .bind(&owner) - .execute(&pool) - .await - .expect("insert stream channel"); - - let dm_id = uuid::Uuid::new_v4(); - sqlx::query( - "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) - VALUES ($1, $2, 'test-dm', 'dm', 'private', $3)", - ) - .bind(dm_id) - .bind(comm_uuid) - .bind(&owner) - .execute(&pool) - .await - .expect("insert dm channel"); - - // Soft-delete the DM. - sqlx::query("UPDATE channels SET deleted_at = NOW() WHERE id = $1") - .bind(dm_id) - .execute(&pool) - .await - .expect("delete channel"); - - // Use comm_id to satisfy unused import warning. - let _ = comm_id; - - let counts = channel_counts(&pool).await.expect("channel_counts"); - let comm_counts: Vec<_> = counts - .iter() - .filter(|r| r.community_id == comm_uuid) - .collect(); - - // Only the stream channel should be counted. - assert_eq!(comm_counts.len(), 1); - assert_eq!(comm_counts[0].channel_type, "stream"); - assert_eq!(comm_counts[0].count, 1); - } - - /// community_hosts returns id → host mapping. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_community_hosts_returns_mapping() { - let pool = get_pool().await; - let (id, _, host) = make_community(&pool).await; - - let hosts = community_hosts(&pool).await.expect("community_hosts"); - let found = hosts.iter().find(|h| h.id == id); - assert!(found.is_some(), "inserted community not found"); - assert_eq!(found.unwrap().host, host); - } - - /// Regression for #7558: maintenance and bootstrap enumeration return only - /// active communities. Archived, logically deleted (quiescing/fenced), and - /// tombstoned rows are skipped on every sweep, and the tombstone row itself - /// is left intact for retention. The usage-metrics map stays unfiltered so - /// its per-community labels and storage attribution keep covering every - /// row the unfiltered usage count queries return. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_community_hosts_excludes_archived_and_deleted_communities() { - let pool = get_pool().await; - let (active, _, active_host) = make_community(&pool).await; - let (archived, _, _) = make_community(&pool).await; - let (quiescing, _, _) = make_community(&pool).await; - let (fenced, _, _) = make_community(&pool).await; - let (tombstone, _, _) = make_community(&pool).await; - - sqlx::query("UPDATE communities SET archived_at = now() WHERE id = $1") - .bind(archived) - .execute(&pool) - .await - .expect("archive fixture"); - crate::test_support::set_deletion_state(&pool, quiescing, "quiescing").await; - crate::test_support::set_deletion_state(&pool, fenced, "fenced").await; - crate::test_support::set_deletion_state(&pool, tombstone, "tombstone").await; - - let db = Db::from_pool(pool.clone()); - for sweep in 0..2 { - for (caller, hosts) in [("maintenance", db.active_community_hosts().await)] { - let hosts = hosts.unwrap_or_else(|e| panic!("{caller} sweep {sweep}: {e}")); - let ids: std::collections::HashSet = hosts.iter().map(|h| h.id).collect(); - assert_eq!( - hosts - .iter() - .find(|h| h.id == active) - .map(|h| h.host.as_str()), - Some(active_host.as_str()), - "{caller} sweep {sweep}: active community must be returned" - ); - for (label, id) in [ - ("archived", archived), - ("quiescing", quiescing), - ("fenced", fenced), - ("tombstone", tombstone), - ] { - assert!( - !ids.contains(&id), - "{caller} sweep {sweep}: {label} community must be excluded" - ); - } - } - } - - let metrics_ids: std::collections::HashSet = db - .usage_community_hosts() - .await - .expect("usage-metrics hosts") - .iter() - .map(|h| h.id) - .collect(); - for (label, id) in [ - ("active", active), - ("archived", archived), - ("quiescing", quiescing), - ("fenced", fenced), - ("tombstone", tombstone), - ] { - assert!( - metrics_ids.contains(&id), - "usage-metrics map must still include the {label} community" - ); - } - - let (state, deleted): (String, bool) = sqlx::query_as( - "SELECT deletion_state, deleted_at IS NOT NULL FROM communities WHERE id = $1", - ) - .bind(tombstone) - .fetch_one(&pool) - .await - .expect("tombstone row is retained"); - assert_eq!(state, "tombstone"); - assert!(deleted, "tombstone keeps its deleted_at"); - } - - /// community_count reflects newly inserted communities. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_community_count_increases() { - let pool = get_pool().await; - let before = community_count(&pool).await.expect("count before"); - make_community(&pool).await; - let after = community_count(&pool).await.expect("count after"); - assert!(after > before, "count should increase after insert"); - } - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn fleet_snapshots_have_fixed_result_shapes() { - let pool = get_pool().await; - let stock = fleet_stock_snapshot_on(&pool) - .await - .expect("fleet stock snapshot"); - assert!(stock.communities_estimated >= 0); - - let now = chrono::Utc::now(); - let activity = fleet_active_users_on(&pool, now) - .await - .expect("fleet activity snapshot"); - assert!(activity.human_1d >= 0); - assert!(activity.human_7d >= activity.human_1d); - assert!(activity.human_30d >= activity.human_7d); - } - - /// git_repo_counts queries git_repo_names (not git_repos) and is scoped per community. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_git_repo_counts_scoped_per_community() { - let pool = get_pool().await; - let (comm_uuid, _, _) = make_community(&pool).await; - let owner = random_pubkey(); - insert_user(&pool, comm_uuid, &owner, false).await; - let owner_hex = hex::encode(&owner); - - // Insert two repos for this community. - for repo_id in &["repo-alpha", "repo-beta"] { - sqlx::query( - "INSERT INTO git_repo_names (community_id, repo_id, owner_pubkey) - VALUES ($1, $2, $3) - ON CONFLICT DO NOTHING", - ) - .bind(comm_uuid) - .bind(repo_id) - .bind(&owner_hex) - .execute(&pool) - .await - .expect("insert git repo"); - } - - let counts = git_repo_counts(&pool).await.expect("git_repo_counts"); - let comm_counts: Vec<_> = counts - .iter() - .filter(|r| r.community_id == comm_uuid) - .collect(); - - assert_eq!(comm_counts.len(), 1, "one row per community"); - assert_eq!(comm_counts[0].count, 2, "two repos"); - } - - /// active_user_counts classifies pubkeys with no users row as "unknown", - /// not "human" — the old LEFT JOIN treated NULL.agent_owner_pubkey as human. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_active_user_counts_unknown_bucket_for_profileless_poster() { - let pool = get_pool().await; - let (comm_uuid, _, _) = make_community(&pool).await; - - // One known human (has a users row). - let human_pk = random_pubkey(); - insert_user(&pool, comm_uuid, &human_pk, false).await; - - // One profileless poster (no users row at all). - let profileless_pk = random_pubkey(); - - // Insert events for both pubkeys in this community. - let event_id1 = random_pubkey(); // 32-byte id - let event_id2 = random_pubkey(); - let sig = vec![0u8; 64]; - for (pk, eid) in [(&human_pk, &event_id1), (&profileless_pk, &event_id2)] { - sqlx::query( - "INSERT INTO events \ - (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at) \ - VALUES ($1, $2, $3, NOW(), 9, '[]', '', $4, NOW()) \ - ON CONFLICT DO NOTHING", - ) - .bind(comm_uuid) - .bind(eid) - .bind(pk) - .bind(&sig) - .execute(&pool) - .await - .expect("insert event"); - } - - let counts = active_user_counts(&pool, "1 day") - .await - .expect("active_user_counts"); - let row = counts.iter().find(|r| r.community_id == comm_uuid); - assert!(row.is_some(), "row for community must exist"); - let row = row.unwrap(); - assert_eq!(row.human, 1, "known human poster counts as human"); - assert_eq!(row.agent, 0, "no agents"); - assert_eq!( - row.unknown, 1, - "profileless poster must land in unknown, not human" - ); - } - - /// Regression: channel_counts returns no row for a community once all - /// channels of a type are soft-deleted. The poller zero-fills from - /// host_map, so absence from this query is the correct "zero" signal. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn test_channel_counts_drops_to_zero_after_last_channel_deleted() { - let pool = get_pool().await; - let (comm_uuid, _, _) = make_community(&pool).await; - let owner = random_pubkey(); - insert_user(&pool, comm_uuid, &owner, false).await; - - // Insert one stream channel. - let ch_id = uuid::Uuid::new_v4(); - sqlx::query( - "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) - VALUES ($1, $2, 'only-stream', 'stream', 'open', $3)", - ) - .bind(ch_id) - .bind(comm_uuid) - .bind(&owner) - .execute(&pool) - .await - .expect("insert channel"); - - // Sanity: row present before deletion. - let before = channel_counts(&pool).await.expect("channel_counts before"); - let before_row = before - .iter() - .find(|r| r.community_id == comm_uuid && r.channel_type == "stream"); - assert_eq!( - before_row.map(|r| r.count), - Some(1), - "1 stream channel before deletion" - ); - - // Soft-delete the channel. - sqlx::query("UPDATE channels SET deleted_at = NOW() WHERE id = $1") - .bind(ch_id) - .execute(&pool) - .await - .expect("soft-delete channel"); - - // After deletion: no row for this community+type — query returns nothing. - let after = channel_counts(&pool).await.expect("channel_counts after"); - let after_row = after - .iter() - .find(|r| r.community_id == comm_uuid && r.channel_type == "stream"); - assert!( - after_row.is_none(), - "no stream row after last channel deleted — poller will zero-fill" - ); - } - - async fn insert_metric_event( - pool: &PgPool, - community_id: Uuid, - pubkey: &[u8], - created_at: DateTime, - deleted: bool, - ) { - sqlx::query( - "INSERT INTO events \ - (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, deleted_at) \ - VALUES ($1, $2, $3, $4, 9, '[]', '', $5, $4, \ - CASE WHEN $6 THEN $4 ELSE NULL END)", - ) - .bind(community_id) - .bind(random_pubkey()) - .bind(pubkey) - .bind(created_at) - .bind(vec![0u8; 64]) - .bind(deleted) - .execute(pool) - .await - .expect("insert metric event"); - } - - /// Fixed-row fleet SQL must preserve every inclusion/exclusion rule while - /// keeping its result shape independent of community cardinality. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn fleet_snapshots_match_seeded_stock_and_activity_exactly() { - let admin_url = crate::test_support::database_url(); - let admin = PgPoolOptions::new() - .max_connections(1) - .connect(&admin_url) - .await - .expect("connect admin to create scratch db"); - let (pool, scratch_name) = create_scratch_db(&admin, "usage_snapshot").await; - let (community_id, _, _) = make_community(&pool).await; - - let human = random_pubkey(); - let agent = random_pubkey(); - let inactive = random_pubkey(); - insert_user(&pool, community_id, &human, false).await; - sqlx::query( - "INSERT INTO users (community_id, pubkey, agent_owner_pubkey) VALUES ($1, $2, $3)", - ) - .bind(community_id) - .bind(&agent) - .bind(&human) - .execute(&pool) - .await - .expect("insert agent"); - insert_user(&pool, community_id, &inactive, false).await; - sqlx::query( - "UPDATE users SET deactivated_at = NOW() WHERE community_id = $1 AND pubkey = $2", - ) - .bind(community_id) - .bind(&inactive) - .execute(&pool) - .await - .expect("deactivate user"); - - for channel_type in ["stream", "forum", "dm", "workflow", "system"] { - sqlx::query( - "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) \ - VALUES ($1, $2, $3, $4::channel_type, 'open', $5)", - ) - .bind(Uuid::new_v4()) - .bind(community_id) - .bind(format!("metric-{channel_type}")) - .bind(channel_type) - .bind(&human) - .execute(&pool) - .await - .expect("insert live channel"); - } - sqlx::query( - "INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by, deleted_at) \ - VALUES ($1, $2, 'deleted-stream', 'stream', 'open', $3, NOW())", - ) - .bind(Uuid::new_v4()) - .bind(community_id) - .bind(&human) - .execute(&pool) - .await - .expect("insert deleted channel"); - - for role in ["owner", "admin", "member"] { - sqlx::query( - "INSERT INTO relay_members (community_id, pubkey, role) VALUES ($1, $2, $3)", - ) - .bind(community_id) - .bind(format!("{role}-pubkey")) - .bind(role) - .execute(&pool) - .await - .expect("insert relay member"); - } - for status in ["active", "disabled", "archived"] { - sqlx::query( - "INSERT INTO workflows \ - (community_id, id, name, owner_pubkey, definition, definition_hash, status, enabled) \ - VALUES ($1, $2, $3, $4, '{}', $5, $6::workflow_status, $7)", - ) - .bind(community_id) - .bind(Uuid::new_v4()) - .bind(format!("metric-{status}")) - .bind(&human) - .bind(vec![0u8; 32]) - .bind(status) - .bind(status == "active") - .execute(&pool) - .await - .expect("insert workflow"); - } - sqlx::query( - "INSERT INTO git_repo_names (community_id, repo_id, owner_pubkey) VALUES ($1, 'metric-repo', $2)", - ) - .bind(community_id) - .bind(hex::encode(&human)) - .execute(&pool) - .await - .expect("insert git repo"); - sqlx::query("ANALYZE communities") - .execute(&pool) - .await - .expect("refresh planner estimate"); - - let observed_at = Utc::now(); - let unknown = random_pubkey(); - insert_metric_event( - &pool, - community_id, - &human, - observed_at - Duration::hours(12), - false, - ) - .await; - insert_metric_event( - &pool, - community_id, - &human, - observed_at - Duration::days(3), - false, - ) - .await; - insert_metric_event( - &pool, - community_id, - &agent, - observed_at - Duration::days(3), - false, - ) - .await; - insert_metric_event( - &pool, - community_id, - &unknown, - observed_at - Duration::days(20), - false, - ) - .await; - insert_metric_event( - &pool, - community_id, - &unknown, - observed_at - Duration::days(31), - false, - ) - .await; - insert_metric_event( - &pool, - community_id, - &unknown, - observed_at + Duration::hours(1), - false, - ) - .await; - insert_metric_event( - &pool, - community_id, - &unknown, - observed_at - Duration::hours(1), - true, - ) - .await; - - let stock = fleet_stock_snapshot_on(&pool).await.expect("fleet stock"); - assert_eq!(stock.communities_estimated, 1); - assert_eq!((stock.users_human, stock.users_agent), (1, 1)); - assert_eq!( - ( - stock.channels_stream, - stock.channels_forum, - stock.channels_dm, - stock.channels_workflow, - stock.channels_system, - ), - (1, 1, 1, 1, 1) - ); - assert_eq!( - ( - stock.members_owner, - stock.members_admin, - stock.members_member - ), - (1, 1, 1) - ); - assert_eq!( - ( - stock.workflows_active, - stock.workflows_disabled, - stock.workflows_archived, - ), - (1, 1, 1) - ); - assert_eq!(stock.git_repos, 1); - - let activity = fleet_active_users_on(&pool, observed_at) - .await - .expect("fleet activity"); - assert_eq!( - (activity.human_1d, activity.agent_1d, activity.unknown_1d), - (1, 0, 0) - ); - assert_eq!( - (activity.human_7d, activity.agent_7d, activity.unknown_7d), - (1, 1, 0) - ); - assert_eq!( - (activity.human_30d, activity.agent_30d, activity.unknown_30d,), - (1, 1, 1) - ); - - drop_scratch_db(&admin, pool, &scratch_name).await; - } - - /// Fleet collection must read a proved replica and skip instead of - /// silently adding load to the writer when no reader is configured. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn fleet_collection_is_replica_only_and_skips_without_reader() { - let admin_url = crate::test_support::database_url(); - let admin = PgPoolOptions::new() - .max_connections(1) - .connect(&admin_url) - .await - .expect("connect admin to create scratch db"); - let (writer, writer_name) = create_scratch_db(&admin, "usage_writer").await; - let (reader, reader_name) = create_scratch_db(&admin, "usage_reader").await; - let (writer_community, _, _) = make_community(&writer).await; - let (reader_community, _, _) = make_community(&reader).await; - insert_user(&writer, writer_community, &random_pubkey(), false).await; - insert_user(&reader, reader_community, &random_pubkey(), false).await; - insert_user(&reader, reader_community, &random_pubkey(), false).await; - - let without_reader = Db::from_pool(writer.clone()); - assert!( - without_reader - .usage_fleet_stock_snapshot() - .await - .expect("skip without reader") - .is_none(), - "telemetry must not fall back to the writer" - ); - - let db = Db::from_pools(writer.clone(), reader.clone()); - db.fence().force_open_for_tests(Utc::now()); - let snapshot = db - .usage_fleet_stock_snapshot() - .await - .expect("replica collection") - .expect("fresh proved reader"); - assert_eq!( - snapshot.users_human, 2, - "fixture proves the reader served the query" - ); - - drop(db); - drop_scratch_db(&admin, reader, &reader_name).await; - drop_scratch_db(&admin, writer, &writer_name).await; - } - - /// A fleet collection abandoned at its relay-side deadline on a reader - /// that went dark mid-query must release its slot in the shared reader - /// pool within SQLx's bounded close-on-drop, not hold it until the kernel - /// gives up on the socket. SQLx's default return-to-pool path pings the - /// dark connection with no timeout while holding the slot. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn abandoned_fleet_collection_releases_its_reader_slot() { - use sqlx::postgres::PgConnectOptions; - use std::time::{Duration, Instant}; - - let admin_url = crate::test_support::database_url(); - let admin = PgPoolOptions::new() - .max_connections(1) - .connect(&admin_url) - .await - .expect("connect admin to create scratch db"); - let (writer, writer_name) = create_scratch_db(&admin, "usage_writer").await; - let (reader, reader_name) = create_scratch_db(&admin, "usage_reader").await; - let (reader_community, _, _) = make_community(&reader).await; - insert_user(&reader, reader_community, &random_pubkey(), false).await; - - let reader_options = reader.connect_options(); - let proxy = crate::test_support::PausingProxy::spawn( - reader_options.get_host().to_owned(), - reader_options.get_port(), - ) - .await; - let proxied: PgConnectOptions = - (*reader_options).clone().host("127.0.0.1").port(proxy.port); - // The production reader options with one slot, so a stranded slot - // blocks every later acquire, and no warm floor, so nothing redials - // it. No before-acquire ping, so the stall lands after the checkout - // is handed out, where the relay deadline drops it. - let read_pool = Db::read_pool_options(1) - .min_connections(0) - .acquire_timeout(Duration::from_secs(15)) - .connect_with(Db::reader_connect_options(proxied)) - .await - .expect("connect reader through proxy"); - let db = Db::from_pools(writer.clone(), read_pool.clone()); - db.fence().force_open_for_tests(Utc::now()); - db.usage_fleet_stock_snapshot() - .await - .expect("healthy collection") - .expect("fresh proved reader"); - - // Leave one established, idle connection for the collection to use. - drop(read_pool.acquire().await.expect("warm reader connection")); - let warm_deadline = Instant::now() + Duration::from_secs(5); - while read_pool.num_idle() != 1 { - assert!( - Instant::now() < warm_deadline, - "warm connection never returned to the pool" - ); - tokio::time::sleep(Duration::from_millis(10)).await; - } - - // A fresh Db has a cold Aurora capability cache, so the first - // post-acquire await is the capability probe, as in production after - // a failed boot ping. This pins close-on-drop ahead of that await. - let cold = Db::from_pools(writer.clone(), read_pool.clone()); - cold.fence().force_open_for_tests(Utc::now()); - proxy.set_paused(true); - // Under the reader's 1s fence-proof bound, so the caller deadline - // (not the proof timeout) is what abandons the checkout. - tokio::time::timeout( - Duration::from_millis(500), - cold.usage_fleet_stock_snapshot(), - ) - .await - .expect_err("a dark reader must stall the collection until its deadline"); - - // Still paused: only close-on-drop can free the slot this fast. The - // reader pool's release check would free it too, but only after its - // 5s timeout, and its follow-up sqlx ping is not bounded at all. - let started = Instant::now(); - while read_pool.size() != 0 { - assert!( - started.elapsed() < Duration::from_secs(3), - "slot release must be bounded by close-on-drop, still held after {:?}", - started.elapsed() - ); - tokio::time::sleep(Duration::from_millis(20)).await; - } - proxy.set_paused(false); - - let mut replacement = read_pool - .acquire() - .await - .expect("the released slot must accept a replacement connection"); - let one: i32 = sqlx::query_scalar("SELECT 1") - .fetch_one(&mut *replacement) - .await - .expect("replacement reader is usable"); - assert_eq!(one, 1); - drop(replacement); - - drop(cold); - drop(db); - read_pool.close().await; - drop_scratch_db(&admin, reader, &reader_name).await; - drop_scratch_db(&admin, writer, &writer_name).await; - } -} diff --git a/crates/buzz-db/src/store/user.rs b/crates/buzz-db/src/store/user.rs index 2c161e8a026..19f80799d77 100644 --- a/crates/buzz-db/src/store/user.rs +++ b/crates/buzz-db/src/store/user.rs @@ -353,7 +353,29 @@ async fn set_agent_owner_with_operation( owner_pubkey: &[u8], operation: crate::observability::WriterOperation, ) -> Result { + let mut connection = crate::observability::acquire_writer(pool, operation).await?; + // Ownership is first-write-wins and is never cleared by supported writers. + // Already-linked agents are the common authorization path: avoid queuing + // those read-only calls behind a community's claim/restriction transaction. + let recorded: Option>> = sqlx::query_scalar( + "SELECT agent_owner_pubkey FROM users WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community_id.as_uuid()) + .bind(agent_pubkey) + .fetch_optional(&mut *connection) + .await?; + match recorded { + None => { + return Err(crate::error::DbError::NotFound( + "agent pubkey not found in users table".into(), + )) + } + Some(Some(_)) => return Ok(false), + Some(None) => {} + } + drop(connection); let mut tx = crate::begin_community_write_transaction(pool, community_id, operation).await?; + crate::relay_invite::lock_admission(tx.conn(), community_id).await?; // Conditional UPDATE: only set owner if currently NULL. This makes // "first mint wins" atomic — no TOCTOU race between concurrent mints. let result = sqlx::query( @@ -382,6 +404,13 @@ async fn set_agent_owner_with_operation( tx.commit().await?; return Ok(false); } + crate::relay_invite::revoke_restricted_agent_invites( + tx.conn(), + community_id, + agent_pubkey, + owner_pubkey, + ) + .await?; tx.commit().await?; Ok(true) } diff --git a/crates/buzz-db/src/store/user_deletion/discovery_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/discovery_postgres_tests.rs index 00b9c9df9eb..503b2b07c69 100644 --- a/crates/buzz-db/src/store/user_deletion/discovery_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/discovery_postgres_tests.rs @@ -102,7 +102,7 @@ async fn channel_memberships_discover_participants_deduplicate_and_preserve_owne // Reuse channel IDs across communities to exercise community-scoped identity. // Two hidden channel memberships still count as one participating community. for channel in [Uuid::from_u128(1), Uuid::from_u128(2)] { - sqlx::query("INSERT INTO channels (community_id, id, name, created_by) VALUES ($1, $2, 'inventory-test', decode($3, 'hex'))") + sqlx::query("INSERT INTO channels (community_id, id, name, created_by) VALUES ($1, $2, 'inventory-test-' || $2::uuid::text, decode($3, 'hex'))") .bind(community).bind(channel).bind(&key) .execute(&pool).await.unwrap(); sqlx::query("INSERT INTO channel_members (community_id, channel_id, pubkey, removed_at, hidden_at) VALUES ($1, $2, decode($3, 'hex'), CASE WHEN $4 THEN now() END, now())") diff --git a/crates/buzz-db/src/store/user_deletion_fences.rs b/crates/buzz-db/src/store/user_deletion_fences.rs new file mode 100644 index 00000000000..2d437fff094 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion_fences.rs @@ -0,0 +1,260 @@ +//! Operator-global restriction storage and identity locks; no serving or worker +//! path calls these helpers yet. Installing fences does not itself enforce them. +//! +//! Callers use a writer-pool READ COMMITTED transaction. Acquire existing +//! community guards first, then `lock_request` for the worker, then all human +//! locks, then scoped agent locks. +//! Within each group acquire the whole set in one call (sorted here), never +//! upgrade shared locks to exclusive. Gate workers may discover agents after +//! locking humans, then lock the complete agent set. Keep the transaction open +//! through the protected write/checkpoint; commit or rollback releases the locks. + +use buzz_core::CommunityId; +use chrono::{DateTime, Utc}; +use nostr::PublicKey; +use sha2::{Digest, Sha256}; +use sqlx::{Postgres, Transaction}; +use uuid::Uuid; + +use super::entity_deletion::{lock_owned, validate_approved_inventory, EntityLease}; +use crate::{DbError, Result}; + +/// A stable lock/restriction identity, independent of mutable profile rows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FenceIdentity { + pubkey: PublicKey, + scope: Option, +} + +impl FenceIdentity { + /// A human key restricted across the operator's hosted communities. + pub fn user(pubkey: PublicKey) -> Self { + Self { + pubkey, + scope: None, + } + } + + /// An agent key restricted only within its ownership community. + pub fn agent(community: CommunityId, pubkey: PublicKey) -> Self { + Self { + pubkey, + scope: Some(community), + } + } + + fn scope_id(self) -> Option { + self.scope.map(|scope| *scope.as_uuid()) + } + + fn lock_key(self) -> i64 { + let mut hash = Sha256::new(); + hash.update(b"buzz:user-deletion-fence:v1\0"); + hash.update([u8::from(self.scope.is_some())]); + if let Some(scope) = self.scope { + hash.update(scope.as_uuid().as_bytes()); + } + hash.update(self.pubkey.to_bytes()); + let digest = hash.finalize(); + let mut bytes = [0; 8]; + bytes.copy_from_slice(&digest[..8]); + i64::from_be_bytes(bytes) + } +} + +/// Durable evidence of the first restriction on an identity and scope. +#[derive(Clone, Debug, PartialEq, Eq, sqlx::FromRow)] +pub struct UserDeletionFence { + /// Stable restriction identifier. + pub id: Uuid, + /// Canonical lowercase public key. + pub pubkey: String, + /// Agent scope, or NULL for a global human restriction. + pub scope_community_id: Option, + /// Request that first installed this restriction. + pub request_id: Uuid, + /// Verified owner at fencing time; absent for a human restriction. + pub source_owner_pubkey: Option, + /// Time of the first insertion; retries preserve it. + pub blocked_at: DateTime, +} + +/// Acquire shared identity locks for normal writes. Does not check restrictions. +pub async fn lock_shared( + tx: &mut Transaction<'_, Postgres>, + identities: &[FenceIdentity], +) -> Result<()> { + lock(tx, identities, false).await +} + +/// Acquire exclusive identity locks for fencing. Does not install restrictions. +pub async fn lock_exclusive( + tx: &mut Transaction<'_, Postgres>, + identities: &[FenceIdentity], +) -> Result<()> { + lock(tx, identities, true).await +} + +async fn lock( + tx: &mut Transaction<'_, Postgres>, + identities: &[FenceIdentity], + exclusive: bool, +) -> Result<()> { + if identities.len() > 4096 { + return Err(DbError::DeletionSafety( + "too many user-deletion identity locks".into(), + )); + } + let (isolation, timeout): (String, String) = sqlx::query_as( + "SELECT current_setting('transaction_isolation'), current_setting('lock_timeout')", + ) + .fetch_one(&mut **tx) + .await?; + if isolation != "read committed" { + return Err(DbError::DeletionSafety( + "user-deletion locks require READ COMMITTED".into(), + )); + } + // Bound each lock wait without widening a caller's shorter timeout. Restore + // the original setting on success; a SQL error requires caller rollback. + sqlx::query( + "SELECT set_config('lock_timeout', + (EXTRACT(EPOCH FROM LEAST(NULLIF(current_setting('lock_timeout')::interval, + interval '0'), interval '5 seconds')) * 1000)::bigint::text, true)", + ) + .execute(&mut **tx) + .await?; + let mut keys: Vec<_> = identities + .iter() + .map(|identity| (identity.scope.is_some(), identity.lock_key())) + .collect(); + keys.sort_unstable(); + keys.dedup(); + for (_, key) in keys { + let query = if exclusive { + "SELECT pg_advisory_xact_lock($1)" + } else { + "SELECT pg_advisory_xact_lock_shared($1)" + }; + sqlx::query(query).bind(key).execute(&mut **tx).await?; + } + sqlx::query("SELECT set_config('lock_timeout', $1, true)") + .bind(timeout) + .execute(&mut **tx) + .await?; + Ok(()) +} + +/// Lock and read the exact identity restriction in the caller's transaction. +/// +/// For multiple identities, acquire the full shared set first. The caller must +/// refuse a restricted operation and retain this transaction through any write. +/// An agent lookup is scoped; it does not resolve or check the human owner. +/// The planned agent-write path locks the verified owner and agent together, +/// then reads the agent restriction only. This requires the gate to install the +/// human and all owned-agent restrictions atomically, and creation/assignment +/// paths to reject restricted owners. These callers are not wired in yet. +pub async fn find( + tx: &mut Transaction<'_, Postgres>, + identity: FenceIdentity, +) -> Result> { + lock_shared(tx, &[identity]).await?; + read(tx, identity).await +} + +async fn read( + tx: &mut Transaction<'_, Postgres>, + identity: FenceIdentity, +) -> Result> { + // Explicit predicates let PostgreSQL use the matching partial unique index. + let sql = if identity.scope.is_some() { + "SELECT id, pubkey, scope_community_id, request_id, source_owner_pubkey, blocked_at + FROM user_deletion_fences WHERE pubkey = $1 AND scope_community_id = $2" + } else { + "SELECT id, pubkey, scope_community_id, request_id, source_owner_pubkey, blocked_at + FROM user_deletion_fences WHERE pubkey = $1 AND scope_community_id IS NULL" + }; + let query = sqlx::query_as(sql).bind(identity.pubkey.to_hex()); + let query = if let Some(scope) = identity.scope_id() { + query.bind(scope) + } else { + query + }; + Ok(query.fetch_optional(&mut **tx).await?) +} + +/// Lock the parent request and validate the worker's lease and approved inventory. +/// +/// Call before acquiring any identity locks in a fencing transaction. Each +/// insertion rechecks this guard; holding the row lock prevents another worker +/// from claiming the request until this transaction ends. The caller must still +/// verify that the identities and agent ownership belong to this request. +pub async fn lock_request(tx: &mut Transaction<'_, Postgres>, lease: &EntityLease) -> Result<()> { + let request = lock_owned(tx, lease).await?; + if request.entity_type != "user" { + return Err(DbError::DeletionSafety( + "fences require a user deletion request".into(), + )); + } + validate_approved_inventory(tx, &request).await +} + +/// Insert an idempotent restriction under a valid worker lease and identity lock. +/// +/// For multiple identities, first call `lock_request`, then acquire the complete exclusive +/// identity set in order, verify agent ownership, and save its checkpoint in this +/// same transaction. A retry preserves the first row; conflicting provenance +/// errors. On any error roll back, including other fences/checkpoints. +pub async fn insert( + tx: &mut Transaction<'_, Postgres>, + identity: FenceIdentity, + lease: &EntityLease, + source_owner: Option, +) -> Result { + if identity.scope.is_some() != source_owner.is_some() { + return Err(DbError::DeletionSafety( + "agent fences require an owner; user fences do not".into(), + )); + } + lock_request(tx, lease).await?; + let request_id = lease.request_id; + lock_exclusive(tx, &[identity]).await?; + let owner = source_owner.map(|key| key.to_hex()); + sqlx::query( + "INSERT INTO user_deletion_fences (pubkey, scope_community_id, request_id, source_owner_pubkey) + VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING", + ) + .bind(identity.pubkey.to_hex()).bind(identity.scope_id()).bind(request_id).bind(&owner) + .execute(&mut **tx).await?; + let saved = read(tx, identity) + .await? + .ok_or_else(|| DbError::DeletionSafety("fence insertion returned no row".into()))?; + if saved.request_id != request_id || saved.source_owner_pubkey != owner { + return Err(DbError::DeletionSafety( + "identity is already fenced by different provenance".into(), + )); + } + Ok(saved) +} + +#[cfg(test)] +#[path = "user_deletion_fences_postgres_tests.rs"] +mod postgres_tests; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lock_mapping_is_stable_across_processes_and_releases() { + // A change to these values would split the lock domain during rollout. + let key = + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + .unwrap(); + assert_eq!(FenceIdentity::user(key).lock_key(), -4153709860967480559); + assert_eq!( + FenceIdentity::agent(CommunityId::from_uuid(Uuid::from_u128(1)), key).lock_key(), + -3253902268089525902, + ); + } +} diff --git a/crates/buzz-db/src/store/user_deletion_fences_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion_fences_postgres_tests.rs new file mode 100644 index 00000000000..27281150dbe --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion_fences_postgres_tests.rs @@ -0,0 +1,453 @@ +use super::*; +use sqlx::PgPool; +use std::time::Duration; + +async fn pool() -> PgPool { + PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap() +} + +async fn request(pool: &PgPool) -> EntityLease { + let db = crate::Db::from_pool(pool.clone()); + let request = db + .user_deletion_store() + .submit( + &format!("demo:{}", Uuid::new_v4().simple()), + "operator", + None, + ) + .await + .unwrap(); + let store = db.entity_deletion_store(); + store + .approve( + request.id, + "approver", + request.inventory_digest.as_deref().unwrap(), + ) + .await + .unwrap(); + store + .claim(request.id, "worker", Duration::from_secs(300)) + .await + .unwrap() + .unwrap() +} + +fn user() -> FenceIdentity { + FenceIdentity::user(nostr::Keys::generate().public_key()) +} + +async fn assert_plain_schema(pool: &PgPool) { + let guards: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_trigger WHERE tgrelid = 'user_deletion_fences'::regclass", + ) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(guards, 0); + let fks: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_constraint + WHERE conrelid = 'user_deletion_fences'::regclass AND contype = 'f'", + ) + .fetch_one(pool) + .await + .unwrap(); + assert_eq!(fks, 0); + crate::Db::from_pool(pool.clone()) + .validate_deletion_catalog() + .await + .unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn desired_schema_is_global_and_has_no_cascades_or_triggers() { + assert_plain_schema(&pool().await).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_is_global_and_has_no_cascades_or_triggers() { + let pool = pool().await; + crate::Db::from_pool(pool.clone()).migrate().await.unwrap(); + assert_plain_schema(&pool).await; + let registered: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM _operator_global_tables WHERE table_name = 'user_deletion_fences')", + ).fetch_one(&pool).await.unwrap(); + assert!(registered); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn fences_are_atomic_idempotent_scoped_and_preserve_provenance() { + let pool = pool().await; + let lease = request(&pool).await; + let human = user(); + let agent_key = nostr::Keys::generate().public_key(); + let a = FenceIdentity::agent(CommunityId::from_uuid(Uuid::new_v4()), agent_key); + let b = FenceIdentity::agent(CommunityId::from_uuid(Uuid::new_v4()), agent_key); + let mut tx = pool.begin().await.unwrap(); + lock_request(&mut tx, &lease).await.unwrap(); + lock_exclusive(&mut tx, &[a, human]).await.unwrap(); + insert(&mut tx, human, &lease, None).await.unwrap(); + insert(&mut tx, a, &lease, Some(human.pubkey)) + .await + .unwrap(); + tx.rollback().await.unwrap(); + let mut tx = pool.begin().await.unwrap(); + assert!(find(&mut tx, human).await.unwrap().is_none()); + assert!(find(&mut tx, a).await.unwrap().is_none()); + tx.commit().await.unwrap(); + + let mut tx = pool.begin().await.unwrap(); + lock_request(&mut tx, &lease).await.unwrap(); + lock_exclusive(&mut tx, &[a, human]).await.unwrap(); + let first = insert(&mut tx, human, &lease, None).await.unwrap(); + let scoped = insert(&mut tx, a, &lease, Some(human.pubkey)) + .await + .unwrap(); + tx.commit().await.unwrap(); + // A new connection/transaction reads durable state, not an in-memory cache. + let mut tx = pool.begin().await.unwrap(); + assert_eq!(insert(&mut tx, human, &lease, None).await.unwrap(), first); + assert_eq!( + insert(&mut tx, a, &lease, Some(human.pubkey)) + .await + .unwrap(), + scoped + ); + tx.commit().await.unwrap(); + let mut tx = pool.begin().await.unwrap(); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM user_deletion_fences") + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!( + count, 2, + "retries must not create duplicate global or scoped rows" + ); + assert!(find(&mut tx, b).await.unwrap().is_none()); + assert!(find(&mut tx, FenceIdentity::user(agent_key)) + .await + .unwrap() + .is_none()); + tx.commit().await.unwrap(); + let other_lease = request(&pool).await; + let mut tx = pool.begin().await.unwrap(); + assert!(insert(&mut tx, human, &other_lease, None).await.is_err()); + tx.rollback().await.unwrap(); + let mut tx = pool.begin().await.unwrap(); + assert!(insert(&mut tx, a, &lease, Some(user().pubkey)) + .await + .is_err()); + tx.rollback().await.unwrap(); + let mut tx = pool.begin().await.unwrap(); + assert_eq!(find(&mut tx, human).await.unwrap(), Some(first)); + assert_eq!(find(&mut tx, a).await.unwrap(), Some(scoped)); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn rejects_missing_requests_and_invalid_owner_shape() { + let pool = pool().await; + let lease = request(&pool).await; + let human = user(); + let agent = FenceIdentity::agent(CommunityId::from_uuid(Uuid::new_v4()), user().pubkey); + let mut tx = pool.begin().await.unwrap(); + let missing = EntityLease { + request_id: Uuid::new_v4(), + ..lease.clone() + }; + assert!(insert(&mut tx, human, &missing, None).await.is_err()); + assert!(insert(&mut tx, human, &lease, Some(user().pubkey)) + .await + .is_err()); + assert!(insert(&mut tx, agent, &lease, None).await.is_err()); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM user_deletion_fences") + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(count, 0); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn identity_locks_share_conflict_and_release_at_transaction_end() { + let pool = pool().await; + let human = user(); + let mut first = pool.begin().await.unwrap(); + lock_shared(&mut first, &[human]).await.unwrap(); + let mut second = pool.begin().await.unwrap(); + lock_shared(&mut second, &[human]).await.unwrap(); + second.commit().await.unwrap(); + let mut second = pool.begin().await.unwrap(); + sqlx::query("SET LOCAL lock_timeout = '100ms'") + .execute(&mut *second) + .await + .unwrap(); + let error = lock_exclusive(&mut second, &[human]).await.unwrap_err(); + assert!(error.to_string().contains("lock timeout"), "{error}"); + second.rollback().await.unwrap(); + first.commit().await.unwrap(); + + let mut gate = pool.begin().await.unwrap(); + lock_exclusive(&mut gate, &[human]).await.unwrap(); + let mut normal = pool.begin().await.unwrap(); + // An unrelated identity is not blocked. + lock_shared(&mut normal, &[user()]).await.unwrap(); + sqlx::query("SET LOCAL lock_timeout = '100ms'") + .execute(&mut *normal) + .await + .unwrap(); + assert!(lock_shared(&mut normal, &[human]).await.is_err()); + normal.rollback().await.unwrap(); + gate.rollback().await.unwrap(); + let mut normal = pool.begin().await.unwrap(); + lock_shared(&mut normal, &[human]).await.unwrap(); + let timeout: String = sqlx::query_scalar("SHOW lock_timeout") + .fetch_one(&mut *normal) + .await + .unwrap(); + assert_eq!(timeout, "0"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn read_waits_for_gate_then_observes_committed_restriction() { + let pool = pool().await; + let lease = request(&pool).await; + let human = user(); + let mut gate = pool.begin().await.unwrap(); + let saved = insert(&mut gate, human, &lease, None).await.unwrap(); + let mut normal = pool.begin().await.unwrap(); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *normal) + .await + .unwrap(); + let reader = tokio::spawn(async move { find(&mut normal, human).await.unwrap() }); + // Observe the actual lock wait before committing, rather than assuming a + // sleep was long enough for the competing transaction to reach the guard. + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE pid = $1 AND locktype = 'advisory' AND NOT granted)", + ).bind(pid).fetch_one(&pool).await.unwrap(); + if waiting { break; } + tokio::task::yield_now().await; + } + }).await.unwrap(); + gate.commit().await.unwrap(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(5), reader) + .await + .unwrap() + .unwrap(), + Some(saved) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn batch_order_is_stable_and_agent_locks_are_community_scoped() { + let pool = pool().await; + let human = user(); + let a = FenceIdentity::agent(CommunityId::from_uuid(Uuid::new_v4()), user().pubkey); + let b = FenceIdentity::agent(CommunityId::from_uuid(Uuid::new_v4()), a.pubkey); + let mut first = pool.begin().await.unwrap(); + lock_exclusive(&mut first, &[a]).await.unwrap(); + let mut second = pool.begin().await.unwrap(); + lock_exclusive(&mut second, &[b]).await.unwrap(); + second.commit().await.unwrap(); + first.commit().await.unwrap(); + let run = |identities: Vec| { + let pool = pool.clone(); + async move { + let mut tx = pool.begin().await.unwrap(); + lock_exclusive(&mut tx, &identities).await.unwrap(); + tx.commit().await.unwrap(); + } + }; + tokio::time::timeout(Duration::from_secs(10), async { + tokio::join!(run(vec![a, human, b, human]), run(vec![b, a, human])); + }) + .await + .unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn rejects_stale_snapshot_isolation_and_oversized_lock_sets() { + let pool = pool().await; + let mut tx = pool.begin().await.unwrap(); + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ") + .execute(&mut *tx) + .await + .unwrap(); + assert!(find(&mut tx, user()).await.is_err()); + tx.rollback().await.unwrap(); + let mut tx = pool.begin().await.unwrap(); + assert!(lock_exclusive(&mut tx, &vec![user(); 4097]).await.is_err()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn insert_requires_approved_inventory_and_current_unexpired_worker() { + let pool = pool().await; + let db = crate::Db::from_pool(pool.clone()); + let store = db.entity_deletion_store(); + let submitted = db + .user_deletion_store() + .submit("demo:unapproved", "operator", None) + .await + .unwrap(); + assert!(store + .claim(submitted.id, "worker", Duration::from_secs(300)) + .await + .unwrap() + .is_none()); + let unapproved = EntityLease { + request_id: submitted.id, + owner: "worker".into(), + generation: 0, + }; + let lease = request(&pool).await; + let wrong_worker = EntityLease { + owner: "other-worker".into(), + ..lease.clone() + }; + let wrong_generation = EntityLease { + generation: lease.generation + 1, + ..lease.clone() + }; + let identity = user(); + for rejected in [&unapproved, &wrong_worker, &wrong_generation] { + let mut tx = pool.begin().await.unwrap(); + assert!(matches!( + insert(&mut tx, identity, rejected, None).await, + Err(DbError::AccessDenied(_)) + )); + tx.rollback().await.unwrap(); + } + // Expire deterministically instead of racing a short wall-clock timeout. + sqlx::query("UPDATE entity_deletion_requests SET lease_expires_at = clock_timestamp() - interval '1 second' WHERE id = $1") + .bind(lease.request_id).execute(&pool).await.unwrap(); + let mut tx = pool.begin().await.unwrap(); + assert!(matches!( + insert(&mut tx, identity, &lease, None).await, + Err(DbError::AccessDenied(_)) + )); + tx.rollback().await.unwrap(); + let successor = store + .claim(lease.request_id, "successor", Duration::from_secs(300)) + .await + .unwrap() + .unwrap(); + let mut tx = pool.begin().await.unwrap(); + assert!(matches!( + insert(&mut tx, identity, &lease, None).await, + Err(DbError::AccessDenied(_)) + )); + tx.rollback().await.unwrap(); + let mut tx = pool.begin().await.unwrap(); + assert!(find(&mut tx, identity).await.unwrap().is_none()); + tx.commit().await.unwrap(); + + let mut tx = pool.begin().await.unwrap(); + let saved = insert(&mut tx, identity, &successor, None).await.unwrap(); + tx.commit().await.unwrap(); + // Exercise the insertion guard independently of claim-time validation. + sqlx::query("DELETE FROM entity_deletion_approvals WHERE request_id = $1") + .bind(successor.request_id) + .execute(&pool) + .await + .unwrap(); + let mut tx = pool.begin().await.unwrap(); + assert!(matches!( + insert(&mut tx, user(), &successor, None).await, + Err(DbError::DeletionSafety(_)) + )); + tx.rollback().await.unwrap(); + let rows: Vec = sqlx::query_as( + "SELECT id, pubkey, scope_community_id, request_id, source_owner_pubkey, blocked_at FROM user_deletion_fences" + ).fetch_all(&pool).await.unwrap(); + assert_eq!(rows, vec![saved]); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn competing_inserts_wait_then_preserve_or_reject_original_provenance() { + let pool = pool().await; + let lease = request(&pool).await; + let other_lease = request(&pool).await; + for (scoped, conflict) in [(false, false), (false, true), (true, false), (true, true)] { + let owner = user().pubkey; + let identity = if scoped { + FenceIdentity::agent(CommunityId::from_uuid(Uuid::new_v4()), user().pubkey) + } else { + user() + }; + let source_owner = scoped.then_some(owner); + let mut first = pool.begin().await.unwrap(); + let saved = insert(&mut first, identity, &lease, source_owner) + .await + .unwrap(); + let next_lease = if conflict && !scoped { + other_lease.clone() + } else { + lease.clone() + }; + let next_owner = if conflict && scoped { + Some(user().pubkey) + } else { + source_owner + }; + let mut second = pool.begin().await.unwrap(); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *second) + .await + .unwrap(); + let writer = tokio::spawn(async move { + let result = insert(&mut second, identity, &next_lease, next_owner).await; + if result.is_ok() { + second.commit().await.unwrap(); + } else { + second.rollback().await.unwrap(); + } + result + }); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE pid = $1 AND NOT granted)", + ) + .bind(pid) + .fetch_one(&pool) + .await + .unwrap(); + if waiting { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + first.commit().await.unwrap(); + let result = tokio::time::timeout(Duration::from_secs(5), writer) + .await + .unwrap() + .unwrap(); + if conflict { + assert!( + matches!(result, Err(DbError::DeletionSafety(ref message)) if message.contains("different provenance")) + ); + } else { + assert_eq!(result.unwrap(), saved); + } + let mut tx = pool.begin().await.unwrap(); + assert_eq!(find(&mut tx, identity).await.unwrap(), Some(saved)); + tx.commit().await.unwrap(); + } +} diff --git a/crates/buzz-db/src/store/verified_profiles.rs b/crates/buzz-db/src/store/verified_profiles.rs new file mode 100644 index 00000000000..db3d09b9942 --- /dev/null +++ b/crates/buzz-db/src/store/verified_profiles.rs @@ -0,0 +1,271 @@ +//! Durable output-only NIP-FI verified profiles. Authorization never reads +//! these tables. +//! +//! A profile is a historical record ("verified as Alice at T"). It is never +//! retracted: on a relay that enforces NIP-FI, a key cannot post without a +//! fresh issuer assertion, so a stale name labels only past activity. + +use crate::{AdmittedTx, Db, DbError, Result}; +use buzz_core::CommunityId; +use chrono::{DateTime, Utc}; +use nostr::{Event, EventBuilder, JsonUtil, Keys, Kind, Tag, Timestamp}; +use sqlx::Row; + +/// Operator-selected publication policy for one issuer. +#[derive(Clone)] +pub struct ProfilePolicy { + /// Exact private issuer identity. + pub issuer: String, + /// Validated public label; `None` disables publication for this issuer. + pub label: Option, + /// Unchanged-name refresh interval. + pub refresh_seconds: i64, +} + +impl std::fmt::Debug for ProfilePolicy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ProfilePolicy([REDACTED])") + } +} + +/// Verified input from a successful human WebSocket admission. +pub struct ProfileAdmission<'a> { + /// Community resolved for this connection. + pub community: CommunityId, + /// Issuer authenticated by the assertion verifier. + pub issuer: &'a str, + /// NIP-42-proven key, equal to the assertion key. + pub pubkey: &'a str, + /// Authenticated iat; retains fractional ordering. + pub issued_at: DateTime, + /// Actual successful admission time. + pub admitted_at: DateTime, + /// Validated public display name. + pub display_name: &'a str, + /// Validated public username. + pub username: &'a str, + /// Validated optional public full name. + pub full_name: Option<&'a str>, + /// Public issuer label from the enabled policy. + pub label: &'a str, + /// Unchanged-name refresh interval from the enabled policy. + pub refresh_seconds: i64, + /// Whether the relay requires an explicit `relay_members` row to connect. + /// Open relays treat enforced NIP-FI admission as eligibility instead. + pub membership_required: bool, +} + +async fn lock_profile(tx: &mut AdmittedTx, pubkey: &str) -> Result<()> { + let key = format!("profile:{}:{pubkey}", tx.community().as_uuid()); + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 30382))") + .bind(key) + .execute(tx.conn()) + .await?; + Ok(()) +} + +impl Db { + /// Publish or refresh a verified profile in one admitted transaction. + /// + /// Skips banned keys, keys without a member row where the relay requires + /// one, assertions older than the issuer's last recorded one, and + /// admissions earlier than the published `verified_at`. Signs a new event + /// only when the issuer, names or label changed or the refresh interval + /// passed, so the latest verification from any issuer wins. Returns the + /// new event for delivery, or `None` when nothing was written. + pub async fn publish_verified_profile( + &self, + input: ProfileAdmission<'_>, + keys: &Keys, + ) -> Result> { + let mut tx = crate::begin_community_write_transaction( + &self.pool, + input.community, + crate::observability::WriterOperation::Authorization, + ) + .await?; + sqlx::query("SET LOCAL lock_timeout = '5s'") + .execute(tx.conn()) + .await?; + lock_profile(&mut tx, input.pubkey).await?; + + let access = sqlx::query( + r#" + SELECT + EXISTS ( + SELECT 1 FROM relay_members + WHERE community_id = $1 AND pubkey = $2 + ) AS member, + EXISTS ( + SELECT 1 FROM community_bans + WHERE community_id = $1 AND pubkey = decode($2, 'hex') + AND banned AND (ban_expires_at IS NULL OR ban_expires_at > now()) + ) AS banned + "#, + ) + .bind(input.community.as_uuid()) + .bind(input.pubkey) + .fetch_one(tx.conn()) + .await?; + if access.try_get::("banned")? + || (input.membership_required && !access.try_get::("member")?) + { + return Ok(None); + } + + let head = sqlx::query( + r#" + SELECT issuer, issued_at::text AS issued_at, event + FROM nip_fi_profile_heads + WHERE community_id = $1 AND pubkey = $2 + FOR UPDATE + "#, + ) + .bind(input.community.as_uuid()) + .bind(input.pubkey) + .fetch_optional(tx.conn()) + .await?; + let (old, same_issuer) = match &head { + Some(row) => { + let same_issuer = row.try_get::("issuer")? == input.issuer; + // Assertion times are only comparable within one issuer. + if same_issuer && nanos(input.issued_at) < parse_nanos(row.try_get("issued_at")?)? { + return Ok(None); + } + let event = + Event::from_json(row.try_get::("event")?.to_string()) + .map_err(|_| DbError::InvalidData("profile event".into()))?; + // Public verified_at never moves backwards. + if verified_at(&event).is_some_and(|at| input.admitted_at.timestamp() < at) { + return Ok(None); + } + (Some(event), same_issuer) + } + None => (None, false), + }; + + let issued_at = nanos(input.issued_at).to_string(); + let changed = !same_issuer + || old.as_ref().is_none_or(|event| { + tag(event, "display_name") != Some(input.display_name) + || tag(event, "username") != Some(input.username) + || tag(event, "full_name") != input.full_name + || tag(event, "issuer_label") != Some(input.label) + || verified_at(event).is_none_or(|at| { + input.admitted_at.timestamp() - at >= input.refresh_seconds + }) + }); + if !changed { + sqlx::query( + r#" + UPDATE nip_fi_profile_heads + SET issued_at = $3::numeric + WHERE community_id = $1 AND pubkey = $2 AND issued_at < $3::numeric + "#, + ) + .bind(input.community.as_uuid()) + .bind(input.pubkey) + .bind(&issued_at) + .execute(tx.conn()) + .await?; + tx.commit().await?; + return Ok(None); + } + + let event = profile_event(keys, &input, old.as_ref())?; + let stored = self + .replace_parameterized_event_in_transaction( + &mut tx, + &event, + input.pubkey, + None, + crate::replaceable::ParameterizedReplacePrecondition::Unconditional, + ) + .await?; + if !matches!( + stored.status, + crate::replaceable::ParameterizedReplaceStatus::Inserted + | crate::replaceable::ParameterizedReplaceStatus::Duplicate + ) { + return Err(DbError::InvalidData( + "profile event did not replace current head".into(), + )); + } + sqlx::query( + r#" + INSERT INTO nip_fi_profile_heads (community_id, pubkey, issuer, issued_at, event) + VALUES ($1, $2, $3, $4::numeric, $5) + ON CONFLICT (community_id, pubkey) DO UPDATE SET + issuer = EXCLUDED.issuer, + issued_at = EXCLUDED.issued_at, + event = EXCLUDED.event + "#, + ) + .bind(input.community.as_uuid()) + .bind(input.pubkey) + .bind(input.issuer) + .bind(&issued_at) + .bind(serde_json::to_value(&event)?) + .execute(tx.conn()) + .await?; + tx.commit().await?; + Ok(Some(event)) + } +} + +fn tag<'a>(event: &'a Event, name: &str) -> Option<&'a str> { + event.tags.iter().find_map(|t| { + let t = t.as_slice(); + (t.first().map(String::as_str) == Some(name)) + .then(|| t.get(1).map(String::as_str)) + .flatten() + }) +} + +fn verified_at(event: &Event) -> Option { + tag(event, "verified_at").and_then(|value| value.parse().ok()) +} + +fn profile_event( + keys: &Keys, + input: &ProfileAdmission<'_>, + previous: Option<&Event>, +) -> Result { + let verified_at = input.admitted_at.timestamp().to_string(); + let mut values = vec![ + ("d", input.pubkey), + ("p", input.pubkey), + ("active", "true"), + ("display_name", input.display_name), + ("username", input.username), + ("issuer_label", input.label), + ]; + values.push(("verified_at", &verified_at)); + if let Some(full_name) = input.full_name { + values.push(("full_name", full_name)); + } + let tags = values + .into_iter() + .map(|(k, v)| Tag::parse([k, v]).map_err(|_| DbError::InvalidData("profile tag".into()))) + .collect::>>()?; + let created_at = (Utc::now().timestamp().max(0) as u64) + .max(previous.map_or(0, |e| e.created_at.as_secs().saturating_add(1))); + EventBuilder::new(Kind::Custom(30382), "") + .tags(tags) + .custom_created_at(Timestamp::from(created_at)) + .sign_with_keys(keys) + .map_err(|_| DbError::InvalidData("profile signing".into())) +} + +// NumericDate supports nanoseconds; PostgreSQL timestamps only retain microseconds. +fn nanos(value: DateTime) -> i128 { + i128::from(value.timestamp()) * 1_000_000_000 + i128::from(value.timestamp_subsec_nanos()) +} +fn parse_nanos(value: &str) -> Result { + value + .parse() + .map_err(|_| DbError::InvalidData("profile assertion timestamp".into())) +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/verified_profiles/postgres_tests.rs b/crates/buzz-db/src/store/verified_profiles/postgres_tests.rs new file mode 100644 index 00000000000..4aad5613f3d --- /dev/null +++ b/crates/buzz-db/src/store/verified_profiles/postgres_tests.rs @@ -0,0 +1,393 @@ +use super::*; +use chrono::Duration; + +const ISSUER: &str = "https://issuer.test"; + +async fn fixture() -> (Db, CommunityId, Keys, String) { + let db = Db::new(&crate::DbConfig { + database_url: crate::test_support::database_url(), + ..crate::DbConfig::default() + }) + .await + .unwrap(); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + db.migrate().await.unwrap(); + } + let community = CommunityId::from_uuid(uuid::Uuid::new_v4()); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community.as_uuid()) + .bind(format!("profile-{}.test", community.as_uuid())) + .execute(&db.pool) + .await + .unwrap(); + let key = Keys::generate().public_key().to_hex(); + set_member(&db, community, &key, true).await; + (db, community, Keys::generate(), key) +} + +async fn set_member(db: &Db, community: CommunityId, key: &str, member: bool) { + let mut tx = crate::begin_community_write_transaction( + &db.pool, + community, + crate::observability::WriterOperation::Authorization, + ) + .await + .unwrap(); + let sql = if member { + "INSERT INTO relay_members (community_id, pubkey, role) VALUES ($1, $2, 'member')" + } else { + "DELETE FROM relay_members WHERE community_id = $1 AND pubkey = $2" + }; + sqlx::query(sql) + .bind(community.as_uuid()) + .bind(key) + .execute(tx.conn()) + .await + .unwrap(); + tx.commit().await.unwrap(); +} + +fn input<'a>( + community: CommunityId, + key: &'a str, + issued_at: DateTime, + admitted_at: DateTime, + full_name: Option<&'a str>, +) -> ProfileAdmission<'a> { + ProfileAdmission { + community, + issuer: ISSUER, + pubkey: key, + issued_at, + admitted_at, + display_name: "Alice", + username: "alice", + full_name, + label: "Example", + refresh_seconds: 3600, + membership_required: true, + } +} + +async fn current(db: &Db, community: CommunityId, key: &str) -> Option { + let value: Option = sqlx::query_scalar( + "SELECT event FROM nip_fi_profile_heads WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community.as_uuid()) + .bind(key) + .fetch_optional(&db.pool) + .await + .unwrap(); + value.map(|v| Event::from_json(v.to_string()).unwrap()) +} + +async fn lifecycle() { + let (db, community, keys, key) = fixture().await; + let start = Utc::now() - Duration::hours(3); + let iat = start - Duration::seconds(10); + let publish = |input| db.publish_verified_profile(input, &keys); + + let first = publish(input(community, &key, iat, start, Some("Alice Example"))) + .await + .unwrap() + .expect("first admission publishes"); + assert_eq!(current(&db, community, &key).await.unwrap().id, first.id); + assert_eq!(first.pubkey, keys.public_key()); + assert_eq!(first.kind, Kind::Custom(30382)); + assert_eq!(first.tags.len(), 8); + assert_eq!(tag(&first, "d"), Some(key.as_str())); + assert_eq!(tag(&first, "active"), Some("true")); + assert_eq!(tag(&first, "display_name"), Some("Alice")); + assert_eq!(tag(&first, "full_name"), Some("Alice Example")); + assert_eq!(tag(&first, "issuer_label"), Some("Example")); + assert_eq!(verified_at(&first), Some(start.timestamp())); + assert!(first.verify().is_ok()); + + let step = |n: i64| start + Duration::seconds(n); + assert!( + publish(input( + community, + &key, + iat + Duration::nanoseconds(2), + step(1), + Some("Alice Example"), + )) + .await + .unwrap() + .is_none(), + "unchanged admission does not refresh early" + ); + + let renamed = publish(input( + community, + &key, + iat + Duration::nanoseconds(3), + step(2), + Some("Alice Renamed"), + )) + .await + .unwrap() + .expect("full-name changes publish immediately"); + assert_eq!(tag(&renamed, "full_name"), Some("Alice Renamed")); + assert!(renamed.created_at > first.created_at); + + let without_full_name = publish(input( + community, + &key, + iat + Duration::nanoseconds(4), + step(3), + None, + )) + .await + .unwrap() + .expect("dropping the full name publishes"); + assert_eq!(tag(&without_full_name, "full_name"), None); + assert_eq!(without_full_name.tags.len(), 7); + + // An assertion older than the last accepted one cannot overwrite. + assert!( + publish(input( + community, + &key, + iat + Duration::nanoseconds(1), + step(4), + Some("Old"), + )) + .await + .unwrap() + .is_none(), + "older fractional iat cannot overwrite" + ); + assert!( + publish(input( + community, + &key, + iat + Duration::nanoseconds(5), + step(2), + Some("Delayed"), + )) + .await + .unwrap() + .is_none(), + "public verified_at cannot move backwards" + ); + assert_eq!( + current(&db, community, &key).await.unwrap().id, + without_full_name.id + ); + + let refreshed = publish(input( + community, + &key, + iat + Duration::nanoseconds(6), + step(3 + 3600), + None, + )) + .await + .unwrap() + .expect("unchanged names refresh after the interval"); + assert_eq!(verified_at(&refreshed), Some(step(3 + 3600).timestamp())); + assert_eq!( + current(&db, community, &key).await.unwrap().id, + refreshed.id + ); + + // Each public field change publishes immediately. + let alicia = |ns: i64, n: i64| ProfileAdmission { + display_name: "Alicia", + username: "alicia", + label: "Example Corp", + ..input( + community, + &key, + iat + Duration::nanoseconds(ns), + step(n), + None, + ) + }; + let mut last = refreshed; + for (field, admission) in [ + ( + "display_name", + ProfileAdmission { + username: "alice", + label: "Example", + ..alicia(7, 3604) + }, + ), + ( + "username", + ProfileAdmission { + label: "Example", + ..alicia(8, 3605) + }, + ), + ("issuer_label", alicia(9, 3606)), + ] { + let event = publish(admission) + .await + .unwrap() + .unwrap_or_else(|| panic!("{field} change publishes")); + assert_ne!(tag(&event, field), tag(&last, field)); + last = event; + } + + // A no-op login still advances the issuer's assertion ordering. + assert!(publish(alicia(20, 3607)).await.unwrap().is_none()); + assert!( + publish(ProfileAdmission { + display_name: "Stale", + ..alicia(15, 3608) + }) + .await + .unwrap() + .is_none(), + "an assertion older than an unchanged one cannot overwrite" + ); + + // The latest verification from any issuer wins; assertion times are not + // compared across issuers. + let other = |n: i64| ProfileAdmission { + issuer: "https://other-issuer.test", + display_name: "Other", + ..input(community, &key, iat - Duration::hours(1), step(n), None) + }; + assert!( + publish(other(3605)).await.unwrap().is_none(), + "an earlier verification from another issuer cannot replace" + ); + let taken = publish(other(3609)) + .await + .unwrap() + .expect("a newer verification from another issuer replaces"); + assert_eq!(tag(&taken, "display_name"), Some("Other")); + let back = publish(alicia(21, 3610)) + .await + .unwrap() + .expect("the original issuer takes the profile back on a newer verification"); + assert_eq!(tag(&back, "display_name"), Some("Alicia")); + assert_eq!(current(&db, community, &key).await.unwrap().id, back.id); + let live: Vec = sqlx::query_scalar( + "SELECT encode(id, 'hex') FROM events WHERE community_id = $1 AND kind = 30382 AND d_tag = $2 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(&key) + .fetch_all(&db.pool) + .await + .unwrap(); + assert_eq!(live, vec![back.id.to_hex()], "one live replaceable event"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn profile_lifecycle_publishes_updates_and_orders() { + lifecycle().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_profile_lifecycle_publishes_updates_and_orders() { + lifecycle().await; +} + +async fn eligibility() { + let (db, community, keys, key) = fixture().await; + set_member(&db, community, &key, false).await; + let iat = Utc::now() - Duration::seconds(60); + let at = |n: i64, membership_required| ProfileAdmission { + membership_required, + ..input(community, &key, iat, iat + Duration::seconds(n), None) + }; + assert!( + db.publish_verified_profile(at(1, true), &keys) + .await + .unwrap() + .is_none(), + "members-required relays need an explicit member row" + ); + assert!(current(&db, community, &key).await.is_none()); + assert!( + db.publish_verified_profile(at(2, false), &keys) + .await + .unwrap() + .is_some(), + "open relays publish for enforced admissions without a member row" + ); + + // A banned key never publishes, and its existing profile stays as a + // historical record. + let published = current(&db, community, &key).await.unwrap(); + let bytes = hex::decode(&key).unwrap(); + crate::moderation::ban_member(&db.pool, community, &bytes, &bytes, None, None) + .await + .unwrap(); + set_member(&db, community, &key, true).await; + for membership_required in [true, false] { + assert!( + db.publish_verified_profile( + ProfileAdmission { + display_name: "Banned Alice", + ..at(3, membership_required) + }, + &keys, + ) + .await + .unwrap() + .is_none(), + "banned keys do not publish" + ); + } + assert_eq!( + current(&db, community, &key).await.unwrap().id, + published.id + ); + crate::moderation::unban_member(&db.pool, community, &bytes, &bytes) + .await + .unwrap(); + assert!(db + .publish_verified_profile( + ProfileAdmission { + display_name: "Restored Alice", + ..at(4, true) + }, + &keys, + ) + .await + .unwrap() + .is_some()); + crate::moderation::ban_member( + &db.pool, + community, + &bytes, + &bytes, + None, + Some(Utc::now() - Duration::minutes(1)), + ) + .await + .unwrap(); + assert!( + db.publish_verified_profile( + ProfileAdmission { + display_name: "Expired-ban Alice", + ..at(5, true) + }, + &keys, + ) + .await + .unwrap() + .is_some(), + "an expired ban does not block" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn profiles_publish_only_for_eligible_keys() { + eligibility().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_profiles_publish_only_for_eligible_keys() { + eligibility().await; +} diff --git a/crates/buzz-db/src/store/workflow.rs b/crates/buzz-db/src/store/workflow.rs index 6f7f64aa2da..e29ed47950f 100644 --- a/crates/buzz-db/src/store/workflow.rs +++ b/crates/buzz-db/src/store/workflow.rs @@ -192,6 +192,48 @@ pub struct WorkflowRecord { pub updated_at: DateTime, } +/// What caused a workflow run, recorded when the run is created. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RunCause { + /// A signed event: the message, reaction or diff signer's pubkey. + Event(Vec), + /// A cron or interval timer. + Schedule, + /// A webhook call. The caller is unknown. + Webhook, + /// A manual trigger: the invoking pubkey. + Manual(Vec), +} + +impl RunCause { + fn source(&self) -> &'static str { + match self { + Self::Event(_) => "event", + Self::Schedule => "schedule", + Self::Webhook => "webhook", + Self::Manual(_) => "manual", + } + } + + fn pubkey(&self) -> Option<&[u8]> { + match self { + Self::Event(pubkey) | Self::Manual(pubkey) => Some(pubkey), + Self::Schedule | Self::Webhook => None, + } + } + + /// Rebuild a stored cause. Missing or inconsistent values give `None`. + fn from_columns(source: Option<&str>, pubkey: Option>) -> Option { + match (source?, pubkey) { + ("event", Some(pubkey)) => Some(Self::Event(pubkey)), + ("manual", Some(pubkey)) => Some(Self::Manual(pubkey)), + ("schedule", None) => Some(Self::Schedule), + ("webhook", None) => Some(Self::Webhook), + _ => None, + } + } +} + /// A single execution of a workflow. #[derive(Debug, Clone)] pub struct WorkflowRunRecord { @@ -217,6 +259,8 @@ pub struct WorkflowRunRecord { /// Serialized `TriggerContext` captured at workflow start. /// NULL for runs created before this column was added (backwards-compatible). pub trigger_context: Option, + /// What caused this run. `None` for runs created before causes were recorded. + pub cause: Option, /// When execution began. pub started_at: Option>, /// When execution finished (success or failure). @@ -589,6 +633,11 @@ pub async fn latest_scheduled_workflow_fire( /// boundary. If run creation succeeds, callers should attach the run id before /// spawning execution. If run creation fails, leaving `workflow_run_id` NULL is /// intentional: the schedule instant was claimed and must not duplicate later. +/// +/// Returns `false` when no unlinked claim matches, or the run is missing or +/// belongs to another workflow. Workflow delete removes only its own fires +/// before its runs, and the fire→run FK is NO ACTION, so a cross-workflow link +/// would block that delete. pub async fn attach_scheduled_workflow_run( pool: &PgPool, community_id: CommunityId, @@ -610,6 +659,10 @@ pub async fn attach_scheduled_workflow_run( AND workflow_id = $2 AND scheduled_for = $3 AND workflow_run_id IS NULL + AND EXISTS ( + SELECT 1 FROM workflow_runs + WHERE community_id = $1 AND workflow_id = $2 AND id = $4 + ) "#, ) .bind(community_id.as_uuid()) @@ -862,6 +915,7 @@ pub async fn create_workflow_run( workflow_id: Uuid, trigger_event_id: Option<&[u8]>, trigger_context: Option<&serde_json::Value>, + cause: &RunCause, ) -> Result { let mut tx = crate::begin_community_write_transaction( pool, @@ -874,8 +928,9 @@ pub async fn create_workflow_run( sqlx::query( r#" INSERT INTO workflow_runs - (community_id, id, workflow_id, status, trigger_event_id, current_step, execution_trace, trigger_context) - VALUES ($1, $2, $3, 'pending', $4, 0, '[]', $5) + (community_id, id, workflow_id, status, trigger_event_id, current_step, execution_trace, + trigger_context, cause_source, cause_pubkey) + VALUES ($1, $2, $3, 'pending', $4, 0, '[]', $5, $6, $7) "#, ) .bind(community_id.as_uuid()) @@ -883,6 +938,8 @@ pub async fn create_workflow_run( .bind(workflow_id) .bind(trigger_event_id) .bind(trigger_context) + .bind(cause.source()) + .bind(cause.pubkey()) .execute(tx.conn()) .await?; tx.commit().await?; @@ -899,7 +956,8 @@ pub async fn get_workflow_run( let row = sqlx::query( r#" SELECT community_id, id, workflow_id, status::text AS status, trigger_event_id, current_step, - execution_trace, trigger_context, started_at, completed_at, error_message, error_code, created_at + execution_trace, trigger_context, cause_source, cause_pubkey, started_at, completed_at, + error_message, error_code, created_at FROM workflow_runs WHERE community_id = $1 AND id = $2 "#, @@ -931,7 +989,8 @@ pub async fn list_workflow_runs_page( let rows = sqlx::query( r#" SELECT community_id, id, workflow_id, status::text AS status, trigger_event_id, current_step, - execution_trace, trigger_context, started_at, completed_at, error_message, error_code, created_at + execution_trace, trigger_context, cause_source, cause_pubkey, started_at, completed_at, + error_message, error_code, created_at FROM workflow_runs WHERE community_id = $1 AND workflow_id = $2 AND ( @@ -1293,6 +1352,10 @@ fn row_to_run_record(row: sqlx::postgres::PgRow) -> Result { current_step: row.try_get("current_step")?, execution_trace: row.try_get("execution_trace")?, trigger_context: row.try_get("trigger_context")?, + cause: RunCause::from_columns( + row.try_get::, _>("cause_source")?.as_deref(), + row.try_get("cause_pubkey")?, + ), started_at: row.try_get("started_at")?, completed_at: row.try_get("completed_at")?, error_message: row.try_get("error_message")?, @@ -1363,6 +1426,7 @@ impl Db { workflow_id: Uuid, trigger_event_id: Option<&[u8]>, trigger_context: Option<&serde_json::Value>, + cause: &RunCause, ) -> Result { crate::workflow::create_workflow_run( &self.pool, @@ -1370,6 +1434,7 @@ impl Db { workflow_id, trigger_event_id, trigger_context, + cause, ) .await } @@ -1753,6 +1818,30 @@ impl Db { #[cfg(test)] mod postgres_tests { + #[test] + fn stored_cause_requires_a_consistent_source_and_pubkey() { + let pubkey = vec![1u8; 32]; + assert_eq!( + RunCause::from_columns(Some("event"), Some(pubkey.clone())), + Some(RunCause::Event(pubkey.clone())) + ); + assert_eq!( + RunCause::from_columns(Some("schedule"), None), + Some(RunCause::Schedule) + ); + for (source, key) in [ + (Some("event"), None), + (Some("manual"), None), + (Some("schedule"), Some(pubkey.clone())), + (Some("webhook"), Some(pubkey.clone())), + (Some("unknown"), None), + (None, Some(pubkey.clone())), + (None, None), + ] { + assert_eq!(RunCause::from_columns(source, key), None, "{source:?}"); + } + } + use super::*; use chrono::TimeZone; @@ -1995,6 +2084,7 @@ mod postgres_tests { { "step": "s1", "status": "completed" } ]), trigger_context: None, + cause: None, started_at: Some(now), completed_at: None, error_message: None, @@ -2024,6 +2114,7 @@ mod postgres_tests { current_step: 0, execution_trace: serde_json::json!([]), trigger_context: None, + cause: None, started_at: None, completed_at: None, error_message: None, @@ -2048,6 +2139,7 @@ mod postgres_tests { current_step: 1, execution_trace: serde_json::json!([]), trigger_context: None, + cause: None, started_at: Some(now), completed_at: Some(now), error_message: Some("step timeout exceeded".to_owned()), @@ -2080,6 +2172,7 @@ mod postgres_tests { current_step: 2, execution_trace: trace.clone(), trigger_context: None, + cause: None, started_at: Some(now), completed_at: Some(now), error_message: None, @@ -2103,6 +2196,7 @@ mod postgres_tests { current_step: 0, execution_trace: serde_json::json!([]), trigger_context: None, + cause: None, started_at: None, completed_at: None, error_message: None, @@ -2446,9 +2540,16 @@ mod postgres_tests { .expect("claim wins"); // Create the run the won claim is responsible for, then attach it. - let run_id = create_workflow_run(&pool, community, workflow_id, None, None) - .await - .expect("create run ok"); + let run_id = create_workflow_run( + &pool, + community, + workflow_id, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("create run ok"); let attached = attach_scheduled_workflow_run(&pool, community, workflow_id, scheduled_for, run_id) @@ -2475,9 +2576,16 @@ mod postgres_tests { // A second attach is a no-op: the `workflow_run_id IS NULL` guard means // an already-linked claim is never re-pointed to a different run. - let other_run = create_workflow_run(&pool, community, workflow_id, None, None) - .await - .expect("create second run ok"); + let other_run = create_workflow_run( + &pool, + community, + workflow_id, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("create second run ok"); let reattached = attach_scheduled_workflow_run(&pool, community, workflow_id, scheduled_for, other_run) .await @@ -2488,6 +2596,50 @@ mod postgres_tests { ); } + /// A claim for workflow B cannot point at A's run. Such a link has a valid + /// run FK but would block A's explicit run delete with no FK action. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn attach_rejects_run_from_another_workflow() { + let pool = setup_pool().await; + let community = make_community(&pool).await; + let (workflow_a, _) = make_workflow_in(&pool, community).await; + let (workflow_b, _) = make_workflow_in(&pool, community).await; + let scheduled_for = Utc.with_ymd_and_hms(2026, 6, 27, 0, 3, 0).unwrap(); + claim_scheduled_workflow_fire(&pool, community, workflow_b, scheduled_for) + .await + .expect("claim B") + .expect("claim wins"); + let run_a = create_workflow_run( + &pool, + community, + workflow_a, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("create A run"); + + assert!( + !attach_scheduled_workflow_run(&pool, community, workflow_b, scheduled_for, run_a) + .await + .expect("reject cross-workflow link"), + "B's fire must not reference A's run" + ); + let linked: Option = sqlx::query_scalar( + "SELECT workflow_run_id FROM scheduled_workflow_fires \ + WHERE community_id = $1 AND workflow_id = $2 AND scheduled_for = $3", + ) + .bind(community.as_uuid()) + .bind(workflow_b) + .bind(scheduled_for) + .fetch_one(&pool) + .await + .expect("read B fire"); + assert_eq!(linked, None); + } + /// Documents the retention-vs-interval coupling Sami flagged for §5c: /// pruning every claim below the workflow's interval makes /// `latest_scheduled_workflow_fire` return `None`, which re-introduces the @@ -2762,12 +2914,26 @@ mod postgres_tests { insert_workflow_with_ids(&pool, community_a, workflow_id, channel_id, "wf-A").await; insert_workflow_with_ids(&pool, community_b, workflow_id, Uuid::new_v4(), "wf-B").await; - let run_a = create_workflow_run(&pool, community_a, workflow_id, None, None) - .await - .expect("run A"); - let run_b = create_workflow_run(&pool, community_b, workflow_id, None, None) - .await - .expect("run B"); + let run_a = create_workflow_run( + &pool, + community_a, + workflow_id, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("run A"); + let run_b = create_workflow_run( + &pool, + community_b, + workflow_id, + None, + None, + &RunCause::Schedule, + ) + .await + .expect("run B"); let token = "shared-approval-token"; let expires = Utc::now() + chrono::Duration::hours(1); diff --git a/crates/buzz-db/src/store/workflow/deletion.rs b/crates/buzz-db/src/store/workflow/deletion.rs index 84f4b828459..cd8a5dedda7 100644 --- a/crates/buzz-db/src/store/workflow/deletion.rs +++ b/crates/buzz-db/src/store/workflow/deletion.rs @@ -90,8 +90,9 @@ async fn delete_workflow_in_transaction( owner_pubkey, Some(d_tag.as_bytes()), ); - crate::observability::observe_advisory_lock( + crate::observability::observe_event_lock( crate::observability::LockType::Replacement, + KIND_WORKFLOW_DEF as i32, sqlx::query("SELECT pg_advisory_xact_lock($1)") .bind(lock_key) .execute(tx.conn()), diff --git a/crates/buzz-db/src/store/workflow/deletion_tests.rs b/crates/buzz-db/src/store/workflow/deletion_tests.rs index 7210d2efb7f..7ddcfa3b0c5 100644 --- a/crates/buzz-db/src/store/workflow/deletion_tests.rs +++ b/crates/buzz-db/src/store/workflow/deletion_tests.rs @@ -112,9 +112,16 @@ async fn workflow_deletion_removes_both_projections_and_is_scoped_and_retryable( assert!(!unchanged.changed); assert_present(&db, &query, id).await; - let run_id = create_workflow_run(&db.pool, community, id, None, None) - .await - .expect("run"); + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); // A fired schedule links both the workflow and a cascading run. Deletion // must also remove the claim despite its NO ACTION run foreign key. sqlx::query( @@ -391,9 +398,16 @@ async fn workflow_deletion_removes_children_without_cascades() { let query = seed(&db, community, &keys, id, &d_tag, now).await; let other = Uuid::new_v4(); seed(&db, community, &keys, other, &other.to_string(), now).await; - let run_id = create_workflow_run(&db.pool, community, id, None, None) - .await - .expect("run"); + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); sqlx::query( "INSERT INTO scheduled_workflow_fires \ (community_id, workflow_id, scheduled_for, workflow_run_id) VALUES ($1, $2, NOW(), $3)", @@ -512,9 +526,16 @@ async fn workflow_deletion_waits_for_and_removes_concurrent_cross_workflow_appro seed(&db, community, &keys, id, &d_tag, now).await; let other = Uuid::new_v4(); seed(&db, community, &keys, other, &other.to_string(), now).await; - let run_id = create_workflow_run(&db.pool, community, id, None, None) - .await - .expect("run"); + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); let mut inserter = db.pool.begin().await.expect("begin approval insert"); sqlx::query( @@ -573,9 +594,16 @@ async fn workflow_deletion_waits_for_concurrent_fire_attach_without_deadlock() { let d_tag = id.to_string(); let now = Timestamp::now().as_secs(); seed(&db, community, &keys, id, &d_tag, now).await; - let run_id = create_workflow_run(&db.pool, community, id, None, None) - .await - .expect("run"); + let run_id = create_workflow_run( + &db.pool, + community, + id, + None, + None, + &crate::workflow::RunCause::Schedule, + ) + .await + .expect("run"); let scheduled_for: chrono::DateTime = sqlx::query_scalar( "INSERT INTO scheduled_workflow_fires (community_id, workflow_id, scheduled_for) \ VALUES ($1, $2, date_trunc('second', NOW())) RETURNING scheduled_for", diff --git a/crates/buzz-db/src/test_support.rs b/crates/buzz-db/src/test_support.rs index 62bb89245af..b7b80752f7d 100644 --- a/crates/buzz-db/src/test_support.rs +++ b/crates/buzz-db/src/test_support.rs @@ -8,6 +8,182 @@ pub(crate) fn database_url() -> String { .unwrap_or_else(|_| DEFAULT_DATABASE_URL.to_owned()) } +/// Exercise the operator prebuild path on a small isolated upgrade fixture. +/// Large deployments use concurrent child builds; tests own their entire database. +pub(crate) async fn prebuild_media_edit_index(pool: &sqlx::PgPool) { + let expression = crate::store::media::MEDIA_EDIT_TARGET_SQL; + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE INDEX idx_events_media_edit_target ON events(community_id,channel_id,({expression}),created_at DESC,id DESC) WHERE kind=40003 AND deleted_at IS NULL"))) + .execute(pool).await.expect("operator media index prebuild on isolated fixture"); +} + +/// A uniquely named database on the test server that is dropped when the +/// guard goes out of scope, including when the test panics. +/// +/// The drop uses `WITH (FORCE)`, which ends every session still connected, +/// so pools on the database need not be closed first. Bind the guard to a +/// named variable for the whole test: `let (pool, _) = ScratchDb::migrated(..)` +/// drops the database immediately. +pub(crate) struct ScratchDb { + name: String, + url: String, + admin_url: String, +} + +impl ScratchDb { + /// Create an empty database named `{prefix}_{uuid}` on the server + /// `admin_url` connects to. + pub(crate) async fn create(admin_url: &str, prefix: &str) -> Self { + use sqlx::Connection as _; + + let name = format!("{prefix}_{}", uuid::Uuid::new_v4().simple()); + let mut admin = sqlx::PgConnection::connect(admin_url) + .await + .expect("connect admin database"); + sqlx::query(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}"))) + .execute(&mut admin) + .await + .expect("create scratch database"); + let _ = admin.close().await; + // Swap the database path segment of the admin URL for the scratch name. + let idx = admin_url.rfind('/').expect("db url has a path segment"); + let url = format!("{}/{name}", &admin_url[..idx]); + Self { + name, + url, + admin_url: admin_url.to_owned(), + } + } + + /// [`ScratchDb::create`], then connect a pool and run every migration. + pub(crate) async fn migrated(admin_url: &str, prefix: &str) -> (sqlx::PgPool, Self) { + let scratch = Self::create(admin_url, prefix).await; + let pool = scratch.connect().await; + crate::migration::run_migrations(&pool) + .await + .expect("migrate scratch db"); + (pool, scratch) + } + + /// [`ScratchDb::create`], then connect a pool and run migrations through + /// `target`. + pub(crate) async fn migrated_through( + admin_url: &str, + prefix: &str, + target: i64, + ) -> (sqlx::PgPool, Self) { + let scratch = Self::create(admin_url, prefix).await; + let pool = scratch.connect().await; + crate::migration::run_migrations_through(&pool, target) + .await + .expect("migrate scratch db through target"); + (pool, scratch) + } + + /// A default pool on this database. + pub(crate) async fn connect(&self) -> sqlx::PgPool { + sqlx::PgPool::connect(&self.url) + .await + .expect("connect scratch db") + } + + pub(crate) fn name(&self) -> &str { + &self.name + } + + pub(crate) fn url(&self) -> &str { + &self.url + } +} + +impl Drop for ScratchDb { + fn drop(&mut self) { + drop_cluster_object( + &self.admin_url, + &format!("scratch database {}", self.name), + format!("DROP DATABASE IF EXISTS {} WITH (FORCE)", self.name), + ); + } +} + +/// A uniquely named role on the test server that is dropped when the guard +/// goes out of scope, including when the test panics. The role must not own +/// objects or hold privileges by then, or the drop fails with a warning. +pub(crate) struct ScratchRole { + name: String, + admin_url: String, +} + +impl ScratchRole { + /// Create a role named `{prefix}_{uuid}` with `options` (for example + /// `LOGIN PASSWORD '...'`) on the server `admin_url` connects to. + pub(crate) async fn create(admin_url: &str, prefix: &str, options: &str) -> Self { + use sqlx::Connection as _; + + let name = format!("{prefix}_{}", uuid::Uuid::new_v4().simple()); + let mut admin = sqlx::PgConnection::connect(admin_url) + .await + .expect("connect admin database"); + sqlx::query(sqlx::AssertSqlSafe(format!("CREATE ROLE {name} {options}"))) + .execute(&mut admin) + .await + .expect("create scratch role"); + let _ = admin.close().await; + Self { + name, + admin_url: admin_url.to_owned(), + } + } + + pub(crate) fn name(&self) -> &str { + &self.name + } +} + +impl Drop for ScratchRole { + fn drop(&mut self) { + drop_cluster_object( + &self.admin_url, + &format!("scratch role {}", self.name), + format!("DROP ROLE IF EXISTS {}", self.name), + ); + } +} + +/// Run one cleanup statement from `Drop` over a fresh admin connection. +/// +/// Drop runs on the test's runtime thread, which cannot drive the test's +/// pools while it blocks here, so the statement runs on a thread with its +/// own runtime. Failures are printed rather than raised: a panic in Drop +/// while a failing test unwinds would abort the test binary. +fn drop_cluster_object(admin_url: &str, object: &str, statement: String) { + use sqlx::Connection as _; + + let url = admin_url.to_owned(); + let cleanup = std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| error.to_string())? + .block_on(async { + let mut connection = sqlx::PgConnection::connect(&url) + .await + .map_err(|error| error.to_string())?; + let result = sqlx::query(sqlx::AssertSqlSafe(statement)) + .execute(&mut connection) + .await; + let _ = connection.close().await; + result.map(drop).map_err(|error| error.to_string()) + }) + }) + .join(); + let error = match cleanup { + Ok(Ok(())) => return, + Ok(Err(error)) => error, + Err(_) => "cleanup thread panicked".to_owned(), + }; + eprintln!("warning: failed to drop {object}: {error}"); +} + /// One-session fixture that bypasses ordinary write-fence triggers while /// retaining application admission. Communities are active, quiescing, fenced. pub(crate) async fn admission_fixture() -> (crate::Db, [buzz_core::CommunityId; 3]) { @@ -103,8 +279,8 @@ where .await .expect("connect deletion executor pool"); let mut tx = pool.begin().await.expect("begin deletion executor"); - sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community.as_uuid()) + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(crate::deletion::community_deletion_lock_key(community)) .execute(&mut *tx) .await .expect("hold exclusive deletion lock"); @@ -142,6 +318,87 @@ where result.unwrap().expect("sweep task") } +/// Seed historical read fixtures through raw SQL on an unarmed test pool. +/// Supported serving APIs reject these old timestamps; this represents data +/// already in storage, while retaining admission, mentions and event follow-ups. +#[cfg(test)] // Keep raw fixture SQL visibly test-only to the source-policy scan. +pub(crate) async fn insert_historical_event( + pool: &sqlx::PgPool, + community: buzz_core::CommunityId, + event: &nostr::Event, + channel: uuid::Uuid, +) { + let mut tx = crate::begin_community_write_transaction( + pool, + community, + crate::observability::WriterOperation::EventWrite, + ) + .await + .expect("admit historical fixture"); + sqlx::query( + "INSERT INTO events (community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id,d_tag) \ + VALUES ($1,$2,$3,to_timestamp($4),$5,$6,$7,$8,$9,$10)", + ) + .bind(community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .bind(event.pubkey.to_bytes().as_slice()) + .bind(event.created_at.as_secs() as f64) + .bind(i32::from(event.kind.as_u16())) + .bind(serde_json::to_value(&event.tags).expect("fixture tags")) + .bind(&event.content) + .bind(event.sig.serialize().as_slice()) + .bind(channel) + .bind(crate::event::extract_d_tag(event)) + .execute(tx.conn()) + .await + .expect("insert historical fixture"); + let created_at = chrono::DateTime::from_timestamp(event.created_at.as_secs() as i64, 0) + .expect("fixture created_at"); + crate::store::event_follow_up::after_admitted_insert( + &mut tx, + event.id.as_bytes(), + created_at, + i32::from(event.kind.as_u16()), + Some(channel), + ) + .await + .expect("fixture follow-ups"); + crate::insert_mentions_in_transaction(&mut tx, event, Some(channel)) + .await + .expect("fixture mentions"); + tx.commit().await.expect("commit historical fixture"); +} + +/// [`insert_historical_event`] plus the thread metadata the serving writer +/// records for it, through the same `insert_thread_metadata` store function +/// (parent and root stubs, reply and descendant counters). For aged rows whose +/// thread state a test reads or deletes through the production paths. +#[cfg(test)] +pub(crate) async fn insert_historical_event_with_thread_metadata( + pool: &sqlx::PgPool, + community: buzz_core::CommunityId, + event: &nostr::Event, + channel: uuid::Uuid, + meta: crate::event::ThreadMetadataParams<'_>, +) { + insert_historical_event(pool, community, event, channel).await; + crate::thread::insert_thread_metadata( + pool, + community, + meta.event_id, + meta.event_created_at, + meta.channel_id, + meta.parent_event_id, + meta.parent_event_created_at, + meta.root_event_id, + meta.root_event_created_at, + meta.depth, + meta.broadcast, + ) + .await + .expect("fixture thread metadata"); +} + /// Move a community fixture into a deletion lifecycle state the way the /// executor does: the tombstone trigger only accepts lifecycle changes from a /// transaction carrying the executor GUCs for that community, including its @@ -291,6 +548,22 @@ pub(crate) async fn named_pool(application_name: &str) -> sqlx::PgPool { .expect("connect named test pool") } +/// Prebuild `idx_channels_listed_name` concurrently, as an operator of a +/// deployment that migrates out of band does before migration 0083 +/// (docs/channel-name-uniqueness-deployment.md). Run it with no open +/// transaction in the database: the build waits for every one. +pub(crate) async fn prebuild_listed_channel_name_index(pool: &sqlx::PgPool) { + sqlx::query( + "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_channels_listed_name \ + ON channels (community_id, lower(name)) \ + WHERE visibility = 'open' AND NOT unlisted \ + AND channel_type IN ('stream', 'forum') AND deleted_at IS NULL", + ) + .execute(pool) + .await + .expect("prebuild idx_channels_listed_name"); +} + /// Wait until the session named `application_name` in this test's database is /// blocked on a lock. pub(crate) async fn wait_for_lock_wait(pool: &sqlx::PgPool, application_name: &str) { @@ -323,10 +596,13 @@ pub(crate) async fn wait_for_lock_wait(pool: &sqlx::PgPool, application_name: &s /// [`PausingProxy::stall_established`] instead holds only the sessions open /// at that moment, for good, while later sessions relay normally: a failover /// whose old sockets stop answering without closing. +/// [`PausingProxy::stall_from`] is the reverse: sessions from a given number +/// on hold for good, so dials past that point stall mid-handshake. pub(crate) struct PausingProxy { pub(crate) port: u16, hold: tokio::sync::watch::Sender, next_session: std::sync::Arc, + held_sessions: tokio::sync::watch::Sender>, } /// Which proxy sessions hold their bytes. @@ -335,11 +611,13 @@ struct ProxyHold { all: bool, /// Sessions numbered below this hold their bytes. below: u64, + /// Sessions numbered at or above this hold their bytes. + from: Option, } impl ProxyHold { fn holds(self, session: u64) -> bool { - self.all || session < self.below + self.all || session < self.below || self.from.is_some_and(|from| session >= from) } } @@ -353,6 +631,7 @@ impl PausingProxy { mut to: tokio::net::tcp::OwnedWriteHalf, mut hold: tokio::sync::watch::Receiver, session: u64, + held_sessions: tokio::sync::watch::Sender>, ) { let mut buf = [0u8; 8192]; loop { @@ -362,6 +641,9 @@ impl PausingProxy { if n == 0 { return; } + if hold.borrow().holds(session) { + held_sessions.send_if_modified(|sessions| sessions.insert(session)); + } if hold.wait_for(|hold| !hold.holds(session)).await.is_err() { return; } @@ -379,6 +661,8 @@ impl PausingProxy { let accept_hold = hold.subscribe(); let next_session = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); let accept_next = next_session.clone(); + let (held_sessions, _) = tokio::sync::watch::channel(Default::default()); + let accept_held_sessions = held_sessions.clone(); tokio::spawn(async move { while let Ok((client, _)) = listener.accept().await { let session = accept_next.fetch_add(1, Ordering::SeqCst); @@ -394,12 +678,14 @@ impl PausingProxy { server_write, accept_hold.clone(), session, + accept_held_sessions.clone(), )); tokio::spawn(pump( server_read, client_write, accept_hold.clone(), session, + accept_held_sessions.clone(), )); } }); @@ -407,9 +693,28 @@ impl PausingProxy { port, hold, next_session, + held_sessions, } } + /// Resume all previously stalled test-proxy sessions. + pub(crate) fn resume_all(&self) { + self.hold.send_replace(ProxyHold::default()); + } + + /// Wait until traffic from at least `count` distinct sessions has hit a hold. + pub(crate) async fn wait_for_held_sessions(&self, count: usize) { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + self.held_sessions + .subscribe() + .wait_for(|sessions| sessions.len() >= count) + .await + .expect("proxy observations remain open"); + }) + .await + .expect("database traffic reached the proxy hold"); + } + pub(crate) fn set_paused(&self, paused: bool) { self.hold.send_modify(|hold| hold.all = paused); } @@ -419,4 +724,18 @@ impl PausingProxy { let below = self.next_session.load(std::sync::atomic::Ordering::SeqCst); self.hold.send_modify(|hold| hold.below = below); } + + /// Relay the first `from` sessions normally and hold every later one, + /// for good. + pub(crate) fn stall_from(&self, from: u64) { + self.hold.send_modify(|hold| hold.from = Some(from)); + } + + /// Sessions accepted so far. + pub(crate) fn sessions(&self) -> u64 { + self.next_session.load(std::sync::atomic::Ordering::SeqCst) + } } + +mod recent_pass_tests; +pub(crate) use recent_pass_tests::replace_between_passes; diff --git a/crates/buzz-db/src/test_support/recent_pass_tests.rs b/crates/buzz-db/src/test_support/recent_pass_tests.rs new file mode 100644 index 00000000000..2654d2bceec --- /dev/null +++ b/crates/buzz-db/src/test_support/recent_pass_tests.rs @@ -0,0 +1,135 @@ +//! The recent-pass snapshot fixture. It writes `events` partitions directly, +//! so it lives in a standalone test module. + +/// Commit a row replacement while a read split at the recent-pass floor (see +/// `recent_pass`) is between its passes. +/// +/// Seeds `channel` with two kind:9 rows above the floor, `old` below it, +/// `ancient` in the partition before every dated monthly, and `new`: dated +/// now, soft-deleted until the replacement. Another session locks the +/// ancient partition, which only the older pass plans, so `read` stops +/// between its passes. The replacement then commits in one transaction, as +/// every replacement does: it deletes `old` and makes `new` live. The lock is +/// released and `read` finishes. +/// +/// Returns `read`'s result and the page its first pass's snapshot holds: +/// `[recent, recent, old, ancient]`. +pub(crate) async fn replace_between_passes( + pool: &sqlx::PgPool, + community: buzz_core::CommunityId, + channel: uuid::Uuid, + read: F, +) -> (T, Vec) +where + F: FnOnce(sqlx::pool::PoolConnection) -> Fut, + Fut: std::future::Future + Send + 'static, + T: Send + 'static, +{ + use nostr::{EventBuilder, Keys, Kind, Timestamp}; + + let author = Keys::generate(); + let now = chrono::Utc::now(); + let floor = crate::store::recent_pass::floor_at(now).timestamp() as u64; + let now = now.timestamp() as u64; + let insert = |at: u64, label: &str| { + let event = EventBuilder::new(Kind::Custom(9), format!("{label} at {at}")) + .custom_created_at(Timestamp::from(at)) + .sign_with_keys(&author) + .expect("sign"); + async move { + // Seeded as stored rows: the serving writers reject the aged ones. + crate::test_support::insert_historical_event(pool, community, &event, channel).await; + event.id + } + }; + let snapshot_page = vec![ + insert(now - 10, "recent").await, + insert(now - 20, "recent").await, + insert(floor - 86_400, "old").await, + insert(1_748_736_000, "ancient").await, // 2025-06-01 + ]; + let new = insert(now - 5, "new").await; + let partition_of = |id: nostr::EventId| async move { + sqlx::query_scalar::<_, String>("SELECT tableoid::regclass::text FROM events WHERE id = $1") + .bind(id.as_bytes().to_vec()) + .fetch_one(pool) + .await + .expect("partition") + }; + let old = snapshot_page[2]; + let (old_partition, ancient_partition, new_partition) = ( + partition_of(old).await, + partition_of(snapshot_page[3]).await, + partition_of(new).await, + ); + assert_ne!( + old_partition, ancient_partition, + "the replacement must not wait on the lock" + ); + assert_ne!( + new_partition, ancient_partition, + "the replacement must not wait on the lock" + ); + sqlx::query("UPDATE events SET deleted_at = now() WHERE id = $1") + .bind(new.as_bytes().to_vec()) + .execute(pool) + .await + .expect("hide the replacement"); + + let mut locker = pool.begin().await.expect("begin locker"); + sqlx::query(sqlx::AssertSqlSafe(format!( + "LOCK TABLE {ancient_partition} IN ACCESS EXCLUSIVE MODE" + ))) + .execute(&mut *locker) + .await + .expect("lock the ancient partition"); + let conn = pool.acquire().await.expect("acquire reader"); + let mut task = tokio::spawn(read(conn)); + let waiting = tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + let blocked: bool = sqlx::query_scalar( + // `pg_locks` spans every database, and the per-test databases + // are clones that share relation OIDs: match this one only. + "SELECT EXISTS(SELECT 1 FROM pg_locks WHERE relation = $1::text::regclass \ + AND NOT granted \ + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()))", + ) + .bind(&ancient_partition) + .fetch_one(&mut *locker) + .await + .expect("inspect the older pass"); + if blocked { + break; + } + tokio::task::yield_now().await; + } + }) + .await; + if waiting.is_err() { + task.abort(); + panic!("the read never reached its older pass"); + } + + let mut replace = pool.begin().await.expect("begin replacement"); + for (partition, deleted_at, id) in [ + (&old_partition, "now()", old), + (&new_partition, "NULL", new), + ] { + sqlx::query(sqlx::AssertSqlSafe(format!( + "UPDATE {partition} SET deleted_at = {deleted_at} WHERE id = $1" + ))) + .bind(id.as_bytes().to_vec()) + .execute(&mut *replace) + .await + .expect("replace"); + } + replace.commit().await.expect("commit replacement"); + locker.rollback().await.expect("release the lock"); + + let result = tokio::time::timeout(std::time::Duration::from_secs(10), &mut task).await; + if result.is_err() { + task.abort(); + panic!("the read did not finish after the lock was released"); + } + (result.unwrap().expect("read task"), snapshot_page) +} diff --git a/crates/buzz-db/tests/observability_source.rs b/crates/buzz-db/tests/observability_source.rs index b1c95d7f1c7..022291b8ab7 100644 --- a/crates/buzz-db/tests/observability_source.rs +++ b/crates/buzz-db/tests/observability_source.rs @@ -8,7 +8,6 @@ fn database_metrics_and_slow_logs_exclude_sensitive_or_unbounded_fields() { "\"community\" =>", "\"event_id\" =>", "\"event_kind\" =>", - "\"kind\" =>", "\"sql\" =>", "\"query\" =>", "\"query_id\" =>", @@ -28,6 +27,35 @@ fn database_metrics_and_slow_logs_exclude_sensitive_or_unbounded_fields() { ); } + // Only the advisory-lock observer carries `kind`, bounded by the kind + // registry so client-chosen kinds collapse to one fallback value. Every + // other database metric and slow warning stays kind-free. + let (before_lock_observer, lock_observer) = implementation + .split_once("async fn observe_lock<") + .expect("advisory locks must record through one observer"); + let (lock_observer, after_lock_observer) = lock_observer + .split_once("\n}\n") + .expect("the advisory-lock observer must end"); + assert_eq!( + lock_observer.matches("\"kind\" =>").count(), + 2, + "both advisory-lock metrics must carry kind" + ); + let event_lock_observer = before_lock_observer + .split_once("pub(crate) async fn observe_event_lock<") + .expect("event-keyed locks must have one observer") + .1; + assert!( + event_lock_observer.contains("buzz_core::kind::registered_kind_label(kind)"), + "the kind label must come from the kind registry" + ); + for outside in [before_lock_observer, after_lock_observer, datastore_macro] { + assert!( + !outside.contains("\"kind\" =>"), + "only advisory-lock metrics may carry kind" + ); + } + assert!(datastore_macro.contains("name: LitStr")); assert!(datastore_macro.contains("\"operation\" => #name")); assert!(datastore_macro.contains("elapsed_ms =")); @@ -264,7 +292,9 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { .expect("channel lookup helper must precede canvas reads") .0; assert!(get_channel.contains("acquire_writer(pool, operation)")); - assert!(get_channel.contains("fetch_optional(&mut *connection)")); + assert!(get_channel.contains("select_channel(&mut connection, community_id, channel_id)")); + assert!(get_channel.contains("conn: &mut sqlx::PgConnection")); + assert!(get_channel.contains("fetch_optional(conn)")); assert!(!get_channel.contains("fetch_optional(pool)")); assert!(channel.contains("pub async fn get_channel_for_event_write(")); let list_channels = channel @@ -409,7 +439,6 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { .0; assert!(thread_summary.contains("WriterOperation::EventWrite")); assert!(thread_summary.contains("fetch_optional(&mut *connection)")); - assert!(thread_summary.contains("fetch_all(&mut *connection)")); assert!(!thread_summary.contains("fetch_optional(pool)")); assert!(!thread_summary.contains("fetch_all(pool)")); @@ -453,42 +482,27 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { .next() .expect("replica-fence production source"); assert!(replica_fence_production.contains("WriterOperation::Bootstrap")); - assert!(replica_fence_production.contains("WriterOperation::Maintenance")); + // The heartbeat probe runs on its own pool, never a serving writer + // checkout: queued behind request traffic, its beat goes stale exactly + // when the writer is saturated. + assert!(!replica_fence_production.contains("WriterOperation::Maintenance")); + assert!(replica_fence_production.contains("pub fn connect_probe_pool(")); + assert!(runtime.contains("replica_fence::connect_probe_pool(&self.pool)")); assert!(!replica_fence_production.contains("pool.begin().await")); assert!(!replica_fence_production.contains("writer.acquire().await")); assert!(!replica_fence_production.contains("fetch_optional(writer)")); - let usage = include_str!("../src/store/usage.rs"); - let usage_production = usage + let leader_lock = include_str!("../src/store/leader_lock.rs"); + let leader_lock_production = leader_lock .split("\n#[cfg(test)]") .next() - .expect("usage production source"); - let usage_leader_lock = usage_production + .expect("leader-lock production source"); + let leader_lock_acquisition = leader_lock_production .split_once("pub async fn try_lock_session_leader(") - .expect("usage store must expose the legacy leader-lock acquisition") - .1 - .split_once("pub async fn usage_community_count(") - .expect("usage leader lock must precede counter reads") - .0; - assert!(usage_leader_lock.contains("acquire_writer_with_legacy_metrics(")); - assert!( - usage_production - .matches("WriterOperation::Maintenance") - .count() - >= 11, - "every periodic usage checkout must be maintenance-attributed" - ); - for bypass in [ - ".fetch_one(pool)", - ".fetch_all(pool)", - ".fetch_optional(pool)", - ".execute(pool)", - ] { - assert!( - !usage_production.contains(bypass), - "usage production path bypasses operation attribution with {bypass}" - ); - } + .expect("leader-lock store must expose the legacy leader-lock acquisition") + .1; + assert!(leader_lock_acquisition.contains("acquire_writer_with_legacy_metrics(")); + assert!(leader_lock_acquisition.contains("WriterOperation::Maintenance")); let channel_reaper = channel .split_once("pub async fn reap_expired_ephemeral_channels(pool:") @@ -595,6 +609,10 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { ), ("archived_identities", archived_identities), ("event", event), + ( + "event_hydration", + include_str!("../src/store/event_hydration.rs"), + ), ("git_repo", include_str!("../src/store/git_repo.rs")), ("push", include_str!("../src/store/push.rs")), ("replica_fence", replica_fence), @@ -609,7 +627,7 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { "relay_operators", include_str!("../src/store/relay_operators.rs"), ), - ("usage", usage), + ("leader_lock", leader_lock), ] { let production = source.split("\n#[cfg(test)]").next().unwrap_or(source); for bypass in [ @@ -884,10 +902,7 @@ fn has_any_tenant_local_chokepoint(source: &str) -> bool { const ADMITTED_TX_SIGNATURE_MARKERS: [&str; 2] = ["&mut AdmittedTx", "&mut crate::AdmittedTx"]; // Narrow reviewed exceptions for non-serving verification probes only. -const GUARDED_WRITE_FUNCTION_EXCEPTIONS: [&str; 2] = [ - "pub async fn verify_floor_guard_behavior(", - "pub async fn verify_channel_roster_fence_behavior(", -]; +const GUARDED_WRITE_FUNCTION_EXCEPTIONS: [&str; 1] = ["pub async fn verify_floor_guard_behavior("]; const GUARDED_TX_ADAPTER_METHOD_PINS: [(&str, &str); 1] = [( "pub async fn replace_member_event(", @@ -1390,10 +1405,7 @@ fn serving_table_writes_expose_syntactic_chokepoint_or_guarded_tx_routes() { // Rolled-back verification probes write `events` rows that never commit, so // they owe no push job or TTL refresh. -const EVENT_INSERT_FOLLOW_UP_EXCEPTIONS: [&str; 2] = [ - "pub async fn verify_floor_guard_behavior(", - "pub async fn verify_channel_roster_fence_behavior(", -]; +const EVENT_INSERT_FOLLOW_UP_EXCEPTIONS: [&str; 1] = ["pub async fn verify_floor_guard_behavior("]; /// `source` with every `#[cfg(test)]` item removed, wherever it sits in the /// file. Each item runs to the `;` that ends it or to the brace that closes @@ -1602,12 +1614,20 @@ fn inserts_events_row(source: &str) -> bool { !events_insert_tails(source).is_empty() } -/// `source` lowercased, with every run of whitespace, `\` line continuations, -/// and `\n`/`\t`/`\r` escapes collapsed to one space. +/// `source` lowercased, with identifier quotes removed and every run of +/// whitespace, `\` line continuations, and `\n`/`\t`/`\r` escapes collapsed +/// to one space. fn normalized_sql(source: &str) -> String { let mut normalized = String::with_capacity(source.len()); let mut chars = source.chars().peekable(); while let Some(ch) = chars.next() { + if ch == '"' { + continue; + } + if ch == '\\' && chars.peek() == Some(&'"') { + chars.next(); + continue; + } if ch.is_whitespace() || ch == '\\' { if ch == '\\' && matches!(chars.peek(), Some('n' | 't' | 'r')) { chars.next(); @@ -1677,6 +1697,9 @@ pub(crate) async fn unhooked_writer(tx: &mut AdmittedTx) { .await .expect("write"); } +pub(crate) async fn quoted_writer(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO \"public\".\"events\" (id) VALUES ($1)"); +} pub(crate) async fn push_only_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events \ (community_id, id) VALUES ($1, $2)") @@ -1692,7 +1715,7 @@ pub(crate) async fn hooked_writer(tx: &mut AdmittedTx) { .execute(tx.conn()) .await .expect("write"); - crate::store::event_follow_up::after_admitted_insert(tx, id, kind, channel) + crate::store::event_follow_up::after_admitted_insert(tx, id, created_at, kind, channel) .await .expect("follow up"); } @@ -1757,7 +1780,7 @@ pub(crate) async fn writer_with_commented_out_hook(tx: &mut AdmittedTx) { .execute(tx.conn()) .await .expect("write"); - // crate::store::event_follow_up::after_admitted_insert(tx, id, kind, channel) + // crate::store::event_follow_up::after_admitted_insert(tx, id, created_at, kind, channel) } pub(crate) async fn writer_with_block_commented_hook(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") @@ -1779,7 +1802,7 @@ pub(crate) async fn writer_with_nested_block_commented_hook(tx: &mut AdmittedTx) .execute(tx.conn()) .await .expect("write"); - /* /* inner */ crate::store::event_follow_up::after_admitted_insert(tx, id, kind, channel) */ + /* /* inner */ crate::store::event_follow_up::after_admitted_insert(tx, id, created_at, kind, channel) */ } pub(crate) async fn writer_with_hook_after_escaped_quote(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") @@ -1807,7 +1830,7 @@ pub(crate) async fn writer_after_block_commented_cfg_test(tx: &mut AdmittedTx) { pub(crate) async fn writer_after_raw_string_example(tx: &mut AdmittedTx) { let _example = r#" fn example() { - crate::store::event_follow_up::after_admitted_insert(tx, id, kind, channel) + crate::store::event_follow_up::after_admitted_insert(tx, id, created_at, kind, channel) } "#; sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") @@ -1841,6 +1864,7 @@ mod tests { event_insert_follow_up_violations(&strip_cfg_test_items(source)), [ "pub(crate) async fn unhooked_writer(tx: &mut AdmittedTx) {", + "pub(crate) async fn quoted_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn push_only_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn lowercase_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn continued_writer(tx: &mut AdmittedTx) {", @@ -1925,19 +1949,70 @@ fn every_production_event_insert_runs_the_follow_up_hook() { ); } -// Fixed channel-less kinds cannot be channel rosters. The startup probes must -// exercise the retained DB backstops directly and roll back all their writes. +// Explicit inventory complements the generic insert scanner: every direct +// production hook must forward the same created_at local bound by its INSERT. +#[test] +fn event_insert_hook_inventory_carries_the_insert_timestamp() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/store"); + let mut actual = Vec::new(); + for file in [ + "event.rs", + "replaceable.rs", + "channel_members.rs", + "relay_members.rs", + "push.rs", + ] { + let source = std::fs::read_to_string(root.join(file)).expect("read writer"); + let production = strip_cfg_test_items(&source); + for function in function_slices(&production) { + let code = mask_comments_and_literals(function); + let Some((_, arguments)) = code.split_once("event_follow_up::after_admitted_insert(") + else { + continue; + }; + let compact: String = arguments.chars().filter(|c| !c.is_whitespace()).collect(); + assert!( + compact.starts_with("tx,id_bytes.as_slice(),created_at,") + || compact.starts_with("tx,incoming_id,created_at,") + || compact.starts_with("&muttx,event.id.as_bytes().as_slice(),created_at,") + || compact + .starts_with("&mutself.tx,event.id.as_bytes().as_slice(),created_at,") + || compact.starts_with("tx,event.id.as_bytes().as_slice(),created_at,"), + "{file}: {} must pass the INSERT's signed created_at", + function_header(function) + ); + assert!( + code.contains(".bind(created_at)"), + "{file}: timestamp must match INSERT bind" + ); + actual.push(format!("{file}: {}", function_header(function))); + } + } + actual.sort(); + let mut expected = [ + "event.rs: async fn insert_event_on(", + "event.rs: pub(crate) async fn insert_event_with_thread_metadata_tx(", + "replaceable.rs: async fn replace_parameterized_event_in_transaction_impl(", + "replaceable.rs: pub(crate) async fn replace_addressable_event_under_lock(", + "channel_members.rs: pub async fn replace_member_event(", + "relay_members.rs: pub(crate) async fn write_nip43_membership_snapshot(", + "push.rs: pub async fn accept_lease_event(", + ]; + expected.sort(); + assert_eq!(actual, expected); +} + +// Fixed channel-less kinds cannot be channel rosters, and the replica-floor +// startup probe rolls back all its writes. // Exemptions match by function header, so a kind 39002 insert added inside one // of these functions would pass the policy; keep them single-purpose. -const EVENT_INSERT_ROSTER_GUARD_EXCEPTIONS: [&str; 4] = [ +const EVENT_INSERT_ROSTER_GUARD_EXCEPTIONS: [&str; 3] = [ // NIP-43 membership is kind 13534 with channel_id NULL. "pub(crate) async fn write_nip43_membership_snapshot(", // Push leases are kind 30350 with channel_id NULL. "pub async fn accept_lease_event(", // Rolled-back replica-floor startup probe. "pub async fn verify_floor_guard_behavior(", - // Rolled-back roster-fence startup probe. - "pub async fn verify_channel_roster_fence_behavior(", ]; fn event_insert_roster_guard_violations(production_source: &str) -> Vec { @@ -1992,9 +2067,6 @@ pub async fn accept_lease_event(tx: &mut AdmittedTx) { pub async fn verify_floor_guard_behavior(pool: &PgPool) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } -pub async fn verify_channel_roster_fence_behavior(pool: &PgPool) { - sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); -} #[cfg(test)] mod tests { fn fixture() { @@ -2038,10 +2110,10 @@ fn every_production_event_insert_runs_the_roster_guard() { violations.is_empty(), "production `INSERT INTO events` writers must run the app-side roster guard: {violations:?}" ); - // Five guarded writers plus the four explicitly exempt writers/probes. + // Five guarded writers plus the three explicitly exempt writers/probes. assert!( - checked_writers >= 9, - "expected at least nine event writers, found {checked_writers}" + checked_writers >= 8, + "expected at least eight event writers, found {checked_writers}" ); } @@ -2161,7 +2233,388 @@ fn every_production_event_insert_names_d_tag() { // The same writer set as the roster-guard scan. A lower count means the // scan stopped seeing a writer, not that one was removed safely. assert!( - checked_writers >= 9, - "expected at least nine event writers, found {checked_writers}" + checked_writers >= 8, + "expected at least eight event writers, found {checked_writers}" ); } + +/// Search-hit hydration must keep each hit's exact `created_at`: the paired +/// `(id, created_at)` key is what lets PostgreSQL prune `events` partitions. +/// This supplements the real PostgreSQL seam tests in `event_hydration`. +#[test] +fn every_search_hydrator_preserves_the_exact_hit_timestamp() { + for (source, path) in [ + ( + include_str!("../../buzz-relay/src/handlers/req.rs"), + "req_search_hydrate", + ), + ( + include_str!("../../buzz-relay/src/api/bridge.rs"), + "bridge_search_hydrate", + ), + ( + include_str!("../../buzz-relay/src/api/profiles.rs"), + "profile_search_hydrate", + ), + ] { + let compact: String = source.chars().filter(|c| !c.is_whitespace()).collect(); + assert!( + compact.contains(&format!(".get_events_by_ids_at_routed(\"{path}\"")), + "{path}: must use exact-key hydration" + ); + assert!( + source.contains("(h.event_id, h.created_at)") + || source.contains("(hit.event_id, hit.created_at)"), + "{path}: retain timestamp" + ); + } +} + +// These startup probes always roll back; they deliberately exercise the DB +// backstops rather than the app check. The two serving writers are exempt only +// while their INSERT remains structurally channel-NULL (checked below). +const EVENT_FLOOR_PROBE_EXCEPTIONS: [&str; 2] = [ + "pub async fn verify_floor_guard_behavior(", + "pub async fn verify_channel_roster_fence_behavior(", +]; + +fn is_channel_null_event_writer(function: &str) -> bool { + let header = function_header(function); + let sql = normalized_sql(function).replace(' ', ""); + if header.starts_with("pub(crate) async fn write_nip43_membership_snapshot(") { + // Kind 13534: channel_id is the tenth value, a literal NULL. + return sql.contains("values($1,$2,$3,$4,$5,$6,$7,$8,$9,null,$10)"); + } + if header.starts_with("pub async fn accept_lease_event(") { + // Kind 30350: channel_id is the literal NULL after received_at. + return sql.contains("now(),null,$8)"); + } + false +} + +fn updates_event_floor_columns(function: &str) -> bool { + let normalized = normalized_sql(function); + normalized.match_indices("update ").any(|(index, marker)| { + let Some((target, assignments)) = normalized[index + marker.len()..].split_once(" set ") + else { + return false; + }; + let mut target = target.split_whitespace(); + let mut table = target.next(); + if table == Some("only") { + table = target.next(); + } + if !matches!(table, Some("events" | "public.events")) { + return false; + } + // The target may have an alias, with or without AS. + let alias = target.collect::>(); + if !matches!(alias.as_slice(), [] | [_] | ["as", _]) { + return false; + } + let assignments = assignments.split(" where ").next().expect("first part"); + let mut depth = 0usize; + assignments + .split(|ch| { + match ch { + '(' => depth += 1, + ')' => depth = depth.saturating_sub(1), + _ => {} + } + ch == ',' && depth == 0 + }) + .any(|assignment| { + assignment.split_once('=').is_some_and(|(columns, _)| { + columns + .trim() + .trim_start_matches('(') + .trim_end_matches(')') + .split(',') + .any(|column| matches!(column.trim(), "created_at" | "channel_id")) + }) + }) + }) +} + +fn event_floor_policy_violations(production: &str) -> Vec { + function_slices(production) + .into_iter() + .filter(|function| { + let header = function_header(function); + if EVENT_FLOOR_PROBE_EXCEPTIONS + .iter() + .any(|exception| header.starts_with(exception)) + { + return false; + } + updates_event_floor_columns(function) + || (inserts_events_row(function) + && !is_channel_null_event_writer(function) + && !mask_comments_and_literals(function) + .contains("replica_fence::guard_event_created_at_floor(")) + }) + .map(|function| function_header(function).to_owned()) + .collect() +} + +#[test] +fn event_floor_policy_rejects_unguarded_inserts_and_floor_column_updates() { + let source = r#" +async fn missing_guard(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO events (id) VALUES ($1)"); + // replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; +} +async fn guarded(tx: &mut AdmittedTx) { + crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; + sqlx::query("INSERT INTO public.events (id) VALUES ($1)"); +} +async fn rewrite_time(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET tags = $1, created_at = $2 WHERE id = $3"); +} +async fn attach_channel(tx: &mut AdmittedTx) { + sqlx::query("uPdAtE public.events\nSET channel_id=$1 WHERE id=$2"); +} +async fn alias_time(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events e SET created_at = $1 WHERE e.id = $2"); +} +async fn as_alias_time(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events AS e SET created_at = $1 WHERE e.id = $2"); +} +async fn only_channel(tx: &mut AdmittedTx) { + sqlx::query("UPDATE ONLY events SET channel_id = $1 WHERE id = $2"); +} +async fn only_public_alias(tx: &mut AdmittedTx) { + sqlx::query("UPDATE ONLY public.events AS e SET channel_id = $1 WHERE e.id = $2"); +} +async fn row_time(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET (created_at, kind) = ($1, 1) WHERE id = $2"); +} +async fn row_channel(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET (kind, channel_id) = (1, $1) WHERE id = $2"); +} +async fn quoted_insert(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO \"events\" (id) VALUES ($1)"); +} +async fn quoted_schema_insert(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO \"public\".\"events\" (id) VALUES ($1)"); +} +async fn quoted_update(tx: &mut AdmittedTx) { + sqlx::query("UPDATE \"events\" SET created_at = $1 WHERE id = $2"); +} +async fn quoted_schema_update(tx: &mut AdmittedTx) { + sqlx::query("UPDATE \"public\".\"events\" SET channel_id = $1 WHERE id = $2"); +} +async fn delete_only(tx: &mut AdmittedTx) { + sqlx::query("UPDATE events SET deleted_at=now() WHERE channel_id=$1 AND created_at<$2"); +} +"#; + assert_eq!( + event_floor_policy_violations(source), + [ + "async fn missing_guard(tx: &mut AdmittedTx) {", + "async fn rewrite_time(tx: &mut AdmittedTx) {", + "async fn attach_channel(tx: &mut AdmittedTx) {", + "async fn alias_time(tx: &mut AdmittedTx) {", + "async fn as_alias_time(tx: &mut AdmittedTx) {", + "async fn only_channel(tx: &mut AdmittedTx) {", + "async fn only_public_alias(tx: &mut AdmittedTx) {", + "async fn row_time(tx: &mut AdmittedTx) {", + "async fn row_channel(tx: &mut AdmittedTx) {", + "async fn quoted_insert(tx: &mut AdmittedTx) {", + "async fn quoted_schema_insert(tx: &mut AdmittedTx) {", + "async fn quoted_update(tx: &mut AdmittedTx) {", + "async fn quoted_schema_update(tx: &mut AdmittedTx) {", + ] + ); +} + +#[test] +fn event_floor_policy_requires_nip43_channel_null_at_its_insert_position() { + let literal_null = r#" +pub(crate) async fn write_nip43_membership_snapshot(tx: &mut AdmittedTx) { + sqlx::query("INSERT INTO events (community_id,id,pubkey,kind,content,tags,sig,created_at,received_at,channel_id,d_tag) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,NULL,$10)"); +} +"#; + assert!(event_floor_policy_violations(literal_null).is_empty()); + let unrelated_null_bind = literal_null.replace("$9,NULL,$10", "$9,$10,$11").replace( + "sqlx::query(", + "let unrelated = query.bind::>(None); sqlx::query(", + ); + assert_eq!( + event_floor_policy_violations(&unrelated_null_bind).len(), + 1, + "an unrelated NULL bind must not exempt a channel-bearing INSERT" + ); +} + +#[test] +fn every_production_channel_event_insert_checks_the_floor_and_never_rewrites_it() { + let files = production_event_writer_source_files(); + let crates_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("crates root"); + assert!( + files.contains(&crates_root.join("buzz-relay/src/state.rs")), + "floor policy must scan the workspace, including relay writers" + ); + let mut guarded_writers = 0; + let mut violations = Vec::new(); + for path in files { + let production = strip_cfg_test_items(&std::fs::read_to_string(&path).expect("source")); + guarded_writers += function_slices(&production) + .into_iter() + .filter(|function| { + inserts_events_row(function) + && mask_comments_and_literals(function) + .contains("replica_fence::guard_event_created_at_floor(") + }) + .count(); + violations.extend( + event_floor_policy_violations(&production) + .into_iter() + .map(|header| format!("{}: {header}", path.display())), + ); + } + assert!( + violations.is_empty(), + "event floor policy violations: {violations:?}" + ); + assert!( + guarded_writers >= 5, + "expected five channel-bearing event writers, found {guarded_writers}" + ); +} + +#[test] +fn event_floor_guard_uses_the_database_statement_clock_and_shared_floor() { + let source = strip_cfg_test_items(include_str!("../src/runtime/replica_fence.rs")); + let guard = function_slices(&source) + .into_iter() + .find(|function| function_header(function).contains("fn guard_event_created_at_floor(")) + .expect("app floor guard"); + assert!( + guard.contains("SELECT $1::timestamptz < clock_timestamp()"), + "the guard must sample the database statement clock, after BEGIN" + ); + assert!( + guard.contains(".bind(CREATED_AT_FLOOR_SECS as f64)"), + "app check, GUC and fence wall must share the same floor constant" + ); +} + +#[cfg(unix)] +#[test] +fn admin_seed_refuses_remote_database_before_invoking_psql() { + use std::os::unix::fs::PermissionsExt; + let root = std::env::temp_dir().join(format!("buzz-seed-policy-{}", uuid::Uuid::new_v4())); + let scripts = root.join("scripts"); + std::fs::create_dir_all(&scripts).expect("scratch scripts directory"); + let script = scripts.join("seed-admin-dashboard.sh"); + std::fs::write( + &script, + include_str!("../../../scripts/seed-admin-dashboard.sh"), + ) + .expect("copy script without developer .env"); + let psql = root.join("psql"); + std::fs::write( + &psql, + "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$SEED_PSQL_WITNESS\"\nexit 1\n", + ) + .expect("stub psql"); + std::fs::set_permissions(&psql, std::fs::Permissions::from_mode(0o755)) + .expect("executable stub"); + let witness = root.join("psql-was-invoked"); + let run = |host: &str, address: &str, service: &str, database: &str| { + let output = std::process::Command::new("/bin/bash") + .arg(&script) + .env("PGHOST", host) + .env("PGHOSTADDR", address) + .env("PGSERVICE", service) + .env("PGDATABASE", database) + .env("PATH", format!("{}:/usr/bin:/bin", root.display())) + .env("SEED_PSQL_WITNESS", &witness) + .output() + .expect("run local seed guard"); + let args = std::fs::read_to_string(&witness).ok(); + if args.is_some() { + std::fs::remove_file(&witness).expect("clear witness"); + } + (output, args) + }; + // Control: a local host with a plain database name reaches psql, so the + // refusals below come from the guard rather than an unrunnable fixture. + // It must also pass -X so a psqlrc cannot \connect after the guard. + let (_, control_args) = run("localhost", "", "", "buzz"); + let cases = [ + ("remote host", "shared-db.example.invalid", "", "", ""), + ("address override", "localhost", "192.0.2.1", "", ""), + ("service override", "localhost", "", "production", ""), + ( + "socket-prefixed host list", + "/tmp,shared-db.example.invalid", + "", + "", + "", + ), + ( + "host list", + "localhost,shared-db.example.invalid", + "", + "", + "", + ), + ( + "database URI", + "localhost", + "", + "", + "postgresql://buzz@shared-db.example.invalid/buzz", + ), + ( + "short database URI", + "localhost", + "", + "", + "postgres://shared-db.example.invalid/buzz", + ), + ( + "database key/value host", + "localhost", + "", + "", + "host=shared-db.example.invalid dbname=buzz", + ), + ( + "database key/value hostaddr", + "localhost", + "", + "", + "hostaddr=192.0.2.1 dbname=buzz", + ), + ( + "database key/value service", + "localhost", + "", + "", + "service=production", + ), + ]; + let results = cases.map(|(name, host, address, service, database)| { + let (output, args) = run(host, address, service, database); + (name, output, args.is_some()) + }); + std::fs::remove_dir_all(root).expect("remove scratch fixture"); + let control_args = control_args.expect("plain local target did not reach psql"); + assert!( + control_args.lines().any(|arg| arg == "-X"), + "psql invoked without -X: {control_args:?}" + ); + for (name, output, invoked) in results { + assert!(!invoked, "{name} reached psql"); + assert!(!output.status.success(), "{name} accepted"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("requires a local PostgreSQL target"), + "{name}: missing refusal" + ); + } +} diff --git a/crates/buzz-deletion/Cargo.toml b/crates/buzz-deletion/Cargo.toml index 6937974c844..bfc8cb8d244 100644 --- a/crates/buzz-deletion/Cargo.toml +++ b/crates/buzz-deletion/Cargo.toml @@ -13,9 +13,9 @@ thiserror = { workspace = true } buzz-core = { workspace = true } buzz-db = { workspace = true } buzz-media = { workspace = true } +buzz-pubsub = { workspace = true } chrono = { workspace = true } clap = { version = "4", features = ["derive"] } -deadpool-redis = { workspace = true } hex = { workspace = true } redis = { workspace = true } serde = { workspace = true } diff --git a/crates/buzz-deletion/src/community.rs b/crates/buzz-deletion/src/community.rs new file mode 100644 index 00000000000..6563795d258 --- /dev/null +++ b/crates/buzz-deletion/src/community.rs @@ -0,0 +1,57 @@ +//! Community submission and preparation shared by the CLI and parent workflows. + +use crate::build_inventory; +use anyhow::Result; +use buzz_core::CommunityId; +use buzz_db::deletion::{DeletionRequest, DeletionStage, DeletionStore}; +use buzz_db::DbError; +use buzz_media::MediaStorage; + +/// Submit operator intent and freeze inventory using the existing community +/// operations. A pinned community ID makes admission create-only: a concurrent +/// existing request is returned unchanged, including blocked or aborted states. +/// Without an ID, the CLI retains its existing same-submitter preparation retry. +/// Callers must already hold operator authority; this does not approve or run deletion. +pub async fn submit_and_prepare( + store: &DeletionStore, + media: &MediaStorage, + host: Option<&str>, + requested_by: &str, + reason: Option<&str>, + expected_community: Option, +) -> Result { + let request = match store + .submit(host, requested_by, reason, expected_community) + .await + { + Ok(request) => request, + Err(error @ DbError::DeletionSafety(_)) if expected_community.is_some() => { + // A separate read sees a concurrent submitter's committed row. + // Database/transport failures are never converted to success. + if let Some(community) = expected_community { + if let Some(existing) = store.find_for_community(community).await? { + if host.is_none_or(|host| existing.community_host.eq_ignore_ascii_case(host)) { + return Ok(existing); + } + } + } + return Err(error.into()); + } + Err(error) => return Err(error.into()), + }; + let inventory = build_inventory(store, media, &request, None).await?; + match store.freeze_inventory(request.id, &inventory).await { + Ok(request) => Ok(request), + Err(error @ DbError::DeletionSafety(_)) if expected_community.is_some() => { + // An operator may have progressed the child during storage listing. + // Preserve their committed state, never reset its approval/inventory. + let current = store.get(request.id).await?; + if current.stage != DeletionStage::Submitted { + Ok(current) + } else { + Err(error.into()) + } + } + Err(error) => Err(error.into()), + } +} diff --git a/crates/buzz-deletion/src/lib.rs b/crates/buzz-deletion/src/lib.rs index 483ce7e90c0..158681a96a0 100644 --- a/crates/buzz-deletion/src/lib.rs +++ b/crates/buzz-deletion/src/lib.rs @@ -5,6 +5,9 @@ /// Synthetic user-deletion request intake. pub mod user; +/// Community submission and preparation shared by operator entry points. +pub mod community; + use std::future::Future; #[cfg(test)] use std::sync::atomic::{AtomicBool, Ordering}; @@ -22,6 +25,7 @@ use buzz_media::{ is_tenant_owned_key, tenant_prefixes, BulkDeleteOutcome, MediaStorage, ObjectVersionKind, ObjectVersionRef, }; +use buzz_pubsub::{redis_connection, RedisConnection}; use clap::Subcommand; use serde::Serialize; use tokio_util::sync::CancellationToken; @@ -337,7 +341,7 @@ impl LoopMode { struct Services { store: DeletionStore, media: Arc, - redis: deadpool_redis::Pool, + redis: RedisConnection, } #[derive(Debug, thiserror::Error)] @@ -461,15 +465,15 @@ async fn run_with_services(command: Command, services: Services) -> Result } => { let relay_url = std::env::var("RELAY_URL").ok(); let host = resolve_submit_host(host.as_deref(), relay_url.as_deref())?; - let request = services - .store - .submit(&host, &requested_by, reason.as_deref()) - .await?; - let inventory = build_inventory(&services, &request, None).await?; - let request = services - .store - .freeze_inventory(request.id, &inventory) - .await?; + let request = community::submit_and_prepare( + &services.store, + &services.media, + Some(&host), + &requested_by, + reason.as_deref(), + None, + ) + .await?; print_json(&request)?; Ok(0) } @@ -609,14 +613,7 @@ async fn connect_services_with_store(store: DeletionStore) -> Result { }; let media = Arc::new(MediaStorage::new(&media_config)?); let redis_url = required_env("REDIS_URL")?; - let mut redis_config = deadpool_redis::Config::from_url(&redis_url); - redis_config.pool = Some(deadpool_redis::PoolConfig::new(env_parse( - "BUZZ_REDIS_POOL_SIZE", - 16, - ))); - let redis = redis_config - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .context("create deletion Redis pool")?; + let redis = redis_connection(&redis_url).context("create deletion Redis connection")?; Ok(Services { store, media, @@ -703,15 +700,13 @@ fn validate_storage_ownership(request: &DeletionRequest, manifest: &StorageManif } async fn build_inventory( - services: &Services, + store: &DeletionStore, + media: &MediaStorage, request: &DeletionRequest, heartbeat_lost: Option<&CancellationToken>, ) -> Result { - let schema = services - .store - .inventory_schema(request.community_id) - .await?; - let storage = enumerate_tenant_prefixes(services, request, heartbeat_lost, None).await?; + let schema = store.inventory_schema(request.community_id).await?; + let storage = enumerate_tenant_prefixes(store, media, request, heartbeat_lost, None).await?; Ok(FrozenInventory { schema, storage }) } @@ -722,12 +717,11 @@ struct ChunkSink<'a> { buffered: Vec, } -async fn flush_chunk(services: &Services, sink: &mut ChunkSink<'_>, prefix: &str) -> Result<()> { +async fn flush_chunk(store: &DeletionStore, sink: &mut ChunkSink<'_>, prefix: &str) -> Result<()> { if sink.buffered.is_empty() { return Ok(()); } - services - .store + store .append_manifest_key_chunk(sink.token, sink.next_chunk_no, prefix, &sink.buffered) .await?; sink.next_chunk_no += 1; @@ -765,7 +759,8 @@ fn manifest_chunk_deleted_detail( /// (never spanning prefixes) for the destructive freeze to bind against these /// digests. async fn enumerate_tenant_prefixes( - services: &Services, + store: &DeletionStore, + media: &MediaStorage, request: &DeletionRequest, heartbeat_lost: Option<&CancellationToken>, mut sink: Option<&mut ChunkSink<'_>>, @@ -782,8 +777,7 @@ async fn enumerate_tenant_prefixes( if heartbeat_lost.is_some_and(CancellationToken::is_cancelled) { return Err(DeletionLeaseLost.into()); } - let page = services - .media + let page = media .list_prefix_versions_page( &prefix, key_marker.take(), @@ -809,7 +803,7 @@ async fn enumerate_tenant_prefixes( if let Some(sink) = sink.as_deref_mut() { sink.buffered.push(encoded); if sink.buffered.len() >= chunk_keys { - flush_chunk(services, sink, &prefix).await?; + flush_chunk(store, sink, &prefix).await?; } } } @@ -824,7 +818,7 @@ async fn enumerate_tenant_prefixes( version_id_marker = Some(next_version_id_marker); } if let Some(sink) = sink.as_deref_mut() { - flush_chunk(services, sink, &prefix).await?; + flush_chunk(store, sink, &prefix).await?; } let (keys_digest, object_count) = digest.finish(); prefixes.push(PrefixManifest { @@ -960,8 +954,14 @@ async fn freeze_destructive_manifest( next_chunk_no: 0, buffered: Vec::new(), }; - let manifest = - enumerate_tenant_prefixes(services, request, Some(heartbeat_lost), Some(&mut sink)).await?; + let manifest = enumerate_tenant_prefixes( + &services.store, + &services.media, + request, + Some(heartbeat_lost), + Some(&mut sink), + ) + .await?; services .store .freeze_destructive_storage_manifest(token, &manifest) @@ -1028,7 +1028,8 @@ async fn run_loop( HEARTBEAT_INTERVAL, |heartbeat_lost| async move { build_inventory( - preparation_services, + &preparation_services.store, + &preparation_services.media, &preparation_request, Some(&heartbeat_lost), ) @@ -1682,24 +1683,24 @@ async fn verify_storage_absence(services: &Services, request: &DeletionRequest) } async fn publish_disconnect_community( - pool: &deadpool_redis::Pool, + pool: &RedisConnection, community: buzz_core::CommunityId, ) -> Result<()> { - let mut connection = pool.get().await?; + let mut connection = pool.clone(); let channel = format!("buzz:{community}:conn-control"); let _: u64 = redis::cmd("PUBLISH") .arg(channel) .arg(r#"{"op":"DisconnectCommunity"}"#) - .query_async(&mut *connection) + .query_async(&mut connection) .await?; Ok(()) } async fn purge_redis_namespace( - pool: &deadpool_redis::Pool, + pool: &RedisConnection, community: buzz_core::CommunityId, ) -> Result { - let mut connection = pool.get().await?; + let mut connection = pool.clone(); let pattern = format!("buzz:{community}:*"); let mut cursor = 0u64; let mut deleted = 0u64; @@ -1710,12 +1711,12 @@ async fn purge_redis_namespace( .arg(&pattern) .arg("COUNT") .arg(1000) - .query_async(&mut *connection) + .query_async(&mut connection) .await?; if !keys.is_empty() { let count: u64 = redis::cmd("UNLINK") .arg(&keys) - .query_async(&mut *connection) + .query_async(&mut connection) .await?; deleted = deleted.saturating_add(count); } @@ -1733,7 +1734,7 @@ fn scan_proves_absence(pages: &[(u64, Vec)]) -> bool { } async fn scan_redis_namespace( - connection: &mut deadpool_redis::Connection, + connection: &mut RedisConnection, pattern: &str, ) -> Result)>> { let mut cursor = 0u64; @@ -1745,7 +1746,7 @@ async fn scan_redis_namespace( .arg(pattern) .arg("COUNT") .arg(1000) - .query_async(&mut **connection) + .query_async(connection) .await?; cursor = page.0; pages.push(page); @@ -1756,10 +1757,10 @@ async fn scan_redis_namespace( } async fn verify_redis_absence( - pool: &deadpool_redis::Pool, + pool: &RedisConnection, community: buzz_core::CommunityId, ) -> Result<()> { - let mut connection = pool.get().await?; + let mut connection = pool.clone(); let pattern = format!("buzz:{community}:*"); // SCAN is weakly consistent. Two complete empty passes ensure a cursor // rollover or concurrent expiry cannot make one sparse pass look absent. @@ -1906,7 +1907,7 @@ mod postgres_tests { .await .expect("create deletion engine test community"); let request = store - .submit(&host, "test", None) + .submit(Some(&host), "test", None, None) .await .expect("submit deletion request"); let inventory = FrozenInventory { @@ -1950,9 +1951,8 @@ mod postgres_tests { }) .expect("construct unused media service"), ), - redis: deadpool_redis::Config::from_url("redis://127.0.0.1:1") - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("construct unused Redis pool"), + redis: redis_connection("redis://127.0.0.1:1") + .expect("construct unused Redis connection"), }; (db, services, claim) } @@ -2021,9 +2021,8 @@ mod postgres_tests { }) .expect("construct unused media service"), ), - redis: deadpool_redis::Config::from_url("redis://127.0.0.1:1") - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("construct unused Redis pool"), + redis: redis_connection("redis://127.0.0.1:1") + .expect("construct unused Redis connection"), }; (db, services, *request, inventory) } @@ -2053,7 +2052,7 @@ mod postgres_tests { .expect("create approved community"); let approved = services .store - .submit(&approved_host, "manual-operator", None) + .submit(Some(&approved_host), "manual-operator", None, None) .await .expect("submit approved request"); let inventory = FrozenInventory { @@ -2139,7 +2138,7 @@ mod postgres_tests { .expect("create manual community"); let manual = services .store - .submit(&operator_host, "manual-operator", None) + .submit(Some(&operator_host), "manual-operator", None, None) .await .expect("submit manual request"); diff --git a/crates/buzz-deletion/src/user.rs b/crates/buzz-deletion/src/user.rs index e10c57febd0..93d1766fdb3 100644 --- a/crates/buzz-deletion/src/user.rs +++ b/crates/buzz-deletion/src/user.rs @@ -152,6 +152,10 @@ pub async fn run(command: Command) -> Result { mod handlers; mod inventory; +/// Standalone delegation of an owned community to community deletion. +pub mod owned_community; +/// Read-only summaries of locally saved request progress and external waits. +pub mod summary; mod transition; mod worker; mod workflow; diff --git a/crates/buzz-deletion/src/user/owned_community.rs b/crates/buzz-deletion/src/user/owned_community.rs new file mode 100644 index 00000000000..c7e9e0be57a --- /dev/null +++ b/crates/buzz-deletion/src/user/owned_community.rs @@ -0,0 +1,194 @@ +//! Standalone owned-community handler; deliberately absent from dispatch and +//! transition rules. The caller owns claim, heartbeat, and release lifecycle. + +use crate::community::submit_and_prepare; +use crate::RETRY_DELAY; +use anyhow::{bail, Context, Result}; +use buzz_core::CommunityId; +use buzz_db::deletion::{DeletionRequest, DeletionRequestOrigin, DeletionStage, DeletionStore}; +use buzz_db::entity_deletion::{EntityDeletionStore, EntityLease, EntityStage}; +use buzz_media::MediaStorage; +use serde_json::{json, Value}; + +/// Durable outcome of one observation; waiting is not successful completion. +#[derive(Debug, PartialEq, Eq)] +pub enum OwnedCommunityOutcome { + /// The child still needs preparation, approval, execution, or intervention. + Waiting, + /// Logical community deletion finished; physical retention can remain. + Completed, +} + +/// Check the child first, submit only if missing, and save the result on this +/// user stage. Errors propagate after recording a retry when the lease is valid. +/// This never approves or runs the child, advances stages, or releases the lease. +pub async fn handle( + store: &EntityDeletionStore, + lease: &EntityLease, + row: &EntityStage, + community_store: &DeletionStore, + media: &MediaStorage, +) -> Result { + if row.request_id != lease.request_id || row.stage != "delete_owned_community" { + bail!("expected this request's delete_owned_community stage"); + } + let row = store.start_stage(lease, row.id).await?; + match observe(store, lease, &row, community_store, media).await { + Ok(outcome) => Ok(outcome), + Err(error) => { + if let Err(save_error) = store + .fail_stage(lease, row.id, &format!("{error:#}"), RETRY_DELAY) + .await + { + return Err(error.context(format!("also could not save retry: {save_error}"))); + } + Err(error) + } + } +} + +async fn observe( + store: &EntityDeletionStore, + lease: &EntityLease, + row: &EntityStage, + community_store: &DeletionStore, + media: &MediaStorage, +) -> Result { + let request = store.get(lease.request_id).await?; + let community_id = row + .target_community_id + .context("missing owned community ID")?; + let inputs = &row.metadata_json["inputs"]; + let inventory = request + .inventory_manifest + .as_ref() + .context("missing inventory")?; + let approved_community = inventory["communities"] + .as_array() + .context("missing inventory communities")? + .iter() + .find(|community| community["community_id"] == community_id.to_string()) + .context("owned community is outside approved inventory")?; + if request.entity_type != "user" + || row.stage != "delete_owned_community" + || inputs["target"] != request.target + || &inputs["community"] != approved_community + || approved_community["relationship"] != "owner" + { + bail!("stage inputs do not match the approved owned-community inventory"); + } + let community = CommunityId::from_uuid(community_id); + let saved_child = row.metadata_json["waiting"]["child_request_id"].as_str(); + let child = match community_store.find_for_community(community).await? { + Some(child) => child, + None if saved_child.is_some() => bail!("previously observed community request is missing"), + None => { + submit_and_prepare( + community_store, + media, + None, + &request.requested_by, + Some(&format!( + "User deletion request {}; stage {}", + request.id, row.id + )), + Some(community), + ) + .await? + } + }; + // The stage tracks the approved community, not one deletion attempt. A + // replacement request returned by community-ID lookup becomes its current + // observation without changing or approving the child. + let completed = child.stage == DeletionStage::RetentionPending + && child.completed_at.is_some() + && child.blocked_reason.is_none(); + let observation = observation(&child, completed); + if completed { + store.save_stage_success(lease, row.id, observation).await?; + Ok(OwnedCommunityOutcome::Completed) + } else { + store.save_stage_waiting(lease, row.id, observation).await?; + Ok(OwnedCommunityOutcome::Waiting) + } +} + +fn observation(child: &DeletionRequest, completed: bool) -> Value { + let id = child.id.to_string(); + let inspect = json!(["buzz-admin", "deletions", "inspect", id]); + let (reason, action, commands) = if completed { + ( + "logical_deletion_complete", + "Community logical deletion is complete. Retained copies remain subject to community retention policy.", + vec![inspect], + ) + } else if child.stage == DeletionStage::Aborted { + ( + "operator_intervention", + "Inspect the aborted child. To continue deletion, submit a replacement for this community; the user stage will follow it on the next invocation.", + vec![inspect, json!(["buzz-admin", "deletions", "submit", "--host", child.community_host, "--requested-by", ""])], + ) + } else if child.blocked_reason.is_some() { + ( + "operator_intervention", + "Inspect and fix the recorded cause, then unblock the community deletion request.", + vec![ + inspect, + json!([ + "buzz-admin", + "deletions", + "unblock", + id, + "--unblocked-by", + "", + "--reason", + "" + ]), + ], + ) + } else { + match child.stage { + DeletionStage::Submitted if child.request_origin == DeletionRequestOrigin::Owner => ( + "owner_preparation_pending", + "Let the community deletion drain prepare and approve the existing owner-origin request after validating its recorded owner intent.", + vec![inspect], + ), + DeletionStage::Submitted => ( + "preparation_required", + "Finish community inventory preparation using the original submitter, then obtain separate community approval.", + vec![inspect, json!(["buzz-admin", "deletions", "submit", "--host", child.community_host, "--requested-by", child.requested_by])], + ), + DeletionStage::Inventoried => ( + "approval_required", + "Review the child's frozen inventory, then have an operator approve the community deletion separately.", + vec![inspect, json!(["buzz-admin", "deletions", "approve", id, "--approved-by", ""])], + ), + _ => ( + "community_execution_pending", + "Community deletion runs independently through its worker/drain or an operator run. Invoke this user-stage handler again after it progresses.", + vec![inspect, json!(["buzz-admin", "deletions", "run", id])], + ), + } + }; + json!({ + "kind": "community_deletion", + "child_request_id": child.id, + "community_id": child.community_id.as_uuid(), + "community_host": child.community_host, + "child_stage": child.stage, + "child_updated_at": child.updated_at, + "observed_at": chrono::Utc::now(), + "inventory_digest": child.inventory_digest, + "blocked_reason": child.blocked_reason, + "last_error": child.last_error, + "next_attempt_at": child.next_attempt_at, + "completed_at": child.completed_at, + "reason": reason, + "operator_action": action, + "commands": commands, + "retention_pending": child.stage == DeletionStage::RetentionPending, + }) +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-deletion/src/user/owned_community/postgres_tests.rs b/crates/buzz-deletion/src/user/owned_community/postgres_tests.rs new file mode 100644 index 00000000000..6c6738d311c --- /dev/null +++ b/crates/buzz-deletion/src/user/owned_community/postgres_tests.rs @@ -0,0 +1,799 @@ +use super::*; +use crate::user::summary::summarize_request; +use buzz_db::entity_deletion::{inventory_digest, NewEntityStage, NextStage, StageTransition}; +use buzz_db::Db; +use buzz_media::{MediaConfig, MediaStorage, S3AddressingStyle}; +use sqlx::PgPool; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use uuid::Uuid; + +struct Fixture { + db: Db, + store: EntityDeletionStore, + lease: EntityLease, + row: EntityStage, + community: CommunityId, +} + +async fn fixture() -> Fixture { + let url = std::env::var("BUZZ_TEST_DATABASE_URL") + .or_else(|_| std::env::var("DATABASE_URL")) + .unwrap(); + let db = Db::from_pool(PgPool::connect(&url).await.unwrap()); + let community = db + .ensure_configured_community("owned.example") + .await + .unwrap() + .id; + let store = db.entity_deletion_store(); + // Owned intake/routing intentionally remain disabled. Seed that future + // approved input, then use the real claim, stage and handler operations. + let target = "11".repeat(32); + let item = json!({"community_id": community.as_uuid(), "relationship": "owner", "label": "owned.example"}); + let inventory = json!({"communities": [item, { + "community_id": Uuid::new_v4(), "relationship": "participant", "label": "not-reached" + }]}); + let digest = inventory_digest(&inventory).unwrap(); + let id: Uuid = sqlx::query_scalar( + "INSERT INTO entity_deletion_requests (target, requested_by, status, inventory_manifest, inventory_digest) + VALUES ($1, 'submitter', 'inventoried', $2, $3) RETURNING id", + ).bind(&target).bind(&inventory).bind(&digest).fetch_one(db.pool()).await.unwrap(); + store.approve(id, "approver", &digest).await.unwrap(); + let lease = store + .claim(id, "worker", Duration::from_secs(60)) + .await + .unwrap() + .unwrap(); + let next = store + .transition_stage(&lease, None, |_, _| { + Ok(StageTransition::Initialize(NewEntityStage { + stage: "delete_owned_community".into(), + community: Some(*community.as_uuid()), + inputs: json!({"target": target, "community": item}), + })) + }) + .await + .unwrap(); + let NextStage::Stage(row) = next else { + panic!("expected stage") + }; + Fixture { + db, + store, + lease, + row, + community, + } +} + +fn media(endpoint: String) -> Arc { + Arc::new( + MediaStorage::new(&MediaConfig { + s3_endpoint: endpoint, + s3_access_key: "test".into(), + s3_secret_key: "test".into(), + s3_bucket: "test".into(), + s3_region: "us-east-1".into(), + s3_addressing_style: S3AddressingStyle::Path, + max_image_bytes: 1, + max_gif_bytes: 1, + max_video_bytes: 1, + max_file_bytes: 1, + public_base_url: "http://localhost/media".into(), + upload_records_enabled: false, + upload_ip_header: None, + upload_port_header: None, + }) + .unwrap(), + ) +} + +fn lookup_only_media() -> Arc { + // Any accidental attempt to inventory an existing child fails immediately. + media("http://127.0.0.1:1".into()) +} + +async fn submission_media() -> (Arc, tokio::task::JoinHandle<()>) { + submission_media_with_pause(None).await +} + +async fn submission_media_with_pause( + mut pause: Option<( + tokio::sync::oneshot::Sender<()>, + tokio::sync::oneshot::Receiver<()>, + )>, +) -> (Arc, tokio::task::JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + // Exercise the real S3 adapter and inventory builder, with one empty + // version listing per tenant prefix. No external storage is needed. + for _ in 0..3 { + let (mut socket, _) = tokio::time::timeout(Duration::from_secs(10), listener.accept()) + .await + .unwrap() + .unwrap(); + let mut headers = [0; 8192]; + let size = tokio::time::timeout(Duration::from_secs(10), socket.read(&mut headers)) + .await + .unwrap() + .unwrap(); + assert!(std::str::from_utf8(&headers[..size]) + .unwrap() + .starts_with("GET ")); + if let Some((started, resume)) = pause.take() { + started.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(10), resume) + .await + .unwrap() + .unwrap(); + } + let body = "testfalse"; + let response = format!("HTTP/1.1 200 OK\r\nContent-Type: application/xml\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + socket.write_all(response.as_bytes()).await.unwrap(); + } + }); + (media(endpoint), server) +} + +async fn child(f: &Fixture) -> DeletionRequest { + f.db.deletion_store() + .find_for_community(f.community) + .await + .unwrap() + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn stage_follows_replacement_child_for_the_same_community() { + let f = fixture().await; + let store = f.db.deletion_store(); + let (media, server) = submission_media().await; + handle(&f.store, &f.lease, &f.row, &store, &media) + .await + .unwrap(); + server.await.unwrap(); + let a = child(&f).await; + let saved = f.store.inspect(f.row.request_id).await.unwrap(); + assert_eq!( + saved.stage_history[0].metadata_json["waiting"]["child_request_id"], + a.id.to_string() + ); + store + .abort(a.id, "operator", "replace request") + .await + .unwrap(); + // Use the same submission/preparation entry point as the community CLI. + let (media, server) = submission_media().await; + let b = submit_and_prepare( + &store, + &media, + Some("owned.example"), + "operator", + None, + None, + ) + .await + .unwrap(); + server.await.unwrap(); + assert_ne!(a.id, b.id); + assert_eq!(b.community_id, a.community_id); + assert_eq!(b.stage, DeletionStage::Inventoried); + let media = lookup_only_media(); + assert_eq!( + handle(&f.store, &f.lease, &f.row, &store, &media) + .await + .unwrap(), + OwnedCommunityOutcome::Waiting + ); + let saved = f.store.inspect(f.row.request_id).await.unwrap(); + assert_eq!(saved.stage_history.len(), 1); + let row = &saved.stage_history[0]; + assert_eq!(row.id, f.row.id); + assert_eq!(row.status, "running"); + assert_eq!( + row.metadata_json["waiting"]["child_request_id"], + b.id.to_string() + ); + assert_eq!(row.metadata_json["waiting"]["child_stage"], "inventoried"); + assert_eq!(saved.execution.retry_count, 0); + assert!(saved.execution.last_error.is_none()); + assert_eq!(store.get(a.id).await.unwrap().stage, DeletionStage::Aborted); + assert_eq!(store.get(b.id).await.unwrap(), b); + assert!(store.inspect(b.id).await.unwrap().approval.is_none()); + // Model the separate community worker completing B, as in the main flow test. + sqlx::query("UPDATE community_deletion_requests SET stage = 'retention_pending', completed_at = now() WHERE id = $1") + .bind(b.id).execute(f.db.pool()).await.unwrap(); + assert_eq!( + handle(&f.store, &f.lease, &f.row, &store, &media) + .await + .unwrap(), + OwnedCommunityOutcome::Completed + ); + let saved = f.store.inspect(f.row.request_id).await.unwrap(); + assert_eq!(saved.stage_history.len(), 1); + assert_eq!(saved.stage_history[0].id, f.row.id); + assert_eq!(saved.stage_history[0].status, "completed"); + assert_eq!( + saved.stage_history[0].metadata_json["result"]["child_request_id"], + b.id.to_string() + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn submission_preserves_operator_transition_during_inventory_listing() { + let f = fixture().await; + let store = f.db.deletion_store(); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (resume_tx, resume_rx) = tokio::sync::oneshot::channel(); + let (media, server) = submission_media_with_pause(Some((started_tx, resume_rx))).await; + let submission = submit_and_prepare(&store, &media, None, "operator", None, Some(f.community)); + let intervention = async { + tokio::time::timeout(Duration::from_secs(10), started_rx) + .await + .unwrap() + .unwrap(); + let request = child(&f).await; + assert_eq!(request.stage, DeletionStage::Submitted); + let aborted = store + .abort(request.id, "operator", "cancel during inventory") + .await + .unwrap(); + resume_tx.send(()).unwrap(); + aborted + }; + let (result, aborted) = tokio::join!(submission, intervention); + server.await.unwrap(); + assert_eq!(result.unwrap(), aborted); + assert_eq!(store.get(aborted.id).await.unwrap(), aborted); + assert!(store.inspect(aborted.id).await.unwrap().approval.is_none()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn operator_guidance_distinguishes_blocked_aborted_and_owner_submitted() { + let f = fixture().await; + let mut child = + f.db.deletion_store() + .submit(Some("owned.example"), "operator", None, None) + .await + .unwrap(); + let observed = observation(&child, false); + assert_eq!(observed["reason"], "preparation_required"); + assert_eq!(observed["commands"][1][2], "submit"); + child.request_origin = DeletionRequestOrigin::Owner; + let observed = observation(&child, false); + assert_eq!(observed["reason"], "owner_preparation_pending"); + assert_eq!(observed["commands"].as_array().unwrap().len(), 1); + child.blocked_reason = Some("unsafe inventory".into()); + let observed = observation(&child, false); + assert_eq!( + observed["commands"][1], + json!([ + "buzz-admin", + "deletions", + "unblock", + child.id.to_string(), + "--unblocked-by", + "", + "--reason", + "" + ]) + ); + child.stage = DeletionStage::Aborted; + let observed = observation(&child, false); + assert_eq!( + observed["commands"][1], + json!([ + "buzz-admin", + "deletions", + "submit", + "--host", + child.community_host, + "--requested-by", + "" + ]) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn submit_wait_approve_observe_and_complete_without_advancing_parent() { + let f = fixture().await; + let (media, server) = submission_media().await; + assert_eq!( + handle(&f.store, &f.lease, &f.row, &f.db.deletion_store(), &media) + .await + .unwrap(), + OwnedCommunityOutcome::Waiting + ); + server.await.unwrap(); + let c = child(&f).await; + assert_eq!(c.stage, DeletionStage::Inventoried); + assert_eq!(c.requested_by, "submitter"); + let summary = summarize_request(&f.store, f.row.request_id).await.unwrap(); + let wait = &summary.unfinished_stages[0]; + assert_eq!(wait.state, "waiting_external"); + let observation = wait.external_observation.as_ref().unwrap(); + assert_eq!(observation["child_request_id"], c.id.to_string()); + assert_eq!(observation["reason"], "approval_required"); + assert!(observation["observed_at"].is_string()); + assert!(observation["commands"].as_array().unwrap().len() >= 2); + assert!(!summary.complete); + assert_eq!(summary.communities_not_reached.len(), 1); + assert_eq!(summary.saved.execution.retry_count, 0); + assert_eq!(summary.saved.request.status, "running"); + assert_eq!(summary.saved.stage_history.len(), 1); + assert!(f + .db + .deletion_store() + .inspect(c.id) + .await + .unwrap() + .approval + .is_none()); + let media = lookup_only_media(); + assert_eq!( + handle(&f.store, &f.lease, &f.row, &f.db.deletion_store(), &media) + .await + .unwrap(), + OwnedCommunityOutcome::Waiting + ); + assert_eq!(child(&f).await, c); // Read-only repeat: no child writes. + f.db.deletion_store() + .approve(c.id, "community-approver", None) + .await + .unwrap(); + // Summary never refreshes child state, even though the DB now says approved. + let summary = summarize_request(&f.store, f.row.request_id).await.unwrap(); + assert_eq!( + summary.unfinished_stages[0] + .external_observation + .as_ref() + .unwrap()["child_stage"], + "inventoried" + ); + handle(&f.store, &f.lease, &f.row, &f.db.deletion_store(), &media) + .await + .unwrap(); + let summary = summarize_request(&f.store, f.row.request_id).await.unwrap(); + assert_eq!( + summary.unfinished_stages[0] + .external_observation + .as_ref() + .unwrap()["child_stage"], + "approved" + ); + // Fixture the independent community worker's terminal result; this test + // does not execute destructive community deletion. + sqlx::query("UPDATE community_deletion_requests SET stage = 'retention_pending', completed_at = now() WHERE id = $1") + .bind(c.id).execute(f.db.pool()).await.unwrap(); + assert_eq!( + handle(&f.store, &f.lease, &f.row, &f.db.deletion_store(), &media) + .await + .unwrap(), + OwnedCommunityOutcome::Completed + ); + let summary = summarize_request(&f.store, f.row.request_id).await.unwrap(); + assert_eq!(summary.completed_stages, 1); + assert!(summary.unfinished_stages.is_empty()); + assert!(!summary.complete); // Only routing may finish the parent. + let row = &summary.saved.stage_history[0]; + assert!(row.is_current); + assert!(row.metadata_json.get("waiting").is_none()); + assert_eq!(row.metadata_json["result"]["retention_pending"], true); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn preparation_failure_is_recoverable_and_does_not_duplicate_child() { + let f = fixture().await; + let media = lookup_only_media(); + assert!( + handle(&f.store, &f.lease, &f.row, &f.db.deletion_store(), &media) + .await + .is_err() + ); + let c = child(&f).await; + assert_eq!(c.stage, DeletionStage::Submitted); + let before = f.store.inspect(f.row.request_id).await.unwrap(); + assert_eq!(before.request.status, "retry_wait"); + assert_eq!(before.execution.retry_count, 1); + assert!(before.stage_history[0].last_error.is_some()); + sqlx::query("UPDATE entity_deletion_requests SET next_attempt_at = now() - interval '1 second' WHERE id = $1") + .bind(f.row.request_id).execute(f.db.pool()).await.unwrap(); + assert_eq!( + handle(&f.store, &f.lease, &f.row, &f.db.deletion_store(), &media) + .await + .unwrap(), + OwnedCommunityOutcome::Waiting + ); + assert_eq!(child(&f).await, c); + let summary = summarize_request(&f.store, f.row.request_id).await.unwrap(); + assert_eq!( + summary.unfinished_stages[0] + .external_observation + .as_ref() + .unwrap()["reason"], + "preparation_required" + ); + assert_eq!(summary.saved.execution.retry_count, 1); + assert!(summary.saved.execution.last_error.is_none()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn concurrent_submission_reuses_request_and_preserves_terminal_states() { + let f = fixture().await; + let store = f.db.deletion_store(); + let (media, server) = submission_media().await; + let (a, b) = tokio::join!( + submit_and_prepare( + &store, + &media, + None, + "operator-a", + Some("a"), + Some(f.community) + ), + submit_and_prepare( + &store, + &media, + None, + "operator-b", + Some("b"), + Some(f.community) + ) + ); + let a = a.unwrap(); + let b = b.unwrap(); + assert_eq!(a.id, b.id); + server.await.unwrap(); // Exactly one caller inventories the child. + let inventoried = child(&f).await; + assert_eq!(inventoried.stage, DeletionStage::Inventoried); + let media = lookup_only_media(); + assert_eq!( + submit_and_prepare(&store, &media, None, "another", None, Some(f.community)) + .await + .unwrap(), + inventoried + ); + store.abort(a.id, "operator", "cancelled").await.unwrap(); + let aborted = child(&f).await; + assert_eq!(aborted.stage, DeletionStage::Aborted); + assert_eq!( + submit_and_prepare(&store, &media, None, "another", None, Some(f.community)) + .await + .unwrap(), + aborted + ); + assert_eq!( + handle(&f.store, &f.lease, &f.row, &f.db.deletion_store(), &media) + .await + .unwrap(), + OwnedCommunityOutcome::Waiting + ); + let summary = summarize_request(&f.store, f.row.request_id).await.unwrap(); + assert_eq!( + summary.unfinished_stages[0] + .external_observation + .as_ref() + .unwrap()["reason"], + "operator_intervention" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn stale_generation_cannot_save_wait_or_execute_handler() { + let f = fixture().await; + f.store.start_stage(&f.lease, f.row.id).await.unwrap(); + sqlx::query("UPDATE entity_deletion_requests SET lease_expires_at = now() - interval '1 second' WHERE id = $1") + .bind(f.row.request_id).execute(f.db.pool()).await.unwrap(); + let new = f + .store + .claim(f.row.request_id, &f.lease.owner, Duration::from_secs(60)) + .await + .unwrap() + .unwrap(); + assert_eq!(new.generation, f.lease.generation + 1); + let before = serde_json::to_value(f.store.inspect(f.row.request_id).await.unwrap()).unwrap(); + let error = f + .store + .save_stage_waiting(&f.lease, f.row.id, json!({"kind": "test"})) + .await + .unwrap_err(); + assert!(buzz_db::deletion::is_stale_deletion_lease(&error)); + assert!(handle( + &f.store, + &f.lease, + &f.row, + &f.db.deletion_store(), + &lookup_only_media() + ) + .await + .is_err()); + assert!(f + .db + .deletion_store() + .find_for_community(f.community) + .await + .unwrap() + .is_none()); + assert_eq!( + serde_json::to_value(f.store.inspect(f.row.request_id).await.unwrap()).unwrap(), + before + ); + f.store + .save_stage_waiting( + &new, + f.row.id, + json!({"kind": "other_external_system", "operator_action": "wait for export"}), + ) + .await + .unwrap(); + let summary = summarize_request(&f.store, f.row.request_id).await.unwrap(); + assert_eq!(summary.unfinished_stages[0].state, "waiting_external"); + assert_eq!( + summary.unfinished_stages[0] + .external_observation + .as_ref() + .unwrap()["kind"], + "other_external_system" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn wrong_community_or_inputs_cannot_submit_a_child() { + let f = fixture().await; + sqlx::query("UPDATE entity_deletion_stage_history SET metadata_json = jsonb_set(metadata_json, '{inputs,target}', '\"different-user\"') WHERE id = $1") + .bind(f.row.id).execute(f.db.pool()).await.unwrap(); + // The caller's original row is stale; validation must reload persisted inputs. + assert!(handle( + &f.store, + &f.lease, + &f.row, + &f.db.deletion_store(), + &lookup_only_media() + ) + .await + .is_err()); + assert!(f + .db + .deletion_store() + .find_for_community(f.community) + .await + .unwrap() + .is_none()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cli_submission_preparation_can_resume_but_cannot_reset_approved_request() { + let f = fixture().await; + let store = f.db.deletion_store(); + // The same function used by the CLI leaves a submitted request when storage fails. + assert!(submit_and_prepare( + &store, + &lookup_only_media(), + Some("owned.example"), + "operator", + None, + None + ) + .await + .is_err()); + let submitted = child(&f).await; + assert_eq!(submitted.stage, DeletionStage::Submitted); + let (media, server) = submission_media().await; + let prepared = submit_and_prepare( + &store, + &media, + Some("owned.example"), + "operator", + None, + None, + ) + .await + .unwrap(); + server.await.unwrap(); + assert_eq!(prepared.id, submitted.id); + assert_eq!(prepared.stage, DeletionStage::Inventoried); + store.approve(prepared.id, "approver", None).await.unwrap(); + let approved = child(&f).await; + assert!(submit_and_prepare( + &store, + &lookup_only_media(), + Some("owned.example"), + "operator", + None, + None + ) + .await + .is_err()); + assert_eq!(child(&f).await, approved); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn submission_checks_community_identity_before_inserting() { + let f = fixture().await; + let other = + f.db.ensure_configured_community("other.example") + .await + .unwrap() + .id; + let store = f.db.deletion_store(); + assert!(submit_and_prepare( + &store, + &lookup_only_media(), + Some("owned.example"), + "operator", + None, + Some(other) + ) + .await + .is_err()); + assert!(store + .find_for_community(f.community) + .await + .unwrap() + .is_none()); + assert!(store.find_for_community(other).await.unwrap().is_none()); + assert!(store.submit(None, "operator", None, None).await.is_err()); + // A request for the pinned ID must not hide a mismatched supplied host. + store + .submit(Some("other.example"), "operator", None, None) + .await + .unwrap(); + assert!(submit_and_prepare( + &store, + &lookup_only_media(), + Some("owned.example"), + "operator", + None, + Some(other) + ) + .await + .is_err()); + assert!(store + .find_for_community(f.community) + .await + .unwrap() + .is_none()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn host_submission_and_parent_submission_share_one_admission_path() { + let f = fixture().await; + let store = f.db.deletion_store(); + // The operator submits first; parent submission must return this exact + // unprepared row without accessing storage or changing its provenance. + let submitted = store + .submit(Some("owned.example"), "operator", Some("manual"), None) + .await + .unwrap(); + assert_eq!( + submit_and_prepare( + &store, + &lookup_only_media(), + None, + "parent", + None, + Some(f.community) + ) + .await + .unwrap(), + submitted + ); + // Once aborted, only the explicit host-based operator path may replace it. + store + .abort(submitted.id, "operator", "cancel") + .await + .unwrap(); + let aborted = child(&f).await; + assert_eq!( + submit_and_prepare( + &store, + &lookup_only_media(), + None, + "parent", + None, + Some(f.community) + ) + .await + .unwrap(), + aborted + ); + let replacement = store + .submit(Some("owned.example"), "operator", None, None) + .await + .unwrap(); + assert_ne!(replacement.id, submitted.id); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn concurrent_cli_and_parent_submission_converge_without_repreparing() { + let f = fixture().await; + let store = f.db.deletion_store(); + let (media, server) = submission_media().await; + let (cli, parent) = tokio::join!( + submit_and_prepare(&store, &media, Some("owned.example"), "cli", None, None), + submit_and_prepare(&store, &media, None, "parent", None, Some(f.community)) + ); + let parent = parent.unwrap(); + match cli { + Ok(cli) => assert_eq!(cli.id, parent.id), + Err(error) => assert!(matches!( + error.downcast_ref::(), + Some(buzz_db::DbError::DeletionSafety(_)) + )), + } + server.await.unwrap(); // Only the creator prepares; three listings total. + let saved = child(&f).await; + assert_eq!(saved.id, parent.id); + assert_eq!(saved.stage, DeletionStage::Inventoried); + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM community_deletion_requests WHERE community_id = $1", + ) + .bind(f.community.as_uuid()) + .fetch_one(f.db.pool()) + .await + .unwrap(); + assert_eq!(count, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn database_failure_is_not_hidden_by_an_existing_child() { + let f = fixture().await; + f.db.deletion_store() + .submit(Some("owned.example"), "cli", None, None) + .await + .unwrap(); + let mut lock = f.db.pool().begin().await.unwrap(); + sqlx::query("SELECT id FROM communities WHERE id = $1 FOR UPDATE") + .bind(f.community.as_uuid()) + .fetch_one(&mut *lock) + .await + .unwrap(); + let url = std::env::var("BUZZ_TEST_DATABASE_URL") + .or_else(|_| std::env::var("DATABASE_URL")) + .unwrap(); + let pool = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .after_connect(|connection, _| { + Box::pin(async move { + sqlx::query("SET lock_timeout = '50ms'") + .execute(connection) + .await?; + Ok(()) + }) + }) + .connect(&url) + .await + .unwrap(); + let store = Db::from_pool(pool).deletion_store(); + let error = submit_and_prepare( + &store, + &lookup_only_media(), + None, + "parent", + None, + Some(f.community), + ) + .await + .unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(buzz_db::DbError::Sqlx(_)) + )); + lock.rollback().await.unwrap(); +} diff --git a/crates/buzz-deletion/src/user/summary.rs b/crates/buzz-deletion/src/user/summary.rs new file mode 100644 index 00000000000..6a0c2422c9a --- /dev/null +++ b/crates/buzz-deletion/src/user/summary.rs @@ -0,0 +1,105 @@ +//! Request summaries from a single user-table snapshot. No child API or +//! community deletion tables are consulted; observations can therefore be stale. + +use buzz_db::entity_deletion::{EntityDeletionStore, EntityInspection, EntityStage}; +use serde::Serialize; +use serde_json::Value; +use uuid::Uuid; + +/// Saved workflow progress, suitable for an operator report or future handler. +#[derive(Debug, Serialize)] +pub struct RequestSummary { + /// The authoritative request, lease/retry state, approvals and stage rows. + pub saved: EntityInspection, + /// True only if the parent is complete and every reached stage is complete. + pub complete: bool, + /// Completed reached stages; this is not a count of all future required work. + pub completed_stages: usize, + /// Reached stages still waiting, failed, pending, or running. + pub unfinished_stages: Vec, + /// Inventory communities that have no stage row yet. Empty does not prove + /// all work is done: runtime routing can still create additional stages. + pub communities_not_reached: Vec, + /// Clarifies whether more execution or an external dependency is outstanding. + pub explanation: &'static str, +} + +/// One unfinished stage with enough saved context to act without a child lookup. +#[derive(Debug, Serialize)] +pub struct UnfinishedStage { + /// Exact stage row, including community, inputs, timestamps, and errors. + pub stage: EntityStage, + /// Display state: failed, pending, running, or waiting_external. + pub state: String, + /// Last saved external observation, including reason, child ID/status, + /// observation time, operator action and command argument arrays when known. + pub external_observation: Option, + /// Whether invoking the handler again is needed to refresh external status. + pub needs_external_refresh: bool, +} + +/// Standalone read-only summary handler. It never submits/checks children, +/// changes a stage, claims a request, or declares completion from child status. +pub async fn summarize_request( + store: &EntityDeletionStore, + request_id: Uuid, +) -> buzz_db::Result { + let saved = store.inspect(request_id).await?; + let completed_stages = saved + .stage_history + .iter() + .filter(|row| row.status == "completed") + .count(); + let unfinished_stages: Vec<_> = saved + .stage_history + .iter() + .filter(|row| row.status != "completed") + .map(|row| { + let observation = row.metadata_json.get("waiting").cloned(); + UnfinishedStage { + stage: row.clone(), + state: if row.status == "running" && observation.is_some() { + "waiting_external".into() + } else { + row.status.clone() + }, + needs_external_refresh: observation.is_some(), + external_observation: observation, + } + }) + .collect(); + let communities_not_reached = saved + .request + .inventory_manifest + .as_ref() + .and_then(|inventory| inventory["communities"].as_array()) + .into_iter() + .flatten() + .filter(|community| { + !saved.stage_history.iter().any(|row| { + row.target_community_id + .is_some_and(|id| community["community_id"] == id.to_string()) + }) + }) + .cloned() + .collect(); + let complete = saved.request.status == "completed" && unfinished_stages.is_empty(); + let explanation = if complete { + "The parent request is complete and every reached stage is complete. Any retained-copy obligations remain in the saved results." + } else if unfinished_stages + .iter() + .any(|row| row.needs_external_refresh) + { + "The request is unfinished. External statuses are last-observed snapshots, not live checks. Revisit those stage handlers to refresh them; this summary performs no external work." + } else { + "The request is unfinished. Inspect its approval, retry and stage state. Completed reached stages do not prove that all workflow steps have been reached." + }; + Ok(RequestSummary { + saved, + complete, + completed_stages, + unfinished_stages, + communities_not_reached, + explanation, + }) +} diff --git a/crates/buzz-deletion/src/user/worker.rs b/crates/buzz-deletion/src/user/worker.rs index 3cf6afe6500..f8df167da97 100644 --- a/crates/buzz-deletion/src/user/worker.rs +++ b/crates/buzz-deletion/src/user/worker.rs @@ -121,6 +121,8 @@ async fn run_stage_with_heartbeat( // Poll renewal alongside the handler. Awaiting renewal inside a selected // timer branch would stop polling a handler that may hold the parent lock. // Both futures live here, so cancellation leaves no detached heartbeat task. + // A handler can finish mid-heartbeat; `heartbeat` is one autocommit + // statement so that drop cannot strand an open transaction on the pool. let renewal = async { loop { interval.tick().await; diff --git a/crates/buzz-dev-mcp/src/shell.rs b/crates/buzz-dev-mcp/src/shell.rs index 028e8ec8da5..33577338428 100644 --- a/crates/buzz-dev-mcp/src/shell.rs +++ b/crates/buzz-dev-mcp/src/shell.rs @@ -1016,7 +1016,9 @@ mod tests { ShellParams { command: "echo hello".into(), workdir: None, - timeout_ms: Some(5_000), + // The production default: a cold Git Bash start on a Windows + // runner can take more than 5 s. `timeout_fires` covers timeouts. + timeout_ms: None, }, CancellationToken::new(), ) @@ -1064,7 +1066,7 @@ mod tests { ShellParams { command: "pwd".into(), workdir: Some(sub.display().to_string()), - timeout_ms: Some(5_000), + timeout_ms: None, }, CancellationToken::new(), ) diff --git a/crates/buzz-feature-flags/Cargo.toml b/crates/buzz-feature-flags/Cargo.toml index 258b54cf6dd..a989789fac0 100644 --- a/crates/buzz-feature-flags/Cargo.toml +++ b/crates/buzz-feature-flags/Cargo.toml @@ -18,5 +18,4 @@ thiserror = { workspace = true } [dev-dependencies] serde_json = { workspace = true } -tempfile = "3" tokio = { workspace = true } diff --git a/crates/buzz-feature-flags/README.md b/crates/buzz-feature-flags/README.md index 6210701a6e5..a9247fe3f9d 100644 --- a/crates/buzz-feature-flags/README.md +++ b/crates/buzz-feature-flags/README.md @@ -15,7 +15,8 @@ Provider-neutral types: - `BooleanFlag` - `IntegerFlag` (`i64`, including negative values) -- `EvaluationContext` (required `CommunityId`, optional actor `PublicKey`) +- `EvaluationContext` (a `CommunityId` with an optional actor `PublicKey`, or + `for_process()` for process-wide settings such as concurrency caps) - `FlagEvaluator` (typed `evaluate_bool` and `evaluate_int`) - `StaticEvaluator` (always returns declared defaults) - `EnvironmentEvaluator` (process-wide immutable environment snapshot) @@ -46,164 +47,38 @@ Normalized names must be unique across declared flags. Collisions (for example uniqueness belongs in a future flag registry; this crate does not add a registry yet. -## Relay Artifact Contract (not yet wired into `buzz-relay`) - -The intended composition root is the outer relay artifact. It must select -exactly one provider at compile time: - -- `static-feature-flags` -- `environment-feature-flags` -- `launchdarkly-feature-flags` - -`launchdarkly-feature-flags` is the only relay feature that forwards to -`buzz-feature-flags/launchdarkly`. `static-feature-flags` and -`environment-feature-flags` keep the reusable crate vendor-neutral and still -allow adapter code to compile in tests. - -The relay artifact boundary, not this reusable crate, owns exact-one -enforcement. Consumer integration PRs must carry `exact-one compile_error guards` -verbatim/equivalently. That keeps `buzz-feature-flags` free to compile multiple -adapters for tests while ensuring a staging or production relay artifact cannot -choose a different evaluator at runtime. - -This repository currently adds the crate and adapter, but does **not** yet wire -relay `AppState` or handlers to consume it. `crates/buzz-relay/Cargo.toml` -still has no dependency on `buzz-feature-flags`, so current workspace/default -builds remain intentionally unchanged. The executable contract for the future -relay integration lives in -`tests/fixtures/relay-feature-selection`. - -## Composition Root Shape (artifact boundary) - -Construct once at process startup, then inject shared `Arc` -into server components. - -```rust -use std::sync::Arc; -use std::time::Duration; - -use buzz_feature_flags::{EnvironmentEvaluator, FlagEvaluator, StaticEvaluator}; -#[cfg(feature = "launchdarkly-feature-flags")] -use buzz_feature_flags::launchdarkly::{ - LaunchDarklyEvaluator, LaunchDarklyInitError, LaunchDarklyRuntimeConfig, - LaunchDarklyStartError, -}; - -#[cfg(not(any( - feature = "static-feature-flags", - feature = "environment-feature-flags", - feature = "launchdarkly-feature-flags", -)))] -compile_error!( - "select exactly one relay feature flag provider feature: static-feature-flags, environment-feature-flags, or launchdarkly-feature-flags" -); - -#[cfg(any( - all(feature = "static-feature-flags", feature = "environment-feature-flags"), - all(feature = "static-feature-flags", feature = "launchdarkly-feature-flags"), - all(feature = "environment-feature-flags", feature = "launchdarkly-feature-flags"), -))] -compile_error!( - "select exactly one relay feature flag provider feature: static-feature-flags, environment-feature-flags, or launchdarkly-feature-flags" -); - -#[cfg(any(feature = "static-feature-flags", feature = "environment-feature-flags"))] -#[derive(Default)] -struct FeatureFlagRuntimeConfig; - -#[cfg(feature = "launchdarkly-feature-flags")] -struct FeatureFlagRuntimeConfig { - sdk_key: String, - relay_proxy_endpoint: Option, -} - -struct RelayCompositionRoot { - feature_flags: Arc, - environment_diagnostics: Option>, - #[cfg(feature = "launchdarkly-feature-flags")] - launchdarkly_lifecycle: Option>, -} - -#[cfg(feature = "launchdarkly-feature-flags")] -enum RelayStartupError { - LaunchDarklyInit(LaunchDarklyInitError), - LaunchDarklyStart(LaunchDarklyStartError), -} - -#[cfg(feature = "static-feature-flags")] -fn build_feature_flag_evaluator(_config: FeatureFlagRuntimeConfig) -> RelayCompositionRoot { - RelayCompositionRoot { - feature_flags: Arc::new(StaticEvaluator), - environment_diagnostics: None, - } -} - -#[cfg(feature = "environment-feature-flags")] -fn build_feature_flag_evaluator(config: FeatureFlagRuntimeConfig) -> RelayCompositionRoot { - let _ = config; - let owner = Arc::new(EnvironmentEvaluator::from_process_environment()); - let feature_flags: Arc = owner.clone(); - RelayCompositionRoot { - feature_flags, - environment_diagnostics: Some(owner), - } -} - -#[cfg(feature = "launchdarkly-feature-flags")] -async fn build_feature_flag_evaluator( - config: FeatureFlagRuntimeConfig, -) -> Result { - let mut runtime_config = LaunchDarklyRuntimeConfig::new(config.sdk_key); - if let Some(relay_proxy_endpoint) = config.relay_proxy_endpoint { - runtime_config = runtime_config.with_relay_proxy_endpoint(relay_proxy_endpoint); - } - - let owner = Arc::new( - LaunchDarklyEvaluator::from_runtime_config(runtime_config) - .map_err(RelayStartupError::LaunchDarklyInit)?, - ); - owner - .start_with_default_executor_and_wait(Duration::from_secs(5)) - .await - .map_err(RelayStartupError::LaunchDarklyStart)?; - - let feature_flags: Arc = owner.clone(); - Ok(RelayCompositionRoot { - feature_flags, - environment_diagnostics: None, - launchdarkly_lifecycle: Some(owner), - }) -} -``` - -Each relay feature produces exactly one `build_feature_flag_evaluator` path, and -runtime config carries only the selected provider's settings. There is no -runtime provider enum, no provider-name environment variable, and no fallback -selector. - -Startup is fail-closed: if the selected provider fails initialization (including -`start_with_default_executor_and_wait` for LaunchDarkly), relay startup must -return an error and stop rather than falling back to another evaluator. - -The extra concrete `Arc` is an owner/lifecycle handle to that same evaluator, -not a layered provider. Consumers receive only the cloned `Arc` view. Retain the environment owner to drain diagnostics after -evaluations, and retain the LaunchDarkly owner so shutdown can call `close()`. - -`EnvironmentEvaluator` snapshots environment values once at construction, -retains only `BUZZ_FEATURE_FLAG_` entries, ignores `EvaluationContext`, and -never rereads process environment during evaluation. - -For deterministic tests or embedding, `EnvironmentEvaluator::from_pairs(...)` -constructs the same immutable snapshot from explicit key/value pairs. - -Environment entries are untyped at construction, so malformed present values -are detected when a typed flag is first evaluated. `take_diagnostics()` drains -each sanitized diagnostic at most once per flag key and expected type. The -composition root should retain the concrete environment evaluator and emit each -drained diagnostic as a warning through the application's logging stack. -Diagnostics contain no raw value or environment-variable name; the value -snapshot itself remains immutable. +## Relay Provider Selection + +`buzz-relay` builds exactly one evaluator at startup, chosen by +`BUZZ_FEATURE_FLAGS_PROVIDER` (outside the `BUZZ_FEATURE_FLAG_` namespace, so +it can never be read as a flag): + +| Value | Evaluator | +|-------|-----------| +| unset, `static` | `StaticEvaluator` | +| `environment` | `EnvironmentEvaluator::from_process_environment()` | +| `launchdarkly` | `LaunchDarklyEvaluator`, from `BUZZ_LAUNCHDARKLY_SDK_KEY` and the optional Relay Proxy URL `BUZZ_LAUNCHDARKLY_RELAY_PROXY_URL` | + +The value is parsed into one provider; there is no stacking, no precedence and +no fallback from one provider to another, and the evaluator never changes for +the life of the process. Every relay build carries the LaunchDarkly adapter +(`buzz-feature-flags/launchdarkly`), which stays inert unless selected, so one +published artifact serves every deployment and the deployment's configuration +pins its provider. + +The composition root lives in `crates/buzz-relay/src/feature_flags.rs`. It +constructs the evaluator once and hands consumers the shared +`Arc`, keeping the concrete owner to drain environment +diagnostics and to call LaunchDarkly's `close()` at shutdown. + +Startup fails on a local configuration error: an unknown provider, +`launchdarkly` without an SDK key, or a malformed Relay Proxy URL. It does not +fail when LaunchDarkly is unreachable: the relay waits briefly for flag data, +then serves declared defaults while the SDK keeps connecting, and +`buzz_feature_flags_ready{provider}` reports whether the provider has +initialized. Once initialized, LaunchDarkly serves its last-known values +through a later outage, so the gauge stays 1 and flag values do not revert to +defaults until the SDK reconnects and receives new data. ## `buzz-db` Boundary (approved correction) @@ -253,8 +128,9 @@ operation already receives an authoritative authenticated actor for domain behavior. Feature targeting must not add actor/pubkey parameters to otherwise actor-free DB APIs. -For LaunchDarkly, the adapter context always includes kind `community` plus -optional global kind `pubkey`. Percentage rollouts must explicitly choose a +For LaunchDarkly, a community evaluation always includes kind `community` plus +optional global kind `pubkey`; a process evaluation is a single kind `relay` +context keyed `relay`. Percentage rollouts must explicitly choose a kind present in evaluation: rollouts must set `contextKind` to a kind present in evaluation (`community` or `pubkey`) when they are intended to bucket Buzz traffic. LaunchDarkly rollouts where configuration omits `contextKind` defaults @@ -265,7 +141,11 @@ zero and pick the first positive-weight variation. - Evaluation context inputs are authoritative server-resolved values (`community`, optional `actor`), not client-supplied targeting attributes. -- Flags may choose between **equivalent** implementations only. +- Flags may choose between **equivalent** implementations only, with one + exception: an operational limit (a concurrency cap) may be set by a flag + when the flag can only *tighten* it. The consumer clamps the value to a + ceiling fixed at startup, and a missing, non-positive or unavailable value + means the ceiling. Shedding under such a limit must be retryable. - Flags must not weaken authorization, tenant isolation, ordering guarantees, transaction/consistency behavior, or schema invariants. - Declared defaults choose the established safe path. @@ -283,12 +163,13 @@ zero and pick the first positive-weight variation. - LaunchDarkly numbers are SDK `f64` values. Integer evaluation accepts only mathematically integral values that convert to `i64` exactly from that `f64` representation; otherwise it returns each flag's declared default. -- Startup chooses one evaluator at compile time (`StaticEvaluator`, +- Startup chooses one evaluator from configuration (`StaticEvaluator`, `EnvironmentEvaluator`, or LaunchDarkly); provider precedence/stacking is out of scope. - If LaunchDarkly is used, call evaluator `close()` during process shutdown. - `close()` blocks the calling thread while it flushes analytics, so async - shutdown code should offload it to a blocking shutdown path. + `close()` blocks the calling thread while it flushes analytics and has no + deadline of its own, so async shutdown code should run it off the runtime + and bound the wait (the relay gives it a detached thread and 2 s). - Safety invariants must never rely on remote-flag availability. ## Build and Test Expectations @@ -319,16 +200,6 @@ cargo tree -p buzz-feature-flags --features launchdarkly Testing expectations: - Run provider-neutral tests and LaunchDarkly-feature tests for this crate. -- Run the relay-artifact compile contract in - `tests/relay_feature_selection_contract.rs`, including zero-feature and - multiple-feature rejection. -- Keep `tests/fixtures/relay-feature-selection/Cargo.lock` checked in for the - nested `--locked` compile contract. Regenerate it from repo root with: - -```bash -cargo generate-lockfile --manifest-path crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.toml -``` - - When `buzz-db` adopts flag-gated query selection, add parity tests proving old/new query paths return equivalent rows, ordering, and transactional behavior for the same inputs. diff --git a/crates/buzz-feature-flags/src/launchdarkly.rs b/crates/buzz-feature-flags/src/launchdarkly.rs index f5ce4a33c86..b966ab96321 100644 --- a/crates/buzz-feature-flags/src/launchdarkly.rs +++ b/crates/buzz-feature-flags/src/launchdarkly.rs @@ -10,6 +10,9 @@ use crate::{BooleanFlag, EvaluationContext, FlagEvaluator, IntegerFlag}; const COMMUNITY_CONTEXT_KIND: &str = "community"; const PUBKEY_CONTEXT_KIND: &str = "pubkey"; +/// Kind and key of the single context that process-wide settings evaluate. +const RELAY_CONTEXT_KIND: &str = "relay"; +const RELAY_CONTEXT_KEY: &str = "relay"; /// Runtime inputs required to initialize a LaunchDarkly-backed evaluator. #[derive(Clone)] @@ -145,6 +148,12 @@ impl LaunchDarklyEvaluator { } } + /// Whether the SDK has received flag data. Until it has, every evaluation + /// returns the flag's declared default. + pub fn initialized(&self) -> bool { + self.client.initialized() + } + /// Gracefully stop background tasks and flush pending analytics events. /// /// This call blocks the current thread until pending analytics delivery @@ -264,10 +273,16 @@ fn authority_has_explicit_port(authority: &Authority) -> bool { /// Build the LaunchDarkly context used for evaluation. /// -/// The adapter always includes a `community` kind context and optionally adds a -/// global `pubkey` kind context when an actor is present. +/// A community evaluation always includes a `community` kind context and +/// optionally adds a global `pubkey` kind context when an actor is present. +/// The process context is a single `relay` kind context keyed `relay`. fn launchdarkly_context(context: &EvaluationContext) -> Result { - let mut community = ContextBuilder::new(context.community().to_string()); + let Some(community_id) = context.community() else { + let mut relay = ContextBuilder::new(RELAY_CONTEXT_KEY); + relay.kind(RELAY_CONTEXT_KIND); + return relay.build(); + }; + let mut community = ContextBuilder::new(community_id.to_string()); community.kind(COMMUNITY_CONTEXT_KIND); let community = community.build()?; @@ -665,6 +680,34 @@ mod tests { evaluator.close(); } + #[tokio::test] + async fn process_context_targets_relay_kind_and_sees_updates_without_restart() { + let test_data = TestData::new(); + test_data.update( + FlagBuilder::new("process-int") + .variations([FlagValue::from(0_i64), FlagValue::from(5_i64)]) + .fallthrough_variation_index(0) + .variation_index_for_key(kind("relay"), "relay", 1), + ); + let evaluator = started_evaluator(&test_data).await; + let flag = IntegerFlag::new("process-int", -1); + let context = EvaluationContext::for_process(); + + assert_eq!(evaluator.evaluate_int(flag, &context), 5); + test_data.update( + FlagBuilder::new("process-int") + .variations([FlagValue::from(0_i64), FlagValue::from(9_i64)]) + .fallthrough_variation_index(0) + .variation_index_for_key(kind("relay"), "relay", 1), + ); + assert_eq!( + evaluator.evaluate_int(flag, &context), + 9, + "a running evaluator serves the updated value" + ); + evaluator.close(); + } + #[tokio::test] async fn actor_context_targets_integer_variation_by_community_and_pubkey() { let community = community("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); diff --git a/crates/buzz-feature-flags/src/lib.rs b/crates/buzz-feature-flags/src/lib.rs index c9169b176bb..9b3740a4275 100644 --- a/crates/buzz-feature-flags/src/lib.rs +++ b/crates/buzz-feature-flags/src/lib.rs @@ -14,22 +14,33 @@ pub use flags::{BooleanFlag, IntegerFlag}; /// LaunchDarkly-backed evaluator adapter. pub mod launchdarkly; -/// Stable targeting context for one Buzz community and an optional actor. +/// Stable targeting context: one Buzz community and an optional actor, or the +/// relay process itself. /// -/// Community is always required because the same Nostr identity can participate -/// in multiple isolated Buzz communities. Community-only contexts support -/// background and system evaluations that have no actor. +/// Community contexts are the norm, because the same Nostr identity can +/// participate in multiple isolated Buzz communities. Community-only contexts +/// support background and system evaluations that have no actor. The process +/// context is for settings that belong to the relay process rather than to any +/// community, such as concurrency caps shared by every community it serves. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct EvaluationContext { - community: CommunityId, + community: Option, actor_pubkey: Option, } impl EvaluationContext { + /// Construct the context for process-wide settings: no community, no actor. + pub const fn for_process() -> Self { + Self { + community: None, + actor_pubkey: None, + } + } + /// Construct a community-only evaluation context. pub const fn for_community(community: CommunityId) -> Self { Self { - community, + community: Some(community), actor_pubkey: None, } } @@ -37,13 +48,13 @@ impl EvaluationContext { /// Construct an evaluation context for an actor within one community. pub const fn for_actor(community: CommunityId, actor_pubkey: PublicKey) -> Self { Self { - community, + community: Some(community), actor_pubkey: Some(actor_pubkey), } } - /// Community that owns this evaluation. - pub const fn community(&self) -> CommunityId { + /// Community that owns this evaluation; `None` for the process context. + pub const fn community(&self) -> Option { self.community } @@ -128,7 +139,7 @@ mod tests { impl FlagEvaluator for CommunityEvaluator { fn evaluate_bool(&self, flag: BooleanFlag, context: &EvaluationContext) -> bool { - if context.community() == self.enabled_community { + if context.community() == Some(self.enabled_community) { true } else { flag.default() @@ -136,7 +147,7 @@ mod tests { } fn evaluate_int(&self, flag: IntegerFlag, context: &EvaluationContext) -> i64 { - if context.community() == self.enabled_community { + if context.community() == Some(self.enabled_community) { 41 } else { flag.default() @@ -186,7 +197,7 @@ mod tests { } fn evaluate_int(&self, flag: IntegerFlag, context: &EvaluationContext) -> i64 { - if context.community() == self.enabled_community + if context.community() == Some(self.enabled_community) && context.actor_pubkey() == Some(&self.expected_actor) { 99 diff --git a/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.lock b/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.lock deleted file mode 100644 index 089c0108ccc..00000000000 --- a/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.lock +++ /dev/null @@ -1,2797 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "aead" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" -dependencies = [ - "crypto-common 0.1.7", - "generic-array", -] - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - -[[package]] -name = "arrayvec" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "aws-lc-rs" -version = "1.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" -dependencies = [ - "aws-lc-sys", - "untrusted 0.7.1", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" -dependencies = [ - "cc", - "cmake", - "dunce", - "fs_extra", - "pkg-config", -] - -[[package]] -name = "base16ct" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "base64" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" - -[[package]] -name = "base64ct" -version = "1.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" - -[[package]] -name = "bech32" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32637268377fc7b10a8c6d51de3e7fba1ce5dd371a96e342b34e6078db558e7f" - -[[package]] -name = "bip39" -version = "2.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc" -dependencies = [ - "bitcoin_hashes", - "serde", - "unicode-normalization", -] - -[[package]] -name = "bitcoin-consensus-encoding" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6712f9c6fd6785b3b270884e57c441c403dc5d7e19ca45368c97c7a1de3000ec" -dependencies = [ - "bitcoin-internals", - "hex-conservative 1.3.0", - "serde", -] - -[[package]] -name = "bitcoin-internals" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d573f4cf32996a8dce612e4348cece65a241f1882ed594047c9ba348e8869fa5" - -[[package]] -name = "bitcoin-io" -version = "0.1.101" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb5de036369d1ac59d3c1819ebc4d850f89466f5401c571a285b6ed564a4cb78" -dependencies = [ - "bitcoin-consensus-encoding", -] - -[[package]] -name = "bitcoin_hashes" -version = "0.14.101" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bca4c7abb40c8817d77403c880988cfd484f23ab2365726afb2f798363e2c4a2" -dependencies = [ - "bitcoin-io", - "hex-conservative 0.2.3", - "serde", -] - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-buffer" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "block-padding" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bs58" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "buzz-core" -version = "0.1.0" -dependencies = [ - "base64 0.22.1", - "chrono", - "hex", - "hmac 0.13.0", - "nostr", - "percent-encoding", - "rand 0.10.3", - "serde", - "serde_json", - "sha2 0.11.0", - "subtle", - "thiserror", - "url", - "uuid", - "zeroize", -] - -[[package]] -name = "buzz-feature-flags" -version = "0.1.0" -dependencies = [ - "buzz-core", - "http", - "launchdarkly-server-sdk", - "thiserror", -] - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" - -[[package]] -name = "cbc" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" -dependencies = [ - "cipher", -] - -[[package]] -name = "cc" -version = "1.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "chacha20" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures 0.2.17", -] - -[[package]] -name = "chacha20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", - "rand_core 0.10.1", -] - -[[package]] -name = "chacha20poly1305" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" -dependencies = [ - "aead", - "chacha20 0.9.1", - "cipher", - "poly1305", - "zeroize", -] - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "cidr" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "579504560394e388085d0c080ea587dfa5c15f7e251b4d5247d1e1a61d1d6928" - -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common 0.1.7", - "inout", - "zeroize", -] - -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - -[[package]] -name = "cmov" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" - -[[package]] -name = "const-oid" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" - -[[package]] -name = "core-foundation" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "rand_core 0.6.4", - "typenum", -] - -[[package]] -name = "crypto-common" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "ctutils" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0" -dependencies = [ - "cmov", -] - -[[package]] -name = "darling" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 3.0.6", -] - -[[package]] -name = "darling_macro" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" -dependencies = [ - "darling_core", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "data-encoding" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" - -[[package]] -name = "defmt" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" -dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "defmt-parser" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" -dependencies = [ - "thiserror", -] - -[[package]] -name = "deranged" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -dependencies = [ - "serde_core", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", - "subtle", -] - -[[package]] -name = "digest" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" -dependencies = [ - "block-buffer 0.12.1", - "const-oid", - "crypto-common 0.2.2", - "ctutils", -] - -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "dyn-clone" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" - -[[package]] -name = "either" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "eventsource-client" -version = "0.17.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96df8cfa11d3c8e4e1a48b81c9c600ecbe8c11d1326f41e1524cc4d42f7bf6d9" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures", - "http", - "launchdarkly-sdk-transport", - "log", - "pin-project", - "rand 0.10.3", - "tokio", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" - -[[package]] -name = "flate2" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" -dependencies = [ - "crc32fast", - "miniz_oxide", - "zlib-rs", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - -[[package]] -name = "futures" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" - -[[package]] -name = "futures-executor" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" - -[[package]] -name = "futures-macro" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "futures-sink" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" - -[[package]] -name = "futures-task" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" - -[[package]] -name = "futures-util" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", - "rand_core 0.10.1", -] - -[[package]] -name = "h2" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http", - "indexmap 2.14.2", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "headers" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb" -dependencies = [ - "base64 0.22.1", - "bytes", - "headers-core", - "http", - "httpdate", - "mime", - "sha1", -] - -[[package]] -name = "headers-core" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" -dependencies = [ - "http", -] - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hex-conservative" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db3fef046dca3ca91ee1408a8c1b80ab777e80a4d308d1bf4e7adb3fcb047e08" -dependencies = [ - "arrayvec", -] - -[[package]] -name = "hex-conservative" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271e0d19bcb473b6675739a2b536076b24a082316cb5199ad918edce10c599e8" -dependencies = [ - "arrayvec", -] - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "hmac" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" -dependencies = [ - "digest 0.11.3", -] - -[[package]] -name = "http" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "http-body" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hybrid-array" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" -dependencies = [ - "typenum", -] - -[[package]] -name = "hyper" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "h2", - "http", - "http-body", - "httparse", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-http-proxy" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd1d471ea2f65ba45eddb1d6ab7d58ac2671d2d4ac14da5c6516ae1d97e1327a" -dependencies = [ - "bytes", - "futures-util", - "headers", - "http", - "hyper", - "hyper-rustls", - "hyper-util", - "pin-project-lite", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "rustls-native-certs", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-timeout" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" -dependencies = [ - "hyper", - "hyper-util", - "pin-project-lite", - "tokio", - "tower-service", -] - -[[package]] -name = "hyper-util" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "libc", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "icu_collections" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" - -[[package]] -name = "icu_properties" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" -dependencies = [ - "displaydoc", - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" - -[[package]] -name = "icu_provider" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "serde", -] - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown 0.17.1", - "serde", - "serde_core", -] - -[[package]] -name = "inout" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" -dependencies = [ - "block-padding", - "generic-array", -] - -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "jiff" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb" -dependencies = [ - "defmt", - "jiff-core", - "jiff-static", - "jiff-tzdb-platform", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", - "windows-link", -] - -[[package]] -name = "jiff-core" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" -dependencies = [ - "defmt", - "log", -] - -[[package]] -name = "jiff-static" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212" -dependencies = [ - "jiff-core", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "jiff-tzdb" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" - -[[package]] -name = "jiff-tzdb-platform" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" -dependencies = [ - "jiff-tzdb", -] - -[[package]] -name = "jobserver" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" -dependencies = [ - "getrandom 0.4.3", - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "launchdarkly-sdk-transport" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "032d66802c461d7254ed1de887be6ca98ebbe126867d9a60c754baae81c4d10d" -dependencies = [ - "bytes", - "futures", - "http", - "http-body-util", - "hyper", - "hyper-http-proxy", - "hyper-rustls", - "hyper-timeout", - "hyper-util", - "log", - "no-proxy", - "tower", -] - -[[package]] -name = "launchdarkly-server-sdk" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22259877ec581fa56a9f0b982e583e16fa01b71ba6d3f786ef5ccfc6ca6f92ff" -dependencies = [ - "aws-lc-rs", - "bitflags 2.13.2", - "bytes", - "chrono", - "crossbeam-channel", - "data-encoding", - "eventsource-client", - "flate2", - "futures", - "http", - "launchdarkly-sdk-transport", - "launchdarkly-server-sdk-evaluation", - "log", - "lru", - "moka", - "parking_lot", - "rand 0.9.5", - "serde", - "serde_json", - "thiserror", - "tokio", - "tokio-stream", - "uuid", -] - -[[package]] -name = "launchdarkly-server-sdk-evaluation" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76560a130b2a7e7fdb9c56043168844cde483e08e7f0e4a5e178e3888edc4336" -dependencies = [ - "base16ct", - "chrono", - "itertools", - "lazy_static", - "log", - "maplit", - "regex", - "semver", - "serde", - "serde_json", - "serde_with", - "sha1", -] - -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "libc" -version = "0.2.189" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" - -[[package]] -name = "litemap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" - -[[package]] -name = "lru" -version = "0.16.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" - -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "mio" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "moka" -version = "0.12.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" -dependencies = [ - "crossbeam-channel", - "crossbeam-epoch", - "crossbeam-utils", - "equivalent", - "parking_lot", - "portable-atomic", - "smallvec", - "tagptr", - "uuid", -] - -[[package]] -name = "no-proxy" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd3f71e44f009513a82ac2612c0c2da7e2924fad776931164317baa9695e150" -dependencies = [ - "cidr", -] - -[[package]] -name = "nostr" -version = "0.44.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ff7b77ef428b40aa2834a6acbae38a0e104c98b306208ca4b87a420d579a4b" -dependencies = [ - "base64 0.22.1", - "bech32", - "bip39", - "bitcoin_hashes", - "cbc", - "chacha20 0.9.1", - "chacha20poly1305", - "getrandom 0.2.17", - "hex", - "instant", - "scrypt", - "secp256k1", - "serde", - "serde_json", - "unicode-normalization", - "url", -] - -[[package]] -name = "num-conv" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - -[[package]] -name = "openssl-probe" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-link", -] - -[[package]] -name = "password-hash" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" -dependencies = [ - "base64ct", - "rand_core 0.6.4", - "subtle", -] - -[[package]] -name = "pbkdf2" -version = "0.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" -dependencies = [ - "digest 0.10.7", - "hmac 0.12.1", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pin-project" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "pkg-config" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" - -[[package]] -name = "poly1305" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" -dependencies = [ - "cpufeatures 0.2.17", - "opaque-debug", - "universal-hash", -] - -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - -[[package]] -name = "portable-atomic-util" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" -dependencies = [ - "portable-atomic", -] - -[[package]] -name = "potential_utf" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" -dependencies = [ - "zerovec", -] - -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rand" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", -] - -[[package]] -name = "rand" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" -dependencies = [ - "chacha20 0.10.2", - "getrandom 0.4.3", - "rand_core 0.10.1", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "ref-cast" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "relay-feature-selection-fixture" -version = "0.0.0" -dependencies = [ - "buzz-feature-flags", -] - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted 0.9.0", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustls" -version = "0.23.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" -dependencies = [ - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-native-certs" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" -dependencies = [ - "openssl-probe", - "rustls-pki-types", - "schannel", - "security-framework", -] - -[[package]] -name = "rustls-pki-types" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" -dependencies = [ - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted 0.9.0", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "salsa20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" -dependencies = [ - "cipher", -] - -[[package]] -name = "schannel" -version = "0.1.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "schemars" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" -dependencies = [ - "dyn-clone", - "ref-cast", - "serde", - "serde_json", -] - -[[package]] -name = "schemars" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" -dependencies = [ - "dyn-clone", - "ref-cast", - "serde", - "serde_json", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "scrypt" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" -dependencies = [ - "password-hash", - "pbkdf2", - "salsa20", - "sha2 0.10.9", -] - -[[package]] -name = "secp256k1" -version = "0.29.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113" -dependencies = [ - "rand 0.8.8", - "secp256k1-sys", - "serde", -] - -[[package]] -name = "secp256k1-sys" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" -dependencies = [ - "cc", -] - -[[package]] -name = "security-framework" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" -dependencies = [ - "bitflags 2.13.2", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "serde_json" -version = "1.0.151" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_with" -version = "3.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4" -dependencies = [ - "base64 0.23.1", - "bs58", - "chrono", - "hex", - "indexmap 1.9.3", - "indexmap 2.14.2", - "jiff", - "schemars 0.9.0", - "schemars 1.2.2", - "serde_core", - "serde_json", - "serde_with_macros", - "time", -] - -[[package]] -name = "serde_with_macros" -version = "3.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d607aa01a3cb0ad757d6fd216136910db3c97b102fe686585689615a02dbcdc" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "sha1" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.1", - "digest 0.11.3", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" - -[[package]] -name = "socket2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "synstructure" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "tagptr" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" - -[[package]] -name = "thiserror" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "time" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" -dependencies = [ - "deranged", - "num-conv", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "time-macros" -version = "0.2.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "tinystr" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" - -[[package]] -name = "tokio" -version = "1.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" -dependencies = [ - "bytes", - "libc", - "mio", - "pin-project-lite", - "socket2", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-stream" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", - "tokio-util", -] - -[[package]] -name = "tokio-util" -version = "0.7.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "libc", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tower" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" -dependencies = [ - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "log", - "pin-project-lite", - "tracing-core", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicode-ident" -version = "1.0.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" - -[[package]] -name = "unicode-normalization" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "universal-hash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common 0.1.7", - "subtle", -] - -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", - "serde_derive", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "uuid" -version = "1.26.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" -dependencies = [ - "getrandom 0.4.3", - "js-sys", - "serde_core", - "wasm-bindgen", -] - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.4+wasi-0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.6", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "web-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "writeable" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" - -[[package]] -name = "yoke" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", - "synstructure", -] - -[[package]] -name = "zerocopy" -version = "0.8.57" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d35102a9f36d089ccae9e4c6802bc118be4487b80aaffc0ab4e0cf5ce92d2873" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.57" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c01f5ab44258da43cf276c74a2763db2ff3969c9c652c3f2de07041d0b2bc" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" - -[[package]] -name = "zerotrie" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.6", -] - -[[package]] -name = "zlib-rs" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.toml b/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.toml deleted file mode 100644 index 2f6cb93f201..00000000000 --- a/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "relay-feature-selection-fixture" -version = "0.0.0" -edition = "2021" -publish = false - -[workspace] - -[features] -static-feature-flags = [] -environment-feature-flags = [] -launchdarkly-feature-flags = ["buzz-feature-flags/launchdarkly"] - -[dependencies] -buzz-feature-flags = { path = "../../.." } diff --git a/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/src/lib.rs b/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/src/lib.rs deleted file mode 100644 index b979395fee2..00000000000 --- a/crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/src/lib.rs +++ /dev/null @@ -1,103 +0,0 @@ -#![allow(dead_code)] - -use std::sync::Arc; - -use buzz_feature_flags::{EnvironmentEvaluator, FlagEvaluator}; -#[cfg(feature = "static-feature-flags")] -use buzz_feature_flags::StaticEvaluator; -#[cfg(feature = "launchdarkly-feature-flags")] -use buzz_feature_flags::launchdarkly::{ - LaunchDarklyEvaluator, LaunchDarklyInitError, LaunchDarklyRuntimeConfig, -}; - -#[cfg(not(any( - feature = "static-feature-flags", - feature = "environment-feature-flags", - feature = "launchdarkly-feature-flags", -)))] -compile_error!( - "select exactly one relay feature flag provider feature: static-feature-flags, environment-feature-flags, or launchdarkly-feature-flags" -); - -#[cfg(any( - all(feature = "static-feature-flags", feature = "environment-feature-flags"), - all(feature = "static-feature-flags", feature = "launchdarkly-feature-flags"), - all(feature = "environment-feature-flags", feature = "launchdarkly-feature-flags"), -))] -compile_error!( - "select exactly one relay feature flag provider feature: static-feature-flags, environment-feature-flags, or launchdarkly-feature-flags" -); - -#[cfg(any(feature = "static-feature-flags", feature = "environment-feature-flags"))] -#[derive(Clone, Debug, Default)] -pub struct FeatureFlagRuntimeConfig; - -#[cfg(feature = "launchdarkly-feature-flags")] -#[derive(Clone, Debug)] -pub struct FeatureFlagRuntimeConfig { - pub sdk_key: String, - pub relay_proxy_endpoint: Option, -} - -pub struct FeatureFlagCompositionRoot { - pub feature_flags: Arc, - pub environment_diagnostics: Option>, - #[cfg(feature = "launchdarkly-feature-flags")] - pub launchdarkly_lifecycle: Option>, -} - -#[cfg(feature = "static-feature-flags")] -pub fn build_feature_flag_evaluator(_config: FeatureFlagRuntimeConfig) -> FeatureFlagCompositionRoot { - FeatureFlagCompositionRoot { - feature_flags: Arc::new(StaticEvaluator), - environment_diagnostics: None, - } -} - -#[cfg(feature = "environment-feature-flags")] -pub fn build_feature_flag_evaluator( - _config: FeatureFlagRuntimeConfig, -) -> FeatureFlagCompositionRoot { - let owner = Arc::new(EnvironmentEvaluator::from_process_environment()); - let feature_flags: Arc = owner.clone(); - FeatureFlagCompositionRoot { - feature_flags, - environment_diagnostics: Some(owner), - } -} - -#[cfg(feature = "launchdarkly-feature-flags")] -pub fn build_feature_flag_evaluator( - config: FeatureFlagRuntimeConfig, -) -> Result { - let mut runtime_config = LaunchDarklyRuntimeConfig::new(config.sdk_key); - if let Some(relay_proxy_endpoint) = config.relay_proxy_endpoint { - runtime_config = runtime_config.with_relay_proxy_endpoint(relay_proxy_endpoint); - } - - let owner = Arc::new(LaunchDarklyEvaluator::from_runtime_config(runtime_config)?); - let feature_flags: Arc = owner.clone(); - Ok(FeatureFlagCompositionRoot { - feature_flags, - environment_diagnostics: None, - launchdarkly_lifecycle: Some(owner), - }) -} - -#[cfg(feature = "static-feature-flags")] -pub fn compile_smoke() { - let _ = build_feature_flag_evaluator(FeatureFlagRuntimeConfig); -} - -#[cfg(feature = "environment-feature-flags")] -pub fn compile_smoke() { - let _ = build_feature_flag_evaluator(FeatureFlagRuntimeConfig); -} - -#[cfg(feature = "launchdarkly-feature-flags")] -pub fn compile_smoke() { - let _ = build_feature_flag_evaluator(FeatureFlagRuntimeConfig { - sdk_key: "fixture-sdk-key".to_owned(), - relay_proxy_endpoint: None, - }); -} diff --git a/crates/buzz-feature-flags/tests/relay_feature_selection_contract.rs b/crates/buzz-feature-flags/tests/relay_feature_selection_contract.rs deleted file mode 100644 index 120ad587879..00000000000 --- a/crates/buzz-feature-flags/tests/relay_feature_selection_contract.rs +++ /dev/null @@ -1,229 +0,0 @@ -use std::{ - env, - ffi::OsString, - path::{Path, PathBuf}, - process::Command, -}; -use tempfile::TempDir; - -const FIXTURE_LOCK_REGEN_RECIPE: &str = - "cargo generate-lockfile --manifest-path crates/buzz-feature-flags/tests/fixtures/relay-feature-selection/Cargo.toml"; - -fn fixture_manifest() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relay-feature-selection/Cargo.toml") -} - -fn fixture_lockfile() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relay-feature-selection/Cargo.lock") -} - -fn crate_readme() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md") -} - -fn cargo_bin() -> OsString { - env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")) -} - -fn cargo_check(target_dir: &Path, case_name: &str, features: &[&str]) -> std::process::Output { - let mut command = Command::new(cargo_bin()); - command - .current_dir(env!("CARGO_MANIFEST_DIR")) - .arg("check") - .arg("--quiet") - .arg("--locked") - .arg("--manifest-path") - .arg(fixture_manifest()) - .arg("--no-default-features") - .env("CARGO_TARGET_DIR", target_dir); - - if !features.is_empty() { - command.arg("--features").arg(features.join(",")); - } - - command - .output() - .unwrap_or_else(|error| { - panic!( - "failed to run cargo check for {case_name}: {error}\nfixture lock regeneration recipe: `{FIXTURE_LOCK_REGEN_RECIPE}`" - ) - }) -} - -fn format_valid_case_failed_status(case_name: &str, stdout: &str, stderr: &str) -> String { - format!( - "expected {case_name} to compile successfully\nstdout:\n{stdout}\nstderr:\n{stderr}\nregenerate fixture lock with `{FIXTURE_LOCK_REGEN_RECIPE}`" - ) -} - -fn format_invalid_case_missing_exact_one(case_name: &str, stderr: &str) -> String { - format!( - "expected {case_name} failure to explain the exact-one contract\nstderr:\n{stderr}\nregenerate fixture lock with `{FIXTURE_LOCK_REGEN_RECIPE}`" - ) -} - -fn assert_valid_case_success(case_name: &str, output: &std::process::Output) { - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - output.status.success(), - "{}", - format_valid_case_failed_status(case_name, &stdout, &stderr) - ); -} - -fn assert_invalid_case_has_exact_one_diagnostic(case_name: &str, output: &std::process::Output) { - assert!( - !output.status.success(), - "expected {case_name} to fail compilation" - ); - - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("select exactly one relay feature flag provider feature"), - "{}", - format_invalid_case_missing_exact_one(case_name, &stderr) - ); -} - -#[test] -fn relay_fixture_lock_regeneration_recipe_is_documented() { - let readme = std::fs::read_to_string(crate_readme()).expect("read crate README"); - assert!( - readme.contains(FIXTURE_LOCK_REGEN_RECIPE), - "README.md must document fixture lock regeneration with `{FIXTURE_LOCK_REGEN_RECIPE}`" - ); -} - -#[test] -fn relay_readme_documents_fail_closed_launchdarkly_startup_contract() { - let readme = std::fs::read_to_string(crate_readme()).expect("read crate README"); - - assert!( - readme.contains("start_with_default_executor_and_wait"), - "README.md must show LaunchDarkly startup via start_with_default_executor_and_wait" - ); - assert!( - readme.contains("async fn build_feature_flag_evaluator"), - "README.md must declare LaunchDarkly build_feature_flag_evaluator as async" - ); - assert!( - readme.contains( - "start_with_default_executor_and_wait(Duration::from_secs(5))\n .await" - ), - "README.md must await start_with_default_executor_and_wait" - ); - assert!( - readme.contains("fail-closed"), - "README.md must state fail-closed startup policy" - ); - assert!( - readme.contains("exact-one compile_error guards"), - "README.md must require exact-one compile_error guards in the consumer" - ); - assert!( - readme.contains("future flag registry"), - "README.md must defer environment-name uniqueness enforcement to a future registry" - ); - assert!( - readme.contains("kind `community` plus") - && readme.contains("optional global kind `pubkey`"), - "README.md must document LaunchDarkly adapter context kinds" - ); - assert!( - readme.contains("rollouts must set `contextKind` to a kind present") - && readme.contains("in evaluation"), - "README.md must document rollout contextKind requirements" - ); - assert!( - readme.contains("omits `contextKind` defaults") && readme.contains("to `user`;"), - "README.md must document LaunchDarkly default rollout context kind" - ); - assert!( - readme.contains("bucket as") - && readme.contains("zero and pick the first positive-weight variation"), - "README.md must document missing-kind rollout bucketing behavior" - ); - assert!( - readme.contains("close()` blocks the calling thread") - && readme.contains("while it flushes analytics"), - "README.md must document blocking LaunchDarkly close semantics" - ); - assert!( - readme.contains("offload it to a blocking shutdown path"), - "README.md must document async shutdown offloading guidance for close()" - ); -} - -#[test] -fn valid_case_failed_status_formatter_includes_fixture_lock_regeneration_recipe() { - let message = format_valid_case_failed_status( - "static", - "", - "error: lock file needs update but --locked was passed", - ); - assert!( - message.contains(FIXTURE_LOCK_REGEN_RECIPE), - "valid-case failure formatter must include fixture lock recipe\nmessage:\n{message}" - ); -} - -#[test] -fn invalid_case_missing_exact_one_formatter_includes_fixture_lock_regeneration_recipe() { - let message = - format_invalid_case_missing_exact_one("none", "error: unrelated nested cargo failure"); - assert!( - message.contains(FIXTURE_LOCK_REGEN_RECIPE), - "invalid-case failure formatter must include fixture lock recipe\nmessage:\n{message}" - ); -} - -#[test] -fn relay_artifact_provider_features_require_exactly_one_selection() { - assert!( - fixture_lockfile().is_file(), - "relay feature selection fixture must check in Cargo.lock for locked nested cargo runs\nregenerate it with `{FIXTURE_LOCK_REGEN_RECIPE}`" - ); - - let target_dir = TempDir::new().expect("temp target dir"); - - let valid_cases = [ - ("static", &["static-feature-flags"][..]), - ("environment", &["environment-feature-flags"][..]), - ("launchdarkly", &["launchdarkly-feature-flags"][..]), - ]; - - for (case_name, features) in valid_cases { - let output = cargo_check(target_dir.path(), case_name, features); - assert_valid_case_success(case_name, &output); - } - - let invalid_cases = [ - ("none", &[][..]), - ( - "static-and-environment", - &["static-feature-flags", "environment-feature-flags"][..], - ), - ( - "static-and-launchdarkly", - &["static-feature-flags", "launchdarkly-feature-flags"][..], - ), - ( - "environment-and-launchdarkly", - &["environment-feature-flags", "launchdarkly-feature-flags"][..], - ), - ( - "all-three", - &[ - "static-feature-flags", - "environment-feature-flags", - "launchdarkly-feature-flags", - ][..], - ), - ]; - - for (case_name, features) in invalid_cases { - let output = cargo_check(target_dir.path(), case_name, features); - assert_invalid_case_has_exact_one_diagnostic(case_name, &output); - } -} diff --git a/crates/buzz-media/Cargo.toml b/crates/buzz-media/Cargo.toml index 7808ecaff43..18a36fdc94e 100644 --- a/crates/buzz-media/Cargo.toml +++ b/crates/buzz-media/Cargo.toml @@ -25,6 +25,7 @@ s3 = { version = "0.37", package = "rust-s3", default-features = false, features infer = "0.19" image = { version = "0.25", default-features = false, features = ["jpeg", "png", "gif", "webp"] } blurhash = "0.2" +webp = { version = "0.3", default-features = false } imagesize = "0.14" bytes = "1" mp4 = "0.14" diff --git a/crates/buzz-media/src/bucket_index.rs b/crates/buzz-media/src/bucket_index.rs index 86a3eff7919..aad51d71fb4 100644 --- a/crates/buzz-media/src/bucket_index.rs +++ b/crates/buzz-media/src/bucket_index.rs @@ -13,7 +13,7 @@ //! //! | Class | Shape | //! |---|---| -//! | thumb | `{sha256}.thumb.jpg` | +//! | thumb | `{sha256}.thumb.{webp,jpg}` | //! | blob | `{sha256}.{ext}` (ext: 1-8 mixed-case alphanumeric) | //! | sidecar | `_meta/{community-uuid}/{sha256}.json` | //! | auxiliary | `_uploads/{community-uuid}/{sha256}/{ulid}.json` | @@ -25,6 +25,7 @@ use std::future::Future; use uuid::Uuid; use crate::error::MediaError; +use crate::thumbnail::Thumb; /// The classification of one bucket key. `Unknown` is the deliberate /// catch-all — a malformed variant of a known prefix (e.g. a truncated @@ -32,7 +33,7 @@ use crate::error::MediaError; /// `Auxiliary`, so visibility gauges stay loud instead of silently wrong. #[derive(Debug, Clone, PartialEq, Eq)] pub enum KeyClass { - /// `{sha256}.thumb.jpg` — attributed to the blob's sha. + /// `{sha256}.thumb.{webp,jpg}` — attributed to the blob's sha. Thumb { sha256: String }, /// `{sha256}.{ext}` — physical bytes, logical join key. Blob { sha256: String, ext: String }, @@ -125,16 +126,10 @@ fn parse_canonical_uuid(s: &str) -> Option { Uuid::parse_str(s).ok() } -/// `{sha256}.thumb.jpg` +/// `{sha256}.thumb.{webp,jpg}` fn parse_thumb_key(key: &str) -> Option { - let mut parts = key.split('.'); - let sha256 = parts.next()?; - let thumb = parts.next()?; - let jpg = parts.next()?; - if parts.next().is_some() || thumb != "thumb" || jpg != "jpg" || !is_sha256(sha256) { - return None; - } - Some(sha256.to_string()) + let (sha256, _) = Thumb::parse(key)?; + is_sha256(sha256).then(|| sha256.to_string()) } /// `{sha256}.{ext}` — exactly two dot-separated segments. @@ -233,8 +228,7 @@ pub struct BucketAggregate { /// sha -> bytes of every blob variant seen for that sha (D-EXT: multiple /// entries is the multi-variant anomaly). blob_variant_bytes: HashMap>, - /// sha -> thumb bytes. At most one thumb key per sha, so a plain insert - /// is correct (no accumulation needed). + /// sha -> bytes of every thumb variant for that sha. thumb_bytes: HashMap, /// (community, sha) -> sidecar object's own byte size (informational; /// not part of logical bytes). @@ -252,7 +246,7 @@ impl BucketAggregate { self.physical_bytes += size; match classify_key(key) { KeyClass::Thumb { sha256 } => { - self.thumb_bytes.insert(sha256, size); + *self.thumb_bytes.entry(sha256).or_default() += size; } KeyClass::Blob { sha256, .. } => { self.blob_variant_bytes @@ -448,10 +442,13 @@ mod tests { #[test] fn classifies_thumb_key() { let s = sha(0xaa); - assert_eq!( - classify_key(&format!("{s}.thumb.jpg")), - KeyClass::Thumb { sha256: s } - ); + for ext in ["webp", "jpg"] { + assert_eq!( + classify_key(&format!("{s}.thumb.{ext}")), + KeyClass::Thumb { sha256: s.clone() } + ); + } + assert_eq!(classify_key(&format!("{s}.thumb.png")), KeyClass::Unknown); } #[test] @@ -630,14 +627,15 @@ mod tests { let mut agg = BucketAggregate::default(); agg.fold(&format!("{s}.jpg"), 1000); agg.fold(&format!("{s}.thumb.jpg"), 50); + agg.fold(&format!("{s}.thumb.webp"), 30); agg.fold(&format!("_meta/{c}/{s}.json"), 5); let snap = agg.finish(); - assert_eq!(snap.per_community[&c].bytes, 1050); + assert_eq!(snap.per_community[&c].bytes, 1080); assert_eq!(snap.per_community[&c].objects, 1); // Fleet physical totals count every object separately. - assert_eq!(snap.physical_objects, 3); - assert_eq!(snap.physical_bytes, 1055); + assert_eq!(snap.physical_objects, 4); + assert_eq!(snap.physical_bytes, 1085); } #[test] diff --git a/crates/buzz-media/src/storage.rs b/crates/buzz-media/src/storage.rs index abe6bdd40ea..f12c0f00519 100644 --- a/crates/buzz-media/src/storage.rs +++ b/crates/buzz-media/src/storage.rs @@ -459,7 +459,11 @@ impl MediaStorage { sha256: &str, ) -> Result { let key = Self::ctx_sidecar_key(ctx, sha256); - let resp = self.bucket.get_object(&key).await?; + let resp = match self.bucket.get_object(&key).await { + Ok(response) => response, + Err(s3::error::S3Error::HttpFailWithBody(404, _)) => return Err(MediaError::NotFound), + Err(error) => return Err(error.into()), + }; let meta: BlobMeta = serde_json::from_slice(&resp.to_vec())?; Ok(meta) } diff --git a/crates/buzz-media/src/thumbnail.rs b/crates/buzz-media/src/thumbnail.rs index 580c4b9f93b..4906b09f3b2 100644 --- a/crates/buzz-media/src/thumbnail.rs +++ b/crates/buzz-media/src/thumbnail.rs @@ -8,9 +8,53 @@ use crate::config::MediaConfig; use crate::error::MediaError; use crate::storage::BlobMeta; -/// Generate thumbnail and blurhash from image bytes (CPU-bound, sync). +/// A stored thumbnail variant: `{sha256}.thumb.{ext}`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Thumb { + pub ext: &'static str, + pub mime: &'static str, +} + +/// Lossy WebP keeps alpha, so upload descriptors reference it. +pub const WEBP: Thumb = Thumb { + ext: "webp", + mime: "image/webp", +}; + +/// JPEG drops alpha. It stays for clients that derive `{sha256}.thumb.jpg`. +pub const JPEG: Thumb = Thumb { + ext: "jpg", + mime: "image/jpeg", +}; + +/// Every variant written for an image. +pub const THUMBS: [Thumb; 2] = [WEBP, JPEG]; + +/// One image's thumbnail bytes, in [`THUMBS`] order. +pub type ThumbBytes = [Vec; THUMBS.len()]; + +/// libwebp quality: ~13 KB for a 320px transparent avatar, about JPEG's size. +const WEBP_QUALITY: f32 = 80.0; + +impl Thumb { + /// Storage key and `/media/` path segment for `sha256`'s thumbnail. + pub fn key(self, sha256: &str) -> String { + format!("{sha256}.thumb.{}", self.ext) + } + + /// Split `{sha256}.thumb.{ext}` into its (unvalidated) hash and variant. + pub fn parse(name: &str) -> Option<(&str, Thumb)> { + let (sha256, ext) = name.split_once(".thumb.")?; + THUMBS + .into_iter() + .find(|t| t.ext == ext) + .map(|t| (sha256, t)) + } +} + +/// Generate thumbnails and blurhash from image bytes (CPU-bound, sync). /// -/// Returns `(metadata, optional thumbnail JPEG bytes)`. +/// Returns `(metadata, thumbnails)`, with no thumbnails for non-images. /// Caller handles S3 writes after `spawn_blocking` returns. pub fn generate_image_metadata_sync( config: &MediaConfig, @@ -18,21 +62,26 @@ pub fn generate_image_metadata_sync( bytes: &[u8], mime: &str, ext: &str, -) -> Result<(BlobMeta, Option>), MediaError> { +) -> Result<(BlobMeta, Option), MediaError> { if !mime.starts_with("image/") { return Ok((BlobMeta::default(), None)); } + crate::validation::check_image_pixels(bytes)?; let img = image::load_from_memory(bytes)?; let (w, h) = (img.width(), img.height()); // Thumbnail: 320px max dimension, preserve aspect ratio let thumb = img.thumbnail(320, 320); - let mut thumb_bytes = Vec::new(); - thumb.write_to(&mut Cursor::new(&mut thumb_bytes), ImageFormat::Jpeg)?; + let rgba = thumb.to_rgba8(); + let webp = webp::Encoder::from_rgba(&rgba, rgba.width(), rgba.height()) + .encode_simple(false, WEBP_QUALITY) + .map_err(|_| MediaError::Internal)? + .to_vec(); + let mut jpeg = Vec::new(); + thumb.write_to(&mut Cursor::new(&mut jpeg), ImageFormat::Jpeg)?; // Blurhash from thumbnail (faster than full image) - let rgba = thumb.to_rgba8(); let bh = blurhash::encode(4, 3, thumb.width(), thumb.height(), rgba.as_raw()).unwrap_or_default(); @@ -40,12 +89,12 @@ pub fn generate_image_metadata_sync( BlobMeta { dim: format!("{w}x{h}"), blurhash: bh, - thumb_url: format!("{}/{sha256}.thumb.jpg", config.public_base_url), + thumb_url: format!("{}/{}", config.public_base_url, WEBP.key(sha256)), ext: ext.to_string(), mime_type: mime.to_string(), size: bytes.len() as u64, ..BlobMeta::default() // uploaded_at set by caller (process_upload) }, - Some(thumb_bytes), + Some([webp, jpeg]), )) } diff --git a/crates/buzz-media/src/upload.rs b/crates/buzz-media/src/upload.rs index 1b998bf843e..0db9dfe0a46 100644 --- a/crates/buzz-media/src/upload.rs +++ b/crates/buzz-media/src/upload.rs @@ -9,7 +9,7 @@ use crate::auth::verify_upload_hash_only; use crate::config::MediaConfig; use crate::error::MediaError; use crate::storage::{BlobMeta, MediaStorage}; -use crate::thumbnail::generate_image_metadata_sync; +use crate::thumbnail::{generate_image_metadata_sync, THUMBS}; use crate::types::BlobDescriptor; use crate::upload_record::{record_upload_event, UploadAttribution, UploadEventFacts}; use crate::validation::{ @@ -516,22 +516,44 @@ async fn prepare_image_metadata( config: &MediaConfig, input: MetadataInput, ) -> Result { - let body_ref = input.body.clone(); - let mime_ref = input.mime.clone(); - let ext_ref = input.ext.clone(); - let sha256_ref = input.sha256.clone(); - let cfg_ref = config.clone(); - let (mut meta, thumb_bytes) = tokio::task::spawn_blocking(move || { - generate_image_metadata_sync(&cfg_ref, &sha256_ref, &body_ref, &mime_ref, &ext_ref) + let mut meta = store_image_thumbnails( + storage, + config, + &input.sha256, + input.body, + &input.mime, + &input.ext, + ) + .await?; + meta.uploaded_at = input.uploaded_at; + Ok(meta) +} + +/// Generate an image's metadata and store every thumbnail variant. +/// +/// Shared by the upload path and on-demand regeneration of missing thumbnails. +pub async fn store_image_thumbnails( + storage: &MediaStorage, + config: &MediaConfig, + sha256: &str, + body: Bytes, + mime: &str, + ext: &str, +) -> Result { + let (cfg_ref, sha256_ref, mime_ref, ext_ref) = ( + config.clone(), + sha256.to_owned(), + mime.to_owned(), + ext.to_owned(), + ); + let (meta, thumbs) = tokio::task::spawn_blocking(move || { + generate_image_metadata_sync(&cfg_ref, &sha256_ref, &body, &mime_ref, &ext_ref) }) .await .map_err(|_| MediaError::Internal)??; - meta.uploaded_at = input.uploaded_at; - - if let Some(ref tb) = thumb_bytes { - let thumb_key = format!("{}.thumb.jpg", input.sha256); - storage.put(&thumb_key, tb, "image/jpeg").await?; + for (thumb, bytes) in THUMBS.into_iter().zip(thumbs.into_iter().flatten()) { + storage.put(&thumb.key(sha256), &bytes, thumb.mime).await?; } Ok(meta) @@ -583,6 +605,64 @@ mod tests { } } + /// A 640x640 image, so its thumbnail is 320x320, whose left half has the + /// given alpha and right half is opaque red. + fn image_with_alpha(alpha: u8, format: image::ImageFormat) -> Vec { + let img = image::RgbaImage::from_fn(640, 640, |x, _| { + image::Rgba([255, 0, 0, if x < 320 { alpha } else { 255 }]) + }); + let mut bytes = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut bytes), format) + .unwrap(); + bytes + } + + #[test] + fn image_thumbnails_are_alpha_webp_and_jpeg() { + for (format, mime, ext) in [ + (image::ImageFormat::Png, "image/png", "png"), + (image::ImageFormat::Gif, "image/gif", "gif"), + ] { + let sha = "a".repeat(64); + let (meta, thumbs) = generate_image_metadata_sync( + &test_config(), + &sha, + &image_with_alpha(0, format), + mime, + ext, + ) + .unwrap(); + assert_eq!( + meta.thumb_url, + format!("https://media.example.com/{sha}.thumb.webp"), + "{ext}" + ); + let [webp, jpeg] = thumbs.unwrap(); + assert_eq!( + image::guess_format(&webp).unwrap(), + image::ImageFormat::WebP, + "{ext}" + ); + let decoded = image::load_from_memory(&webp).unwrap().to_rgba8(); + assert_eq!(decoded.dimensions(), (320, 320), "{ext}"); + assert_eq!( + decoded.get_pixel(0, 0)[3], + 0, + "{ext}: transparent stays transparent" + ); + assert_eq!( + decoded.get_pixel(319, 0)[3], + 255, + "{ext}: opaque stays opaque" + ); + assert_eq!( + image::guess_format(&jpeg).unwrap(), + image::ImageFormat::Jpeg, + "{ext}: JPEG stays for installed clients" + ); + } + } + #[test] fn test_build_descriptor_video_omits_empty_thumb_and_blurhash() { // Video uploads produce a BlobMeta with empty thumb_url and blurhash. @@ -649,7 +729,7 @@ mod tests { let meta = BlobMeta { dim: "800x600".to_string(), blurhash: "LEHV6nWB2yk8pyo0adR*.7kCMdnj".to_string(), - thumb_url: format!("https://media.example.com/{hash}.thumb.jpg"), + thumb_url: format!("https://media.example.com/{hash}.thumb.webp"), ext: "jpg".to_string(), mime_type: "image/jpeg".to_string(), size: 100_000, diff --git a/crates/buzz-media/src/validation.rs b/crates/buzz-media/src/validation.rs index 0a748ca8522..50305f9197b 100644 --- a/crates/buzz-media/src/validation.rs +++ b/crates/buzz-media/src/validation.rs @@ -277,16 +277,21 @@ pub fn validate_content(bytes: &[u8], config: &MediaConfig) -> Result Result<(), MediaError> { + const MAX_PIXELS: u64 = 25_000_000; let size = imagesize::blob_size(bytes).map_err(|_| MediaError::InvalidImage)?; if (size.width as u64) * (size.height as u64) > MAX_PIXELS { return Err(MediaError::ImageTooLarge); } - - Ok(mime) + Ok(()) } /// Validate an MP4 file on disk. diff --git a/crates/buzz-pairing-cli/src/main.rs b/crates/buzz-pairing-cli/src/main.rs index 2d03d594a8a..8341fb097df 100644 --- a/crates/buzz-pairing-cli/src/main.rs +++ b/crates/buzz-pairing-cli/src/main.rs @@ -27,6 +27,11 @@ use clap::{Parser, Subcommand}; use futures_util::{SinkExt, StreamExt}; use nostr::{Event, EventBuilder, Keys, RelayUrl, SecretKey, ToBech32}; use tokio::time::timeout; +use tokio_tungstenite::tungstenite::{ + client::IntoClientRequest, + handshake::client::Request, + http::{header::USER_AGENT, HeaderValue}, +}; use tokio_tungstenite::{connect_async, tungstenite::Message}; use zeroize::Zeroizing; @@ -133,7 +138,7 @@ async fn cmd_source(relay_url: String, nsec: Option) -> Result<(), CliEr // Connect to relay and handle NIP-42 auth if required. // Auth uses the session's ephemeral keys so the relay accepts our events. - let (ws, _) = connect_async(&relay_url).await?; + let (ws, _) = connect_async(relay_request(&relay_url)?).await?; let (mut write, mut read) = ws.split(); handle_nip42_auth(&mut read, &mut write, &session, &relay_url).await?; @@ -235,7 +240,7 @@ async fn cmd_target(relay_override: Option, show_secret: bool) -> Result let (mut session, offer_event) = PairingSession::new_target(&qr)?; // Connect to relay and handle NIP-42 auth if required. - let (ws, _) = connect_async(&relay_url).await?; + let (ws, _) = connect_async(relay_request(&relay_url)?).await?; let (mut write, mut read) = ws.split(); handle_nip42_auth(&mut read, &mut write, &session, &relay_url).await?; @@ -629,3 +634,27 @@ fn hex_to_32(s: &str) -> Result<[u8; 32], CliError> { .try_into() .map_err(|_| CliError::Other(format!("expected 32 bytes, got wrong length for '{s}'"))) } + +/// `User-Agent` sent on the relay WebSocket upgrade. +const RELAY_USER_AGENT: &str = concat!("buzz-pairing-cli/", env!("CARGO_PKG_VERSION")); + +/// The relay upgrade request for `url`, naming this tool and its version. +fn relay_request(url: &str) -> Result { + let mut request = url.into_client_request()?; + request + .headers_mut() + .insert(USER_AGENT, HeaderValue::from_static(RELAY_USER_AGENT)); + Ok(request) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relay_request_carries_user_agent() { + let request = relay_request("wss://relay.example.com").unwrap(); + assert_eq!(request.headers()[USER_AGENT], RELAY_USER_AGENT); + assert!(RELAY_USER_AGENT.starts_with("buzz-pairing-cli/")); + } +} diff --git a/crates/buzz-pubsub/Cargo.toml b/crates/buzz-pubsub/Cargo.toml index 2ee2d6b47dd..0d859b5e8d4 100644 --- a/crates/buzz-pubsub/Cargo.toml +++ b/crates/buzz-pubsub/Cargo.toml @@ -11,7 +11,6 @@ description = "Redis pub/sub fan-out, presence, and typing indicators for Buzz" buzz-core = { workspace = true } buzz-auth = { workspace = true } redis = { workspace = true } -deadpool-redis = { workspace = true } tokio = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } @@ -21,6 +20,7 @@ tracing = { workspace = true } thiserror = { workspace = true } nostr = { workspace = true } futures-util = { workspace = true } +arc-swap = { workspace = true } [dev-dependencies] tokio = { workspace = true } diff --git a/crates/buzz-pubsub/src/cache_invalidation.rs b/crates/buzz-pubsub/src/cache_invalidation.rs index f48158c9c57..48d864d9bba 100644 --- a/crates/buzz-pubsub/src/cache_invalidation.rs +++ b/crates/buzz-pubsub/src/cache_invalidation.rs @@ -1,10 +1,10 @@ //! Cross-pod cache-key invalidation over Redis pub/sub. //! //! Each relay pod keeps in-memory (moka) membership / accessible-channels / -//! visibility caches. A membership or visibility change is applied to the local -//! caches only on the pod that processed the write; other pods would otherwise -//! rely on the 10s TTL to expire stale entries. This module carries the same -//! key drops to every pod immediately. +//! visibility / restriction caches. A change is applied to the local caches +//! only on the pod that processed the write; other pods would otherwise rely +//! on each cache's max age to expire stale entries. This module carries the +//! same key drops to every pod immediately. //! //! The message is a pure cache-key drop — never an "evict these subscriptions" //! payload. The per-event access gate (`filter_fanout_by_access`) is the @@ -56,6 +56,11 @@ pub fn parse_cache_invalidation_channel(channel: &str) -> Option { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "op")] pub enum CacheInvalidation { + /// Drop a serving-host snapshot after policy or binding/lifecycle changes. + CommunityHost { + /// Normalized host whose routing and policy snapshot changed. + host: String, + }, /// Drop the `(channel_id, pubkey)` membership entry and the user's /// accessible-channels entry. Mirrors `invalidate_membership`. Membership { @@ -76,6 +81,10 @@ pub enum CacheInvalidation { /// Drop all membership / accessible / visibility caches. Mirrors /// `invalidate_channel_deleted`. ChannelDeleted, + /// Drop every cached ban/timeout row in the community after a + /// restriction write. Mirrors `invalidate_restrictions`. A pod that + /// predates this variant skips it and serves its rows until they age out. + Restrictions, } /// A cache invalidation received from a community-scoped Redis channel. @@ -235,8 +244,12 @@ mod tests { #[test] fn unit_variants_roundtrip_through_json() { for msg in [ + CacheInvalidation::CommunityHost { + host: "a.example".into(), + }, CacheInvalidation::AccessibleAll, CacheInvalidation::ChannelDeleted, + CacheInvalidation::Restrictions, CacheInvalidation::Visibility { channel_id: Uuid::from_u128(0xabcd), }, diff --git a/crates/buzz-pubsub/src/connection.rs b/crates/buzz-pubsub/src/connection.rs new file mode 100644 index 00000000000..5a824eff1df --- /dev/null +++ b/crates/buzz-pubsub/src/connection.rs @@ -0,0 +1,387 @@ +//! The relay's shared Redis command connection. +//! +//! Every non-pub/sub Redis command (PUBLISH, rate-limit scripts, replay +//! guards, presence, the session directory, the mesh registry) goes through +//! one multiplexed connection. Redis pipelines concurrent commands on a single +//! socket and executes them one at a time anyway, so a pool of exclusively +//! checked-out sockets only added a queue to wait in and a PING round trip per +//! checkout. +//! +//! Recovery lives here rather than in redis-rs's `ConnectionManager`, which +//! keeps a socket that stops answering and caches a failed AUTH handshake +//! until the process restarts. This connection retires its socket on any +//! setup failure, response timeout or dropped connection, and the next command +//! dials a fresh one. A failed command is never replayed: a timed-out mutation +//! may already have run. + +use std::sync::Arc; +use std::time::Duration; + +use arc_swap::ArcSwap; +use futures_util::future::{BoxFuture, FutureExt, Shared}; +use redis::aio::{ConnectionLike, MultiplexedConnection}; +use redis::{AsyncConnectionConfig, Client, Cmd, Pipeline, RedisFuture, RedisResult, Value}; + +use crate::error::PubSubError; + +/// Bound on one connect attempt, handshake included. A command issued while +/// the connection is down waits at most this long for it before failing. +pub const REDIS_CONNECT_TIMEOUT: Duration = Duration::from_secs(1); + +/// Bound on one command's response (the redis 1.x driver default, pinned +/// here because callers budget against it). +pub const REDIS_RESPONSE_TIMEOUT: Duration = Duration::from_millis(500); + +/// Shared Redis command connection. Cloning is an `Arc` bump; every clone +/// sends on the same socket and moves to its replacement together. +#[derive(Clone)] +pub struct RedisConnection(Arc); + +struct Inner { + client: Client, + config: AsyncConnectionConfig, + /// The current socket's dial. Every command shares it; a failed or + /// retired dial is swapped for a fresh one. + socket: ArcSwap, +} + +/// One dial of the shared socket, awaited by every command that arrives while +/// it runs. Lazy: nothing connects until a command polls it. +type Dial = Shared>>; + +fn dial(client: &Client, config: &AsyncConnectionConfig) -> Arc { + let (client, config) = (client.clone(), config.clone()); + let dial = async move { + client + .get_multiplexed_async_connection_with_config(&config) + .await + }; + Arc::new(dial.boxed().shared()) +} + +/// Build the shared connection without dialing; the first command connects. +/// +/// There are no retries inside a command: a failed connect or command is that +/// command's error, and the next command dials afresh if the socket was +/// retired. So no caller waits longer than [`REDIS_CONNECT_TIMEOUT`] plus +/// [`REDIS_RESPONSE_TIMEOUT`] per command, during an outage or otherwise. +pub fn redis_connection(redis_url: &str) -> Result { + let client = Client::open(redis_url)?; + let config = AsyncConnectionConfig::new() + .set_connection_timeout(Some(REDIS_CONNECT_TIMEOUT)) + .set_response_timeout(Some(REDIS_RESPONSE_TIMEOUT)); + let socket = ArcSwap::new(dial(&client, &config)); + Ok(RedisConnection(Arc::new(Inner { + client, + config, + socket, + }))) +} + +impl RedisConnection { + async fn socket(&self) -> RedisResult<(Arc, MultiplexedConnection)> { + let current = self.0.socket.load_full(); + match (*current).clone().await { + Ok(socket) => Ok((current, socket)), + Err(err) => { + self.retire(¤t); + Err(err) + } + } + } + + /// Replace `current` unless another command already did, so one failure + /// wave costs one dial. The retired socket closes once the commands still + /// waiting on it finish or time out, which frees their reply slots. + fn retire(&self, current: &Arc) { + self.0 + .socket + .compare_and_swap(current, dial(&self.0.client, &self.0.config)); + } + + fn settle(&self, current: &Arc, result: RedisResult) -> RedisResult { + if let Err(err) = &result { + // A timeout can't tell a slow server from a socket that will never + // answer again, so it retires the socket too: on a healthy server + // that costs one handshake. + if err.is_timeout() || err.is_unrecoverable_error() { + self.retire(current); + } + } + result + } +} + +impl ConnectionLike for RedisConnection { + fn req_packed_command<'a>(&'a mut self, cmd: &'a Cmd) -> RedisFuture<'a, Value> { + async move { + let (current, mut socket) = self.socket().await?; + let result = socket.send_packed_command(cmd).await; + self.settle(¤t, result) + } + .boxed() + } + + fn req_packed_commands<'a>( + &'a mut self, + cmd: &'a Pipeline, + offset: usize, + count: usize, + ) -> RedisFuture<'a, Vec> { + async move { + let (current, mut socket) = self.socket().await?; + let result = socket.send_packed_commands(cmd, offset, count).await; + self.settle(¤t, result) + } + .boxed() + } + + fn get_db(&self) -> i64 { + self.0.client.get_connection_info().redis_settings().db() + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + use std::time::Instant; + + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + use super::*; + + /// Scheduling slack on top of a timeout before a test calls it unbounded. + const SLACK: Duration = Duration::from_millis(400); + /// The per-command bounds callers budget against (session-directory and + /// audio permit budgets in buzz-relay). Literal on purpose: raising a + /// timeout constant must fail these tests rather than move them with it. + const PROMISED_CONNECT_BOUND: Duration = Duration::from_millis(1000); + const PROMISED_RESPONSE_BOUND: Duration = Duration::from_millis(500); + + /// How a fake Redis peer treats one accepted socket. + #[derive(Clone, Copy)] + enum Peer { + /// Accept, then never answer anything (stalls the connect handshake). + Silent, + /// Answer the handshake, never answer a command. + WithholdReplies, + /// Answer the handshake and one PING, then close the socket. + OnePingThenClose, + /// Answer the handshake and one PING, then stay open and silent. + OnePingThenSilent, + /// Reject AUTH in the handshake. + RejectAuth, + /// Answer everything. + Healthy, + } + + /// Fake RESP peer on loopback. `script(n)` picks how the n-th accepted + /// socket (from 0) behaves. Returns its URL and an accept counter. + async fn fake_redis(script: fn(usize) -> Peer) -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let url = format!("redis://{}", listener.local_addr().expect("addr")); + let accepted = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&accepted); + tokio::spawn(async move { + while let Ok((mut socket, _)) = listener.accept().await { + let peer = script(counter.fetch_add(1, Ordering::SeqCst)); + tokio::spawn(async move { + let mut buf = vec![0u8; 4096]; + let mut answered_ping = false; + loop { + let Ok(n) = socket.read(&mut buf).await else { + return; + }; + if n == 0 { + return; + } + if matches!(peer, Peer::Silent) { + continue; + } + let chunk = String::from_utf8_lossy(&buf[..n]).to_ascii_uppercase(); + // The handshake pipelines AUTH (with a password) and + // CLIENT SETINFO calls, in that order. + let auth = if matches!(peer, Peer::RejectAuth) { + "-WRONGPASS invalid username-password pair\r\n" + } else { + "+OK\r\n" + }; + let mut reply = auth.repeat(chunk.matches("AUTH").count()); + reply.push_str(&"+OK\r\n".repeat(chunk.matches("SETINFO").count())); + let pings = chunk.matches("PING").count(); + match peer { + Peer::Healthy => reply.push_str(&"+PONG\r\n".repeat(pings)), + Peer::OnePingThenClose if pings > 0 => { + reply.push_str("+PONG\r\n"); + let _ = socket.write_all(reply.as_bytes()).await; + return; // dropping the socket closes it + } + Peer::OnePingThenSilent if pings > 0 && !answered_ping => { + reply.push_str("+PONG\r\n"); + answered_ping = true; + } + _ => {} + } + if !reply.is_empty() && socket.write_all(reply.as_bytes()).await.is_err() { + return; + } + } + }); + } + }); + (url, accepted) + } + + async fn timed_ping(conn: &RedisConnection) -> (redis::RedisResult, Duration) { + let started = Instant::now(); + let result = redis::cmd("PING") + .query_async::(&mut conn.clone()) + .await; + (result, started.elapsed()) + } + + #[tokio::test] + async fn stalled_handshake_fails_each_command_at_the_connect_timeout() { + let (url, accepted) = fake_redis(|_| Peer::Silent).await; + let conn = redis_connection(&url).expect("lazy build never dials"); + for attempt in 1..=2 { + let (result, elapsed) = timed_ping(&conn).await; + assert!(result.is_err(), "attempt {attempt}: {result:?}"); + // The connect timeout fired (not an instant refusal), and no + // in-command retry stacked a second attempt on top of it. + assert!( + elapsed >= REDIS_CONNECT_TIMEOUT - Duration::from_millis(50), + "attempt {attempt} failed early: {elapsed:?}" + ); + assert!( + elapsed < PROMISED_CONNECT_BOUND + SLACK, + "attempt {attempt} waited {elapsed:?}" + ); + } + assert_eq!(accepted.load(Ordering::SeqCst), 2, "one dial per command"); + } + + #[tokio::test] + async fn withheld_reply_fails_the_command_at_the_response_timeout() { + let (url, _) = fake_redis(|_| Peer::WithholdReplies).await; + let conn = redis_connection(&url).expect("lazy build never dials"); + let (result, elapsed) = timed_ping(&conn).await; + let error = result.expect_err("no reply must fail the command"); + assert!(error.is_timeout(), "{error:?}"); + assert!( + elapsed >= REDIS_RESPONSE_TIMEOUT - Duration::from_millis(50), + "failed early: {elapsed:?}" + ); + assert!( + elapsed < PROMISED_RESPONSE_BOUND + SLACK, + "waited {elapsed:?}" + ); + } + + #[tokio::test] + async fn dropped_connection_is_redialed_by_a_later_command() { + let (url, accepted) = fake_redis(|_| Peer::OnePingThenClose).await; + let conn = redis_connection(&url).expect("lazy build never dials"); + let (first, _) = timed_ping(&conn).await; + assert_eq!(first.expect("first ping"), "PONG"); + // The peer closed the socket. Each later command is bounded, and the + // shared connection redials instead of staying dead. + let mut recovered = false; + for _ in 0..5 { + let (result, elapsed) = timed_ping(&conn).await; + assert!( + elapsed < PROMISED_CONNECT_BOUND + PROMISED_RESPONSE_BOUND + SLACK, + "waited {elapsed:?}" + ); + if result.is_ok() { + recovered = true; + break; + } + } + assert!(recovered, "no later command reconnected"); + assert!(accepted.load(Ordering::SeqCst) >= 2, "never redialed"); + } + + #[tokio::test] + async fn silent_socket_is_replaced_for_every_clone() { + // The first socket answers one PING, then stays open but never answers + // again (a dropped NAT entry, a failed-over endpoint). New sockets work. + let (url, accepted) = fake_redis(|n| { + if n == 0 { + Peer::OnePingThenSilent + } else { + Peer::Healthy + } + }) + .await; + let conn = redis_connection(&url).expect("lazy build never dials"); + let existing_clone = conn.clone(); + let (first, _) = timed_ping(&conn).await; + assert_eq!(first.expect("first ping"), "PONG"); + let (stalled, elapsed) = timed_ping(&conn).await; + let error = stalled.expect_err("the silent socket must time out"); + assert!(error.is_timeout(), "{error:?}"); + assert!( + elapsed < PROMISED_RESPONSE_BOUND + SLACK, + "waited {elapsed:?}" + ); + // The timeout retired the socket for every clone: the next command, + // through a handle cloned before the stall, dials once and succeeds. + let (recovered, _) = timed_ping(&existing_clone).await; + assert_eq!(recovered.expect("ping on a fresh socket"), "PONG"); + assert_eq!(accepted.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn failed_auth_handshake_is_retried_by_a_later_command() { + // The serving socket drops, the reconnect's AUTH is rejected (a + // credential rotation caught mid-way), then the server accepts again. + let (url, accepted) = fake_redis(|n| match n { + 0 => Peer::OnePingThenClose, + 1 => Peer::RejectAuth, + _ => Peer::Healthy, + }) + .await; + let url = url.replace("redis://", "redis://:pw@"); + let conn = redis_connection(&url).expect("lazy build never dials"); + let (first, _) = timed_ping(&conn).await; + assert_eq!(first.expect("first ping"), "PONG"); + let mut errors = Vec::new(); + let mut recovered = false; + for _ in 0..5 { + match timed_ping(&conn).await.0 { + Ok(pong) => { + assert_eq!(pong, "PONG"); + recovered = true; + break; + } + Err(error) => errors.push(error), + } + } + assert!( + errors + .iter() + .any(|e| e.kind() == redis::ErrorKind::AuthenticationFailed), + "the rejected handshake never surfaced: {errors:?}" + ); + // The AUTH failure was not cached: the same handle redialed past it. + assert!(recovered, "never recovered: {errors:?}"); + assert_eq!(accepted.load(Ordering::SeqCst), 3, "{errors:?}"); + } + + #[tokio::test] + async fn unreachable_redis_fails_each_command_within_the_bounds() { + // Port 1 refuses (or times out) on every CI runner; nothing listens. + let conn = redis_connection("redis://127.0.0.1:1").expect("lazy build never dials"); + for _ in 0..2 { + let (result, elapsed) = timed_ping(&conn).await; + assert!(result.is_err()); + assert!( + elapsed < PROMISED_CONNECT_BOUND + PROMISED_RESPONSE_BOUND + SLACK, + "command waited {elapsed:?}" + ); + } + } +} diff --git a/crates/buzz-pubsub/src/error.rs b/crates/buzz-pubsub/src/error.rs index 96bc1016c9b..4346718f3a9 100644 --- a/crates/buzz-pubsub/src/error.rs +++ b/crates/buzz-pubsub/src/error.rs @@ -7,10 +7,6 @@ pub enum PubSubError { #[error("Redis error: {0}")] Redis(#[from] redis::RedisError), - /// Failed to acquire a connection from the Redis pool. - #[error("Redis pool error: {0}")] - Pool(#[from] deadpool_redis::PoolError), - /// JSON serialization or deserialization failed. #[error("Serialization error: {0}")] Serialization(#[from] serde_json::Error), diff --git a/crates/buzz-pubsub/src/lib.rs b/crates/buzz-pubsub/src/lib.rs index 487ea9b6302..e7f85d53801 100644 --- a/crates/buzz-pubsub/src/lib.rs +++ b/crates/buzz-pubsub/src/lib.rs @@ -7,9 +7,9 @@ //! ```text //! buzz-relay process //! │ -//! ├── deadpool-redis pool → PUBLISH, SET, ZADD, etc. +//! ├── shared RedisConnection (one multiplexed socket) → PUBLISH, SET, ZADD, etc. //! │ -//! └── dedicated redis::aio::PubSub connection (NOT from pool) +//! └── dedicated redis::aio::PubSub connection (NOT the shared one) //! └── dynamic SUBSCRIBE buzz:{community}:channel:{id} / buzz:{community}:global //! └── run_subscriber() → broadcast::channel(4096) → N WS receivers //! ``` @@ -18,13 +18,18 @@ //! backoff (1s → 2s → 4s → … → 30s max). //! //! Dedicated pub/sub connection is stateful and cannot be shared. -//! Pool connections handle all other commands. +//! The shared [`RedisConnection`] handles all other commands. //! Lagged receivers get `RecvError::Lagged`. /// Cross-pod cache-key invalidation over Redis pub/sub. pub mod cache_invalidation; /// Cross-pod connection-control commands over Redis pub/sub. pub mod conn_control; +/// The shared Redis command connection. +pub mod connection; +pub use connection::{ + redis_connection, RedisConnection, REDIS_CONNECT_TIMEOUT, REDIS_RESPONSE_TIMEOUT, +}; /// Error types for pub/sub operations. pub mod error; /// Redis-backed NIP-98 replay seen-set. @@ -51,7 +56,7 @@ use std::time::Duration; use buzz_core::TenantContext; use nostr::PublicKey; -use tokio::sync::{broadcast, mpsc, Mutex}; +use tokio::sync::{broadcast, mpsc, oneshot, watch, Mutex, Notify}; use crate::cache_invalidation::{ cache_invalidation_channel, CacheInvalidation, ScopedCacheInvalidation, @@ -72,6 +77,20 @@ pub struct ChannelEvent { pub event: nostr::Event, } +/// Health of this node's Redis event subscription link. +/// +/// `epoch` advances on every event that can lose messages without a replay: +/// the link connects, drops, or skips a message it could not decode. A reader +/// that needs every message records the epoch when its interest is confirmed +/// and treats any later change as a possible loss. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct LinkState { + /// Advances on every possible loss. + pub epoch: u64, + /// Whether the link is connected and its desired topics are subscribed. + pub up: bool, +} + /// Configuration for the pub/sub subsystem. #[derive(Debug, Clone)] pub struct PubSubConfig { @@ -100,9 +119,13 @@ impl PubSubConfig { } } +/// Capacity of the subscriber command queue. A full queue loses only a +/// subscribe hint: the desired-topic map is reconciled separately. +const SUBSCRIPTION_COMMAND_CAPACITY: usize = 4096; + /// Central pub/sub manager for a Buzz relay instance. pub struct PubSubManager { - pool: deadpool_redis::Pool, + pool: crate::RedisConnection, /// Redis URL used by the reconnect loop to re-establish pub/sub connections. redis_url: String, /// Delay before unsubscribing after the last local interest is released. @@ -111,28 +134,31 @@ pub struct PubSubManager { desired_topics: subscriber::DesiredTopics, subscription_tx: mpsc::Sender, subscription_rx: Mutex>>, + /// Coalesced wake-up: reconcile desired topics with the live Redis link. + subscription_changed: Arc, broadcast_tx: broadcast::Sender, cache_invalidation_tx: broadcast::Sender, conn_control_tx: broadcast::Sender, nip_fi_disconnect_tx: broadcast::Sender, + link: watch::Sender, } impl PubSubManager { /// Creates a new `PubSubManager` connected to the given Redis URL. - pub async fn new(redis_url: &str, pool: deadpool_redis::Pool) -> Result { + pub async fn new(redis_url: &str, pool: crate::RedisConnection) -> Result { Self::with_config(PubSubConfig::new(redis_url), pool).await } /// Creates a new `PubSubManager` using explicit pub/sub configuration. pub async fn with_config( config: PubSubConfig, - pool: deadpool_redis::Pool, + pool: crate::RedisConnection, ) -> Result { let (broadcast_tx, _) = broadcast::channel(4096); let (cache_invalidation_tx, _) = broadcast::channel(4096); let (conn_control_tx, _) = broadcast::channel(4096); let (nip_fi_disconnect_tx, _) = broadcast::channel(4096); - let (subscription_tx, subscription_rx) = mpsc::channel(4096); + let (subscription_tx, subscription_rx) = mpsc::channel(SUBSCRIPTION_COMMAND_CAPACITY); Ok(Self { pool, @@ -141,10 +167,12 @@ impl PubSubManager { desired_topics: Arc::new(Mutex::new(HashMap::new())), subscription_tx, subscription_rx: Mutex::new(Some(subscription_rx)), + subscription_changed: Arc::new(Notify::new()), broadcast_tx, cache_invalidation_tx, conn_control_tx, nip_fi_disconnect_tx, + link: watch::Sender::new(LinkState::default()), }) } @@ -163,6 +191,8 @@ impl PubSubManager { self.broadcast_tx.clone(), self.desired_topics.clone(), subscription_rx, + self.subscription_changed.clone(), + self.link.clone(), ) .await; } @@ -213,7 +243,8 @@ impl PubSubManager { /// Retain local interest in a scoped Redis event topic. /// /// The first retain for a topic asks the subscriber task to `SUBSCRIBE`. - /// Additional retains only increment the local desired refcount. + /// Additional retains only increment the local desired refcount. It never + /// waits on the subscriber: callers hold a connection's lifecycle lock. pub async fn retain_topic(&self, ctx: &TenantContext, topic: EventTopic) { let topic_key = EventTopicKey::from_context(ctx, topic); let should_subscribe = { @@ -225,13 +256,50 @@ impl PubSubManager { }; if should_subscribe { - let _ = self + match self .subscription_tx - .send(subscriber::SubscriptionCommand::Subscribe(topic_key)) - .await; + .try_send(subscriber::SubscriptionCommand::Subscribe(topic_key)) + { + // A queued command subscribes in order; a closed queue means + // the subscriber is gone, and a restart re-subscribes the + // whole desired-topic map. + Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {} + Err(mpsc::error::TrySendError::Full(_)) => { + // The wake-up is lossless and coalesced: the subscriber + // reconciles the desired-topic map on the live link + // instead of waiting for a Redis reconnect. + self.subscription_changed.notify_one(); + tracing::warn!( + ?topic_key, + "pubsub subscription command queue full; reconciliation scheduled" + ); + } + } } } + /// Watch this node's Redis event link (see [`LinkState`]). + pub fn link_state(&self) -> watch::Receiver { + self.link.subscribe() + } + + /// Wait until Redis has confirmed a subscription to an already retained + /// topic, and return the link epoch it was confirmed on. Fails when the + /// link drops before it answers; the caller bounds the wait. + pub async fn confirm_topic( + &self, + ctx: &TenantContext, + topic: EventTopic, + ) -> Result { + let (reply, answer) = oneshot::channel(); + let topic_key = EventTopicKey::from_context(ctx, topic); + self.subscription_tx + .send(subscriber::SubscriptionCommand::Confirm(topic_key, reply)) + .await + .map_err(|_| PubSubError::SubscriberStopped)?; + answer.await.map_err(|_| PubSubError::SubscriberStopped) + } + /// Release local interest in a scoped Redis event topic. /// /// When the last retain is released, unsubscribe is delayed by the configured @@ -304,7 +372,7 @@ impl PubSubManager { ctx: &TenantContext, invalidation: &CacheInvalidation, ) -> Result { - let mut conn = self.pool.get().await?; + let mut conn = self.pool.clone(); let payload = serde_json::to_string(invalidation)?; let subscriber_count: i64 = redis::cmd("PUBLISH") .arg(cache_invalidation_channel(ctx)) @@ -324,7 +392,7 @@ impl PubSubManager { ctx: &TenantContext, command: &ConnControl, ) -> Result { - let mut conn = self.pool.get().await?; + let mut conn = self.pool.clone(); let payload = serde_json::to_string(command)?; let subscriber_count: i64 = redis::cmd("PUBLISH") .arg(conn_control_channel(ctx)) @@ -345,7 +413,7 @@ impl PubSubManager { command: &NipFiDisconnect, ) -> Result { use crate::conn_control::encode_nip_fi_disconnect; - let mut conn = self.pool.get().await?; + let mut conn = self.pool.clone(); let payload = encode_nip_fi_disconnect(command)?; let subscriber_count: i64 = redis::cmd("PUBLISH") .arg(channel) @@ -438,10 +506,8 @@ impl PubSubManager { #[cfg(test)] pub(crate) mod test_util { - pub fn make_test_pool() -> deadpool_redis::Pool { - let cfg = deadpool_redis::Config::from_url("redis://127.0.0.1:6379"); - cfg.create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("Failed to create Redis pool") + pub fn make_test_pool() -> crate::RedisConnection { + crate::redis_connection("redis://127.0.0.1:6379").expect("Failed to build Redis connection") } } @@ -516,30 +582,32 @@ mod tests { let channel_id = Uuid::new_v4(); let pubkey = Keys::generate().public_key().to_bytes().to_vec(); - let sent = CacheInvalidation::Membership { - channel_id, - pubkey: pubkey.clone(), - }; - let ctx = ctx(0xaaaa, "a.example"); - - manager - .publish_cache_invalidation(&ctx, &sent) - .await - .expect("publish failed"); - - let received = tokio::time::timeout(tokio::time::Duration::from_secs(2), rx.recv()) - .await - .expect("timeout") - .expect("channel closed"); - - assert_eq!( - received, - ScopedCacheInvalidation { - community_id: ctx.community(), - invalidation: sent, - } - ); + for sent in [ + CacheInvalidation::Membership { + channel_id, + pubkey: pubkey.clone(), + }, + CacheInvalidation::CommunityHost { + host: ctx.host().to_owned(), + }, + ] { + manager + .publish_cache_invalidation(&ctx, &sent) + .await + .expect("publish failed"); + let received = tokio::time::timeout(tokio::time::Duration::from_secs(2), rx.recv()) + .await + .expect("timeout") + .expect("channel closed"); + assert_eq!( + received, + ScopedCacheInvalidation { + community_id: ctx.community(), + invalidation: sent, + } + ); + } } #[tokio::test] @@ -558,7 +626,7 @@ mod tests { let status = presence::get_presence(&pool, &ctx, &pubkey).await.unwrap(); assert_eq!(status.as_deref(), Some("online")); - let mut conn = pool.get().await.unwrap(); + let mut conn = pool.clone(); let ttl: i64 = redis::cmd("TTL") .arg(presence::presence_key(&ctx, &pubkey)) .query_async(&mut conn) @@ -659,6 +727,185 @@ mod tests { assert_eq!(manager.topic_refcount(&ctx_b, topic).await, 0); } + /// A retain past a full command queue neither waits for the subscriber + /// (callers hold a lifecycle lock) nor loses the topic: it leaves a + /// reconciliation wake-up, and the topic is in the desired map the + /// subscriber re-reads. Retains that fit in the queue leave no wake-up, + /// so first retains do not each make the subscriber rescan the map. + /// Mutation: `send().await` instead of `try_send` hangs at the timeout + /// below; no `notify_one` fails the wake-up check; `notify_one` on every + /// first retain fails the no-wake-up check. + #[tokio::test] + async fn queue_full_retain_does_not_wait_and_schedules_reconciliation() { + let manager = make_manager().await; + let filler = ctx(0xaaaa, "a.example"); + for id in 0..SUBSCRIPTION_COMMAND_CAPACITY { + manager + .retain_topic(&filler, EventTopic::Channel(Uuid::from_u128(id as u128))) + .await; + } + // Retains that fit in the queue leave no reconciliation wake-up. + assert!( + tokio::time::timeout( + Duration::from_millis(10), + manager.subscription_changed.notified() + ) + .await + .is_err(), + "a queued subscribe needs no reconciliation" + ); + + let dropped_ctx = ctx(0xbbbb, "b.example"); + let dropped = EventTopic::Channel(Uuid::from_u128(0xcccc)); + tokio::time::timeout( + Duration::from_secs(1), + manager.retain_topic(&dropped_ctx, dropped), + ) + .await + .expect("a retain must not wait on a full command queue"); + assert_eq!(manager.topic_refcount(&dropped_ctx, dropped).await, 1); + + tokio::time::timeout( + Duration::from_millis(10), + manager.subscription_changed.notified(), + ) + .await + .expect("a queue-full retain must leave a reconciliation wake-up"); + let missing = subscriber::missing_desired_topics( + &manager.desired_topics, + &std::collections::HashSet::new(), + ) + .await; + assert!(missing.contains(&EventTopicKey::from_context(&dropped_ctx, dropped))); + } + + /// Fill the command queue with first retains of fresh topics, then retain + /// `topic`, without yielding: on this single-threaded runtime the + /// subscriber cannot drain the queue in between, so `topic`'s subscribe + /// hint is dropped. + async fn retain_with_dropped_hint( + manager: &PubSubManager, + filler: &TenantContext, + first_filler: u128, + target: &TenantContext, + topic: EventTopic, + ) { + tokio::task::unconstrained(async { + let mut id = first_filler; + while manager.subscription_tx.capacity() > 0 { + manager + .retain_topic(filler, EventTopic::Channel(Uuid::from_u128(id))) + .await; + id += 1; + } + manager.retain_topic(target, topic).await; + }) + .await; + } + + /// Publish to `topic` until the live link delivers it. + async fn delivered( + manager: &PubSubManager, + rx: &mut broadcast::Receiver, + ctx: &TenantContext, + topic: EventTopic, + ) -> bool { + let event = EventBuilder::new(Kind::TextNote, "reconciled") + .sign_with_keys(&Keys::generate()) + .expect("sign"); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + manager + .publish_event(ctx, topic, &event) + .await + .expect("publish"); + let wait = tokio::time::sleep(Duration::from_millis(100)); + tokio::pin!(wait); + loop { + tokio::select! { + () = &mut wait => break, + received = rx.recv() => match received { + Ok(received) if received.event.id == event.id => return, + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => panic!("closed"), + }, + } + } + } + }) + .await + .is_ok() + } + + /// A subscribe hint lost to a full command queue is recovered by the + /// running subscriber on the same Redis link: first for a new topic, then + /// for one released, unsubscribed, and retained again. The link never + /// reconnects and nothing sends `Confirm` for the topic, so only the + /// reconciliation wake-up can subscribe it. Mutation: drop the + /// subscriber's `subscription_changed` arm, or the `notify_one` in + /// `retain_topic` → the topic is never delivered → RED. + #[tokio::test] + #[ignore = "requires Redis"] + async fn live_subscriber_recovers_a_dropped_subscribe_hint() { + let manager = Arc::new( + PubSubManager::with_config( + PubSubConfig::new("redis://127.0.0.1:6379") + .with_unsubscribe_debounce(Duration::from_millis(1)), + make_test_pool(), + ) + .await + .unwrap(), + ); + let mut rx = manager.subscribe_local(); + let mut link = manager.link_state(); + let subscriber = tokio::spawn(Arc::clone(&manager).run_subscriber()); + link.wait_for(|state| state.up).await.expect("link up"); + let epoch = link.borrow().epoch; + + let filler = ctx(Uuid::new_v4().as_u128(), "filler.example"); + let target = ctx(Uuid::new_v4().as_u128(), "target.example"); + let topic = EventTopic::Channel(Uuid::new_v4()); + + retain_with_dropped_hint(&manager, &filler, 0, &target, topic).await; + assert!( + delivered(&manager, &mut rx, &target, topic).await, + "a dropped hint for a new topic must be reconciled" + ); + + manager.release_topic(&target, topic).await; + // Wait until Redis shows the debounced unsubscribe took effect, so + // the re-retain below starts from an unsubscribed topic. + let channel = EventTopicKey::from_context(&target, topic).redis_channel(); + let mut redis = redis::Client::open("redis://127.0.0.1:6379") + .unwrap() + .get_multiplexed_async_connection() + .await + .expect("redis"); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let (_, subscribers): (String, i64) = redis::cmd("PUBSUB") + .arg("NUMSUB") + .arg(&channel) + .query_async(&mut redis) + .await + .expect("numsub"); + if subscribers == 0 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("the released topic must be unsubscribed"); + retain_with_dropped_hint(&manager, &filler, 1 << 32, &target, topic).await; + assert!( + delivered(&manager, &mut rx, &target, topic).await, + "a dropped hint after an unsubscribe must be reconciled" + ); + assert_eq!(link.borrow().epoch, epoch, "the link must not reconnect"); + subscriber.abort(); + } + #[tokio::test] async fn retain_release_refcounts_and_debounces_last_release() { let pool = make_test_pool(); diff --git a/crates/buzz-pubsub/src/nip98_replay.rs b/crates/buzz-pubsub/src/nip98_replay.rs index 858f0f5ace8..f59a07b56bb 100644 --- a/crates/buzz-pubsub/src/nip98_replay.rs +++ b/crates/buzz-pubsub/src/nip98_replay.rs @@ -21,12 +21,12 @@ use nostr::EventId; /// the TTL window return `nil`, which we surface as `Ok(false)` so the caller /// rejects the request as replay. pub struct RedisNip98ReplayGuard { - pool: deadpool_redis::Pool, + pool: crate::RedisConnection, } impl RedisNip98ReplayGuard { - /// Create a new replay guard backed by the given Redis connection pool. - pub fn new(pool: deadpool_redis::Pool) -> Self { + /// Create a new replay guard backed by the shared Redis connection. + pub fn new(pool: crate::RedisConnection) -> Self { Self { pool } } } @@ -47,16 +47,7 @@ impl Nip98ReplayGuard for RedisNip98ReplayGuard { // implausibly long. let ttl = ttl_secs.clamp(DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS); - let mut conn = self.pool.get().await.map_err(|e| { - // Structured field for ops; the user-facing AuthError stays a - // bounded category string. - tracing::warn!( - scope = %scope, - error = %e, - "nip98 replay: redis pool acquire failed — caller MUST fail closed" - ); - AuthError::Internal(format!("Redis pool: {e}")) - })?; + let mut conn = self.pool.clone(); let key = nip98_replay_key_for_scope(scope, event_id); @@ -69,7 +60,7 @@ impl Nip98ReplayGuard for RedisNip98ReplayGuard { .arg("NX") .arg("EX") .arg(ttl) - .query_async(&mut *conn) + .query_async(&mut conn) .await .map_err(|e| { tracing::warn!( @@ -102,15 +93,12 @@ impl Nip98ReplayGuard for RedisNip98ReplayGuard { mod tests { use super::*; use buzz_core::{CommunityId, TenantContext}; - use deadpool_redis::{Config, Runtime}; use nostr::{EventBuilder, Keys, Kind}; use uuid::Uuid; - fn redis_pool() -> deadpool_redis::Pool { + fn redis_pool() -> crate::RedisConnection { let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); - Config::from_url(url) - .create_pool(Some(Runtime::Tokio1)) - .expect("create pool") + crate::redis_connection(&url).expect("redis connection") } fn fresh_ctx() -> TenantContext { diff --git a/crates/buzz-pubsub/src/nip_fi_command_replay.rs b/crates/buzz-pubsub/src/nip_fi_command_replay.rs index d21bd5c55de..47b3c0369d2 100644 --- a/crates/buzz-pubsub/src/nip_fi_command_replay.rs +++ b/crates/buzz-pubsub/src/nip_fi_command_replay.rs @@ -15,13 +15,13 @@ use buzz_auth::{ /// `try_claim` issues `SET buzz:nip-fi:command:{hash} 1 NX EX `; `OK` /// is a first claim and `nil` is a replay. pub struct RedisCommandReplayGuard { - pool: deadpool_redis::Pool, + pool: crate::RedisConnection, prefix: &'static str, } impl RedisCommandReplayGuard { - /// Create a new replay guard backed by the given Redis connection pool. - pub fn new(pool: deadpool_redis::Pool) -> Self { + /// Create a new replay guard backed by the shared Redis connection. + pub fn new(pool: crate::RedisConnection) -> Self { Self { pool, prefix: COMMAND_REPLAY_PREFIX, @@ -30,19 +30,12 @@ impl RedisCommandReplayGuard { /// A guard for shadow pods: claims live under /// `buzz:nip-fi:shadow-command:{hash}`, disjoint from enforce claims. - pub fn shadow(pool: deadpool_redis::Pool) -> Self { + pub fn shadow(pool: crate::RedisConnection) -> Self { Self { pool, prefix: SHADOW_COMMAND_REPLAY_PREFIX, } } - - async fn conn(&self) -> Result { - self.pool.get().await.map_err(|e| { - tracing::warn!(error = %e, "nip-fi command replay: redis pool acquire failed"); - AuthError::Internal(format!("Redis pool: {e}")) - }) - } } impl CommandReplayGuard for RedisCommandReplayGuard { @@ -55,14 +48,14 @@ impl CommandReplayGuard for RedisCommandReplayGuard { { Box::pin(async move { let ttl = ttl_secs.clamp(DEFAULT_REPLAY_TTL_SECS, MAX_REPLAY_TTL_SECS); - let mut conn = self.conn().await?; + let mut conn = self.pool.clone(); let result: Option = redis::cmd("SET") .arg(namespaced_command_replay_key(self.prefix, issuer, jti)) .arg("1") .arg("NX") .arg("EX") .arg(ttl) - .query_async(&mut *conn) + .query_async(&mut conn) .await .map_err(|e| { tracing::warn!(error = %e, "nip-fi command replay: redis SET NX EX failed"); diff --git a/crates/buzz-pubsub/src/presence.rs b/crates/buzz-pubsub/src/presence.rs index 4de5fae8a3d..67bc359832b 100644 --- a/crates/buzz-pubsub/src/presence.rs +++ b/crates/buzz-pubsub/src/presence.rs @@ -4,8 +4,8 @@ //! TTL is 3x the 60s heartbeat interval so a single missed heartbeat doesn't //! cause presence flap. Clean disconnect deletes immediately. +use crate::RedisConnection; use buzz_core::TenantContext; -use deadpool_redis::Pool; use nostr::PublicKey; use std::collections::HashMap; @@ -26,12 +26,12 @@ pub fn presence_key(ctx: &TenantContext, pubkey: &PublicKey) -> String { /// Sets presence status for `pubkey` with a [`PRESENCE_TTL_SECS`]-second TTL. pub async fn set_presence( - pool: &Pool, + pool: &RedisConnection, ctx: &TenantContext, pubkey: &PublicKey, status: &str, ) -> Result<(), PubSubError> { - let mut conn = pool.get().await?; + let mut conn = pool.clone(); let key = presence_key(ctx, pubkey); redis::cmd("SET") .arg(&key) @@ -45,11 +45,11 @@ pub async fn set_presence( /// Removes the presence entry for `pubkey`. Call on clean disconnect. pub async fn clear_presence( - pool: &Pool, + pool: &RedisConnection, ctx: &TenantContext, pubkey: &PublicKey, ) -> Result<(), PubSubError> { - let mut conn = pool.get().await?; + let mut conn = pool.clone(); let key = presence_key(ctx, pubkey); redis::cmd("DEL") .arg(&key) @@ -61,7 +61,7 @@ pub async fn clear_presence( /// Sets one status for every pubkey in `pubkeys`, each with the /// [`PRESENCE_TTL_SECS`] TTL, in one atomic round trip. pub async fn set_presence_many( - pool: &Pool, + pool: &RedisConnection, ctx: &TenantContext, pubkeys: &[PublicKey], status: &str, @@ -69,7 +69,7 @@ pub async fn set_presence_many( if pubkeys.is_empty() { return Ok(()); } - let mut conn = pool.get().await?; + let mut conn = pool.clone(); let mut pipe = redis::pipe(); pipe.atomic(); for pubkey in pubkeys { @@ -86,14 +86,14 @@ pub async fn set_presence_many( /// Removes the presence entries for every pubkey in `pubkeys`. pub async fn clear_presence_many( - pool: &Pool, + pool: &RedisConnection, ctx: &TenantContext, pubkeys: &[PublicKey], ) -> Result<(), PubSubError> { if pubkeys.is_empty() { return Ok(()); } - let mut conn = pool.get().await?; + let mut conn = pool.clone(); let keys: Vec = pubkeys .iter() .map(|pubkey| presence_key(ctx, pubkey)) @@ -107,11 +107,11 @@ pub async fn clear_presence_many( /// Returns the current presence status for `pubkey`, or `None` if not set or expired. pub async fn get_presence( - pool: &Pool, + pool: &RedisConnection, ctx: &TenantContext, pubkey: &PublicKey, ) -> Result, PubSubError> { - let mut conn = pool.get().await?; + let mut conn = pool.clone(); let key = presence_key(ctx, pubkey); let value: Option = redis::cmd("GET").arg(&key).query_async(&mut conn).await?; Ok(value) @@ -119,14 +119,14 @@ pub async fn get_presence( /// Returns `pubkey_hex → status` for all currently-set keys. pub async fn get_presence_bulk( - pool: &Pool, + pool: &RedisConnection, ctx: &TenantContext, pubkeys: &[PublicKey], ) -> Result, PubSubError> { if pubkeys.is_empty() { return Ok(HashMap::new()); } - let mut conn = pool.get().await?; + let mut conn = pool.clone(); let keys: Vec = pubkeys .iter() .map(|pubkey| presence_key(ctx, pubkey)) @@ -161,10 +161,8 @@ mod tests { // A backend outage must surface as `Err`, not a silently-empty `Ok`. // `synthesize_presence` relies on this to return an error response // rather than a fake-empty "all offline" snapshot on a Redis failure. - // Pool points at a closed port so the connection attempt fails. - let pool = deadpool_redis::Config::from_url("redis://127.0.0.1:1") - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("pool builds lazily"); + // The connection points at a closed port so the connection attempt fails. + let pool = crate::redis_connection("redis://127.0.0.1:1").expect("pool builds lazily"); let ctx = ctx(0xaaaa, "a.example"); let pubkey = make_pubkey(); @@ -284,7 +282,7 @@ mod tests { result.get(&untouched.to_hex()).map(String::as_str), Some("away") ); - let mut conn = pool.get().await.unwrap(); + let mut conn = pool.clone(); let ttl: i64 = redis::cmd("TTL") .arg(presence_key(&ctx, &pk2)) .query_async(&mut conn) @@ -309,7 +307,7 @@ mod tests { set_presence(&pool, &ctx, &pubkey, "online").await.unwrap(); - let mut conn = pool.get().await.unwrap(); + let mut conn = pool.clone(); let ttl: i64 = redis::cmd("TTL") .arg(presence_key(&ctx, &pubkey)) .query_async(&mut conn) diff --git a/crates/buzz-pubsub/src/publisher.rs b/crates/buzz-pubsub/src/publisher.rs index 8ad06cc56b8..85712f57b6f 100644 --- a/crates/buzz-pubsub/src/publisher.rs +++ b/crates/buzz-pubsub/src/publisher.rs @@ -1,7 +1,7 @@ //! Event publishing — PUBLISH to Redis via pool connection. +use crate::RedisConnection; use buzz_core::TenantContext; -use deadpool_redis::Pool; use nostr::JsonUtil; use uuid::Uuid; @@ -20,12 +20,12 @@ pub fn global_key(ctx: &TenantContext) -> String { /// Returns the number of subscribers that received the message. pub async fn publish_event( - pool: &Pool, + pool: &RedisConnection, ctx: &TenantContext, topic: EventTopic, event: &nostr::Event, ) -> Result { - let mut conn = pool.get().await?; + let mut conn = pool.clone(); let key = crate::topic::EventTopicKey::from_context(ctx, topic).redis_channel(); let payload = event.as_json(); let subscriber_count: i64 = redis::cmd("PUBLISH") diff --git a/crates/buzz-pubsub/src/rate_limiter.rs b/crates/buzz-pubsub/src/rate_limiter.rs index 8d5494f1d5a..095e6591e10 100644 --- a/crates/buzz-pubsub/src/rate_limiter.rs +++ b/crates/buzz-pubsub/src/rate_limiter.rs @@ -37,21 +37,18 @@ return {count, ttl} /// from a prior crash), the key is repaired with a fresh EXPIRE and a warning /// is logged. async fn run_rate_limit( - pool: &deadpool_redis::Pool, + pool: &crate::RedisConnection, key: &str, window_secs: u64, limit: u64, ) -> Result { - let mut conn = pool - .get() - .await - .map_err(|e| AuthError::Internal(format!("Redis pool: {e}")))?; + let mut conn = pool.clone(); let script = Script::new(RATE_LIMIT_SCRIPT); let (count, ttl): (u64, i64) = script .key(key) .arg(window_secs as i64) - .invoke_async(&mut *conn) + .invoke_async(&mut conn) .await .map_err(|e| AuthError::Internal(format!("Redis rate limit script: {e}")))?; @@ -62,7 +59,7 @@ async fn run_rate_limit( let _: () = redis::cmd("EXPIRE") .arg(key) .arg(window_secs as i64) - .query_async(&mut *conn) + .query_async(&mut conn) .await .map_err(|e| AuthError::Internal(format!("Redis EXPIRE repair: {e}")))?; // After repair, the window resets to the full duration. @@ -86,12 +83,12 @@ async fn run_rate_limit( /// managed atomically via a Lua script to prevent keys from persisting without /// expiry. pub struct RedisRateLimiter { - pool: deadpool_redis::Pool, + pool: crate::RedisConnection, } impl RedisRateLimiter { /// Create a new `RedisRateLimiter` backed by the given connection pool. - pub fn new(pool: deadpool_redis::Pool) -> Self { + pub fn new(pool: crate::RedisConnection) -> Self { Self { pool } } } diff --git a/crates/buzz-pubsub/src/subscriber.rs b/crates/buzz-pubsub/src/subscriber.rs index 88826ed99be..49cd27417d3 100644 --- a/crates/buzz-pubsub/src/subscriber.rs +++ b/crates/buzz-pubsub/src/subscriber.rs @@ -6,10 +6,10 @@ use std::time::Duration; use futures_util::StreamExt; use nostr::JsonUtil; -use tokio::sync::{broadcast, mpsc, Mutex}; +use tokio::sync::{broadcast, mpsc, oneshot, watch, Mutex, Notify}; use crate::topic::EventTopicKey; -use crate::ChannelEvent; +use crate::{ChannelEvent, LinkState}; /// Initial reconnect backoff (1 second). const BACKOFF_INITIAL_SECS: u64 = 1; @@ -21,12 +21,24 @@ pub(crate) type DesiredTopics = Arc>>; /// Commands sent from relay subscription registration/removal to the Redis /// pub/sub task. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug)] pub(crate) enum SubscriptionCommand { /// Ensure the topic is subscribed on the current Redis pub/sub connection. Subscribe(EventTopicKey), /// Unsubscribe only if the desired refcount is still zero when processed. UnsubscribeIfIdle(EventTopicKey), + /// Subscribe if needed, then answer with the link epoch on which the + /// server has confirmed the subscription. + Confirm(EventTopicKey, oneshot::Sender), +} + +/// Record a possible loss of messages: the epoch advances, so every reader +/// that started on the old epoch can tell. +fn mark_loss(link: &watch::Sender, up: bool) { + link.send_modify(|state| { + state.epoch += 1; + state.up = up; + }); } /// Runs a dynamically scoped subscriber and forwards events to broadcast. @@ -39,18 +51,26 @@ pub(crate) async fn run_subscriber( broadcast_tx: broadcast::Sender, desired_topics: DesiredTopics, mut subscription_rx: mpsc::Receiver, + subscription_changed: Arc, + link: watch::Sender, ) { let mut backoff_secs = BACKOFF_INITIAL_SECS; loop { - match connect_and_subscribe( + let result = connect_and_subscribe( &redis_url, &broadcast_tx, desired_topics.clone(), &mut subscription_rx, + &subscription_changed, + &link, ) - .await - { + .await; + if link.borrow().up { + // Messages published while the link is down are not replayed. + mark_loss(&link, false); + } + match result { Ok(()) => { // Stream ended cleanly (Redis returned None). The connection was // established and ran successfully, so reset backoff to the initial @@ -77,6 +97,8 @@ async fn connect_and_subscribe( broadcast_tx: &broadcast::Sender, desired_topics: DesiredTopics, subscription_rx: &mut mpsc::Receiver, + subscription_changed: &Notify, + link: &watch::Sender, ) -> Result<(), redis::RedisError> { let client = redis::Client::open(redis_url)?; let conn = client.get_async_pubsub().await?; @@ -101,9 +123,20 @@ async fn connect_and_subscribe( topic_count = active_topics.len(), "Redis pub/sub subscriber connected with dynamic scoped subscriptions" ); + mark_loss(link, true); loop { tokio::select! { + () = subscription_changed.notified() => { + // Retains signal this besides their best-effort queue hint. + // Re-read the source of truth so a hint lost to a full queue + // cannot leave the live connection missing a topic. + for topic in missing_desired_topics(&desired_topics, &active_topics).await { + let channel = topic.redis_channel(); + sink.subscribe(&channel).await?; + active_topics.insert(channel); + } + } Some(command) = subscription_rx.recv() => { match command { SubscriptionCommand::Subscribe(topic) => { @@ -112,6 +145,14 @@ async fn connect_and_subscribe( sink.subscribe(&channel).await?; } } + SubscriptionCommand::Confirm(topic, reply) => { + let channel = topic.redis_channel(); + if !active_topics.contains(&channel) { + sink.subscribe(&channel).await?; + active_topics.insert(channel); + } + let _ = reply.send(link.borrow().epoch); + } SubscriptionCommand::UnsubscribeIfIdle(topic) => { if desired_refcount(&desired_topics, topic).await == 0 { let channel = topic.redis_channel(); @@ -132,6 +173,7 @@ async fn connect_and_subscribe( Ok(p) => p, Err(e) => { tracing::warn!("Failed to get pub/sub message payload: {e}"); + mark_loss(link, true); continue; } }; @@ -149,6 +191,7 @@ async fn connect_and_subscribe( Ok(e) => e, Err(e) => { tracing::warn!("Failed to deserialize event from pub/sub: {e}"); + mark_loss(link, true); continue; } }; @@ -171,6 +214,21 @@ async fn connect_and_subscribe( } } +/// Retained topics the live connection has not subscribed yet. +pub(crate) async fn missing_desired_topics( + desired_topics: &DesiredTopics, + active_topics: &HashSet, +) -> Vec { + desired_topics + .lock() + .await + .iter() + .filter_map(|(topic, count)| { + (*count > 0 && !active_topics.contains(&topic.redis_channel())).then_some(*topic) + }) + .collect() +} + async fn desired_refcount(desired_topics: &DesiredTopics, topic: EventTopicKey) -> usize { desired_topics .lock() diff --git a/crates/buzz-push-gateway/src/app_attest.rs b/crates/buzz-push-gateway/src/app_attest.rs index a6b5076f115..bce5a5e4b4f 100644 --- a/crates/buzz-push-gateway/src/app_attest.rs +++ b/crates/buzz-push-gateway/src/app_attest.rs @@ -85,13 +85,25 @@ impl AppAttestVerifier { client_data: &[u8], ) -> Result { if attestation_b64.len() > crate::model::MAX_APP_ATTESTATION_BYTES.div_ceil(3) * 4 { - return Err(AppAttestError::Invalid); + return Err(verification_error( + "attestation", + error::AppAttestError::ResourceLimit, + )); } let cbor = STANDARD .decode(attestation_b64) - .map_err(|_| AppAttestError::Invalid)?; - if cbor.is_empty() || cbor.len() > crate::model::MAX_APP_ATTESTATION_BYTES { - return Err(AppAttestError::Invalid); + .map_err(|_| verification_error("attestation", error::AppAttestError::InvalidBase64))?; + if cbor.is_empty() { + return Err(verification_error( + "attestation", + error::AppAttestError::InvalidCbor, + )); + } + if cbor.len() > crate::model::MAX_APP_ATTESTATION_BYTES { + return Err(verification_error( + "attestation", + error::AppAttestError::ResourceLimit, + )); } let verified = proof::enroll( &cbor, @@ -101,7 +113,7 @@ impl AppAttestVerifier { &self.apple_root_cert_pem, matches_development(self.environment), ) - .map_err(verification_error)?; + .map_err(|error| verification_error("attestation", error))?; observe_properties("attestation", verified.flags, &verified.properties); Ok(VerifiedAttestation { key_id: verified.key_id, @@ -118,16 +130,31 @@ impl AppAttestVerifier { stored_challenge: &str, ) -> Result { if assertion_b64.len() > MAX_ASSERTION_BYTES.div_ceil(3) * 4 { - return Err(AppAttestError::Invalid); + return Err(verification_error( + "assertion", + error::AppAttestError::ResourceLimit, + )); } let cbor = STANDARD .decode(assertion_b64) - .map_err(|_| AppAttestError::Invalid)?; - if cbor.is_empty() || cbor.len() > MAX_ASSERTION_BYTES { - return Err(AppAttestError::Invalid); + .map_err(|_| verification_error("assertion", error::AppAttestError::InvalidBase64))?; + if cbor.is_empty() { + return Err(verification_error( + "assertion", + error::AppAttestError::InvalidCbor, + )); + } + if cbor.len() > MAX_ASSERTION_BYTES { + return Err(verification_error( + "assertion", + error::AppAttestError::ResourceLimit, + )); } if challenge != stored_challenge { - return Err(AppAttestError::Invalid); + return Err(verification_error( + "assertion", + error::AppAttestError::InvalidNonce, + )); } let verified = proof::assert( &cbor, @@ -136,7 +163,7 @@ impl AppAttestVerifier { public_key, previous_counter, ) - .map_err(verification_error)?; + .map_err(|error| verification_error("assertion", error))?; observe_properties("assertion", verified.flags, &verified.properties); Ok(VerifiedAssertion { counter: verified.counter, @@ -144,19 +171,22 @@ impl AppAttestVerifier { } } -fn verification_error(error: error::AppAttestError) -> AppAttestError { +fn verification_error(operation: &'static str, error: error::AppAttestError) -> AppAttestError { use error::AppAttestError as E; let reason = match error { E::ResourceLimit => "capacity", + E::InvalidBase64 => "encoding", E::InvalidCbor | E::InvalidFormat | E::AuthenticatorDataTooShort => "structure", - E::InvalidCertificate => "certificate", + E::InvalidCertificate(_) => "certificate", E::InvalidNonce | E::InvalidSignature => "signature", E::InvalidCounter => "counter", E::InvalidAppID | E::InvalidAAGUID | E::InvalidCredentialID | E::InvalidPublicKey => { "identity" } }; - tracing::debug!(reason, "App Attest verification rejected"); + // Warn-level so operators can tell which check rejected a device; the + // HTTP response deliberately stays a uniform `invalid_attestation`. + tracing::warn!(operation, reason, detail = %error, "App Attest verification rejected"); AppAttestError::Invalid } diff --git a/crates/buzz-push-gateway/src/app_attest/certificate.rs b/crates/buzz-push-gateway/src/app_attest/certificate.rs index 6a7656df017..218d6a147f3 100644 --- a/crates/buzz-push-gateway/src/app_attest/certificate.rs +++ b/crates/buzz-push-gateway/src/app_attest/certificate.rs @@ -1,5 +1,5 @@ //! Apple certificate adapters; path and signature validation remain in webpki. -use super::error::AppAttestError as Error; +use super::error::{AppAttestError as Error, CertificateCheck as Check}; use aws_lc_rs::digest::{digest, SHA256}; use p256::elliptic_curve::sec1::ToSec1Point; use rustls_pki_types::{CertificateDer, UnixTime}; @@ -24,23 +24,30 @@ impl webpki::ExtendedKeyUsageValidator for AppleUsage { } } -fn parsed(bytes: &[u8]) -> Result, Error> { - let (rest, cert) = parse_x509_certificate(bytes).map_err(|_| Error::InvalidCertificate)?; +fn parsed(bytes: &[u8], index: usize) -> Result, Error> { + let invalid = || Error::InvalidCertificate(Check::Encoding { index }); + let (rest, cert) = parse_x509_certificate(bytes).map_err(|_| invalid())?; if !rest.is_empty() { - return Err(Error::InvalidCertificate); + return Err(invalid()); } // RFC 5280 requires each extension at most once, including unknown OIDs. - cert.extensions_map() - .map_err(|_| Error::InvalidCertificate)?; + cert.extensions_map().map_err(|_| invalid())?; Ok(cert) } +fn path_rejected(error: webpki::Error) -> Error { + Error::InvalidCertificate(Check::Path(format!("{error:?}"))) +} + pub(super) fn verify_chain(certificates: &[Vec], root: &[u8]) -> Result<(), Error> { - let leaf = certificates.first().ok_or(Error::InvalidCertificate)?; + let leaf = certificates + .first() + .ok_or(Error::InvalidCertificate(Check::Chain))?; let root = CertificateDer::from(root); - let anchor = webpki::anchor_from_trusted_cert(&root).map_err(|_| Error::InvalidCertificate)?; + let anchor = webpki::anchor_from_trusted_cert(&root) + .map_err(|_| Error::InvalidCertificate(Check::Root))?; let leaf_der = CertificateDer::from(leaf.as_slice()); - let end = webpki::EndEntityCert::try_from(&leaf_der).map_err(|_| Error::InvalidCertificate)?; + let end = webpki::EndEntityCert::try_from(&leaf_der).map_err(path_rejected)?; let intermediates: Vec<_> = certificates[1..] .iter() .map(|c| CertificateDer::from(c.as_slice())) @@ -54,14 +61,17 @@ pub(super) fn verify_chain(certificates: &[Vec], root: &[u8]) -> Result<(), None, None, ) - .map_err(|_| Error::InvalidCertificate)?; + .map_err(path_rejected)?; for (index, bytes) in certificates.iter().enumerate() { - let cert = parsed(bytes)?; - if let Some(usage) = cert.key_usage().map_err(|_| Error::InvalidCertificate)? { + let cert = parsed(bytes, index)?; + let usage = cert + .key_usage() + .map_err(|_| Error::InvalidCertificate(Check::Encoding { index }))?; + if let Some(usage) = usage { if (index == 0 && !usage.value.digital_signature()) || (index > 0 && !usage.value.key_cert_sign()) { - return Err(Error::InvalidCertificate); + return Err(Error::InvalidCertificate(Check::KeyUsage { index })); } } } @@ -69,7 +79,7 @@ pub(super) fn verify_chain(certificates: &[Vec], root: &[u8]) -> Result<(), } pub(super) fn public_key(bytes: &[u8]) -> Result<[u8; 65], Error> { - let cert = parsed(bytes)?; + let cert = parsed(bytes, 0)?; let spki = cert.public_key(); if spki.algorithm.algorithm.to_id_string() != "1.2.840.10045.2.1" || spki @@ -93,7 +103,7 @@ pub(super) fn public_key(bytes: &[u8]) -> Result<[u8; 65], Error> { } pub(super) fn verify_nonce(bytes: &[u8], expected: &[u8]) -> Result<(), Error> { - let cert = parsed(bytes)?; + let cert = parsed(bytes, 0)?; let extension = cert .extensions() .iter() diff --git a/crates/buzz-push-gateway/src/app_attest/compatibility_tests.rs b/crates/buzz-push-gateway/src/app_attest/compatibility_tests.rs index aa90d9f64dd..03a88a3ac6e 100644 --- a/crates/buzz-push-gateway/src/app_attest/compatibility_tests.rs +++ b/crates/buzz-push-gateway/src/app_attest/compatibility_tests.rs @@ -131,6 +131,48 @@ fn shared_signed_certificate_constraint_corpus() { ); } +#[test] +fn certificate_rejections_name_the_failed_check() { + use super::error::CertificateCheck as Check; + use super::testing::{rejected_certificate_chains, test_root_der, valid_certificate_chain}; + let root = test_root_der(); + // A path rejection keeps webpki's full error, whose variant names the check. + let path = |variant: &str| Err(variant.to_owned()); + let is = |check: Check| Ok(Error::InvalidCertificate(check)); + let expected = [ + ("wrong usage", is(Check::KeyUsage { index: 0 })), + ("expired", path("CertExpired {")), + ("unknown critical", path("UnsupportedCriticalExtension")), + ("duplicate nonce", is(Check::Encoding { index: 0 })), + ("trailing", path("TrailingData(Certificate)")), + ]; + let cases = rejected_certificate_chains(); + assert_eq!(cases.len(), expected.len()); + for ((name, chain), (expected_name, expected)) in cases.iter().zip(expected) { + assert_eq!(*name, expected_name); + let error = super::certificate::verify_chain(chain, &root).unwrap_err(); + match expected { + Ok(expected) => assert_eq!(error, expected, "{name}"), + Err(variant) => assert!( + matches!(&error, Error::InvalidCertificate(Check::Path(detail)) if detail.starts_with(&variant)), + "{name}: {error:?}" + ), + } + } + assert_eq!( + Error::InvalidCertificate(Check::Path("UnknownIssuer".into())).to_string(), + "invalid certificate path or structure (path rejected: UnknownIssuer)" + ); + assert_eq!( + super::certificate::verify_chain(&[], &root), + Err(Error::InvalidCertificate(Check::Chain)) + ); + assert_eq!( + super::certificate::verify_chain(&valid_certificate_chain(), b"not a certificate"), + Err(Error::InvalidCertificate(Check::Root)) + ); +} + #[test] fn enrolled_key_verifies_following_assertion() { use super::testing::{build_test_assertion, build_test_attestation}; diff --git a/crates/buzz-push-gateway/src/app_attest/error.rs b/crates/buzz-push-gateway/src/app_attest/error.rs index 5b41aed50c0..63865168c17 100644 --- a/crates/buzz-push-gateway/src/app_attest/error.rs +++ b/crates/buzz-push-gateway/src/app_attest/error.rs @@ -1,9 +1,41 @@ use std::{error::Error, fmt}; +/// The certificate check that rejected an attestation, so operators can tell +/// an untrusted path from a malformed or misused certificate. +#[derive(Debug, PartialEq)] +pub enum CertificateCheck { + /// `x5c` is not an array, or is empty. A missing `x5c` fails the CBOR + /// schema first, as `InvalidCbor`. + Chain, + /// The configured Apple root is not exactly one PEM certificate. + Root, + /// The certificate at this `x5c` index is not exactly one DER X.509 + /// certificate with unique extensions. + Encoding { index: usize }, + /// webpki rejected the path; holds its error. + Path(String), + /// The certificate at this `x5c` index lacks the key usage its position requires. + KeyUsage { index: usize }, +} + +impl fmt::Display for CertificateCheck { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Chain => write!(f, "x5c is not a non-empty array"), + Self::Root => write!(f, "invalid configured root"), + Self::Encoding { index } => write!(f, "invalid encoding at x5c[{index}]"), + Self::Path(error) => write!(f, "path rejected: {error}"), + Self::KeyUsage { index } => write!(f, "invalid key usage at x5c[{index}]"), + } + } +} + #[derive(Debug, PartialEq)] pub enum AppAttestError { /// Certificate structure or trust validation failed. - InvalidCertificate, + InvalidCertificate(CertificateCheck), + /// The proof is not valid standard base64. + InvalidBase64, /// CBOR is malformed, ambiguous, or does not match the operation schema. InvalidCbor, /// An operational parsing budget was exceeded. @@ -22,7 +54,10 @@ pub enum AppAttestError { impl fmt::Display for AppAttestError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::InvalidCertificate => write!(f, "invalid certificate path or structure"), + Self::InvalidCertificate(check) => { + write!(f, "invalid certificate path or structure ({check})") + } + Self::InvalidBase64 => write!(f, "invalid base64 encoding"), Self::InvalidCbor => write!(f, "invalid CBOR structure"), Self::ResourceLimit => write!(f, "verification resource limit"), AppAttestError::InvalidNonce => write!(f, "invalid nonce"), diff --git a/crates/buzz-push-gateway/src/app_attest/proof.rs b/crates/buzz-push-gateway/src/app_attest/proof.rs index 42a629aced1..fae0d870349 100644 --- a/crates/buzz-push-gateway/src/app_attest/proof.rs +++ b/crates/buzz-push-gateway/src/app_attest/proof.rs @@ -3,7 +3,7 @@ use super::{ authenticator, cbor::{self, Value}, certificate, - error::AppAttestError as Error, + error::{AppAttestError as Error, CertificateCheck}, properties::ClientProperties, }; use aws_lc_rs::{ @@ -49,22 +49,24 @@ pub(super) fn enroll( let statement = envelope.field("attStmt")?; statement.text_keys()?; let Value::Array(chain) = statement.field("x5c")? else { - return Err(Error::InvalidCertificate); + return Err(Error::InvalidCertificate(CertificateCheck::Chain)); }; let certificates = chain .iter() .map(|c| c.bytes().map(|b| b.to_vec())) .collect::, _>>()?; - let leaf = certificates.first().ok_or(Error::InvalidCertificate)?; + let leaf = certificates + .first() + .ok_or(Error::InvalidCertificate(CertificateCheck::Chain))?; statement.field("receipt")?.bytes()?; let auth_bytes = envelope.field("authData")?.bytes()?; if root_pem.len() > cbor::MAX_BYTES { return Err(Error::ResourceLimit); } - let (rest, root) = - x509_parser::pem::parse_x509_pem(root_pem).map_err(|_| Error::InvalidCertificate)?; + let (rest, root) = x509_parser::pem::parse_x509_pem(root_pem) + .map_err(|_| Error::InvalidCertificate(CertificateCheck::Root))?; if root.label != "CERTIFICATE" || !rest.iter().all(u8::is_ascii_whitespace) { - return Err(Error::InvalidCertificate); + return Err(Error::InvalidCertificate(CertificateCheck::Root)); } certificate::verify_chain(&certificates, &root.contents)?; let public_key = certificate::public_key(leaf)?; diff --git a/crates/buzz-push-gateway/src/app_attest/testing.rs b/crates/buzz-push-gateway/src/app_attest/testing.rs index 22eacaafdf9..329a835f455 100644 --- a/crates/buzz-push-gateway/src/app_attest/testing.rs +++ b/crates/buzz-push-gateway/src/app_attest/testing.rs @@ -336,28 +336,14 @@ fn certificate_chain(change: impl FnOnce(&mut X509Builder)) -> Vec> { ] } -/// Run the same signed-certificate corpus against an alternative adapter. -pub fn compare_certificate_constraints( - verify_chain: impl Fn(&[Vec], &[u8]) -> Result<(), E>, - verify_nonce: impl Fn(&[u8], &[u8]) -> Result<(), E>, -) { +/// Signed certificate chains that each break one path or usage constraint. +pub fn rejected_certificate_chains() -> Vec<(&'static str, Vec>)> { use openssl::x509::extension::KeyUsage; - let root = X509::from_pem(TEST_ROOT_CA_CERT_PEM) - .unwrap() - .to_der() - .unwrap(); - let valid = certificate_chain(|builder| { - builder - .append_extension(KeyUsage::new().digital_signature().build().unwrap()) - .unwrap(); - }); - verify_chain(&valid, &root).unwrap(); let wrong_usage = certificate_chain(|builder| { builder .append_extension(KeyUsage::new().key_encipherment().build().unwrap()) .unwrap(); }); - assert!(verify_chain(&wrong_usage, &root).is_err()); let expired = certificate_chain(|builder| { builder .set_not_before(&Asn1Time::from_unix(0).unwrap()) @@ -366,7 +352,6 @@ pub fn compare_certificate_constraints( .set_not_after(&Asn1Time::from_unix(1).unwrap()) .unwrap(); }); - assert!(verify_chain(&expired, &root).is_err()); let unknown_critical = certificate_chain(|builder| { let oid = Asn1Object::from_str("1.2.3.4.5").unwrap(); let value = Asn1OctetString::new_from_bytes(b"\x05\x00").unwrap(); @@ -376,8 +361,29 @@ pub fn compare_certificate_constraints( ) .unwrap(); }); - assert!(verify_chain(&unknown_critical, &root).is_err()); - let duplicate_nonce = certificate_chain(|builder| { + let mut trailing = valid_certificate_chain(); + trailing[0].push(0); + vec![ + ("wrong usage", wrong_usage), + ("expired", expired), + ("unknown critical", unknown_critical), + ("duplicate nonce", duplicate_nonce_chain()), + ("trailing", trailing), + ] +} + +/// A signed chain that satisfies every path and usage constraint. +pub fn valid_certificate_chain() -> Vec> { + use openssl::x509::extension::KeyUsage; + certificate_chain(|builder| { + builder + .append_extension(KeyUsage::new().digital_signature().build().unwrap()) + .unwrap(); + }) +} + +fn duplicate_nonce_chain() -> Vec> { + certificate_chain(|builder| { let oid = Asn1Object::from_str("1.2.840.113635.100.8.2").unwrap(); let value = Asn1OctetString::new_from_bytes(b"\x30\x00").unwrap(); builder @@ -385,10 +391,26 @@ pub fn compare_certificate_constraints( openssl::x509::X509Extension::new_from_der(&oid, false, &value).unwrap(), ) .unwrap(); - }); - assert!(verify_chain(&duplicate_nonce, &root).is_err()); - assert!(verify_nonce(&duplicate_nonce[0], &[7; 32]).is_err()); - let mut trailing = valid; - trailing[0].push(0); - assert!(verify_chain(&trailing, &root).is_err()); + }) +} + +/// DER of the test root that signs every chain above. +pub fn test_root_der() -> Vec { + X509::from_pem(TEST_ROOT_CA_CERT_PEM) + .unwrap() + .to_der() + .unwrap() +} + +/// Run the same signed-certificate corpus against an alternative adapter. +pub fn compare_certificate_constraints( + verify_chain: impl Fn(&[Vec], &[u8]) -> Result<(), E>, + verify_nonce: impl Fn(&[u8], &[u8]) -> Result<(), E>, +) { + let root = test_root_der(); + verify_chain(&valid_certificate_chain(), &root).unwrap(); + for (name, chain) in rejected_certificate_chains() { + assert!(verify_chain(&chain, &root).is_err(), "{name}"); + } + assert!(verify_nonce(&duplicate_nonce_chain()[0], &[7; 32]).is_err()); } diff --git a/crates/buzz-push-gateway/src/main.rs b/crates/buzz-push-gateway/src/main.rs index 2a18d815a5f..8bbb1fc7476 100644 --- a/crates/buzz-push-gateway/src/main.rs +++ b/crates/buzz-push-gateway/src/main.rs @@ -17,11 +17,19 @@ use std::{ }, }; use tracing_subscriber::EnvFilter; + +/// Without `RUST_LOG`, keep the gateway's own warnings, such as App Attest +/// rejection reasons, alongside `EnvFilter`'s error-level default for all +/// other targets. +fn log_env_filter(rust_log: Option<&str>) -> EnvFilter { + EnvFilter::new(rust_log.unwrap_or("error,buzz_push_gateway=warn")) +} + #[tokio::main] async fn main() -> Result<(), Box> { tracing_subscriber::fmt() .json() - .with_env_filter(EnvFilter::from_default_env()) + .with_env_filter(log_env_filter(std::env::var("RUST_LOG").ok().as_deref())) .init(); if std::env::args().nth(1).as_deref() == Some("--migrate-only") { let database_url = std::env::var("DATABASE_URL")?; @@ -147,3 +155,53 @@ async fn shutdown_signal() -> std::io::Result<()> { tokio::signal::ctrl_c().await } } + +#[cfg(test)] +mod tests { + use super::log_env_filter; + use std::sync::{Arc, Mutex}; + + #[derive(Clone, Default)] + struct Capture(Arc>>); + impl std::io::Write for Capture { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + fn emitted(rust_log: Option<&str>) -> String { + let capture = Capture::default(); + let writer = capture.clone(); + let subscriber = tracing_subscriber::fmt() + .with_env_filter(log_env_filter(rust_log)) + .with_writer(move || writer.clone()) + .finish(); + tracing::subscriber::with_default(subscriber, || { + tracing::info!(target: "buzz_push_gateway", "gateway-info"); + tracing::warn!(target: "buzz_push_gateway", "gateway-warn"); + tracing::warn!(target: "sqlx", "dependency-warn"); + tracing::error!(target: "sqlx", "dependency-error"); + }); + let bytes = capture.0.lock().unwrap().clone(); + String::from_utf8(bytes).unwrap() + } + + // The only test in this binary, so no other thread races tracing's + // global callsite-interest cache. + #[test] + fn default_log_filter_keeps_gateway_warnings_and_dependency_errors() { + let logs = emitted(None); + assert!(logs.contains("gateway-warn"), "{logs}"); + assert!(logs.contains("dependency-error"), "{logs}"); + assert!(!logs.contains("gateway-info"), "{logs}"); + assert!(!logs.contains("dependency-warn"), "{logs}"); + + let logs = emitted(Some("info")); + assert!(logs.contains("gateway-info"), "{logs}"); + assert!(logs.contains("dependency-warn"), "{logs}"); + } +} diff --git a/crates/buzz-push-gateway/tests/app_attest_rejection_logs.rs b/crates/buzz-push-gateway/tests/app_attest_rejection_logs.rs new file mode 100644 index 00000000000..d56f224832c --- /dev/null +++ b/crates/buzz-push-gateway/tests/app_attest_rejection_logs.rs @@ -0,0 +1,61 @@ +//! App Attest rejections must tell operators which check failed. This is the +//! only test in its binary, so no other thread races tracing's global +//! callsite-interest cache. +use base64::{engine::general_purpose::STANDARD, Engine as _}; +use buzz_push_gateway::app_attest::AppAttestVerifier; +use std::sync::{Arc, Mutex}; + +#[derive(Clone, Default)] +struct Capture(Arc>>); +impl std::io::Write for Capture { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[test] +fn attestation_rejections_log_operation_reason_and_failed_check() { + let root = std::fs::read(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/apple-app-attestation-root.pem" + )) + .unwrap(); + let verifier = AppAttestVerifier::new("TEAM.test.app".into(), root).unwrap(); + let key_id = STANDARD.encode([7; 32]); + let cases = [ + ("not base64!", "encoding", "invalid base64 encoding"), + ("", "structure", "invalid CBOR structure"), + ( + &*STANDARD.encode(b"not cbor"), + "structure", + "invalid CBOR structure", + ), + ]; + for (attestation, reason, detail) in cases { + let capture = Capture::default(); + let writer = capture.clone(); + let subscriber = tracing_subscriber::fmt() + .json() + .with_max_level(tracing::Level::WARN) + .with_writer(move || writer.clone()) + .finish(); + let result = tracing::subscriber::with_default(subscriber, || { + verifier.verify_attestation(attestation, &key_id, b"client-data") + }); + assert!(result.is_err()); + let bytes = capture.0.lock().unwrap().clone(); + let line: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(line["level"], "WARN", "{line}"); + assert_eq!( + line["fields"]["message"], + "App Attest verification rejected" + ); + assert_eq!(line["fields"]["operation"], "attestation"); + assert_eq!(line["fields"]["reason"], reason, "{line}"); + assert_eq!(line["fields"]["detail"], detail, "{line}"); + } +} diff --git a/crates/buzz-relay-mesh/Cargo.toml b/crates/buzz-relay-mesh/Cargo.toml index 5760f13770a..72b8a7abb1f 100644 --- a/crates/buzz-relay-mesh/Cargo.toml +++ b/crates/buzz-relay-mesh/Cargo.toml @@ -9,12 +9,12 @@ repository.workspace = true [dependencies] tokio = { workspace = true } +buzz-pubsub = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } postcard = { workspace = true } iroh = { workspace = true } redis = { workspace = true } -deadpool-redis = { workspace = true } thiserror = { workspace = true } tracing = { workspace = true } uuid = { workspace = true } diff --git a/crates/buzz-relay-mesh/src/registry.rs b/crates/buzz-relay-mesh/src/registry.rs index 635dff6328e..4d8bd447cf1 100644 --- a/crates/buzz-relay-mesh/src/registry.rs +++ b/crates/buzz-relay-mesh/src/registry.rs @@ -17,6 +17,11 @@ use sha2::{Digest, Sha256}; use crate::{MeshError, RuntimeId}; pub const READY_KEY_PREFIX: &str = "mesh:ready:"; +/// Sorted set of live ready-record keys, scored by expiry (unix seconds). +/// Reconcile reads this instead of SCANning the whole keyspace, so its cost +/// scales with the number of peers rather than with every key in Redis. The +/// name deliberately does not match `mesh:ready:*`. +pub const READY_INDEX_KEY: &str = "mesh:ready-index"; pub const DEFAULT_REGISTRY_REFRESH: Duration = Duration::from_secs(15); pub const REGISTRY_EXPIRY_MULTIPLIER: u64 = 3; pub const ATTESTATION_CONTEXT: &str = "buzz-relay-mesh-ready-v1"; @@ -155,16 +160,54 @@ pub fn expiry_for(refresh: Duration) -> Duration { refresh.saturating_mul(REGISTRY_EXPIRY_MULTIPLIER as u32) } +fn unix_now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Decode and authenticate the value stored at `key`; `None` (with a warn) +/// for anything a peer must not dial. +fn decode_ready_record(key: &str, raw: &str) -> Option { + match serde_json::from_str::(raw) { + Ok(record) if record.key() == key => match record.verify_attestation() { + Ok(()) => Some(record), + Err(err) => { + tracing::warn!( + key, + runtime_id = %record.runtime_id, + %err, + "mesh ready registry attestation failed — skipping" + ); + None + } + }, + Ok(record) => { + tracing::warn!( + key, + runtime_id = %record.runtime_id, + "mesh ready registry key/runtime mismatch — skipping" + ); + None + } + Err(err) => { + tracing::warn!(key, %err, "mesh ready registry decode failed — skipping"); + None + } + } +} + /// Redis-backed mesh bootstrap registry. #[derive(Clone)] pub struct ReadyRegistry { - pool: deadpool_redis::Pool, + redis: buzz_pubsub::RedisConnection, refresh: Duration, } impl ReadyRegistry { - pub fn new(pool: deadpool_redis::Pool, refresh: Duration) -> Self { - Self { pool, refresh } + pub fn new(redis: buzz_pubsub::RedisConnection, refresh: Duration) -> Self { + Self { redis, refresh } } pub fn refresh_interval(&self) -> Duration { @@ -181,15 +224,37 @@ impl ReadyRegistry { /// rule stays explicit at the relay boundary. pub async fn publish_ready(&self, record: &ReadyRecord) -> Result<(), MeshError> { record.verify_attestation()?; - let mut conn = self.conn().await?; + let mut conn = self.redis.clone(); let payload = serde_json::to_string(record) .map_err(|e| MeshError::Transport(format!("ready registry encode: {e}")))?; let ttl_secs = self.expiry().as_secs().max(1); - redis::cmd("SET") - .arg(record.key()) + let now = unix_now_secs(); + let key = record.key(); + // One MULTI: the record, its index entry, pruning of entries whose + // owners stopped refreshing, and an index TTL so a fully stopped fleet + // leaves nothing behind. + redis::pipe() + .atomic() + .cmd("SET") + .arg(&key) .arg(payload) .arg("EX") .arg(ttl_secs) + .ignore() + .cmd("ZADD") + .arg(READY_INDEX_KEY) + .arg(now + ttl_secs) + .arg(&key) + .ignore() + .cmd("ZREMRANGEBYSCORE") + .arg(READY_INDEX_KEY) + .arg("-inf") + .arg(format!("({now}")) + .ignore() + .cmd("EXPIRE") + .arg(READY_INDEX_KEY) + .arg(ttl_secs) + .ignore() .query_async::<()>(&mut conn) .await?; Ok(()) @@ -197,19 +262,56 @@ impl ReadyRegistry { /// Remove this runtime on clean shutdown. A crash is handled by TTL expiry. pub async fn clear_ready(&self, runtime_id: RuntimeId) -> Result<(), MeshError> { - let mut conn = self.conn().await?; - redis::cmd("DEL") - .arg(ready_key(runtime_id)) + let mut conn = self.redis.clone(); + let key = ready_key(runtime_id); + redis::pipe() + .atomic() + .cmd("DEL") + .arg(&key) + .ignore() + .cmd("ZREM") + .arg(READY_INDEX_KEY) + .arg(&key) + .ignore() .query_async::<()>(&mut conn) .await?; Ok(()) } - /// Scan all ready records. Malformed/stale/unauthenticated values are - /// skipped with a warn: a bad registry entry must not prevent bootstrap - /// from healthy peers. - pub async fn scan_ready(&self) -> Result, MeshError> { - let mut conn = self.conn().await?; + /// Read every indexed ready record: one ZRANGE plus one pipelined GET + /// round trip, independent of the size of the Redis keyspace. + /// Malformed/stale/unauthenticated values are skipped with a warn: a bad + /// registry entry must not prevent bootstrap from healthy peers. + pub async fn ready_records(&self) -> Result, MeshError> { + let mut conn = self.redis.clone(); + let keys: Vec = redis::cmd("ZRANGE") + .arg(READY_INDEX_KEY) + .arg(0) + .arg(-1) + .query_async(&mut conn) + .await?; + if keys.is_empty() { + return Ok(Vec::new()); + } + let mut pipe = redis::pipe(); + for key in &keys { + pipe.cmd("GET").arg(key); + } + let raws: Vec> = pipe.query_async(&mut conn).await?; + Ok(keys + .iter() + .zip(raws) + .filter_map(|(key, raw)| decode_ready_record(key, &raw?)) + .collect()) + } + + /// Full-keyspace SCAN for ready records, including those published by + /// relays that predate [`READY_INDEX_KEY`]. Cost is O(total Redis keys), + /// so the runtime runs it only at boot, on an unknown inbound peer, and + /// once every [`crate::runtime::LEGACY_SCAN_INTERVAL`]. Mixed-version compatibility only: delete it (and those call + /// sites) once every deployed relay writes the index. + pub async fn legacy_scan_ready(&self) -> Result, MeshError> { + let mut conn = self.redis.clone(); let mut cursor = 0u64; let mut out = Vec::new(); @@ -226,25 +328,8 @@ impl ReadyRegistry { for key in keys { let raw: Option = redis::cmd("GET").arg(&key).query_async(&mut conn).await?; - let Some(raw) = raw else { continue }; - match serde_json::from_str::(&raw) { - Ok(record) if record.key() == key => match record.verify_attestation() { - Ok(()) => out.push(record), - Err(err) => tracing::warn!( - key, - runtime_id = %record.runtime_id, - %err, - "mesh ready registry attestation failed — skipping" - ), - }, - Ok(record) => tracing::warn!( - key, - runtime_id = %record.runtime_id, - "mesh ready registry key/runtime mismatch — skipping" - ), - Err(err) => { - tracing::warn!(key, %err, "mesh ready registry decode failed — skipping") - } + if let Some(record) = raw.and_then(|raw| decode_ready_record(&key, &raw)) { + out.push(record); } } @@ -264,13 +349,6 @@ impl ReadyRegistry { published: false, } } - - async fn conn(&self) -> Result { - self.pool - .get() - .await - .map_err(|e| MeshError::Transport(format!("redis pool: {e}"))) - } } /// Readiness-gated registry heartbeat. @@ -324,6 +402,10 @@ mod tests { nostr::Keys::generate() } + fn lazy_redis(url: &str) -> buzz_pubsub::RedisConnection { + buzz_pubsub::redis_connection(url).expect("redis connection") + } + fn ready_record(byte: u8) -> ReadyRecord { ReadyRecord::new(rid(byte), &relay_keys(), vec![], 1, vec![]) } @@ -341,12 +423,12 @@ mod tests { assert_eq!(expiry_for(Duration::from_secs(15)), Duration::from_secs(45)); } - #[test] - fn heartbeat_starts_unpublished() { - let pool = deadpool_redis::Config::from_url("redis://127.0.0.1:6379") - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); - let registry = ReadyRegistry::new(pool, Duration::from_secs(15)); + #[tokio::test] + async fn heartbeat_starts_unpublished() { + let registry = ReadyRegistry::new( + lazy_redis("redis://127.0.0.1:6379"), + Duration::from_secs(15), + ); let heartbeat = registry.heartbeat(ready_record(1)); assert!(!heartbeat.published()); assert_eq!(heartbeat.record().runtime_id, rid(1)); @@ -382,4 +464,144 @@ mod tests { record.runtime_pubkey = rid(12).to_hex(); assert!(record.verify_attestation().is_err()); } + + /// Redis-backed registry tests. CI runs them in the relay integration lane + /// (`--run-ignored ignored-only`, `BUZZ_TEST_REDIS_URL`). They share the + /// fleet-wide index key, so they assert only on their own records. + mod external_infra_redis { + use super::*; + + fn pool() -> buzz_pubsub::RedisConnection { + let url = std::env::var("BUZZ_TEST_REDIS_URL") + .unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string()); + lazy_redis(&url) + } + + fn fresh_record() -> ReadyRecord { + let runtime_id = RuntimeId(nostr::Keys::generate().public_key().to_bytes()); + ReadyRecord::new(runtime_id, &relay_keys(), vec![], 1, vec![]) + } + + fn ids(records: &[ReadyRecord]) -> Vec { + records.iter().map(|r| r.runtime_id).collect() + } + + async fn index_score(pool: &buzz_pubsub::RedisConnection, member: &str) -> Option { + let mut conn = pool.clone(); + redis::cmd("ZSCORE") + .arg(READY_INDEX_KEY) + .arg(member) + .query_async(&mut conn) + .await + .expect("zscore") + } + + #[tokio::test] + #[ignore = "requires Redis"] + async fn published_records_are_read_from_the_index_and_cleared_from_it() { + let pool = pool(); + let registry = ReadyRegistry::new(pool.clone(), Duration::from_secs(15)); + let (a, b) = (fresh_record(), fresh_record()); + registry.publish_ready(&a).await.unwrap(); + registry.publish_ready(&b).await.unwrap(); + + let indexed = ids(®istry.ready_records().await.unwrap()); + assert!(indexed.contains(&a.runtime_id) && indexed.contains(&b.runtime_id)); + let scanned = ids(®istry.legacy_scan_ready().await.unwrap()); + assert!(scanned.contains(&a.runtime_id) && scanned.contains(&b.runtime_id)); + + registry.clear_ready(a.runtime_id).await.unwrap(); + assert_eq!(index_score(&pool, &a.key()).await, None); + let indexed = ids(®istry.ready_records().await.unwrap()); + assert!(!indexed.contains(&a.runtime_id)); + assert!(indexed.contains(&b.runtime_id)); + assert!(!ids(®istry.legacy_scan_ready().await.unwrap()).contains(&a.runtime_id)); + + registry.clear_ready(b.runtime_id).await.unwrap(); + } + + #[tokio::test] + #[ignore = "requires Redis"] + async fn pre_index_records_are_found_only_by_the_legacy_scan() { + let pool = pool(); + let registry = ReadyRegistry::new(pool.clone(), Duration::from_secs(15)); + let legacy = fresh_record(); + { + // What a relay that predates the index writes. + let mut conn = pool.clone(); + redis::cmd("SET") + .arg(legacy.key()) + .arg(serde_json::to_string(&legacy).unwrap()) + .arg("EX") + .arg(45) + .query_async::<()>(&mut conn) + .await + .unwrap(); + } + + assert!(!ids(®istry.ready_records().await.unwrap()).contains(&legacy.runtime_id)); + assert!(ids(®istry.legacy_scan_ready().await.unwrap()).contains(&legacy.runtime_id)); + + registry.clear_ready(legacy.runtime_id).await.unwrap(); + } + + #[tokio::test] + #[ignore = "requires Redis"] + async fn publish_prunes_expired_index_entries_and_bounds_the_index() { + let pool = pool(); + let registry = ReadyRegistry::new(pool.clone(), Duration::from_secs(15)); + // An owner that stopped refreshing: its key has expired, its + // index entry's score is in the past. + let gone = ready_key(fresh_record().runtime_id); + { + let mut conn = pool.clone(); + redis::cmd("ZADD") + .arg(READY_INDEX_KEY) + .arg(unix_now_secs() - 1) + .arg(&gone) + .query_async::<()>(&mut conn) + .await + .unwrap(); + } + // Indexed but expired: skipped, not an error. + registry.ready_records().await.unwrap(); + + let fresh = fresh_record(); + registry.publish_ready(&fresh).await.unwrap(); + assert_eq!(index_score(&pool, &gone).await, None); + let score = index_score(&pool, &fresh.key()).await.expect("indexed"); + assert!(score > unix_now_secs() as f64); + + let mut conn = pool.clone(); + let ttl: i64 = redis::cmd("TTL") + .arg(READY_INDEX_KEY) + .query_async(&mut conn) + .await + .unwrap(); + assert!(ttl > 0 && ttl <= 45, "index TTL {ttl}"); + drop(conn); + + registry.clear_ready(fresh.runtime_id).await.unwrap(); + } + + #[tokio::test] + #[ignore = "requires Redis"] + async fn indexed_entry_whose_record_expired_is_skipped() { + let pool = pool(); + let registry = ReadyRegistry::new(pool.clone(), Duration::from_secs(15)); + let record = fresh_record(); + registry.publish_ready(&record).await.unwrap(); + { + let mut conn = pool.clone(); + redis::cmd("DEL") + .arg(record.key()) + .query_async::<()>(&mut conn) + .await + .unwrap(); + } + assert!(index_score(&pool, &record.key()).await.is_some()); + assert!(!ids(®istry.ready_records().await.unwrap()).contains(&record.runtime_id)); + registry.clear_ready(record.runtime_id).await.unwrap(); + } + } } diff --git a/crates/buzz-relay-mesh/src/runtime.rs b/crates/buzz-relay-mesh/src/runtime.rs index e56af33206e..8347aec855a 100644 --- a/crates/buzz-relay-mesh/src/runtime.rs +++ b/crates/buzz-relay-mesh/src/runtime.rs @@ -9,7 +9,7 @@ //! runtime id is present in the (attested) membership table; unknown ids get //! one registry rescan before rejection. Membership is a hint — admission //! here gates *dialability*, never session ownership. -//! - **Reconcile loop**: periodically rescans the Redis ready registry and +//! - **Reconcile loop**: periodically reads the Redis ready-registry index and //! dials every known, non-draining peer we are not yet connected to. This is //! what makes the mesh *warm*: failover is "next frame goes elsewhere," not //! "wait for a handshake." @@ -41,10 +41,22 @@ use crate::{InboundHandler, MeshDatagram, MeshError, MeshStream, RelayPeerTransp /// How often the reconcile loop rescans the registry and dials missing peers. pub const DEFAULT_RECONCILE_INTERVAL: Duration = Duration::from_secs(5); +/// How often a reconcile pass also runs the full-keyspace legacy SCAN, so peers +/// running a relay that predates the ready-record index stay in the table +/// during a mixed-version rollout (membership peer records expire after five +/// minutes). Measured in elapsed time, not passes: a pass waits on its dials, +/// so a pass count would stretch exactly while peers are unreachable. Delete +/// with [`ReadyRegistry::legacy_scan_ready`]. +pub const LEGACY_SCAN_INTERVAL: Duration = Duration::from_secs(60); /// How often each side sends a gossip digest on every control stream. pub const DEFAULT_GOSSIP_INTERVAL: Duration = Duration::from_secs(2); /// Bound on queued control-stream frames per peer before backpressure. const CONTROL_QUEUE_DEPTH: usize = 64; +/// Bound on one outbound connect attempt. Without it a dial to a dead +/// address (a stale ready record left by a crashed pod) waits out QUIC's +/// 30s idle timeout. Peers are in-cluster, so a live handshake takes +/// milliseconds. +pub const DIAL_TIMEOUT: Duration = Duration::from_secs(2); struct PeerEntry { peer: MeshPeer, @@ -149,7 +161,7 @@ impl MeshRuntime { /// Force one reconcile pass right now (bootstrap fast-path: dial the seed /// records without waiting for the first interval tick). pub async fn reconcile_now(&self) { - reconcile_once(&self.inner).await; + reconcile_once(&self.inner, RegistryRead::LegacyScan).await; } /// Stop all loops and drop all peer connections. @@ -316,29 +328,88 @@ async fn accept_loop(inner: Arc) { } /// Admission check for inbound connections: the runtime id must appear in the -/// attested membership table. Unknown ids get one registry rescan (covers the -/// bootstrap race where a fresh pod dials us before our next reconcile tick). +/// attested membership table. Unknown ids get one index read, then one legacy +/// scan (covers the bootstrap race where a fresh pod dials us before our next +/// reconcile tick, including a pod running a relay that predates the index). async fn is_known_peer(inner: &Arc, runtime_id: RuntimeId) -> bool { if inner.membership.has_peer(runtime_id) { return true; } - if let Some(registry) = &inner.registry { - match registry.scan_ready().await { - Ok(records) => inner.membership.apply_ready_records(records), - Err(err) => tracing::warn!(%err, "mesh: registry rescan on inbound failed"), + for read in [RegistryRead::Index, RegistryRead::LegacyScan] { + refresh_from_registry(inner, read).await; + if inner.membership.has_peer(runtime_id) { + return true; } } - inner.membership.has_peer(runtime_id) + false +} + +/// How a reconcile pass reads the ready registry. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RegistryRead { + /// O(peers): the ready-record index. + Index, + /// O(total Redis keys): also finds peers that predate the index. + LegacyScan, +} + +impl RegistryRead { + /// Steady-state choice for a pass starting `since_last_scan` after the + /// previous legacy scan: the legacy scan once [`LEGACY_SCAN_INTERVAL`] has + /// elapsed, the index otherwise. + fn due(since_last_scan: Duration) -> Self { + if since_last_scan >= LEGACY_SCAN_INTERVAL { + Self::LegacyScan + } else { + Self::Index + } + } +} + +async fn refresh_from_registry(inner: &Arc, read: RegistryRead) { + let Some(registry) = &inner.registry else { + return; + }; + let result = match read { + RegistryRead::Index => registry.ready_records().await, + RegistryRead::LegacyScan => registry.legacy_scan_ready().await, + }; + match result { + Ok(records) => inner.membership.apply_ready_records(records), + Err(err) => tracing::warn!(%err, ?read, "mesh: registry read failed"), + } +} + +/// When the reconcile loop last ran the legacy scan. +struct LegacyScanClock { + last_scan: Instant, +} + +impl LegacyScanClock { + /// `reconcile_now` scans at boot, so the clock starts with the loop. + fn starting_at(now: Instant) -> Self { + Self { last_scan: now } + } + + /// The read for a pass starting at `now`; a due scan restarts the clock. + fn next_read(&mut self, now: Instant) -> RegistryRead { + let read = RegistryRead::due(now.saturating_duration_since(self.last_scan)); + if read == RegistryRead::LegacyScan { + self.last_scan = now; + } + read + } } async fn reconcile_loop(inner: Arc) { + let mut clock = LegacyScanClock::starting_at(Instant::now()); loop { - reconcile_once(&inner).await; + reconcile_once(&inner, clock.next_read(Instant::now())).await; tokio::time::sleep(inner.reconcile_interval).await; } } -async fn reconcile_once(inner: &Arc) { +async fn reconcile_once(inner: &Arc, read: RegistryRead) { let started = Instant::now(); { let peers = inner.peers.read().expect("peer lock poisoned"); @@ -351,19 +422,19 @@ async fn reconcile_once(inner: &Arc) { tracing::info!(pruned, "mesh: pruned expired peer records"); } - if let Some(registry) = &inner.registry { - match registry.scan_ready().await { - Ok(records) => inner.membership.apply_ready_records(records), - Err(err) => tracing::warn!(%err, "mesh: registry scan failed"), - } - } + refresh_from_registry(inner, read).await; inner.membership.publish_table_metrics(); let candidates = dial_candidates(inner); metrics::gauge!(telemetry::RECONCILE_CANDIDATES).set(candidates.len() as f64); - for runtime_id in candidates { - dial_peer(inner, runtime_id).await; - } + // Dial concurrently so one unreachable peer cannot delay the rest. The + // candidate set is bounded by the membership table. + futures_util::future::join_all( + candidates + .into_iter() + .map(|runtime_id| dial_peer(inner, runtime_id)), + ) + .await; metrics::histogram!(telemetry::RECONCILE_PASS_SECONDS).record(started.elapsed().as_secs_f64()); } @@ -384,8 +455,8 @@ fn dial_candidates(inner: &Inner) -> Vec { .collect() } -/// Dial `runtime_id`'s addresses in turn. Each dial can take a minute against -/// a dead runtime, so before every attempt this re-reads the record and stops +/// Dial `runtime_id`'s addresses in turn. Each attempt is capped at +/// `DIAL_TIMEOUT`, and before every attempt this re-reads the record and stops /// once it has expired or started draining, or a connection has landed /// (inbound accept, or a tie-break). async fn dial_peer(inner: &Arc, runtime_id: RuntimeId) { @@ -413,7 +484,13 @@ async fn dial_peer(inner: &Arc, runtime_id: RuntimeId) { } }; let started = Instant::now(); - let result = inner.endpoint.connect(endpoint_addr).await; + let result = + match tokio::time::timeout(DIAL_TIMEOUT, inner.endpoint.connect(endpoint_addr)).await { + Ok(result) => result, + Err(_) => Err(MeshError::Transport(format!( + "connect timed out after {DIAL_TIMEOUT:?}" + ))), + }; telemetry::record_dial(result.is_ok(), started.elapsed()); match result { Ok(peer) => { @@ -665,6 +742,45 @@ mod tests { SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0) } + #[test] + fn steady_state_reads_the_index_and_scans_on_elapsed_time() { + let cases = [ + (Duration::ZERO, RegistryRead::Index), + (DEFAULT_RECONCILE_INTERVAL, RegistryRead::Index), + ( + LEGACY_SCAN_INTERVAL - Duration::from_millis(1), + RegistryRead::Index, + ), + (LEGACY_SCAN_INTERVAL, RegistryRead::LegacyScan), + // One pass that sat on slow dials past the interval: the very next + // pass scans, however few passes have run. + (2 * LEGACY_SCAN_INTERVAL, RegistryRead::LegacyScan), + ]; + for (since_last_scan, want) in cases { + assert_eq!( + RegistryRead::due(since_last_scan), + want, + "{since_last_scan:?} since the last scan" + ); + } + // A legacy scan per interval keeps pre-index peers fresher than the + // membership peer-record TTL. + assert!(LEGACY_SCAN_INTERVAL < crate::membership::DEFAULT_PEER_RECORD_TTL); + } + + #[test] + fn a_legacy_scan_restarts_the_clock() { + let start = Instant::now(); + let mut clock = LegacyScanClock::starting_at(start); + let at = |secs| start + Duration::from_secs(secs); + assert_eq!(clock.next_read(at(5)), RegistryRead::Index); + assert_eq!(clock.next_read(at(60)), RegistryRead::LegacyScan); + // The next passes read the index until another interval elapses. + assert_eq!(clock.next_read(at(65)), RegistryRead::Index); + assert_eq!(clock.next_read(at(119)), RegistryRead::Index); + assert_eq!(clock.next_read(at(120)), RegistryRead::LegacyScan); + } + const RECONCILE_INTERVAL: Duration = Duration::from_millis(200); /// Long enough that the background reconcile loop never runs a second /// pass during a test, so the test drives every dial and state sync. @@ -1071,6 +1187,57 @@ mod tests { b_accept.abort(); } + /// Regression: a stale ready record (a crashed pod's address) held the + /// boot-time reconcile pass for QUIC's 30s idle timeout, once per dead + /// peer. Each dial is bounded by `DIAL_TIMEOUT` and the pass dials + /// concurrently, so three dead peers cost one timeout and the live peer + /// still connects in the same pass. + #[tokio::test] + async fn reconcile_pass_bounds_dials_to_unresponsive_peers() { + let (a, _) = runtime_with(30, |membership| membership, QUIET).await; + let (live, live_addrs, live_accept) = accepting_endpoint(31, false).await; + a.membership() + .apply_gossip_record(GossipRecord::new(live.runtime_id(), live_addrs, 1)); + + // Bound UDP sockets that never read: handshakes vanish without an + // ICMP refusal, exactly like a vacated pod IP. + let mut black_holes = Vec::new(); + let mut dead_ids = Vec::new(); + for key_byte in 32..35u8 { + let socket = std::net::UdpSocket::bind(loopback_any()).unwrap(); + let id = crate::endpoint::runtime_id_from_public_key( + SecretKey::from_bytes(&[key_byte; 32]).public(), + ); + a.membership().apply_gossip_record(GossipRecord::new( + id, + vec![socket.local_addr().unwrap().to_string()], + 1, + )); + black_holes.push(socket); + dead_ids.push(id); + } + + let started = Instant::now(); + timeout(DIAL_TIMEOUT * 2, a.reconcile_now()) + .await + .expect("dead peers must cost one dial timeout, not one each"); + assert!( + started.elapsed() >= DIAL_TIMEOUT, + "dead dials ran to the timeout" + ); + + assert_eq!( + state_of(&a, live.runtime_id()), + Some(ConnectionState::Connected) + ); + for id in dead_ids { + assert_eq!(state_of(&a, id), Some(ConnectionState::Disconnected)); + } + a.shutdown(); + live_accept.abort(); + drop(black_holes); + } + #[tokio::test] async fn reconcile_pass_prunes_expired_peer_records() { use metrics_util::debugging::{DebugValue, DebuggingRecorder}; diff --git a/crates/buzz-relay/CHANGELOG.md b/crates/buzz-relay/CHANGELOG.md index 7ee7e9a303b..4e02e85ef9a 100644 --- a/crates/buzz-relay/CHANGELOG.md +++ b/crates/buzz-relay/CHANGELOG.md @@ -1,5 +1,306 @@ # Changelog +## relay-v0.3.0 + +- fix(relay): bound invite preview host lookup ([#9308](https://github.com/block/buzz/pull/9308)) ([`2c5c8343e`](https://github.com/block/buzz/commit/2c5c8343ef8c39cad0cb27cbc07bffc7141e345a)) +- fix(relay): saturate filter limits instead of casting ([#9230](https://github.com/block/buzz/pull/9230)) ([`47674dc32`](https://github.com/block/buzz/commit/47674dc3224383b110c36ee1b752c7fd60ee3d7d)) +- fix(relay): fence pending subscriptions on close or replacement ([#2382](https://github.com/block/buzz/pull/2382)) ([`30e1fa47f`](https://github.com/block/buzz/commit/30e1fa47fb9a67cbc408cfcee83dcf280ab49595)) +- Serve video and poster previews for invite links ([#9306](https://github.com/block/buzz/pull/9306)) ([`773849665`](https://github.com/block/buzz/commit/773849665e0592b9f99dbfbaa2f706de01a8f5a7)) +- fix(db): give the replica-fence probe its own pool and instrument it ([#9297](https://github.com/block/buzz/pull/9297)) ([`5b1698ec2`](https://github.com/block/buzz/commit/5b1698ec244d6687ff60be0c29b95348d18c610f)) +- fix(relay): never close connections when cross-node fan-out falls behind ([#9302](https://github.com/block/buzz/pull/9302)) ([`dd9da3ac6`](https://github.com/block/buzz/commit/dd9da3ac6d854ec199e8b3dc661fdb84eb995a8c)) +- feat(relay): let an operator mint invites for a community owner or admin ([#9265](https://github.com/block/buzz/pull/9265)) ([`2b16d0ea1`](https://github.com/block/buzz/commit/2b16d0ea1a5550146c3dbe303ad918debcf0094e)) +- fix(relay): deliver slow cross-node events late instead of closing their recipients ([#9235](https://github.com/block/buzz/pull/9235)) ([`15174bc2b`](https://github.com/block/buzz/commit/15174bc2b2631531bc45d8ec72d8499f1b194660)) +- [buzz] Recover database pool capacity after stalled connections ([#9267](https://github.com/block/buzz/pull/9267)) ([`22d96d94e`](https://github.com/block/buzz/commit/22d96d94ef043292803b6d5c929652abd69612dd)) +- Record why relay connections close and quiet close warnings ([#9245](https://github.com/block/buzz/pull/9245)) ([`31fa53174`](https://github.com/block/buzz/commit/31fa53174d5bf7995c6cab18954514cc036125e2)) +- fix(relay): say "channel owner or admin" in the call_webhook save refusal ([#9169](https://github.com/block/buzz/pull/9169)) ([`4bfe60197`](https://github.com/block/buzz/commit/4bfe60197e8c390a8701053228cd50c5391f37d3)) +- fix(cli): preserve attachments across successive edits ([#9226](https://github.com/block/buzz/pull/9226)) ([`8130cd9fc`](https://github.com/block/buzz/commit/8130cd9fc7d8fce315eb34fb14207d915841e8c5)) +- fix(media): revoke private channel attachment reads ([#9077](https://github.com/block/buzz/pull/9077)) ([`96af488d9`](https://github.com/block/buzz/commit/96af488d968a1ae9d961c2132bea27822735f8da)) +- Manage community NIP-FI policy with enable, disable and status ([#9176](https://github.com/block/buzz/pull/9176)) ([`2cd40badb`](https://github.com/block/buzz/commit/2cd40badb85de059a6916206e133da7a0a88fb2e)) +- [buzz] Recover interrupted default-channel auto-joins ([#9045](https://github.com/block/buzz/pull/9045)) ([`39d5159ca`](https://github.com/block/buzz/commit/39d5159caf748d9696646fc0c761ff639d919f0d)) +- fix(db): keep retained fence proofs when a probe fails ([#9200](https://github.com/block/buzz/pull/9200)) ([`38795ada8`](https://github.com/block/buzz/commit/38795ada8749509607caddbafd4049162f8a31f9)) +- fix(relay): set received_at in the system-channel fan-out test helper ([#9214](https://github.com/block/buzz/pull/9214)) ([`6c3ffd160`](https://github.com/block/buzz/commit/6c3ffd160bc0caf8946ce57f3aa50e4f5c615e8e)) +- Allow operators to set initial NIP-FI policy on create ([#9211](https://github.com/block/buzz/pull/9211)) ([`446e9e076`](https://github.com/block/buzz/commit/446e9e0762a4bfe4c74e138eacf44d7d9d657ca9)) +- feat(relay): runtime-tunable history-read and AUTH concurrency caps via feature flags ([#9170](https://github.com/block/buzz/pull/9170)) ([`a17243d84`](https://github.com/block/buzz/commit/a17243d846c887fbab862f494ec474821e6ca1cc)) +- fix(relay): route live REQ events by each filter's own channel scope ([#8519](https://github.com/block/buzz/pull/8519)) ([`01d977860`](https://github.com/block/buzz/commit/01d9778606bd5a1bbe80a743a1c2cc659721cf12)) +- fix(relay): deliver multi-node fan-out concurrently and never drop silently ([#9195](https://github.com/block/buzz/pull/9195)) ([`27ab6a085`](https://github.com/block/buzz/commit/27ab6a085a6689da5c0c81ca74ee5ccc90ed2003)) +- perf(db): bound since-limited events reads with the month-floor literal ([#9197](https://github.com/block/buzz/pull/9197)) ([`0d5edb8bb`](https://github.com/block/buzz/commit/0d5edb8bb36bbcbe78180ad3d63eaca38a6fdd20)) +- perf(relay): serve restriction rows for 10 s with cross-pod invalidation ([#9199](https://github.com/block/buzz/pull/9199)) ([`744f3946f`](https://github.com/block/buzz/commit/744f3946f6fe1ff7a649c132638d5af608900dbd)) +- Pin sqlx to the upstream fix for a cancelled BEGIN ([#9192](https://github.com/block/buzz/pull/9192)) ([`abb2586f8`](https://github.com/block/buzz/commit/abb2586f8ca67414b5c6e796d2c468755fe26ee3)) +- fix(relay): regenerate missing image thumbnails on request ([#9174](https://github.com/block/buzz/pull/9174)) ([`1bb2ad443`](https://github.com/block/buzz/commit/1bb2ad443d4ee4512dd0927888ad21a4a1c041bc)) +- Cache channel memberships once per user ([#9060](https://github.com/block/buzz/pull/9060)) ([`32997e2e1`](https://github.com/block/buzz/commit/32997e2e1b57d0d1140075f644938ca1538a6309)) +- fix(relay): close legacy sockets after community FI upgrades ([#8991](https://github.com/block/buzz/pull/8991)) ([`4e28176f1`](https://github.com/block/buzz/commit/4e28176f13957f4bb77f58c5b4aa0ad137017423)) +- fix(relay): close a WS search whose hit hydration fails instead of sending EOSE ([#9148](https://github.com/block/buzz/pull/9148)) ([`1bb44ae9e`](https://github.com/block/buzz/commit/1bb44ae9effd78a87c684a47edf5cc335b8091a8)) +- perf(db): stop the events recent pass at a ceiling for regular-kind reads ([#9157](https://github.com/block/buzz/pull/9157)) ([`8ae35c5c9`](https://github.com/block/buzz/commit/8ae35c5c92694af7488bbf6a2140c27aed9d0798)) +- feat(relay): project compact viewer memberships ([#9118](https://github.com/block/buzz/pull/9118)) ([`bb3c5f717`](https://github.com/block/buzz/commit/bb3c5f7175041907db50df9640d6377a69cf9be9)) +- feat(relay): log WebSocket EVENT writes on the access target ([#9154](https://github.com/block/buzz/pull/9154)) ([`fba8a7a94`](https://github.com/block/buzz/commit/fba8a7a94febd4fbfb97df90f7c6be8fb258cf4c)) +- perf(db): plan multi-value #d reads with their values ([#9131](https://github.com/block/buzz/pull/9131)) ([`bd1b17dee`](https://github.com/block/buzz/commit/bd1b17dee8348b21b33abe35ee4eafa8730f8a83)) +- feat(cli): send NIP-FI evidence via credential chain and Buzz desktop ([#8999](https://github.com/block/buzz/pull/8999)) ([`e3a0f3d59`](https://github.com/block/buzz/commit/e3a0f3d59dfd08696cff80badb2d80d9a5096a61)) +- feat(protocol): define compact membership discovery ([#9117](https://github.com/block/buzz/pull/9117)) ([`66c3d6917`](https://github.com/block/buzz/commit/66c3d6917ddd88c98a0bc2a31663d60f209e0088)) +- perf(db): hydrate search hits with exact event timestamps ([#9126](https://github.com/block/buzz/pull/9126)) ([`cec47c20a`](https://github.com/block/buzz/commit/cec47c20a3f1220961a80306209b0668fff57b6a)) +- perf(db): prune post-commit push enqueue by signed event timestamp ([#9128](https://github.com/block/buzz/pull/9128)) ([`997ce3a2c`](https://github.com/block/buzz/commit/997ce3a2c9cd9e51f8168c64756782aca1c51b89)) +- perf(db): use exact event timestamps for transactional deletion ([#9130](https://github.com/block/buzz/pull/9130)) ([`0cfa50ac7`](https://github.com/block/buzz/commit/0cfa50ac70b26208367c56dc5ddf3fcef61808e4)) +- perf(redis): index mesh ready records and share one Redis connection ([#9113](https://github.com/block/buzz/pull/9113)) ([`b6d440314`](https://github.com/block/buzz/commit/b6d4403149af700c0c11ce07b85c3bc105a1b605)) +- feat(cli): user status expiry and status read ([#8777](https://github.com/block/buzz/pull/8777)) ([`b0f68a06a`](https://github.com/block/buzz/commit/b0f68a06ad25889fb304a88889a679a7ef15b862)) +- feat(relay): add kind 30180 custom emoji entry ([#8783](https://github.com/block/buzz/pull/8783)) ([`5c91e0d6f`](https://github.com/block/buzz/commit/5c91e0d6fe4e834b2aba49a3e8e9653bffafd4b4)) +- feat(cli): report a message to relay moderators ([#8829](https://github.com/block/buzz/pull/8829)) ([`82bc5a47c`](https://github.com/block/buzz/commit/82bc5a47c5e58d4c4579420cd4dab16b8a3f3da3)) +- buzz-db: read explicit #h sets one channel at a time ([#9110](https://github.com/block/buzz/pull/9110)) ([`0ada1d370`](https://github.com/block/buzz/commit/0ada1d37077f701507855fe58a4e78ac4e345f30)) +- fix(db): end each table's maintenance transaction before the next ([#9096](https://github.com/block/buzz/pull/9096)) ([`4c7c15a9c`](https://github.com/block/buzz/commit/4c7c15a9c2b91504c7d2c2562c8c75a667199f33)) +- fix(relay): read kind:39000/39001 inputs behind the replacement lock ([#9035](https://github.com/block/buzz/pull/9035)) ([`1a42b5c39`](https://github.com/block/buzz/commit/1a42b5c39cdebfc703004fec951790e363de9d9c)) +- fix(db): unlock the storage-accounting lease before its session closes ([#9097](https://github.com/block/buzz/pull/9097)) ([`580caca66`](https://github.com/block/buzz/commit/580caca66714b3e09fd3e0eb2e522d6f4aa5cc12)) +- test(relay,db): remove three timing races from Postgres and E2E tests ([#9098](https://github.com/block/buzz/pull/9098)) ([`a22ff133b`](https://github.com/block/buzz/commit/a22ff133b49a06a447ca341c12f00f335990c3b4)) +- fix(db): keep busy-reader history reads off the writer and cap them per pod ([#9132](https://github.com/block/buzz/pull/9132)) ([`47be2e2d3`](https://github.com/block/buzz/commit/47be2e2d3f2a438b3a5fd7df0c710b81d8c0d87e)) +- perf(db): split newest-first events reads at a month floor so Postgres prunes partitions ([#9091](https://github.com/block/buzz/pull/9091)) ([`74abe2f0f`](https://github.com/block/buzz/commit/74abe2f0fe1a5341c8c7637b79569dd59176be27)) +- fix(relay): bound mesh dials and keep failing pods out of the mesh ([#8752](https://github.com/block/buzz/pull/8752)) ([`9b4b73eb0`](https://github.com/block/buzz/commit/9b4b73eb088dc18c58b4da8388436bea9c89fdb1)) +- Expose strict code-entry pairing and live authorization bindings ([#9061](https://github.com/block/buzz/pull/9061)) ([`120d75d97`](https://github.com/block/buzz/commit/120d75d9762e0ea9876dc8df7f7bb834c3dfb042)) +- perf(relay): cache the community-active check on socket admission ([#9109](https://github.com/block/buzz/pull/9109)) ([`50c10dc7b`](https://github.com/block/buzz/commit/50c10dc7b26e63dc8b02b6533b50727ce121b09c)) +- fix(db): auto-migrate prebuild-guarded indexes on small databases ([#8802](https://github.com/block/buzz/pull/8802)) ([`ff15c347c`](https://github.com/block/buzz/commit/ff15c347c2f6cc688c163495125e849f85bbd55c)) +- perf(db): serve single-root thread reply reads from thread_metadata ([#9075](https://github.com/block/buzz/pull/9075)) ([`aa749a862`](https://github.com/block/buzz/commit/aa749a862ef60887de5507b425a70f3024a6b61c)) +- feat(db): enforce unique listed channel names with an index ([#8787](https://github.com/block/buzz/pull/8787)) ([`700e69019`](https://github.com/block/buzz/commit/700e69019321a927ce853f2572524bb6635b8834)) +- Honor relay mode for community NIP-FI enforcement ([#8988](https://github.com/block/buzz/pull/8988)) ([`64d12e297`](https://github.com/block/buzz/commit/64d12e29751981ad92ab3cc8edadaf3e3b5797f3)) +- refactor(relay): remove database usage-metric queries ([#9040](https://github.com/block/buzz/pull/9040)) ([`506a588f8`](https://github.com/block/buzz/commit/506a588f889b6d010705a564e91fdfa1660c06e7)) +- feat(relay): persist NIP-FI upgrades ([#8985](https://github.com/block/buzz/pull/8985)) ([`a1f79e3ab`](https://github.com/block/buzz/commit/a1f79e3aba6fd6d352d53f249cf0ef0fdf83316f)) +- relay: time every WebSocket read and every stored EVENT outcome ([#9052](https://github.com/block/buzz/pull/9052)) ([`4813b8cd1`](https://github.com/block/buzz/commit/4813b8cd15411355f05599e263ab15dd04e7afcc)) +- fix(media): keep transparency in image thumbnails with WebP ([#9003](https://github.com/block/buzz/pull/9003)) ([`f9ef721e6`](https://github.com/block/buzz/commit/f9ef721e688847ed0c1512081160b6e42cdf92fd)) +- perf(relay): keep 1 s read caches warm when the pool is saturated ([#9012](https://github.com/block/buzz/pull/9012)) ([`d21f0c0fd`](https://github.com/block/buzz/commit/d21f0c0fdbec9534b9396552b2550ab306d218df)) +- feat(relay): match verified names in profile search ([#9019](https://github.com/block/buzz/pull/9019)) ([`3d26ed7df`](https://github.com/block/buzz/commit/3d26ed7dfdd237f99bb65b623070d546384c2538)) +- fix(db): use ScratchDb in the storage usage delivery test ([#9032](https://github.com/block/buzz/pull/9032)) ([`865b15037`](https://github.com/block/buzz/commit/865b150371d4e15562d63f0e9837bca0c32540d7)) +- feat(relay): log reads, logins and connections on access target ([#8376](https://github.com/block/buzz/pull/8376)) ([`0a06c0b3c`](https://github.com/block/buzz/commit/0a06c0b3cb1741447c122a4f2275ca4ee541014b)) +- feat(relay): push per-community storage usage to kgoose ([#8714](https://github.com/block/buzz/pull/8714)) ([`fa7a3bfbd`](https://github.com/block/buzz/commit/fa7a3bfbda8300d4d9686c1d45ecd1ee649dd443)) +- fix(relay): stop logging unmapped-host NIP-FI denials as server failures ([#8997](https://github.com/block/buzz/pull/8997)) ([`6847882b1`](https://github.com/block/buzz/commit/6847882b149f88f044064887791f47a488833fa0)) +- fix(relay): apply kind 5 / 9005 deletions atomically ([#8944](https://github.com/block/buzz/pull/8944)) ([`88697f1c5`](https://github.com/block/buzz/commit/88697f1c597cda5790d4c702520d0651c48496c0)) +- fix(db): drop a superseded head's mention rows with it ([#8948](https://github.com/block/buzz/pull/8948)) ([`b8b425e8b`](https://github.com/block/buzz/commit/b8b425e8b1bf3d6895afeba702929d7dc0bc64d5)) +- perf(db): bind the channel scope as one array ([#8946](https://github.com/block/buzz/pull/8946)) ([`298a555e3`](https://github.com/block/buzz/commit/298a555e341ff7cf8faaefd833d6c6022bab6a4c)) +- feat(relay): record NIP-FI enforce denials at parity with shadow ([#8974](https://github.com/block/buzz/pull/8974)) ([`f6198f699`](https://github.com/block/buzz/commit/f6198f699750a8e99b59c93df29cc7d0c325892a)) +- Enable incremental artifact reads on every relay ([#8975](https://github.com/block/buzz/pull/8975)) ([`a9aa1f73b`](https://github.com/block/buzz/commit/a9aa1f73b01b37cccaaa60b615625c2fe64315ff)) +- fix(relay): send membership notices on channel delete, moderation kick and moderation DM ([#8977](https://github.com/block/buzz/pull/8977)) ([`ce47aefdc`](https://github.com/block/buzz/commit/ce47aefdc3fc9b9c845eaf047a8335a421f14580)) +- perf(search): rank only the newest prefix matches and plan with the real tsquery ([#8976](https://github.com/block/buzz/pull/8976)) ([`d3a4909cc`](https://github.com/block/buzz/commit/d3a4909ccad7c75a8c13ca91ccdaffd2c83024df)) +- perf(relay): cut writer-pool round trips past the 48k relay ceiling ([#8846](https://github.com/block/buzz/pull/8846)) ([`d44031f41`](https://github.com/block/buzz/commit/d44031f4187b285dad9b367c114f017c7858df9b)) +- fix(search): skip message prefix search below three characters ([#8947](https://github.com/block/buzz/pull/8947)) ([`d005c7bb9`](https://github.com/block/buzz/commit/d005c7bb9cff17bc7fd44587f5586e08f67e21cf)) +- db: recycle pool connections after 5 minutes instead of 30 ([#8951](https://github.com/block/buzz/pull/8951)) ([`46da35810`](https://github.com/block/buzz/commit/46da35810d6575f63a92ce5917c5abc901b29f52)) +- fix(relay): cap bridge searches in flight per user ([#8956](https://github.com/block/buzz/pull/8956)) ([`02925ceb6`](https://github.com/block/buzz/commit/02925ceb6e7318f2214de274050825bb1da6477c)) +- fix(search): cancel abandoned searches and bound the search pool ([#8954](https://github.com/block/buzz/pull/8954)) ([`949f61dfa`](https://github.com/block/buzz/commit/949f61dfab060fa12e83f63c210b0cecd8c3ce2c)) +- fix(db): preserve partition reader grants ([#8485](https://github.com/block/buzz/pull/8485)) ([`8f83c6320`](https://github.com/block/buzz/commit/8f83c6320994be69f486ba42bf69cea6d8bb9df8)) +- fix(relay): refuse a second listed open channel with the same name ([#8782](https://github.com/block/buzz/pull/8782)) ([`5f8d0aab9`](https://github.com/block/buzz/commit/5f8d0aab98298f05b8676c1176d693e8db2c89d6)) +- test(relay): hold the replica's second aux page and move media's DB tests ([#8740](https://github.com/block/buzz/pull/8740)) ([`322fdbf08`](https://github.com/block/buzz/commit/322fdbf086cd5fc6a7a528236446c68f372145b5)) +- feat(relay): auto-join new community members to default channels ([#8594](https://github.com/block/buzz/pull/8594)) ([`cde6c1bf5`](https://github.com/block/buzz/commit/cde6c1bf5b1fa1fde6045de8ea29f6ac1c7e6867)) +- feat(relay): publish NIP-FI verified profiles ([#8774](https://github.com/block/buzz/pull/8774)) ([`7d00c7080`](https://github.com/block/buzz/commit/7d00c708059df3b73bc7eb78d28066a707b7dbad)) +- test(db): drop scratch databases and roles even when a test fails ([#8747](https://github.com/block/buzz/pull/8747)) ([`b7b545f09`](https://github.com/block/buzz/commit/b7b545f090bfa17c23317f243becc15f807b636d)) +- feat(relay): NIP-AR sync subscriptions ([#8522](https://github.com/block/buzz/pull/8522)) ([`a56966b77`](https://github.com/block/buzz/commit/a56966b777278f703040b4686820a201bc278c57)) +- feat(relay): add incremental artifact reads ([#8523](https://github.com/block/buzz/pull/8523)) ([`a57349b23`](https://github.com/block/buzz/commit/a57349b237c67c3983dd7a09af378977ccd1e3f9)) +- perf(relay): route author- and #p-scoped global subscriptions by selector ([#8666](https://github.com/block/buzz/pull/8666)) ([`cc04cdca1`](https://github.com/block/buzz/commit/cc04cdca1a7a4094183dfaedbf09a52f5aa25d70)) +- test(relay): fix main's build after the test-state helper rename ([#8718](https://github.com/block/buzz/pull/8718)) ([`0e8fb49bd`](https://github.com/block/buzz/commit/0e8fb49bd09c070b619d3b560a5c55b4c3cc1eb6)) +- fix(db): keep lease releases durable and deflake PostgreSQL lane tests ([#8676](https://github.com/block/buzz/pull/8676)) ([`ef4130da4`](https://github.com/block/buzz/commit/ef4130da4bfeea9fe37477d621166675e0ab3ef7)) +- relay: open the search pool lazily so a dead reader can't block boot ([#8662](https://github.com/block/buzz/pull/8662)) ([`efcdf0010`](https://github.com/block/buzz/commit/efcdf00101f56e11998e072a62502f1bcadc313c)) +- fix: don't notify workflow owners through their attribution tag ([#8694](https://github.com/block/buzz/pull/8694)) ([`4b21a10c4`](https://github.com/block/buzz/commit/4b21a10c4b100bfccfa03ab4a0e85329c9880c9f)) +- perf(relay): cut connect-burst CPU in log filtering and open-channel lookup ([#8670](https://github.com/block/buzz/pull/8670)) ([`1f16f621d`](https://github.com/block/buzz/commit/1f16f621d87cdc0b03f41105f9d4201313054664)) +- Deny workflow runs for banned owners ([#8242](https://github.com/block/buzz/pull/8242)) ([`1fe120165`](https://github.com/block/buzz/commit/1fe120165f3026777c76526c4430e8ba14c76a75)) +- fix(relay): close a REQ whose history read failed instead of sending EOSE ([#8692](https://github.com/block/buzz/pull/8692)) ([`76cd4294f`](https://github.com/block/buzz/commit/76cd4294f65bde33eff031315509e81deccf7c9d)) +- db: warm the relay read pool toward its ceiling at boot ([#8651](https://github.com/block/buzz/pull/8651)) ([`6d719c680`](https://github.com/block/buzz/commit/6d719c680a85c98153324809988be37425fba73e)) +- db: answer match-nothing event reads without taking a connection ([#8663](https://github.com/block/buzz/pull/8663)) ([`f6d31d13e`](https://github.com/block/buzz/commit/f6d31d13e433da3c70158cc24f1107b2b2ca1143)) +- Add standalone owned-community deletion handlers ([#8645](https://github.com/block/buzz/pull/8645)) ([`8caf8351c`](https://github.com/block/buzz/commit/8caf8351c124a2a39f160e342587d427e8c32a51)) +- fix(relay): revoke invitations and restrict claims ([#8237](https://github.com/block/buzz/pull/8237)) ([`d6196a16c`](https://github.com/block/buzz/commit/d6196a16c1eec7268e1fc5124ca89ee3d03d6d3e)) +- perf(db,relay): bound thread participant scans and coalesce live summaries ([#8635](https://github.com/block/buzz/pull/8635)) ([`0a362eef1`](https://github.com/block/buzz/commit/0a362eef150ab16453993d442a8037baad766797)) +- Add user deletion fence storage ([#8632](https://github.com/block/buzz/pull/8632)) ([`2c28e0713`](https://github.com/block/buzz/commit/2c28e07133d306ced204ca17f97c4cb93c916f72)) +- Stop requiring the 0032 roster trigger at relay startup ([#8611](https://github.com/block/buzz/pull/8611)) ([`646ef8abf`](https://github.com/block/buzz/commit/646ef8abf9bc5ac3e698826b38811033537a4806)) +- fix(relay): store a kind:9000 and its membership writes in one transaction ([#8606](https://github.com/block/buzz/pull/8606)) ([`78b5dae1f`](https://github.com/block/buzz/commit/78b5dae1f608a33850137b5be5a1909390035cce)) +- feat(relay): log who and why for NIP-FI shadow would-deny ([#8634](https://github.com/block/buzz/pull/8634)) ([`24a370606`](https://github.com/block/buzz/commit/24a370606044c0c7be787cc2fd98ec0bfe1d606b)) +- refactor(schema): stop auto-fencing new tables in desired-state bootstrap ([#8620](https://github.com/block/buzz/pull/8620)) ([`f33ebaafa`](https://github.com/block/buzz/commit/f33ebaafa15626e0f8bc3e23341835e08ebf4a33)) +- test(relay): give group-state Postgres tests a normal acquire timeout ([#8564](https://github.com/block/buzz/pull/8564)) ([`403855d78`](https://github.com/block/buzz/commit/403855d7884971b4103ba094e3d24ba28bbf093a)) +- chore(toolchain): bump Rust to 1.98.1 for macOS 27 proc-macro loading ([#8598](https://github.com/block/buzz/pull/8598)) ([`8216db1c7`](https://github.com/block/buzz/commit/8216db1c712cefdc0e2af7191d501adae03ba392)) +- Generate user community inventory for the dummy deletion workflow ([#8605](https://github.com/block/buzz/pull/8605)) ([`834dca26b`](https://github.com/block/buzz/commit/834dca26bf0613581fc8199810f4693392aada3b)) +- fix(db): keep the reader pool warm and drop its pre-acquire ping ([#8495](https://github.com/block/buzz/pull/8495)) ([`0e36dbc82`](https://github.com/block/buzz/commit/0e36dbc823f4754b98da64944cc015a9f7acbd6e)) +- feat(relay): add an unlisted channel setting ([#8579](https://github.com/block/buzz/pull/8579)) ([`a3a47e629`](https://github.com/block/buzz/commit/a3a47e6294c29b5ce3fb7747cb0e42e45a8d5440)) +- perf(push): avoid empty push delivery claims ([#8524](https://github.com/block/buzz/pull/8524)) ([`b8b1ab5b3`](https://github.com/block/buzz/commit/b8b1ab5b3cac3692f4231a32679de8d2e7113b70)) +- feat(relay): verify NIP-FI agent tokens and admit agents through owners ([#8401](https://github.com/block/buzz/pull/8401)) ([`369ffa038`](https://github.com/block/buzz/commit/369ffa0380ab2a987b5321d431b9b567aa2b8b38)) +- feat(relay): add several people with one kind:9000 ([#8575](https://github.com/block/buzz/pull/8575)) ([`d0dee1cb5`](https://github.com/block/buzz/commit/d0dee1cb50736c5dff4b4b2ad3dad0acf2be7794)) +- Run user deletion through saved stage transitions ([#8520](https://github.com/block/buzz/pull/8520)) ([`4250014ba`](https://github.com/block/buzz/commit/4250014baee071f0f940c081afbbbf876c0d32d0)) +- fix(mesh): expire dead peer records and instrument mesh boot ([#8503](https://github.com/block/buzz/pull/8503)) ([`7ce422417`](https://github.com/block/buzz/commit/7ce422417b139c2d622eccc6066b494c2e18bb9c)) +- fix(db): rebuild events_pkey in declared order after pgschema apply ([#8525](https://github.com/block/buzz/pull/8525)) ([`20ba95ed8`](https://github.com/block/buzz/commit/20ba95ed8906b2b7ae1819bdddadf82c09778097)) +- Add user deletion request intake ([#8496](https://github.com/block/buzz/pull/8496)) ([`2d289f720`](https://github.com/block/buzz/commit/2d289f720de0012fa36b5f6faa0e3bdd845ccfcf)) +- fix(relay): apply channel setting changes atomically and lock every membership writer ([#8516](https://github.com/block/buzz/pull/8516)) ([`a2d28eb6c`](https://github.com/block/buzz/commit/a2d28eb6c478b97c371e1e67a92d43bdfb8dd7b0)) +- fix(db): keep pgschema re-apply from dropping runtime partitions ([#8487](https://github.com/block/buzz/pull/8487)) ([`347ce88d5`](https://github.com/block/buzz/commit/347ce88d5dd8bc631c073f1947fea6b75d5a43c0)) +- fix(db): bound every statement and the #p mention scan ([#8461](https://github.com/block/buzz/pull/8461)) ([`2f2f6e277`](https://github.com/block/buzz/commit/2f2f6e2774fb0899d2a927f5e5b1987603765f31)) +- feat(relay): add announce channels with a join_role setting ([#8143](https://github.com/block/buzz/pull/8143)) ([`d97f6b4c6`](https://github.com/block/buzz/commit/d97f6b4c6ed616be0c3f1eb0e13d1eaa9e338a66)) +- test(relay): cover system channels in the workflows API and push matcher ([#8509](https://github.com/block/buzz/pull/8509)) ([`c37d6b8eb`](https://github.com/block/buzz/commit/c37d6b8eb62b6b1747985092a7c9dc677da89a61)) +- fix(relay): push system channel events to a lease that names them ([#8517](https://github.com/block/buzz/pull/8517)) ([`cd8a96817`](https://github.com/block/buzz/commit/cd8a9681793fef83001eb44954734b47c1938550)) +- fix(relay): scope push matches with the read path's channel rule ([#8507](https://github.com/block/buzz/pull/8507)) ([`4dea51f64`](https://github.com/block/buzz/commit/4dea51f644cc5069aea24ff2f4df943f82d7b1c4)) +- fix(sdk): reject malformed mention pubkeys before signing p tags ([#6372](https://github.com/block/buzz/pull/6372)) ([`a5767c67d`](https://github.com/block/buzz/commit/a5767c67deb951d64b8465b5da32c1dfc7a9ba40)) +- docs(db): database target architecture and schema-change rules ([#8273](https://github.com/block/buzz/pull/8273)) ([`fcdabcf77`](https://github.com/block/buzz/commit/fcdabcf774203884c4f5b258aad000a740586eb6)) +- fix(relay): advance the partition catch-all by default ([#8464](https://github.com/block/buzz/pull/8464)) ([`ca3be5501`](https://github.com/block/buzz/commit/ca3be55018a37c4e7d342057260dd773190eae68)) +- feat(relay): write the NIP-43 member list in the membership transaction ([#8482](https://github.com/block/buzz/pull/8482)) ([`039e1c8d5`](https://github.com/block/buzz/commit/039e1c8d59232eb29d80e59b394d5cde825b389a)) +- fix(relay): delete the startup NIP-33 d_tag backfill ([#8468](https://github.com/block/buzz/pull/8468)) ([`c99872f74`](https://github.com/block/buzz/commit/c99872f749cb1214a3e69371c83a7f2f72aef704)) +- fix(mobile): restore Solo chats from channel labels ([#8466](https://github.com/block/buzz/pull/8466)) ([`c9e35f8ac`](https://github.com/block/buzz/commit/c9e35f8ac71f4f2eb7a8e256d0bc83f3518031af)) +- fix(relay): show only legacy channel types to reads that name no channel ([#8469](https://github.com/block/buzz/pull/8469)) ([`25bcb791b`](https://github.com/block/buzz/commit/25bcb791b4105594940bb77cadaf556a34427a8c)) +- fix(relay): take NIP-43 snapshot reconcile off the startup path ([#8467](https://github.com/block/buzz/pull/8467)) ([`e6c56ee5e`](https://github.com/block/buzz/commit/e6c56ee5ee80eace3c9eddf0bf22a020fa8f48f3)) +- test(buzz-db): fix two PostgreSQL-lane timing flakes ([#8472](https://github.com/block/buzz/pull/8472)) ([`6e6173acd`](https://github.com/block/buzz/commit/6e6173acd58029bac800583c4cc7482dafed693a)) +- feat(mobile): account onboarding, key recovery and hosted reconnect ([#8375](https://github.com/block/buzz/pull/8375)) ([`b6aa5539e`](https://github.com/block/buzz/commit/b6aa5539e3a44fe32a4bfe2963dfb23f10316985)) +- feat(relay): tag every membership notice with its channel type ([#8406](https://github.com/block/buzz/pull/8406)) ([`cc6336d98`](https://github.com/block/buzz/commit/cc6336d9851983ca341d40cf2332052e9394a4f2)) +- fix(relay): wait for the peer's Close before dropping any WebSocket ([#8426](https://github.com/block/buzz/pull/8426)) ([`91e7b469b`](https://github.com/block/buzz/commit/91e7b469b82b235c62885f82a6323b7e666e9254)) +- test(auth): read the clock once in NIP-FI until test ([#8457](https://github.com/block/buzz/pull/8457)) ([`af7979e1c`](https://github.com/block/buzz/commit/af7979e1ca0c40af2ba4a8d05edad6bb5796c584)) +- feat(relay): resolve NIP-FI issuer bindings from the database ([#8377](https://github.com/block/buzz/pull/8377)) ([`5b433d929`](https://github.com/block/buzz/commit/5b433d92926504370c6e12f651d5d010b5af33c2)) +- feat(relay): start a channel with its members in one create ([#8421](https://github.com/block/buzz/pull/8421)) ([`3ffbfa693`](https://github.com/block/buzz/commit/3ffbfa693c6727b04b01ef727ce4848e4695ac40)) +- feat(relay): store per-community NIP-FI issuer bindings ([#8372](https://github.com/block/buzz/pull/8372)) ([`6286a5432`](https://github.com/block/buzz/commit/6286a5432111f529835da320e801af1901889b03)) +- fix(db): validate channel roster snapshots in the app writer ([#8316](https://github.com/block/buzz/pull/8316)) ([`97e1f6a08`](https://github.com/block/buzz/commit/97e1f6a0828d97d0031e2a31402554b679bf1146)) +- fix(db): admit fleet sweeps per tenant instead of in-SQL fence predicate ([#8318](https://github.com/block/buzz/pull/8318)) ([`60de1db0b`](https://github.com/block/buzz/commit/60de1db0b8813766d8e004297798f2ff759d3089)) +- buzz-db: tolerate absent universal write-fence objects (expand) ([#8322](https://github.com/block/buzz/pull/8322)) ([`2745a419a`](https://github.com/block/buzz/commit/2745a419a836fb6bc4753f0caf3c9cf9c9a4d274)) +- feat(auth): support explicit mesh JWKS transport ([#8382](https://github.com/block/buzz/pull/8382)) ([`2d0f78c6e`](https://github.com/block/buzz/commit/2d0f78c6e1c43762aeb51efa633e9387fc301649)) +- feat(buzz-db): retire the channel-TTL trigger ([#8210](https://github.com/block/buzz/pull/8210)) ([`c0ab78949`](https://github.com/block/buzz/commit/c0ab789499bde118a468178d23b726fd109a8e1c)) +- fix(relay): confirm requested channels in one membership query ([#8378](https://github.com/block/buzz/pull/8378)) ([`d039d9a2d`](https://github.com/block/buzz/commit/d039d9a2d541fe8b767462b2ddaca73889154c69)) +- fix(search): normalize profile name tiers in one place ([#8334](https://github.com/block/buzz/pull/8334)) ([`7852b1670`](https://github.com/block/buzz/commit/7852b1670c7588875fc43ef2613c8348893d5ab6)) +- feat(relay): add profile search over name and display_name only ([#8301](https://github.com/block/buzz/pull/8301)) ([`f148c0f22`](https://github.com/block/buzz/commit/f148c0f22c35105524527dec8e4a7285c26804c6)) +- feat(search): add newest-first sort to bridge search ([#8371](https://github.com/block/buzz/pull/8371)) ([`cdfc38ecb`](https://github.com/block/buzz/commit/cdfc38ecbd4eb1a1cf5d45de9a5e982292574d5d)) +- chore(push): retire push notification database trigger ([#8352](https://github.com/block/buzz/pull/8352)) ([`676617467`](https://github.com/block/buzz/commit/6766174673b99f031a1cee7a2d5ef007b5a8e66c)) +- feat(relay): let channel-state filters opt in to system channels ([#8182](https://github.com/block/buzz/pull/8182)) ([`d28f6b2f7`](https://github.com/block/buzz/commit/d28f6b2f7095b50a2c987a42e9b4ca345f8e9dac)) +- feat(relay): leave system channels out of reads that do not name them ([#8181](https://github.com/block/buzz/pull/8181)) ([`cdf03f618`](https://github.com/block/buzz/commit/cdf03f618aee1fb2be91c0be9b8d5370d0e3109d)) +- test: fix recurring CI flakes in desktop and Postgres lanes ([#8343](https://github.com/block/buzz/pull/8343)) ([`7b11c6147`](https://github.com/block/buzz/commit/7b11c6147df099cd28729f340ea032630bab38cc)) +- feat(relay): deliver full signed events to operator listeners ([#8309](https://github.com/block/buzz/pull/8309)) ([`8b60dcf8e`](https://github.com/block/buzz/commit/8b60dcf8e3f520c651598aa13b4cccc0009bc255)) +- fix(relay): match pushed-down tags by position, not containment ([#8335](https://github.com/block/buzz/pull/8335)) ([`e645918c6`](https://github.com/block/buzz/commit/e645918c6334f8a4d89638349106e73d318adff5)) +- feat(relay): add the system channel type ([#8180](https://github.com/block/buzz/pull/8180)) ([`71d7aa043`](https://github.com/block/buzz/commit/71d7aa04369a6e86e158dc6d46246c8a3ce6d166)) +- feat(relay): match label and creator filters before the page limit ([#8176](https://github.com/block/buzz/pull/8176)) ([`a3909acc6`](https://github.com/block/buzz/commit/a3909acc672619375669dff5274bb8e3cdfdc88b)) +- feat(relay): channel labels ([#8175](https://github.com/block/buzz/pull/8175)) ([`2f79374f4`](https://github.com/block/buzz/commit/2f79374f4867035c33dace91c683440e7e011826)) +- fix(relay): reject unreadable write targets as missing ([#8249](https://github.com/block/buzz/pull/8249)) ([`b3795236c`](https://github.com/block/buzz/commit/b3795236ccde4cefaebfd3da06ce4c838b76e78a)) +- fix(ci): remove Detect Changed Paths timeout and deletion test race ([#8300](https://github.com/block/buzz/pull/8300)) ([`ea24a3ee3`](https://github.com/block/buzz/commit/ea24a3ee3d74679c8c489b83d351409e1b8d503e)) +- test(buzz-db): drop partition scratch schemas on panic ([#8293](https://github.com/block/buzz/pull/8293)) ([`2270b66e1`](https://github.com/block/buzz/commit/2270b66e147c8955edbfc445aed4b9633f9dff6e)) +- buzz-db: admit every fenced-table writer in app code ([#8219](https://github.com/block/buzz/pull/8219)) ([`d25384a4f`](https://github.com/block/buzz/commit/d25384a4f3c3a940b5b999f26105091c58ab76d6)) +- feat(relay): publish channel type and creator on every channel-state event ([#8174](https://github.com/block/buzz/pull/8174)) ([`8bb49a1b6`](https://github.com/block/buzz/commit/8bb49a1b6a5ffb5b89eb2e860673ee7bff2fd29b)) +- fix(buzz-db): delete workflow and membership children explicitly ([#8212](https://github.com/block/buzz/pull/8212)) ([`52d13efc0`](https://github.com/block/buzz/commit/52d13efc08ec2b80878f24672913ac465b37e148)) +- feat(relay): allow HTTP operator listener delivery URLs ([#8287](https://github.com/block/buzz/pull/8287)) ([`8599efb6a`](https://github.com/block/buzz/commit/8599efb6a3cfbd3d4bc4534f6de766b4481c7fca)) +- fix(relay): partition audit observability follow-ups ([#7994](https://github.com/block/buzz/pull/7994)) ([`85b733178`](https://github.com/block/buzz/commit/85b7331784804fbf9bb07df4199d4dc6a2b42ade)) +- fix(relay): hide deletions of author-only events from other readers ([#8197](https://github.com/block/buzz/pull/8197)) ([`40c1c474e`](https://github.com/block/buzz/commit/40c1c474e74686cbd3218866ee926211cb3365db)) +- feat(relay): accept an owner's presence for its agents (kind 20003) ([#8261](https://github.com/block/buzz/pull/8261)) ([`1d9f2c81a`](https://github.com/block/buzz/commit/1d9f2c81a5583f12be1239a088e2f0b379292dc3)) +- perf(relay): drop per-pulse ban reads and owner-link writes on HTTP ([#8233](https://github.com/block/buzz/pull/8233)) ([`326e2301c`](https://github.com/block/buzz/commit/326e2301cb4b1edcb8a72d01ac4b19a83545365f)) +- feat(relay): accept typing indicators over HTTP POST /events ([#8207](https://github.com/block/buzz/pull/8207)) ([`6c388bde6`](https://github.com/block/buzz/commit/6c388bde62114feabf5408729533ee52a19845a5)) +- refactor(push): one app profile per gateway ([#8206](https://github.com/block/buzz/pull/8206)) ([`868e2f8f3`](https://github.com/block/buzz/commit/868e2f8f3271af6625981219b0bce2093033e7be)) +- perf(relay): cache ephemeral-path serving and restriction reads ([#8208](https://github.com/block/buzz/pull/8208)) ([`bcc46fe83`](https://github.com/block/buzz/commit/bcc46fe8359a2bfd2bc26e6a7a1a1f8c29d44149)) +- fix(push): isolate push enqueue and stop workers on rollback ([#8216](https://github.com/block/buzz/pull/8216)) ([`5b907b838`](https://github.com/block/buzz/commit/5b907b838a44d7985e98836177aec2903717381f)) +- feat(relay): reshape read-state API to the sidebar wire format ([#8220](https://github.com/block/buzz/pull/8220)) ([`1e80066c9`](https://github.com/block/buzz/commit/1e80066c932250b87bd8a794f4143c0a88021c30)) +- feat(buzz-db): run push enqueue and channel TTL refresh in app code ([#8135](https://github.com/block/buzz/pull/8135)) ([`16eb0b668`](https://github.com/block/buzz/commit/16eb0b6685a9ea5cd06275aed172903dac69f225)) +- fix(push): stop backfilling messages on lease activation ([#8178](https://github.com/block/buzz/pull/8178)) ([`4db7bb0e7`](https://github.com/block/buzz/commit/4db7bb0e7f904b2f0ea232aacae6cd7f6b8a3b39)) +- feat: raise hosted community limit to fifty ([#8186](https://github.com/block/buzz/pull/8186)) ([`8f66f7051`](https://github.com/block/buzz/commit/8f66f7051c68560feb27dbc74b069c851bc018bd)) +- feat(db): advance an empty partition catch-all under bounded locks ([#7993](https://github.com/block/buzz/pull/7993)) ([`a8fe2b612`](https://github.com/block/buzz/commit/a8fe2b612c1c83de8f0983fa7a5cc1cb81ac7be8)) +- feat(relay): record when a read-state account starts ([#8157](https://github.com/block/buzz/pull/8157)) ([`7afdc2aac`](https://github.com/block/buzz/commit/7afdc2aac930cd02001825d0b528f6f48595cd4a)) +- fix(deletion): give the scheduled drain the cold-start DB connector ([#8146](https://github.com/block/buzz/pull/8146)) ([`c6340a45a`](https://github.com/block/buzz/commit/c6340a45a072c1793280cdcaec793d4a5dd82d97)) +- refactor(schema): fan desired-state schema out to one file per table ([#8131](https://github.com/block/buzz/pull/8131)) ([`745501962`](https://github.com/block/buzz/commit/745501962e68041b3aee5c83fd3ea3bf5a496dbc)) +- refactor(db): type-level admitted event-write transactions (AdmittedTx) ([#8130](https://github.com/block/buzz/pull/8130)) ([`f8bf2c529`](https://github.com/block/buzz/commit/f8bf2c529cdf2c193ad0be6cf333def124d182f2)) +- feat(admin): add community archive commands ([#7107](https://github.com/block/buzz/pull/7107)) ([`1972b7d25`](https://github.com/block/buzz/commit/1972b7d256a5d0bb90eea6ef78e93d6b55bb1a12)) +- feat(relay): add community reads to the admin API ([#8011](https://github.com/block/buzz/pull/8011)) ([`032198ce4`](https://github.com/block/buzz/commit/032198ce43680947c288bfd219d6a9b81d882348)) +- perf(relay): bound fleet usage metrics collection ([#7176](https://github.com/block/buzz/pull/7176)) ([`6d07a2913`](https://github.com/block/buzz/commit/6d07a291376477942b70ba44489a47c9f6bfe006)) +- buzz-db: purge retention-free deletions in the app and index mentions in the event transaction ([#8128](https://github.com/block/buzz/pull/8128)) ([`da651ad67`](https://github.com/block/buzz/commit/da651ad6726154ff1fe314fc64462031970f1106)) +- feat(relay): time post-metrics-bind startup steps ([#8132](https://github.com/block/buzz/pull/8132)) ([`e097c4299`](https://github.com/block/buzz/commit/e097c42996c9a634209fd46df86998ee4a71ea48)) +- feat(relay): private read-state accessory API ([#7906](https://github.com/block/buzz/pull/7906)) ([`1a2ddf9ea`](https://github.com/block/buzz/commit/1a2ddf9eaa87031a0d49ca1d882a46b5b89beb8d)) +- Route serving event writes through the tenant lock ([#7828](https://github.com/block/buzz/pull/7828)) ([`d0fd96fca`](https://github.com/block/buzz/commit/d0fd96fca6704548cebe2f69d8dff0e3c80e77e2)) +- feat(pairing): enter desktop codes on mobile ([#8085](https://github.com/block/buzz/pull/8085)) ([`5173fad66`](https://github.com/block/buzz/commit/5173fad6602ae82c06f338d19ef0f18eff57159b)) +- fix(db): enumerate only active communities for maintenance ([#8061](https://github.com/block/buzz/pull/8061)) ([`7f6ffd5ee`](https://github.com/block/buzz/commit/7f6ffd5ee5ae1b66d660245acf465b88e17639bc)) +- refactor(relay): bind HTTP tenants through one shadow-aware helper ([#8062](https://github.com/block/buzz/pull/8062)) ([`8af2d91f3`](https://github.com/block/buzz/commit/8af2d91f37270365d5cd9170ac48349baa08475e)) +- feat(relay): add NIP-FI shadow mode for HTTP, WebSocket and admin ([#8034](https://github.com/block/buzz/pull/8034)) ([`df3f28a2c`](https://github.com/block/buzz/commit/df3f28a2c44f0bd258cff046717cde3fa026662e)) +- Add application-owned writer lock foundations ([#7706](https://github.com/block/buzz/pull/7706)) ([`fe9e2409a`](https://github.com/block/buzz/commit/fe9e2409a02fbac415d5c66181135be3eec28a86)) +- test(relay): configure a community in the Git ban-lookup fixture ([#8039](https://github.com/block/buzz/pull/8039)) ([`448407a97`](https://github.com/block/buzz/commit/448407a972ca9da0c1e13d49ee2c2170821be8a2)) +- fix(relay): restore buzz-relay build after #8005 and #8028 ([#8036](https://github.com/block/buzz/pull/8036)) ([`639593bba`](https://github.com/block/buzz/commit/639593bba97b4ed1386d5128bceecfab2072df31)) +- feat(nip-fi): bind assertions to the request Host's community ([#8028](https://github.com/block/buzz/pull/8028)) ([`2ebfde914`](https://github.com/block/buzz/commit/2ebfde9147140a4036b11bfc2c6b0da68688a05c)) +- fix(relay): close community ban gaps across audio, agents and HTTP ([#8005](https://github.com/block/buzz/pull/8005)) ([`a38707d35`](https://github.com/block/buzz/commit/a38707d35c5d7028a83dcb4b85482a26f8b67605)) +- refactor(buzz-relay): share NIP-FI assertion evaluation across adapters ([#7990](https://github.com/block/buzz/pull/7990)) ([`9b083957f`](https://github.com/block/buzz/commit/9b083957f6802fd8e0efc7414269714619139cf2)) +- fix(relay): gate owner-only kinds in shared fan-out access filter ([#8006](https://github.com/block/buzz/pull/8006)) ([`24c1e702a`](https://github.com/block/buzz/commit/24c1e702a68c7b1623f4a33dd2745a39b0597098)) +- fix(relay): deny channel writes when the channel lookup fails ([#8007](https://github.com/block/buzz/pull/8007)) ([`15772c54f`](https://github.com/block/buzz/commit/15772c54f36d1ed68c9c77ffb63235acb5ee8a64)) +- feat(nip-fi): admin disconnect/deny API with in-memory deny-until-TTL map (S4) ([#7977](https://github.com/block/buzz/pull/7977)) ([`16839a077`](https://github.com/block/buzz/commit/16839a07738cf6189ee2f21c02d923b0f9dbe80d)) +- fix(deletion): require sole owner at admission ([#7966](https://github.com/block/buzz/pull/7966)) ([`53a12100b`](https://github.com/block/buzz/commit/53a12100b34577286c89102f1875ca2b6eea61e5)) +- feat(relay): add direct staff ban/timeout/delete with staff guard ([#7883](https://github.com/block/buzz/pull/7883)) ([`020193f8e`](https://github.com/block/buzz/commit/020193f8e36bede04a57e0c06ba60e26ed67612b)) +- feat(buzz-relay): idempotent owner community deletion with quota reservation ([#7969](https://github.com/block/buzz/pull/7969)) ([`d7a35afa9`](https://github.com/block/buzz/commit/d7a35afa9859a0c666de93ab1cd4f8a433a1cfe8)) +- fix(db): audit partition catalog before creation ([#6515](https://github.com/block/buzz/pull/6515)) ([`14a752fb2`](https://github.com/block/buzz/commit/14a752fb2445790bf4620348e485e8576371f906)) +- feat(buzz-relay): NIP-FI stateless enforcement (S3) — upgrade gate, NIP-42 pairing, session lifetime, JWKS warm ([#7224](https://github.com/block/buzz/pull/7224)) ([`8519db153`](https://github.com/block/buzz/commit/8519db1532efd6cda8f72bb6454c00fc3f87cfba)) +- Automate owner deletion preparation ([#7830](https://github.com/block/buzz/pull/7830)) ([`bba75a71e`](https://github.com/block/buzz/commit/bba75a71eb5a719b597479ec848053cde364befd)) +- feat(relay): implement NIP-AR channel artifacts ([#7919](https://github.com/block/buzz/pull/7919)) ([`12670bd0f`](https://github.com/block/buzz/commit/12670bd0f037c66a682272bb81c46c3f254fad74)) +- 🤖 perf: bound long-thread aux reads and make query deadlines terminal ([#7854](https://github.com/block/buzz/pull/7854)) ([`9b1c4f98e`](https://github.com/block/buzz/commit/9b1c4f98e2981d6d89fbfa3154b8ef0b3b6ad334)) +- Add owner deletion admission control plane ([#7818](https://github.com/block/buzz/pull/7818)) ([`15d44dcce`](https://github.com/block/buzz/commit/15d44dcceee0679979991b3100f21f01fc799693)) +- feat(nip-fi): harden Blossom kind-24242 verifier to NIP-FI spec ([#7288](https://github.com/block/buzz/pull/7288)) ([`f7ff4294f`](https://github.com/block/buzz/commit/f7ff4294fa95191d1fc7b29a765e6f0b48db6bd8)) +- Make relay readiness process-local ([#7341](https://github.com/block/buzz/pull/7341)) ([`b37e47721`](https://github.com/block/buzz/commit/b37e477211313a94344a31aea4b180ed4effe0b8)) +- fix(relay): fail startup on invalid operator listener config ([#7933](https://github.com/block/buzz/pull/7933)) ([`ebe99a46e`](https://github.com/block/buzz/commit/ebe99a46e8802b9ff20fdf6a1028ce93bdefaa43)) +- fix(db): limit event transactions to listener mention kinds ([#7932](https://github.com/block/buzz/pull/7932)) ([`1846094b3`](https://github.com/block/buzz/commit/1846094b3111a059f856bb4f3466c102fad17ef7)) +- feat(relay): deliver pubkey mentions to relay companions ([#7793](https://github.com/block/buzz/pull/7793)) ([`c4c86006f`](https://github.com/block/buzz/commit/c4c86006f2d67b2ea9055780129ee7ce95c54e0a)) +- feat(push): support configurable HTTP(S) delivery URLs ([#7877](https://github.com/block/buzz/pull/7877)) ([`781d39510`](https://github.com/block/buzz/commit/781d39510cf23cfe224e8f521ae06a23377e06de)) +- feat(relay): enforce NIP-FI assertion+NIP-98 pairing on HTTP ingress ([#7264](https://github.com/block/buzz/pull/7264)) ([`6410e685a`](https://github.com/block/buzz/commit/6410e685a80d42db0645fadc9bbe710559ef911e)) +- fix(ci): run the admin disabled-mode DB test in the PostgreSQL lane ([#7900](https://github.com/block/buzz/pull/7900)) ([`b65cff31a`](https://github.com/block/buzz/commit/b65cff31a4c5f4a0af63952b60a21fd73195321a)) +- fix(relay-admin): make thread deletions atomic and fence expired action leases under row lock ([#7853](https://github.com/block/buzz/pull/7853)) ([`676e8c438`](https://github.com/block/buzz/commit/676e8c43825fa478850a3a320b1367d3288cce1a)) +- feat(desktop): relay admin console for the /api/admin/v1 operator surface ([#4768](https://github.com/block/buzz/pull/4768)) ([`8f8c4dfad`](https://github.com/block/buzz/commit/8f8c4dfadecb2298a9140af5d323487aaad844ab)) +- chore(mesh): upgrade MeshLLM to 0.76.2 ([#7559](https://github.com/block/buzz/pull/7559)) ([`4544ba171`](https://github.com/block/buzz/commit/4544ba1713d8d7f5959d7d63886ff3927357e1ac)) +- feat(relay): add opt-in newest-first thread windows ([#7823](https://github.com/block/buzz/pull/7823)) ([`5a349db91`](https://github.com/block/buzz/commit/5a349db91c23fa70c8c8aa43a3a5ba0005d8dd41)) +- Use worker snapshots for relay storage metrics ([#7845](https://github.com/block/buzz/pull/7845)) ([`4142d2b84`](https://github.com/block/buzz/commit/4142d2b84e1c3230fbe6c4b2d1e994721c409092)) +- feat(canvas): add version history with atomic restore ([#6780](https://github.com/block/buzz/pull/6780)) ([`b6a26556e`](https://github.com/block/buzz/commit/b6a26556ec904cdebe0fbc7e6c25b4ea2cf294d1)) +- fix(audit): frame hash inputs with TLV ([#7492](https://github.com/block/buzz/pull/7492)) ([`7881447c1`](https://github.com/block/buzz/commit/7881447c193edf2ed3a860d959d11dc94f0946fb)) +- feat(relay): add admin HTTP routes for member restriction management ([#7302](https://github.com/block/buzz/pull/7302)) ([`77729abfb`](https://github.com/block/buzz/commit/77729abfb692b25a0f4ec4a69add86af2e32c0dd)) +- fix(relay): fire kick live side effects at convergence; persist target; fence re-add race with held lock ([#7298](https://github.com/block/buzz/pull/7298)) ([`ce41be9c4`](https://github.com/block/buzz/commit/ce41be9c4b1ca50dea0b04379333eb082826ba0f)) +- feat(relay): add atomic complete read-state snapshots ([#7572](https://github.com/block/buzz/pull/7572)) ([`6a86531ac`](https://github.com/block/buzz/commit/6a86531ac9d27b5123cca14636ced581578975df)) +- fix(mobile): avoid opening empty threads on message tap ([#7756](https://github.com/block/buzz/pull/7756)) ([`a61239f0d`](https://github.com/block/buzz/commit/a61239f0d8036aff58176f5c0ce7f080c66e21b7)) +- fix(workflows): make deletion persistent and retryable ([#7735](https://github.com/block/buzz/pull/7735)) ([`5079c770f`](https://github.com/block/buzz/commit/5079c770fe30bb3d8204822ce6c2431eacac6d4b)) +- fix(relay): exclude ephemeral activity from message quota ([#7736](https://github.com/block/buzz/pull/7736)) ([`5511b56fc`](https://github.com/block/buzz/commit/5511b56fcf0047f9d0d4887dc75125b6933a6bbd)) +- feat(db): expose connection setup metrics ([#7286](https://github.com/block/buzz/pull/7286)) ([`4c2086c08`](https://github.com/block/buzz/commit/4c2086c0844c30a0956aa1e3b1c2901f0357fb56)) +- Isolate S3 storage metrics from the relay ([#7543](https://github.com/block/buzz/pull/7543)) ([`6b1e45d2f`](https://github.com/block/buzz/commit/6b1e45d2f6084a3754a09bb1b800f370ce5399dd)) +- feat(mobile): show build number with version in settings ([#7697](https://github.com/block/buzz/pull/7697)) ([`b36600fc4`](https://github.com/block/buzz/commit/b36600fc440615e2565f94bffc800e0495180f6b)) +- Add authenticated WebSocket recovery telemetry ([#7546](https://github.com/block/buzz/pull/7546)) ([`891208914`](https://github.com/block/buzz/commit/891208914ed51c55b11ef6102f10ed08b5d9bb30)) +- Instrument database pool roles ([#7356](https://github.com/block/buzz/pull/7356)) ([`213092074`](https://github.com/block/buzz/commit/213092074c269bee90c87163672f9c2b8d714cfe)) +- fix(db): allow naturally expired push lease replacement ([#7653](https://github.com/block/buzz/pull/7653)) ([`c507a4d48`](https://github.com/block/buzz/commit/c507a4d488ca27796e78d876b9c24ee38442cc1b)) +- feat(push): make gateway origin configurable ([#7261](https://github.com/block/buzz/pull/7261)) ([`76f7e5ef0`](https://github.com/block/buzz/commit/76f7e5ef0cc4a7d71d9562ecfb3e4a6887a51461)) +- feat(git): add default-branch management to relay and CLI ([#7562](https://github.com/block/buzz/pull/7562)) ([`6146c4fd1`](https://github.com/block/buzz/commit/6146c4fd16f734b525f9ac31e1a3433ccc1ec96f)) +- fix(relay): reject presence updates when Redis storage fails ([#7532](https://github.com/block/buzz/pull/7532)) ([`00209076c`](https://github.com/block/buzz/commit/00209076c7a10d9e4a475466c313e8ebecf041f5)) +- feat(mesh): upgrade to mesh-llm 0.76.0-rc8 and recommend Qwen3.8 27B ([#6189](https://github.com/block/buzz/pull/6189)) ([`44316ff72`](https://github.com/block/buzz/commit/44316ff72f5f7de014c66b01cbf534298a70c249)) +- refactor(relay): extract NIP-29 membership authorization ([#7285](https://github.com/block/buzz/pull/7285)) ([`cd02b693a`](https://github.com/block/buzz/commit/cd02b693aae86444b0b5636474a3d202c6fc8f26)) +- feat(relay): add early startup lifecycle logs ([#7258](https://github.com/block/buzz/pull/7258)) ([`88687876f`](https://github.com/block/buzz/commit/88687876f7808a2fd742b7eb2e4b9f87d999ad8d)) +- Show status and huddle indicators beside names ([#7112](https://github.com/block/buzz/pull/7112)) ([`c6ca9d94d`](https://github.com/block/buzz/commit/c6ca9d94d94230a315257a87beb8dc116fec56cc)) +- feat(cli): add buzz gifs command group and NIP-30 emoji tags on messages ([#7259](https://github.com/block/buzz/pull/7259)) ([`47d068e21`](https://github.com/block/buzz/commit/47d068e2109d077414cbf2f4f1c927f6d051037a)) +- Add operation-aware database pool acquisition metrics ([#7195](https://github.com/block/buzz/pull/7195)) ([`91ab9d31b`](https://github.com/block/buzz/commit/91ab9d31b8f7249ff1db141ae9d8bb3f2a20bcdd)) +- chore(db): drop Phase-A NIP-FI relay-side authority ledger ([#7221](https://github.com/block/buzz/pull/7221)) ([`04babf026`](https://github.com/block/buzz/commit/04babf02655440b4dfd37f2e2df605ead0a030d8)) +- feat(relay): add detailed readiness metrics ([#7149](https://github.com/block/buzz/pull/7149)) ([`beb76406c`](https://github.com/block/buzz/commit/beb76406c12ab8a7af9b2fcf7547c353e3369c34)) +- feat(mobile): prepare `buzz-push-gateway` for deployment ([#7158](https://github.com/block/buzz/pull/7158)) ([`42b42447b`](https://github.com/block/buzz/commit/42b42447b0dc47c3e1a4d95caab893567dcd1677)) +- feat(buzz-auth): add production NIP-FI federated assertion runtime ([#7109](https://github.com/block/buzz/pull/7109)) ([`70895b355`](https://github.com/block/buzz/commit/70895b355fcea9f99894b426c020052b715bd368)) +- ci: run PostgreSQL tests in isolated lane ([#6730](https://github.com/block/buzz/pull/6730)) ([`bd7349041`](https://github.com/block/buzz/commit/bd73490418266f267d9bb3bdf13e64582adc8e80)) +- feat(db): add NIP-FI identity and final-admission schema foundation ([#6994](https://github.com/block/buzz/pull/6994)) ([`9ab163190`](https://github.com/block/buzz/commit/9ab163190b4d4994a742a66d5fa4cae23c35fa4e)) +- fix(relay): reject a frame on its own acknowledgement channel ([#6961](https://github.com/block/buzz/pull/6961)) ([`2f3dd850d`](https://github.com/block/buzz/commit/2f3dd850db3afe27e56f18cbcd3548eabdd9b9c2)) +- fix(acp): wake agents from workflow messages ([#6953](https://github.com/block/buzz/pull/6953)) ([`93237b4a7`](https://github.com/block/buzz/commit/93237b4a745b14cb8bfe292053bf34adef652d29)) +- Enforce NIP-OA authorization time bounds ([#7004](https://github.com/block/buzz/pull/7004)) ([`e47690c21`](https://github.com/block/buzz/commit/e47690c21b519128b40c917456b3e3f33f018fe4)) +- feat(db): configurable writer session timeouts (lock, idle-txn, statement) ([#6229](https://github.com/block/buzz/pull/6229)) ([`3ed623bb2`](https://github.com/block/buzz/commit/3ed623bb217bf9697b0ce4562529254977e0ea04)) +- feat(mobile): push notifications MVP ([#6269](https://github.com/block/buzz/pull/6269)) ([`c432a111c`](https://github.com/block/buzz/commit/c432a111ca9ddd31a85e1312d5995f8b92191b82)) +- refactor(db): extract domain stores from database runtime ([#6987](https://github.com/block/buzz/pull/6987)) ([`a3730784f`](https://github.com/block/buzz/commit/a3730784fc851bb1125b40cca9b0a30788a293c1)) +- refactor(relay): NIP-98 admin auth with Operator/Moderator roles and NIP-11 discovery ([#3777](https://github.com/block/buzz/pull/3777)) ([`86b9142a0`](https://github.com/block/buzz/commit/86b9142a09f2af3ba2fff7effa6a6cd53b40f51c)) +- refactor(db): split channel membership store ([#6782](https://github.com/block/buzz/pull/6782)) ([`e76c81968`](https://github.com/block/buzz/commit/e76c81968b65b0755b83efdd59dc3375c59ddf40)) +- feat(auth): add NIP-FI canonical assertion verifier and contracts ([#6776](https://github.com/block/buzz/pull/6776)) ([`953a1798b`](https://github.com/block/buzz/commit/953a1798b23b04289b3a225f463e60a172c1aac3)) +- test(db): use canonical channel roster fixtures ([#6819](https://github.com/block/buzz/pull/6819)) ([`57216c942`](https://github.com/block/buzz/commit/57216c942f171db305135bcb6a4ede2d87e0be8a)) +- fix(cli): enrich template cardinality error with per-candidate presence and profile hints ([#4825](https://github.com/block/buzz/pull/4825)) ([`0808ab485`](https://github.com/block/buzz/commit/0808ab485c39c3c12ef02af2188c65a5145eb99d)) +- fix(db): disable heartbeat vacuum truncation ([#6898](https://github.com/block/buzz/pull/6898)) ([`0ccf934b8`](https://github.com/block/buzz/commit/0ccf934b88f610f5f235862ecd51e2dcbae2cb74)) +- fix(db): exclude kind:30179 ciphertext from brownfield FTS ([#6822](https://github.com/block/buzz/pull/6822)) ([`b3baa56ba`](https://github.com/block/buzz/commit/b3baa56ba83d01a0b7292d81aae9370f5616c62b)) +- broker: define the agent-to-broker action contract ([#6742](https://github.com/block/buzz/pull/6742)) ([`b622003f7`](https://github.com/block/buzz/commit/b622003f74aa5bf9b659786452813299a25e4897)) +- feat(projects): add agent and CLI project-home support ([#6590](https://github.com/block/buzz/pull/6590)) ([`de188ebf0`](https://github.com/block/buzz/commit/de188ebf06f701ca0f47c51f859da21e19a35f04)) +- refactor(db): finish replaceable event store extraction ([#6777](https://github.com/block/buzz/pull/6777)) ([`ef0d20256`](https://github.com/block/buzz/commit/ef0d2025683869418e8eee22ac5b5ac16c5198b7)) +- feat(desktop): add KLIPY GIF search to composers ([#5554](https://github.com/block/buzz/pull/5554)) ([`8471049c4`](https://github.com/block/buzz/commit/8471049c430073474939336dfc6aa98272bc8762)) +- Remove public relay signing key fallback ([#6729](https://github.com/block/buzz/pull/6729)) ([`ee6ca5fa2`](https://github.com/block/buzz/commit/ee6ca5fa28bce04dfecb6717de65b08a57f2ac47)) +- Qualify canonical relay images for staged delivery ([#6781](https://github.com/block/buzz/pull/6781)) ([`f24971033`](https://github.com/block/buzz/commit/f24971033178926153b49d320bd876d15d9cb2bf)) +- Add database pressure observability ([#6700](https://github.com/block/buzz/pull/6700)) ([`113a33b7e`](https://github.com/block/buzz/commit/113a33b7e49b7173ee1767c49ef2f49c63803034)) +- Support community deletion in versioned media buckets ([#6738](https://github.com/block/buzz/pull/6738)) ([`d12dea4e6`](https://github.com/block/buzz/commit/d12dea4e67c5224a626d9c00f45e68d1def72d4c)) +- Extract community persistence ([#6668](https://github.com/block/buzz/pull/6668)) ([`9d1e4b257`](https://github.com/block/buzz/commit/9d1e4b257657f382d3111ce748f3da8d063b7671)) +- Centralize replaceable event persistence ([#6660](https://github.com/block/buzz/pull/6660)) ([`8d2d0ff5a`](https://github.com/block/buzz/commit/8d2d0ff5ad42733e9949442c4b6358d0ba87f9a8)) +- perf(desktop): persist channel heads, collapse thread reads and reply sends ([#6572](https://github.com/block/buzz/pull/6572)) ([`2d280376a`](https://github.com/block/buzz/commit/2d280376ad36134cec1f23bead6d866d30bed147)) +- Add mobile Huddles voice MVP ([#6056](https://github.com/block/buzz/pull/6056)) ([`8c0f42e18`](https://github.com/block/buzz/commit/8c0f42e187ca82d701251fc849217530178ebace)) +- Repair stale large channel roster snapshots ([#6251](https://github.com/block/buzz/pull/6251)) ([`24ec6a468`](https://github.com/block/buzz/commit/24ec6a468ec9d0d425ee58fbfc4d416412c446ad)) +- feat(workflows): reply in-thread from send_message action ([#6178](https://github.com/block/buzz/pull/6178)) ([`c6e3fe7df`](https://github.com/block/buzz/commit/c6e3fe7dfa751096d8c4083aaf15d6f6af296572)) +- feat(workflows): add workflow editor ([#6248](https://github.com/block/buzz/pull/6248)) ([`1934e83bf`](https://github.com/block/buzz/commit/1934e83bf5a5d8cd00f0cf28b558547b8d0dffb0)) +- fix(media): accept portrait video resolutions ([#6058](https://github.com/block/buzz/pull/6058)) ([`196d62f97`](https://github.com/block/buzz/commit/196d62f97c21d053ddf8715d75ef57e92bd0051f)) +- Revert "fix(acp): gate relay-signed workflow messages on their attributed author" ([#6311](https://github.com/block/buzz/pull/6311)) ([`08eb46ef3`](https://github.com/block/buzz/commit/08eb46ef3c0894baa7e48d9229f45349751a4a57)) +- fix(desktop): exclude archived agents from nest, order regeneration ([#5905](https://github.com/block/buzz/pull/5905)) ([`121e4b3ce`](https://github.com/block/buzz/commit/121e4b3ce7acab6ac310257f444997f58a97cb2e)) +- fix(workflows): preserve multi-channel listing semantics ([#6009](https://github.com/block/buzz/pull/6009)) ([`f7a01bda7`](https://github.com/block/buzz/commit/f7a01bda7b1bf95cdbc9dc21bb69970955b14ecc)) +- fix(acp): gate relay-signed workflow messages on their attributed author ([#6129](https://github.com/block/buzz/pull/6129)) ([`54f11219e`](https://github.com/block/buzz/commit/54f11219efe6b2617ba74d1ef8701fb5413956d8)) +- feat(workflows): add responsive library card actions ([#6008](https://github.com/block/buzz/pull/6008)) ([`edc4a09aa`](https://github.com/block/buzz/commit/edc4a09aaa41c29e2495a28247c895febaf6587d)) +- Projects v3: unify sharing, discussions, and issue ownership ([#5792](https://github.com/block/buzz/pull/5792)) ([`122a8b898`](https://github.com/block/buzz/commit/122a8b8988869f0b1a7c056a76f7d16bfb0f6fdd)) +- fix(channels): return complete member rosters ([#5765](https://github.com/block/buzz/pull/5765)) ([`e0940927f`](https://github.com/block/buzz/commit/e0940927ff381f6a353c637732c7a81886f9639d)) +- Make workflow run history authoritative in Desktop ([#5780](https://github.com/block/buzz/pull/5780)) ([`2693e0db1`](https://github.com/block/buzz/commit/2693e0db1fc4980a551c2492031812dc4bad985f)) +- feat(deletion): add durable whole-community deletion ([#4425](https://github.com/block/buzz/pull/4425)) ([`8a2c9af2d`](https://github.com/block/buzz/commit/8a2c9af2dbe0cf315e77f43a4560d3572da5e554)) +- fix(relay): stop panicking the ingest worker on reactions to project events ([#5294](https://github.com/block/buzz/pull/5294)) ([`16b7ae7ce`](https://github.com/block/buzz/commit/16b7ae7ce623a57be1461adee3b8fce4115b3c3a)) +- fix(relay): log event kind on the HTTP bridge /events line ([#5291](https://github.com/block/buzz/pull/5291)) ([`e8153f8f2`](https://github.com/block/buzz/commit/e8153f8f27f5a35f56b2a578ab749190787d9e91)) +- feat(tracing): add PostgreSQL tracing spans ([#3678](https://github.com/block/buzz/pull/3678)) ([`397796c5f`](https://github.com/block/buzz/commit/397796c5f343db4251198f44505b1afebe88223f)) +- Fix macOS attachment picker lifecycle and allow inert HTML downloads ([#5569](https://github.com/block/buzz/pull/5569)) ([`bba3e0638`](https://github.com/block/buzz/commit/bba3e06386b8a0ca22e9867dc81aac1ca2b1b737)) +- chore: mesh upgrade, clean up legacy special case code, simplify model selection for mesh ([#5289](https://github.com/block/buzz/pull/5289)) ([`240cdd3ea`](https://github.com/block/buzz/commit/240cdd3ea17a8f4d521c8398a929294210bd1e1a)) +- fix(channels): restore member invitations to private channels ([#5493](https://github.com/block/buzz/pull/5493)) ([`2777189d9`](https://github.com/block/buzz/commit/2777189d960fa5b1d863166f36d6e37ff8ce0819)) +- fix(search): surface exact short profile names ([#5480](https://github.com/block/buzz/pull/5480)) ([`3c76f682c`](https://github.com/block/buzz/commit/3c76f682c3c2dfe2cd296c277c5e63799d3424f9)) +- feat(desktop): NIP-AM agent-usage backend — P2 emission/transport/archive + P4a aggregation/D6 ([#4000](https://github.com/block/buzz/pull/4000)) ([`5e4c05f90`](https://github.com/block/buzz/commit/5e4c05f90b062898e1827ba45cb826c6ff913741)) + + ## relay-v0.2.1 - fix(sdk): preserve self-mention p tags in message and forum event builders ([#4975](https://github.com/block/buzz/pull/4975)) ([`78c87ae20e`](https://github.com/block/buzz/commit/78c87ae20e182fffdd99744d6c9ff99df82b159c)) diff --git a/crates/buzz-relay/Cargo.toml b/crates/buzz-relay/Cargo.toml index ef0808ef65c..cd5a79e526d 100644 --- a/crates/buzz-relay/Cargo.toml +++ b/crates/buzz-relay/Cargo.toml @@ -4,7 +4,7 @@ default-run = "buzz-relay" # Independent version: buzz-relay ships as a pinnable artifact # (ghcr.io/block/buzz), released on its own cadence via `just release-relay`. # It does NOT inherit the workspace version. -version = "0.2.1" +version = "0.3.0" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -19,6 +19,9 @@ path = "src/main.rs" buzz-core = { workspace = true } buzz-conformance = { workspace = true } buzz-db = { workspace = true } +# The relay chooses its flag provider at startup (BUZZ_FEATURE_FLAGS_PROVIDER), +# so every build carries the LaunchDarkly adapter; it is inert unless selected. +buzz-feature-flags = { workspace = true, features = ["launchdarkly"] } buzz-datastore-tracing = { workspace = true } buzz-deletion = { workspace = true } buzz-auth = { workspace = true } @@ -56,7 +59,6 @@ uuid = { workspace = true } chrono = { workspace = true } dashmap = { workspace = true } futures-util = { workspace = true } -deadpool-redis = { workspace = true } redis = { workspace = true } # Redis TLS (rediss://, e.g. ElastiCache) uses rustls, which needs a process # CryptoProvider installed at startup. Both aws-lc-rs and ring are compiled in @@ -93,6 +95,7 @@ async-compression = { version = "0.4.42", features = ["tokio", "gzip"] } dev = ["buzz-auth/dev"] [dev-dependencies] +buzz-cli = { path = "../buzz-cli" } # Generate ephemeral P-256 signing fixtures; already in the runtime dependency graph. ring = "0.17" # The mesh-llm smoke harnesses moved to `crates/buzz-mesh-smoke`. A diff --git a/crates/buzz-relay/src/access.rs b/crates/buzz-relay/src/access.rs new file mode 100644 index 00000000000..93c3fc0896f --- /dev/null +++ b/crates/buzz-relay/src/access.rs @@ -0,0 +1,2400 @@ +//! Stdout access log for security investigations: who read what, and who +//! tried to authenticate. +//! +//! Every line goes to the [`TARGET`] tracing target (stdout, never the +//! `audit_log` table) and carries an `event` field to filter on. Search text, +//! event content, tokens, and assertions are never recorded: filters are +//! reduced to a [`FilterSummary`], and failures to fixed reason codes. +//! +//! `event=auth` lines cover WebSocket AUTH (root and audio): one line per +//! attempt; root lines carry the TCP `peer_addr`. `event=http` lines come from +//! [`http_access_log`]: one per HTTP request, with what the handler proved and +//! decided recorded through its [`AccessSlot`]. Every matched route is logged +//! except public documents and probes; a request that matched no route is +//! logged only at status 400 or above, as `route=""`. `route` is the +//! matched template, never the raw path. +//! `event=write` lines cover WebSocket EVENT: one per frame, with the OK the +//! relay answered (see [`WriteLog`]). +//! A successful bridge read that returned nothing (`result_count=0`) logs at +//! DEBUG: polling clients make most of them. WebSocket `req` lines stay at +//! INFO, because an empty subscription can still deliver live events. +//! +//! With `BUZZ_CLIENT_IP_HEADER` set, `http`, `auth` and `close` lines also +//! carry `client_ip`: the rightmost entry of that request header, only when it +//! parses as an IP address. It never replaces `peer_addr`. + +use std::net::{IpAddr, SocketAddr}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +use buzz_core::CommunityId; +use nostr::{Alphabet, Filter, PublicKey, SingleLetterTag}; +use tracing::Level; +use uuid::Uuid; + +/// The tracing target for every access line. +pub(crate) const TARGET: &str = "buzz_relay::access"; + +/// Most identifiers listed per field; a longer list adds its `*_count`. +const LIST_CAP: usize = 10; + +macro_rules! emit { + ($level:expr, $($fields:tt)+) => { + match $level { + Level::WARN => tracing::warn!(target: TARGET, $($fields)+), + Level::INFO => tracing::info!(target: TARGET, $($fields)+), + _ => tracing::debug!(target: TARGET, $($fields)+), + } + }; +} + +/// What a REQ or COUNT asked for, merged across its filters. List fields hold +/// the first [`LIST_CAP`] distinct values; their `*_count` fields sum the +/// per-filter set sizes, so a value repeated in two filters counts twice, and +/// are absent when the list already shows that many values. A list field is +/// `*` when any filter leaves that dimension open, because that filter reads +/// every value; `since`/`until`/`limit` likewise take the widest +/// bound and are absent when any filter leaves them open. No field understates +/// what the read covered. Only well-formed channel ids and pubkeys are listed, +/// so client-chosen tag text never reaches the log. +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct FilterSummary { + filters: usize, + kinds: Option, + kind_count: Option, + channel_ids: Option, + channel_count: Option, + authors: Option, + author_count: Option, + p_tags: Option, + p_count: Option, + ids: usize, + since: Option, + until: Option, + limit: Option, + search: bool, +} + +/// The value logged for a list dimension that some filter leaves open. +const OPEN: &str = "*"; + +impl FilterSummary { + pub(crate) fn new(filters: &[Filter]) -> Self { + let h = SingleLetterTag::lowercase(Alphabet::H); + let p = SingleLetterTag::lowercase(Alphabet::P); + let (mut kinds, mut channels, mut authors, mut p_tags) = ( + Listed::default(), + Listed::default(), + Listed::default(), + Listed::default(), + ); + let mut ids = 0; + for filter in filters { + for k in filter.kinds.iter().flatten() { + kinds.offer(k.as_u16()); + } + for c in filter.generic_tags.get(&h).into_iter().flatten() { + channels.count(Uuid::parse_str(c).is_ok().then_some(c)); + } + for a in filter.authors.iter().flatten() { + authors.offer(*a); + } + for v in filter.generic_tags.get(&p).into_iter().flatten() { + p_tags.count(PublicKey::from_hex(v).is_ok().then_some(v)); + } + ids += filter.ids.as_ref().map_or(0, |s| s.len()); + } + let open = |bounded: &dyn Fn(&Filter) -> bool| filters.iter().any(|f| !bounded(f)); + let bound = |pick: fn(&Filter) -> Option, widest: fn(u64, u64) -> u64| { + let values: Option> = filters.iter().map(pick).collect(); + values?.into_iter().reduce(widest) + }; + let (kind_count, kinds) = kinds.finish(open(&|f| f.kinds.is_some()), u16::to_string); + let (channel_count, channel_ids) = channels + .finish(open(&|f| f.generic_tags.contains_key(&h)), |c| { + c.to_string() + }); + let (author_count, authors) = + authors.finish(open(&|f| f.authors.is_some()), PublicKey::to_hex); + let (p_count, p_tags) = p_tags.finish(open(&|f| f.generic_tags.contains_key(&p)), |v| { + v.to_string() + }); + Self { + filters: filters.len(), + kinds, + kind_count, + channel_ids, + channel_count, + authors, + author_count, + p_tags, + p_count, + ids, + since: bound(|f| f.since.map(|t| t.as_secs()), u64::min), + until: bound(|f| f.until.map(|t| t.as_secs()), u64::max), + limit: bound(|f| f.limit.map(|l| l as u64), u64::max).map(|l| l as usize), + search: filters.iter().any(|f| f.search.is_some()), + } + } +} + +/// The first [`LIST_CAP`] distinct values offered, in order, and how many +/// values were seen. Working state never exceeds the cap, however long the +/// filter lists are. +struct Listed { + listed: Vec, + seen: usize, +} + +impl Default for Listed { + fn default() -> Self { + Self { + listed: Vec::new(), + seen: 0, + } + } +} + +impl Listed { + fn offer(&mut self, value: T) { + self.count(Some(value)); + } + + /// Count one value, listing it when it is `Some` (well-formed). + fn count(&mut self, value: Option) { + self.seen += 1; + if let Some(value) = value { + if self.listed.len() < LIST_CAP && !self.listed.contains(&value) { + self.listed.push(value); + } + } + } + + /// The count, unless the list shows exactly that many values, and the + /// comma-joined list: [`OPEN`] when a filter leaves the dimension open, + /// `None` when nothing was listed. + fn finish(self, open: bool, show: impl Fn(&T) -> String) -> (Option, Option) { + let count = (open || self.seen != self.listed.len()).then_some(self.seen); + let shown = if open { + Some(OPEN.to_owned()) + } else { + (!self.listed.is_empty()) + .then(|| self.listed.iter().map(show).collect::>().join(",")) + }; + (count, shown) + } +} + +/// Lines a connection may write for client-repeatable refusals before the +/// rest are only counted. +const REFUSAL_LINES: u64 = 16; + +/// Per-connection bound on the access lines a client can trigger without +/// being served: reads refused or denied, EVENTs rejected, and AUTH frames +/// after the login was decided. Each kind has its own counter. The first [`REFUSAL_LINES`] of each are logged; the rest are +/// counted and reported on the close line. Served reads are never capped. +#[derive(Debug, Default)] +pub(crate) struct RefusalBudget { + reads: AtomicU64, + writes: AtomicU64, + auths: AtomicU64, +} + +impl RefusalBudget { + /// Whether this refused read may write its line. + pub(crate) fn read(&self) -> bool { + Self::charge(&self.reads) + } + + /// Whether this rejected EVENT may write its line. + pub(crate) fn write(&self) -> bool { + Self::charge(&self.writes) + } + + /// Whether this post-decision AUTH frame may write its line. + pub(crate) fn auth(&self) -> bool { + Self::charge(&self.auths) + } + + /// A charge logs while under budget, or once `close` has been written. + fn charge(seen: &AtomicU64) -> bool { + let prev = seen.fetch_add(1, Ordering::AcqRel); + !(REFUSAL_LINES..CLOSED).contains(&prev) + } + + /// Ends counting for `close` and returns how many were suppressed. + /// Swapping in [`CLOSED`] and every charge's `fetch_add` are + /// read-modify-writes on one atomic, so each charge lands either before + /// the swap (in `seen`) or after it (sees `CLOSED` and logs its own + /// line): none is both counted and logged, and none is lost. + fn close(seen: &AtomicU64) -> u64 { + seen.swap(CLOSED, Ordering::AcqRel) + .saturating_sub(REFUSAL_LINES) + } +} + +/// Counter value once `close` has been written. +const CLOSED: u64 = 1 << 63; + +/// How a read ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ReadOutcome { + /// Dropped before a terminal frame: connection teardown or session expiry. + Aborted, + Served, + Denied(&'static str), + Error(&'static str), +} + +impl ReadOutcome { + /// The `outcome` and `reason` this read logs and is measured under. + fn parts(self) -> (&'static str, Option<&'static str>) { + match self { + Self::Aborted => ("aborted", None), + Self::Served => ("served", None), + Self::Denied(r) => ("denied", Some(r)), + Self::Error(r) => ("error", Some(r)), + } + } +} + +/// One access line per WebSocket REQ, COUNT or sync, written when the handler +/// finishes (a sync's initial set completes), including when its future is +/// dropped mid-read. +pub(crate) struct ReadLog { + event: &'static str, + conn_id: Uuid, + community: CommunityId, + pubkey: Option, + sub_id: String, + summary: FilterSummary, + outcome: ReadOutcome, + /// REQ: stored events handed to the connection's writer so far. + /// COUNT: the total returned. + results: u64, + /// Charged if the read ends denied; `None` once already charged. + budget: Option>, + /// When the handler took the frame; the read's duration ends at drop. + started: std::time::Instant, +} + +impl ReadLog { + pub(crate) fn req( + conn: &crate::connection::ConnectionState, + sub_id: &str, + filters: &[Filter], + ) -> Self { + Self::new("req", conn, sub_id, filters) + } + + pub(crate) fn count( + conn: &crate::connection::ConnectionState, + sub_id: &str, + filters: &[Filter], + ) -> Self { + Self::new("count", conn, sub_id, filters) + } + + /// A NIP-AR sync, summarized as the live filter it registers. Its line + /// is written once the initial set ends; live delivery is not counted. + pub(crate) fn sync( + conn: &crate::connection::ConnectionState, + sub_id: &str, + channels: &[Uuid], + ) -> Self { + let filter = crate::handlers::artifact_sync::live_filter(channels); + Self::new("sync", conn, sub_id, std::slice::from_ref(&filter)) + } + + /// Log a read refused before its handler ran; other frames log nothing. + pub(crate) fn refused( + msg: &crate::protocol::ClientMessage, + conn: &crate::connection::ConnectionState, + reason: &'static str, + ) { + use crate::protocol::ClientMessage as M; + match msg { + M::Req { + sub_id, filters, .. + } => Self::refused_read("req", conn, sub_id, filters, reason), + M::Count { sub_id, filters } => { + Self::refused_read("count", conn, sub_id, filters, reason) + } + M::ArtifactSync { sub_id, filter } => { + Self::refused_sync(conn, sub_id, filter.as_ref().ok(), reason) + } + // Admission refuses only reads and EVENTs. + _ => {} + } + } + + /// Log a `event` ("req", "count" or "sync") refused before its handler ran. + pub(crate) fn refused_read( + event: &'static str, + conn: &crate::connection::ConnectionState, + sub_id: &str, + filters: &[Filter], + reason: &'static str, + ) { + if conn.refusal_budget.read() { + let mut log = Self::new(event, conn, sub_id, filters); + log.budget = None; + log.deny(reason); + } else { + // Over budget the line is suppressed, but the read still counts. + crate::metrics::record_ws_read_finished(event, "denied", Some(reason), 0.0); + } + } + + /// Log a sync refused before its handler ran. An invalid filter is + /// summarized as no filter. + pub(crate) fn refused_sync( + conn: &crate::connection::ConnectionState, + sub_id: &str, + filter: Option<&buzz_core::artifact_sync::ArtifactSyncFilter>, + reason: &'static str, + ) { + let filters: Vec = filter + .map(|f| crate::handlers::artifact_sync::live_filter(&f.channels)) + .into_iter() + .collect(); + Self::refused_read("sync", conn, sub_id, &filters, reason); + } + + fn new( + event: &'static str, + conn: &crate::connection::ConnectionState, + sub_id: &str, + filters: &[Filter], + ) -> Self { + let pubkey = match conn.auth_state_snapshot() { + crate::connection::AuthState::Authenticated(ctx) => Some(ctx.pubkey.to_hex()), + _ => None, + }; + Self { + event, + conn_id: conn.conn_id, + community: conn.tenant.community(), + pubkey, + sub_id: sub_id.to_owned(), + // The summary is the costly part; skip it when the line is off. + // An `error` line is WARN, so it keeps the summary at `=warn`. + summary: if tracing::enabled!(target: TARGET, Level::WARN) { + FilterSummary::new(filters) + } else { + FilterSummary::default() + }, + outcome: ReadOutcome::Aborted, + results: 0, + budget: Some(Arc::clone(&conn.refusal_budget)), + started: std::time::Instant::now(), + } + } + + /// Refused before any stored event was read. + pub(crate) fn deny(&mut self, reason: &'static str) { + self.outcome = ReadOutcome::Denied(reason); + } + + /// Ended by a server-side failure. + pub(crate) fn error(&mut self, reason: &'static str) { + self.outcome = ReadOutcome::Error(reason); + } + + /// Ended by a failed database read. + pub(crate) fn db_failed(&mut self, e: &buzz_db::DbError) { + self.error(if e.is_statement_cancelled() { + "query_timed_out" + } else { + "database_error" + }); + } + + /// One stored event was handed to the writer. Counted as it happens, so + /// a read that later fails or is cancelled still logs its progress. + pub(crate) fn queued_one(&mut self) { + self.results += 1; + } + + /// Completed: every stored event was queued before EOSE. + pub(crate) fn served(&mut self) { + self.outcome = ReadOutcome::Served; + } + + /// A COUNT completed with `total`. + pub(crate) fn counted(&mut self, total: u64) { + self.outcome = ReadOutcome::Served; + self.results = total; + } +} + +impl Drop for ReadLog { + fn drop(&mut self) { + let (outcome, reason) = self.outcome.parts(); + // Measured before the refusal budget, which only suppresses the line. + crate::metrics::record_ws_read_finished( + self.event, + outcome, + reason, + self.started.elapsed().as_secs_f64(), + ); + if let (ReadOutcome::Denied(_), Some(budget)) = (self.outcome, &self.budget) { + if !budget.read() { + return; + } + } + let s = &self.summary; + let (events_queued, count) = match (self.event, self.outcome) { + ("count", ReadOutcome::Served) => (None, Some(self.results)), + ("count", _) => (None, None), + _ => (Some(self.results), None), + }; + // A client closing mid-read (`aborted`) or a refusal is routine; only + // a server-side failure is a WARN. + let level = match self.outcome { + ReadOutcome::Error(_) => Level::WARN, + _ => Level::INFO, + }; + emit!( + level, + event = self.event, + conn_id = %self.conn_id, + community = %self.community, + pubkey = self.pubkey.as_deref(), + sub_id = self.sub_id.as_str(), + filters = s.filters, + kinds = s.kinds.as_deref(), + kind_count = s.kind_count, + channel_ids = s.channel_ids.as_deref(), + channel_count = s.channel_count, + authors = s.authors.as_deref(), + author_count = s.author_count, + p_tags = s.p_tags.as_deref(), + p_count = s.p_count, + ids = s.ids, + since = s.since, + until = s.until, + limit = s.limit, + search = s.search, + outcome, + reason, + events_queued, + count, + "access" + ); + } +} + +/// The NIP-01 OK prefixes a write's `reason` may take; any other message +/// logs `other`, so the text after the prefix never reaches the log. +const OK_PREFIXES: [&str; 9] = [ + "duplicate", + "pow", + "blocked", + "rate-limited", + "invalid", + "restricted", + "mute", + "error", + "auth-required", +]; + +/// The fixed reason for a refused write: its OK message's NIP-01 prefix. +fn ok_reason(message: &str) -> &'static str { + let prefix = message.split_once(':').map_or(message, |(p, _)| p); + OK_PREFIXES + .into_iter() + .find(|p| *p == prefix) + .unwrap_or("other") +} + +/// One access line per WebSocket EVENT, written when its handler ends and +/// recording the OK the relay answered: `accepted`, `rejected` or `error` +/// (WARN) with the OK prefix as `reason`, or `aborted` if the handler ended +/// before deciding one. `outcome` is the relay's decision; an OK that could not +/// be queued (outbound channel full or closed) adds `ok_queued=false`. +/// Only the event's `kind` and id are logged, never its content or tags. +/// Rejected lines are capped per connection by [`RefusalBudget`], on their own +/// counter, separate from refused reads'. +pub(crate) struct WriteLog { + conn_id: Uuid, + community: CommunityId, + pubkey: Option, + kind: u32, + event_id: String, + /// The OK decided, as (accepted, reason, queued); `None` until one is. + answer: Option<(bool, &'static str, bool)>, + budget: Arc, +} + +impl WriteLog { + pub(crate) fn new(conn: &crate::connection::ConnectionState, event: &nostr::Event) -> Self { + let pubkey = match conn.auth_state_snapshot() { + crate::connection::AuthState::Authenticated(ctx) => Some(ctx.pubkey.to_hex()), + _ => None, + }; + Self { + conn_id: conn.conn_id, + community: conn.tenant.community(), + pubkey, + kind: buzz_core::kind::event_kind_u32(event), + event_id: event.id.to_hex(), + answer: None, + budget: Arc::clone(&conn.refusal_budget), + } + } + + /// Log an EVENT refused before its handler ran, under a fixed `reason`; + /// `queued` is whether its OK was queued. + pub(crate) fn refused( + conn: &crate::connection::ConnectionState, + event: &nostr::Event, + reason: &'static str, + queued: bool, + ) { + Self::new(conn, event).answer = Some((false, reason, queued)); + } + + /// Send the EVENT's OK and record it for the line. + pub(crate) fn ok( + &mut self, + conn: &crate::connection::ConnectionState, + event_id: &str, + accepted: bool, + message: &str, + ) { + let queued = conn.send(crate::protocol::RelayMessage::ok( + event_id, accepted, message, + )); + let reason = if accepted { "" } else { ok_reason(message) }; + self.answer = Some((accepted, reason, queued)); + } +} + +impl Drop for WriteLog { + fn drop(&mut self) { + let (outcome, reason) = match self.answer { + None => ("aborted", None), + Some((true, ..)) => ("accepted", None), + Some((false, "error", _)) => ("error", Some("error")), + Some((false, reason, _)) => ("rejected", Some(reason)), + }; + // Present only when an OK was decided but could not be queued. + let ok_queued = matches!(self.answer, Some((.., false))).then_some(false); + if outcome == "rejected" && !self.budget.write() { + return; + } + let level = if outcome == "error" { + Level::WARN + } else { + Level::INFO + }; + emit!( + level, + event = "write", + conn_id = %self.conn_id, + community = %self.community, + pubkey = self.pubkey.as_deref(), + kind = self.kind, + event_id = self.event_id.as_str(), + outcome, + reason, + ok_queued, + "access" + ); + } +} + +/// Which credential an auth attempt presented. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum AuthMethod { + /// WebSocket login (NIP-42). + Nip42, + /// HTTP signed request (NIP-98). + Nip98, + /// Enterprise identity assertion (NIP-FI). + NipFi, + /// Blossom upload authorization (kind 24242). + Blossom, + /// Dev-mode `X-Pubkey` header: a claimed key that nothing signed. + XPubkey, + /// Admitted by network position alone (`BUZZ_ADMIN_AUTH=disabled`): + /// no proof and no key. + NetworkTrusted, +} + +impl AuthMethod { + const fn as_str(self) -> &'static str { + match self { + Self::Nip42 => "nip42", + Self::Nip98 => "nip98", + Self::NipFi => "nip_fi", + Self::Blossom => "blossom", + Self::XPubkey => "x_pubkey", + Self::NetworkTrusted => "network_trusted", + } + } +} + +/// Why a proven identity was refused. One code per meaning on every +/// transport (WebSocket, HTTP, git, audio), so a single filter finds them all. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum AuthReason { + NotRelayMember, + MembershipUnavailable, + Banned, + BanCheckUnavailable, + AllowlistDenied, + AllowlistUnavailable, + QuotaExceeded, + AdmissionUnavailable, + ConcurrencyLimit, + ReplayCheckUnavailable, + AuthorizationUnavailable, + VerifierUnavailable, + KeyMismatch, + DenySet, + SessionExpired, + RosterUnavailable, + OriginMismatch, + AdminHostMismatch, + NotStaff, + NotOperator, + NotOperatorListener, + NotModerator, + NotRelayAdmin, + Restricted, + NipOaOwnerUnlinked, + OwnerMismatch, + ChannelMembershipDenied, + AlreadyAuthenticated, + AlreadyFailed, + Timeout, + Disconnect, + Shutdown, +} + +impl AuthReason { + pub(crate) const fn as_str(self) -> &'static str { + match self { + Self::NotRelayMember => "not_relay_member", + Self::MembershipUnavailable => "membership_unavailable", + Self::Banned => "banned", + Self::BanCheckUnavailable => "ban_check_unavailable", + Self::AllowlistDenied => "allowlist_denied", + Self::AllowlistUnavailable => "allowlist_unavailable", + Self::QuotaExceeded => "quota_exceeded", + Self::AdmissionUnavailable => "admission_unavailable", + Self::ConcurrencyLimit => "concurrency_limit", + Self::ReplayCheckUnavailable => "replay_check_unavailable", + Self::AuthorizationUnavailable => "authorization_unavailable", + Self::VerifierUnavailable => "verifier_unavailable", + Self::KeyMismatch => "key_mismatch", + Self::DenySet => "deny_set", + Self::SessionExpired => "session_expired", + Self::RosterUnavailable => "roster_unavailable", + Self::OriginMismatch => "origin_mismatch", + Self::AdminHostMismatch => "admin_host_mismatch", + Self::NotStaff => "not_staff", + Self::NotOperator => "not_operator", + Self::NotOperatorListener => "not_operator_listener", + Self::NotModerator => "not_moderator", + Self::NotRelayAdmin => "not_relay_admin", + Self::Restricted => "restricted", + Self::NipOaOwnerUnlinked => "nip_oa_owner_unlinked", + Self::OwnerMismatch => "owner_mismatch", + Self::ChannelMembershipDenied => "channel_membership_denied", + Self::AlreadyAuthenticated => "already_authenticated", + Self::AlreadyFailed => "already_failed", + Self::Timeout => "timeout", + Self::Disconnect => "disconnect", + Self::Shutdown => "shutdown", + } + } +} + +/// How an auth attempt ended. `Denied` means the identity was proven but not +/// admitted; `Failed` means the proof itself was rejected, with the code of +/// that proof type's single mapper. `Challenged` is a request that carried no +/// credentials and was answered with a challenge, the normal first step of a +/// git exchange. Reasons are fixed codes, never raw error text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum AuthResult { + Success, + Denied(AuthReason), + Challenged, + Failed(&'static str), + /// Cut off before a decision (connection cancelled or session expired). + Aborted(&'static str), +} + +impl AuthResult { + /// The line's level, `outcome`, and `reason`. + fn parts(self) -> (Level, &'static str, Option<&'static str>) { + match self { + Self::Success => (Level::INFO, "success", None), + Self::Denied(r) => (Level::WARN, "denied", Some(r.as_str())), + Self::Challenged => (Level::INFO, "challenged", None), + Self::Failed(r) => (Level::WARN, "failed", Some(r)), + Self::Aborted(r) => (Level::WARN, "aborted", Some(r)), + } + } + + /// The access result for a WebSocket auth terminal. Only a bad proof is + /// `Failed`; every policy refusal, including a fail-closed lookup error, + /// is `Denied` with the metric's stable label as its reason. + pub(crate) fn from_outcome(outcome: crate::metrics::AuthOutcome) -> Self { + use crate::metrics::AuthOutcome as O; + Self::Denied(match outcome { + O::Success => return Self::Success, + O::Invalid => return Self::Failed(outcome.as_str()), + O::Banned => AuthReason::Banned, + O::BanCheckError => AuthReason::BanCheckUnavailable, + O::AllowlistCheckError => AuthReason::AllowlistUnavailable, + O::AllowlistDenied => AuthReason::AllowlistDenied, + O::RelayMembershipCheckError => AuthReason::MembershipUnavailable, + O::NotRelayMember => AuthReason::NotRelayMember, + O::PairingMismatch => AuthReason::KeyMismatch, + O::ConcurrencyLimit => AuthReason::ConcurrencyLimit, + O::Timeout => AuthReason::Timeout, + O::Disconnect => AuthReason::Disconnect, + O::Shutdown => AuthReason::Shutdown, + }) + } +} + +/// One WebSocket auth attempt (NIP-42 or audio) whose exits are spread +/// across a long handler: it logs exactly once, at [`AuthLine::finish`], or +/// on drop as `aborted` if the handler returned (cancellation, teardown) +/// without deciding. HTTP requests use [`AccessSlot`] instead. +pub(crate) struct AuthLine<'a> { + attempt: AuthAttempt<'a>, + abort_reason: &'static str, + done: bool, +} + +impl<'a> AuthLine<'a> { + pub(crate) fn new(attempt: AuthAttempt<'a>) -> Self { + Self { + attempt, + abort_reason: "connection_closed", + done: false, + } + } + + /// Record that the signature proved `pubkey`. + pub(crate) fn proven(&mut self, pubkey: PublicKey) { + self.attempt.pubkey = Some(pubkey); + self.attempt.pubkey_verified = true; + } + + /// The `aborted` reason logged if the line is dropped undecided. + pub(crate) fn abort_reason(&mut self, reason: &'static str) { + self.abort_reason = reason; + } + + /// Log the final decision; later calls are no-ops. + pub(crate) fn finish(&mut self, result: AuthResult) { + if !std::mem::replace(&mut self.done, true) { + self.attempt.log(result); + } + } +} + +impl Drop for AuthLine<'_> { + fn drop(&mut self) { + self.finish(AuthResult::Aborted(self.abort_reason)); + } +} + +/// The client IP in `header`, when configured: the rightmost entry of the +/// field's comma-separated list, across repeated fields (the one the +/// operator's proxy appended), and only if it parses as an IP address. +pub(crate) fn client_ip( + headers: &axum::http::HeaderMap, + header: Option<&axum::http::HeaderName>, +) -> Option { + let value = headers.get_all(header?).iter().next_back()?.to_str().ok()?; + value.rsplit(',').next()?.trim().parse().ok() +} + +/// A fixed code for a rejected proof. `Nip98Invalid` and `Internal` carry +/// free text that can echo request data, so they collapse to one code each. +pub(crate) fn auth_error_code(e: &buzz_auth::AuthError) -> &'static str { + use buzz_auth::AuthError as E; + match e { + E::InvalidSignature => "invalid_signature", + E::ChallengeMismatch => "challenge_mismatch", + E::RelayUrlMismatch => "relay_url_mismatch", + E::EventExpired => "event_expired", + E::Nip98Invalid(_) => "nip98_invalid", + E::Nip98Replay => "nip98_replay", + E::PubkeyMismatch => "pubkey_mismatch", + E::InsufficientScope { .. } => "insufficient_scope", + E::ChannelAccessDenied => "channel_access_denied", + E::Internal(_) => "internal", + } +} + +/// One auth attempt. `pubkey_verified` is false when the key is only what +/// the client claimed (a failed signature, or a key never checked). +pub(crate) struct AuthAttempt<'a> { + method: AuthMethod, + community: Option, + conn_id: Option, + route: Option<&'a str>, + peer_addr: Option, + client_ip: Option, + pubkey: Option, + pubkey_verified: bool, +} + +impl AuthAttempt<'_> { + /// A WebSocket login on `conn` by `pubkey`. + pub(crate) fn nip42( + conn: &crate::connection::ConnectionState, + pubkey: PublicKey, + pubkey_verified: bool, + ) -> Self { + Self { + method: AuthMethod::Nip42, + community: Some(conn.tenant.community()), + conn_id: Some(conn.conn_id), + route: None, + peer_addr: Some(conn.remote_addr), + client_ip: conn.community_control.client_ip(), + pubkey: Some(pubkey), + pubkey_verified, + } + } + + /// An HTTP signed-request attempt on `route` (a URL path, never a query). + pub(crate) fn http<'r>( + method: AuthMethod, + route: &'r str, + pubkey: Option, + pubkey_verified: bool, + ) -> AuthAttempt<'r> { + AuthAttempt { + method, + community: None, + conn_id: None, + route: Some(route), + peer_addr: None, + client_ip: None, + pubkey, + pubkey_verified, + } + } + + /// This attempt, from a request whose configured header gave `client_ip`. + pub(crate) fn with_client_ip(self, client_ip: Option) -> Self { + Self { client_ip, ..self } + } + + /// This attempt, bound to `community`. + pub(crate) fn in_community(self, community: CommunityId) -> Self { + Self { + community: Some(community), + ..self + } + } + + /// Finish the WebSocket login with `outcome`, logging it only if this + /// call won the connection's single auth terminal. + pub(crate) fn reject( + &self, + conn: &crate::connection::ConnectionState, + outcome: crate::metrics::AuthOutcome, + ) -> bool { + let won = conn.reject_auth(outcome); + if won { + self.log(AuthResult::from_outcome(outcome)); + } + won + } + + /// Log an AUTH frame that arrived after the connection's login was + /// decided, within the connection's [`RefusalBudget`]. A frame over + /// budget is only counted, but still settles its frame's line. + pub(crate) fn log_after_decision( + &self, + conn: &crate::connection::ConnectionState, + result: AuthResult, + ) { + if conn.refusal_budget.auth() { + self.log(result); + } else { + crate::connection::note_auth_line_written(); + } + } + + pub(crate) fn log(&self, result: AuthResult) { + crate::connection::note_auth_line_written(); + let (level, outcome, reason) = result.parts(); + let pubkey = self.pubkey.as_ref().map(PublicKey::to_hex); + emit!( + level, + event = "auth", + method = self.method.as_str(), + conn_id = self.conn_id.map(tracing::field::display), + community = self.community.map(tracing::field::display), + route = self.route, + peer_addr = self.peer_addr.map(tracing::field::display), + client_ip = self.client_ip.map(tracing::field::display), + pubkey = pubkey.as_deref(), + pubkey_verified = pubkey.is_some().then_some(self.pubkey_verified), + outcome, + reason, + "access" + ); + } +} + +/// Frames the connection's writer accepted: stored events and live pushes +/// alike. A frame counts once its flush succeeds, so a frame the socket +/// rejects, or one stranded by a failed flush, is never counted. This is not +/// client delivery confirmation. +#[derive(Debug, Default)] +pub(crate) struct QueuedTotals { + events: AtomicU64, + bytes: AtomicU64, +} + +impl QueuedTotals { + pub(crate) fn events(&self) -> u64 { + self.events.load(Ordering::Relaxed) + } + + pub(crate) fn bytes(&self) -> u64 { + self.bytes.load(Ordering::Relaxed) + } +} + +/// `(events, bytes)` a frame contributes to [`QueuedTotals`]. +fn frame_size(frame: &axum::extract::ws::Message) -> (u64, u64) { + use axum::extract::ws::Message; + match frame { + Message::Text(text) => ( + u64::from(text.as_str().starts_with("[\"EVENT\"")), + text.len() as u64, + ), + Message::Binary(bytes) => (0, bytes.len() as u64), + _ => (0, 0), + } +} + +/// A WebSocket writer that adds each frame to [`QueuedTotals`] once the +/// inner sink accepts it and a later flush succeeds. +pub(crate) struct CountingSink { + inner: S, + totals: std::sync::Arc, + pending: (u64, u64), +} + +impl CountingSink { + pub(crate) fn new(inner: S, totals: std::sync::Arc) -> Self { + Self { + inner, + totals, + pending: (0, 0), + } + } + + fn settle(&mut self, flushed: &Result<(), E>) { + let (events, bytes) = std::mem::take(&mut self.pending); + if flushed.is_ok() { + self.totals.events.fetch_add(events, Ordering::Relaxed); + self.totals.bytes.fetch_add(bytes, Ordering::Relaxed); + } + } +} + +impl futures_util::Sink for CountingSink +where + S: futures_util::Sink + Unpin, +{ + type Error = S::Error; + + fn poll_ready( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.inner).poll_ready(cx) + } + + fn start_send( + mut self: std::pin::Pin<&mut Self>, + item: axum::extract::ws::Message, + ) -> Result<(), Self::Error> { + let (events, bytes) = frame_size(&item); + std::pin::Pin::new(&mut self.inner).start_send(item)?; + self.pending.0 += events; + self.pending.1 += bytes; + Ok(()) + } + + fn poll_flush( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + let flushed = futures_util::ready!(std::pin::Pin::new(&mut self.inner).poll_flush(cx)); + self.settle(&flushed); + std::task::Poll::Ready(flushed) + } + + fn poll_close( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + let closed = futures_util::ready!(std::pin::Pin::new(&mut self.inner).poll_close(cx)); + self.settle(&closed); + std::task::Poll::Ready(closed) + } +} + +/// The connection's one line, written once when the last holder drops it: +/// after a normal close, a refusal during startup, or the handler being +/// dropped. `pubkey` is the identity it logged in as, if any, with its +/// `method` and `pubkey_verified`; the login also wrote its own `auth` line. +/// `close_reason` is why the connection ended: the first reason recorded wins, +/// else `refused` for a refusal, else `handler_dropped`. +pub(crate) struct CloseLine { + conn_id: Uuid, + community: CommunityId, + peer_addr: SocketAddr, + client_ip: Option, + opened: std::time::Instant, + pubkey: std::sync::Mutex>, + refused: std::sync::OnceLock<&'static str>, + close_reason: std::sync::OnceLock<&'static str>, + pub(crate) queued: std::sync::Arc, + pub(crate) refusals: std::sync::Arc, +} + +impl CloseLine { + /// The line for a connection upgraded now. + pub(crate) fn open( + conn_id: Uuid, + community: CommunityId, + peer_addr: SocketAddr, + client_ip: Option, + ) -> std::sync::Arc { + std::sync::Arc::new(Self { + conn_id, + community, + peer_addr, + client_ip, + opened: std::time::Instant::now(), + pubkey: std::sync::Mutex::new(None), + refused: std::sync::OnceLock::new(), + close_reason: std::sync::OnceLock::new(), + queued: Default::default(), + refusals: Default::default(), + }) + } + + pub(crate) fn conn_id(&self) -> Uuid { + self.conn_id + } + + /// Record the identity the connection logged in as. + pub(crate) fn logged_in(&self, pubkey: PublicKey) { + *self.pubkey.lock().unwrap_or_else(|e| e.into_inner()) = Some(pubkey); + } + + /// Record why the relay refused the connection before serving it. + pub(crate) fn refused(&self, reason: &'static str) { + let _ = self.refused.set(reason); + } + + /// Record why the connection ended. Only the first reason is kept, so the + /// cause recorded before cancelling outranks the generic one cleanup adds. + pub(crate) fn closed(&self, reason: &'static str) { + let _ = self.close_reason.set(reason); + } +} + +impl Drop for CloseLine { + fn drop(&mut self) { + let pubkey = self + .pubkey + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map(PublicKey::to_hex); + emit!( + Level::INFO, + event = "close", + conn_id = %self.conn_id, + community = %self.community, + peer_addr = %self.peer_addr, + client_ip = self.client_ip.map(tracing::field::display), + refused = self.refused.get().copied(), + close_reason = self + .close_reason + .get() + .copied() + .or(self.refused.get().map(|_| "refused")) + .unwrap_or("handler_dropped"), + pubkey = pubkey.as_deref(), + method = pubkey.is_some().then_some(AuthMethod::Nip42.as_str()), + pubkey_verified = pubkey.is_some().then_some(true), + duration_ms = u64::try_from(self.opened.elapsed().as_millis()).unwrap_or(u64::MAX), + events_queued = self.queued.events(), + bytes_queued = self.queued.bytes(), + reads_suppressed = RefusalBudget::close(&self.refusals.reads), + writes_suppressed = RefusalBudget::close(&self.refusals.writes), + auth_suppressed = RefusalBudget::close(&self.refusals.auths), + "access" + ); + } +} + +/// The `event` value of every HTTP request line. +pub(crate) const HTTP_EVENT: &str = "http"; + +/// The `route` of a logged request that matched no route. +const UNMATCHED_ROUTE: &str = ""; + +/// Matched routes that never get a line: public documents and probes. +/// `/` is listed only for requests that are not WebSocket upgrades. +const EXCLUDED_ROUTES: [&str; 5] = [ + "/info", + "/.well-known/nostr.json", + "/health", + "/_liveness", + "/_readiness", +]; + +/// What one HTTP request proved and what was decided about it, written by +/// handlers through [`AccessSlot`] and logged once by [`http_access_log`]. +#[derive(Default)] +struct AccessNote { + method: Option, + community: Option, + pubkey: Option, + pubkey_verified: bool, + decision: Option, + summary: Option, + detail: Detail, +} + +/// What a route did, beyond its auth decision. Each route sets only its own +/// fields; invite codes, tokens and Blossom hashes have no field. +#[derive(Debug, Default)] +pub(crate) struct Detail { + /// A bridge read: events returned, or the count a `/count` answered. + pub(crate) result_count: Option, + /// A bridge write: whether it was stored, and the event's kind and id. + pub(crate) accepted: Option, + pub(crate) kind: Option, + pub(crate) event_id: Option, + /// A bridge body that failed to parse: its error category and position. + pub(crate) category: Option<&'static str>, + pub(crate) line: Option, + pub(crate) column: Option, + /// An ingest rejection's fixed code, never its message. + pub(crate) reject_reason: Option<&'static str>, + /// A minted invite: its id, expiry, and use limit (absent: unlimited). + pub(crate) invite_id: Option, + pub(crate) expires_at: Option, + pub(crate) max_uses: Option, + /// An invite claim: whether it added the member (`false`: already one). + pub(crate) joined: Option, + /// An admin feedback attachment read. + pub(crate) feedback_id: Option, + pub(crate) attachment_sha256: Option, +} + +/// The access note of one HTTP request. [`http_access_log`] puts it in the +/// request's extensions; handlers take it as an extractor (a detached note +/// when the layer is absent, as in handler unit tests) and pass `&AccessSlot` +/// to their helpers. A refusal is final: a later admission leaves it, and +/// a later refusal replaces an admission. +#[derive(Clone, Default)] +pub struct AccessSlot(Arc>); + +impl AccessSlot { + fn note(&self) -> std::sync::MutexGuard<'_, AccessNote> { + self.0.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// The credential presented and the key it claims. A proven key is + /// never replaced by a claimed one. + pub(crate) fn attempt(&self, method: AuthMethod, pubkey: Option, verified: bool) { + let mut note = self.note(); + note.method = Some(method); + if verified || !note.pubkey_verified { + note.pubkey = pubkey.or(note.pubkey); + note.pubkey_verified = verified; + } + } + + /// The credential presented, keeping any key already recorded. + pub(crate) fn method(&self, method: AuthMethod) { + self.note().method = Some(method); + } + + pub(crate) fn in_community(&self, community: CommunityId) { + self.note().community = Some(community); + } + + /// The note of the request `parts` belongs to. + pub(crate) fn of(parts: &axum::http::request::Parts) -> Self { + parts.extensions.get::().cloned().unwrap_or_default() + } + + /// Record the decision. A refusal is final; a later refusal replaces an + /// earlier admission, never the reverse. + pub(crate) fn finish(&self, result: AuthResult) { + let mut note = self.note(); + if matches!(note.decision, None | Some(AuthResult::Success)) { + note.decision = Some(result); + } + } + + /// Pass `checked` through, finishing with `refusal`'s result when it is + /// an error. + pub(crate) fn gate( + &self, + checked: Result, + refusal: impl FnOnce(&E) -> AuthResult, + ) -> Result { + if let Err(e) = &checked { + self.finish(refusal(e)); + } + checked + } + + /// Record the filters the request reads. Built at WARN, not INFO, + /// because a denied, failed or aborted request logs its line at WARN. + pub(crate) fn read(&self, filters: &[Filter]) { + if tracing::enabled!(target: TARGET, Level::WARN) { + self.note().summary = Some(FilterSummary::new(filters)); + } + } + + pub(crate) fn detail(&self, detail: Detail) { + self.note().detail = detail; + } + + /// Write this note's line as the layer would for `route` answered with + /// `status`. + #[cfg(test)] + pub(crate) fn emit(&self, route: &str, status: u16) { + drop(HttpLine { + slot: self.clone(), + route: Some(route.to_owned()), + http_method: axum::http::Method::POST, + peer_addr: None, + client_ip: None, + started: std::time::Instant::now(), + status: Some(axum::http::StatusCode::from_u16(status).unwrap()), + }); + } + + /// Write this note's line as the layer would for a `route` request + /// dropped before its response was ready. + #[cfg(test)] + pub(crate) fn abandon(&self, route: &str) { + drop(HttpLine { + slot: self.clone(), + route: Some(route.to_owned()), + http_method: axum::http::Method::GET, + peer_addr: None, + client_ip: None, + started: std::time::Instant::now(), + status: None, + }); + } +} + +impl axum::extract::FromRequestParts for AccessSlot { + type Rejection = std::convert::Infallible; + + async fn from_request_parts( + parts: &mut axum::http::request::Parts, + _: &S, + ) -> Result { + Ok(Self::of(parts)) + } +} + +/// Middleware: one access line per HTTP request, written when the response +/// is ready, or as `request=aborted` if the request is dropped first. Public +/// documents, probes, SPA pages and static files are skipped; a request +/// that matched no route is logged only at status 400 or above. +pub(crate) async fn http_access_log( + axum::extract::State(state): axum::extract::State>, + mut req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + let route = match req.extensions().get::() { + Some(m) if excluded_route(m.as_str(), &req) => return next.run(req).await, + Some(m) => Some(m.as_str().to_owned()), + None if crate::router::is_document_request(&state, &req) => return next.run(req).await, + None => None, + }; + let slot = AccessSlot::default(); + req.extensions_mut().insert(slot.clone()); + let mut line = HttpLine { + slot, + route, + http_method: req.method().clone(), + peer_addr: req + .extensions() + .get::>() + .map(|c| c.0), + client_ip: client_ip(req.headers(), state.config.client_ip_header.as_ref()), + started: std::time::Instant::now(), + status: None, + }; + let response = next.run(req).await; + line.status = Some(response.status()); + response +} + +/// Whether a matched route is never logged. +fn excluded_route(route: &str, req: &axum::extract::Request) -> bool { + let upgrade = req.headers().contains_key(axum::http::header::UPGRADE) + || req.method() == axum::http::Method::CONNECT; + EXCLUDED_ROUTES.contains(&route) || (route == "/" && !upgrade) +} + +/// A request's pending line, written on drop. +struct HttpLine { + slot: AccessSlot, + /// The matched template; `None` for a request that matched no route. + route: Option, + http_method: axum::http::Method, + peer_addr: Option, + client_ip: Option, + started: std::time::Instant, + /// `None` until the response is ready. + status: Option, +} + +impl Drop for HttpLine { + fn drop(&mut self) { + let status = self.status.map(|s| s.as_u16()); + let skip = match (&self.route, status) { + // A successful upgrade: the connection's own lines cover it. + (_, Some(101)) => true, + (None, Some(s)) => s < 400, + (None, None) => true, + (Some(_), _) => false, + }; + if skip { + return; + } + let note = self.slot.note(); + let aborted = status.is_none(); + let (level, outcome, reason) = note.decision.map_or((Level::INFO, None, None), |d| { + let (level, outcome, reason) = d.parts(); + (level, Some(outcome), reason) + }); + // A challenge is git's normal first step, so its 401 stays INFO. + let challenged = matches!(note.decision, Some(AuthResult::Challenged)); + let level = if aborted || (!challenged && status.is_some_and(|s| s >= 400)) { + Level::WARN + } else { + level + }; + // A served read that returned nothing is routine polling. + let level = if level == Level::INFO && note.detail.result_count == Some(0) { + Level::DEBUG + } else { + level + }; + let pubkey = note.pubkey.as_ref().map(PublicKey::to_hex); + let s = note.summary.as_ref(); + let d = ¬e.detail; + emit!( + level, + event = HTTP_EVENT, + route = self.route.as_deref().unwrap_or(UNMATCHED_ROUTE), + http_method = %self.http_method, + peer_addr = self.peer_addr.map(tracing::field::display), + client_ip = self.client_ip.map(tracing::field::display), + method = note.method.map(AuthMethod::as_str), + community = note.community.map(tracing::field::display), + pubkey = pubkey.as_deref(), + pubkey_verified = pubkey.is_some().then_some(note.pubkey_verified), + outcome = outcome.unwrap_or("undecided"), + reason, + request = aborted.then_some("aborted"), + status, + time_to_response_ms = + u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + result_count = d.result_count, + accepted = d.accepted, + kind = d.kind, + event_id = d.event_id.as_deref(), + category = d.category, + line = d.line, + column = d.column, + reject_reason = d.reject_reason, + invite_id = d.invite_id.map(tracing::field::display), + expires_at = d.expires_at, + max_uses = d.max_uses, + joined = d.joined, + feedback_id = d.feedback_id.map(tracing::field::display), + attachment_sha256 = d.attachment_sha256.as_deref(), + filters = s.map(|s| s.filters), + kinds = s.and_then(|s| s.kinds.as_deref()), + kind_count = s.and_then(|s| s.kind_count), + channel_ids = s.and_then(|s| s.channel_ids.as_deref()), + channel_count = s.and_then(|s| s.channel_count), + authors = s.and_then(|s| s.authors.as_deref()), + author_count = s.and_then(|s| s.author_count), + p_tags = s.and_then(|s| s.p_tags.as_deref()), + p_count = s.and_then(|s| s.p_count), + ids = s.map(|s| s.ids), + since = s.and_then(|s| s.since), + until = s.and_then(|s| s.until), + limit = s.and_then(|s| s.limit), + search = s.map(|s| s.search), + "access" + ); + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use std::collections::BTreeSet; + use std::sync::{Arc, Mutex}; + use tracing_subscriber::prelude::*; + + #[derive(Clone, Default)] + pub(crate) struct Captured(Arc>>); + + impl std::io::Write for Captured { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + impl Captured { + /// Everything written so far, on every target. + pub(crate) fn raw(&self) -> String { + String::from_utf8(self.0.lock().unwrap().clone()).unwrap() + } + + /// Access lines written so far, parsed from the production JSON shape. + pub(crate) fn lines(&self) -> Vec { + String::from_utf8(self.0.lock().unwrap().clone()) + .unwrap() + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .filter(|v: &serde_json::Value| v["target"] == TARGET) + .collect() + } + } + + fn json_subscriber(out: &Captured) -> impl tracing::Subscriber + Send + Sync { + let writer = out.clone(); + tracing_subscriber::registry().with( + tracing_subscriber::fmt::layer() + .json() + .event_format(crate::telemetry::TraceContextLookup::default().json_formatter(false)) + .with_writer(move || writer.clone()), + ) + } + + /// Like [`capture`], with the access target filtered to WARN. + pub(crate) fn capture_warn(f: impl FnOnce() -> R) -> (R, Captured) { + let _lock = crate::test_support::tracing_dispatch_lock(); + let out = Captured::default(); + let subscriber = json_subscriber(&out) + .with(tracing_subscriber::filter::Targets::new().with_target(TARGET, Level::WARN)); + let r = tracing::subscriber::with_default(subscriber, f); + (r, out) + } + + /// Run `f` with JSON logs captured, using production's JSON formatter. + pub(crate) fn capture(f: impl FnOnce() -> R) -> (R, Captured) { + let _lock = crate::test_support::tracing_dispatch_lock(); + let out = Captured::default(); + let r = tracing::subscriber::with_default(json_subscriber(&out), f); + (r, out) + } + + /// Capture JSON logs on this thread until the guard drops, for async + /// tests on a current-thread runtime that `.await` the code under test + /// directly (spawned tasks on other threads are not captured). + pub(crate) fn capture_scoped() -> (tracing::subscriber::DefaultGuard, Captured) { + let out = Captured::default(); + (tracing::subscriber::set_default(json_subscriber(&out)), out) + } + + /// Like [`capture_scoped`], with only the access target on, at `level`: + /// the HTTP span (target `buzz_relay`) is filtered out. + pub(crate) fn capture_access_only( + level: Level, + ) -> (tracing::subscriber::DefaultGuard, Captured) { + let out = Captured::default(); + let subscriber = json_subscriber(&out) + .with(tracing_subscriber::filter::Targets::new().with_target(TARGET, level)); + (tracing::subscriber::set_default(subscriber), out) + } + + /// A replay guard whose check never finishes, so a request parks in its + /// replay wait; `arrived` fires once a request reaches it. + #[derive(Default)] + pub(crate) struct StallingReplayGuard { + pub(crate) arrived: tokio::sync::Notify, + } + + impl buzz_auth::Nip98ReplayGuard for StallingReplayGuard { + fn try_mark_in_scope<'a>( + &'a self, + _scope: &'a str, + _event_id: &'a nostr::EventId, + _ttl_secs: u64, + ) -> std::pin::Pin< + Box> + Send + 'a>, + > { + self.arrived.notify_one(); + Box::pin(std::future::pending()) + } + } + + /// The one line of a request dropped mid-flight: aborted at WARN, with + /// the proven caller it had recorded and no status. + pub(crate) fn assert_one_aborted_line(out: &Captured, pubkey: &PublicKey) -> serde_json::Value { + let lines = out.lines(); + assert_eq!(lines.len(), 1, "exactly one access line: {lines:?}"); + let line = lines[0].clone(); + assert_eq!(line["event"], HTTP_EVENT, "{line}"); + assert_eq!(line["request"], "aborted", "{line}"); + assert_eq!(line["level"], "WARN", "{line}"); + assert_eq!(line["pubkey"], pubkey.to_hex(), "{line}"); + assert_eq!(line["pubkey_verified"], true, "{line}"); + assert!(line.get("status").is_none(), "{line}"); + line + } + + fn filter(json: serde_json::Value) -> Filter { + serde_json::from_value(json).unwrap() + } + + const PK_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + + fn pk() -> String { + nostr::Keys::generate().public_key().to_hex() + } + + /// A request dropped before its response is ready keeps its login and + /// says the request aborted, at WARN, with no status. + #[test] + fn admitted_request_never_completed_logs_aborted() { + let key = nostr::Keys::generate().public_key(); + let (_, out) = capture(|| { + let slot = AccessSlot::default(); + slot.attempt(AuthMethod::Nip98, Some(key), true); + slot.finish(AuthResult::Success); + slot.abandon("/query"); + }); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + let line = &lines[0]; + assert_eq!(line["outcome"], "success", "{line}"); + assert_eq!(line["pubkey"], key.to_hex(), "{line}"); + assert_eq!(line["request"], "aborted", "{line}"); + assert_eq!(line["level"], "WARN", "{line}"); + assert!(line.get("status").is_none(), "{line}"); + } + + /// The completed counterpart carries its status and no `request` field. + #[test] + fn admitted_request_completed_logs_no_abort() { + let (_, out) = capture(|| { + let slot = AccessSlot::default(); + slot.attempt(AuthMethod::Nip98, None, false); + slot.finish(AuthResult::Success); + slot.emit("/query", 200); + }); + let line = &out.lines()[0]; + assert!(line.get("request").is_none(), "{line}"); + assert_eq!(line["status"], 200, "{line}"); + assert_eq!(line["level"], "INFO", "{line}"); + } + + /// Only a served bridge read that returned nothing drops to DEBUG. + #[test] + fn empty_served_http_reads_log_at_debug() { + let level = |result_count, result, status| { + let (_, out) = capture(|| { + let slot = AccessSlot::default(); + slot.attempt(AuthMethod::Nip98, None, false); + slot.finish(result); + slot.detail(Detail { + result_count, + ..Default::default() + }); + match status { + Some(status) => slot.emit("/query", status), + None => slot.abandon("/query"), + } + }); + out.lines()[0]["level"].as_str().unwrap().to_owned() + }; + let denied = AuthResult::Denied(AuthReason::NotRelayMember); + assert_eq!(level(Some(0), AuthResult::Success, Some(200)), "DEBUG"); + assert_eq!(level(Some(3), AuthResult::Success, Some(200)), "INFO"); + assert_eq!(level(None, AuthResult::Success, Some(200)), "INFO"); + assert_eq!(level(Some(0), AuthResult::Success, Some(500)), "WARN"); + assert_eq!(level(Some(0), AuthResult::Success, None), "WARN"); + assert_eq!(level(Some(0), denied, Some(403)), "WARN"); + } + + #[test] + fn summary_merges_filters_to_the_widest_bounds() { + let s = FilterSummary::new(&[ + filter(serde_json::json!({"kinds": [9, 7], "since": 100, "until": 200, "limit": 10})), + filter(serde_json::json!({"kinds": [7, 5], "since": 50, "until": 300, "limit": 50})), + ]); + assert_eq!(s.filters, 2); + // `7` is in both filters: the list hides one value, so the count shows. + assert_eq!((s.kinds.as_deref(), s.kind_count), (Some("7,9,5"), Some(4))); + assert_eq!((s.since, s.until, s.limit), (Some(50), Some(300), Some(50))); + assert!(!s.search); + } + + #[test] + fn summary_omits_a_bound_any_filter_leaves_open() { + let s = FilterSummary::new(&[ + filter(serde_json::json!({"since": 100, "limit": 10})), + filter(serde_json::json!({"until": 300})), + ]); + assert_eq!((s.since, s.until, s.limit), (None, None, None)); + } + + /// Lists stop at [`LIST_CAP`] distinct values, and then carry the exact + /// count; cross-filter duplicates count twice. A list that shows every + /// value has no count. + #[test] + fn summary_caps_lists_and_counts_only_what_they_hide() { + let channels: Vec = (0..14).map(|_| Uuid::new_v4().to_string()).collect(); + let authors: Vec = (0..5_000).map(|_| pk()).collect(); + let kinds: Vec = (0..=u16::MAX).collect(); + let s = FilterSummary::new(&[ + filter(serde_json::json!({ + "#h": channels, "authors": authors, "kinds": kinds + })), + filter(serde_json::json!({"#h": [channels[0]], "authors": [authors[0]], "kinds": [1]})), + ]); + assert_eq!(s.channel_count, Some(15)); + assert_eq!(s.author_count, Some(5_001)); + assert_eq!(s.kind_count, Some(65_537)); + for list in [&s.channel_ids, &s.authors, &s.kinds] { + let listed: BTreeSet<&str> = list.as_deref().unwrap().split(',').collect(); + assert_eq!(listed.len(), LIST_CAP); + } + let s = FilterSummary::new(&[filter(serde_json::json!({"#p": [PK_A], "ids": [PK_A]}))]); + assert_eq!( + (s.p_tags.as_deref(), s.p_count, s.ids), + (Some(PK_A), None, 1) + ); + } + + #[test] + fn summary_marks_a_dimension_any_filter_leaves_open() { + let s = FilterSummary::new(&[ + filter( + serde_json::json!({"kinds": [9], "authors": [PK_A], "#h": [Uuid::nil().to_string()]}), + ), + filter(serde_json::json!({"#p": [PK_A]})), + ]); + assert_eq!(s.kinds.as_deref(), Some("*")); + assert_eq!(s.authors.as_deref(), Some("*")); + assert_eq!(s.channel_ids.as_deref(), Some("*")); + assert_eq!(s.p_tags.as_deref(), Some("*")); + assert_eq!( + (s.kind_count, s.author_count, s.channel_count, s.p_count), + (Some(1), Some(1), Some(1), Some(1)) + ); + } + + /// A read's level follows its outcome: only a server-side error is WARN. + #[test] + fn read_lines_warn_only_on_error() { + let read = |outcome| ReadLog { + event: "req", + conn_id: Uuid::nil(), + community: CommunityId::from_uuid(Uuid::nil()), + pubkey: None, + sub_id: "s".into(), + summary: FilterSummary::default(), + outcome, + results: 0, + budget: None, + started: std::time::Instant::now(), + }; + let (_, out) = capture(|| { + drop(read(ReadOutcome::Error("database_error"))); + drop(read(ReadOutcome::Aborted)); + drop(read(ReadOutcome::Denied("auth_required"))); + }); + let levels: Vec<_> = out + .lines() + .iter() + .map(|l| format!("{}={}", l["outcome"], l["level"])) + .collect(); + assert_eq!( + levels, + [ + r#""error"="WARN""#, + r#""aborted"="INFO""#, + r#""denied"="INFO""# + ] + ); + } + + /// Under `buzz_relay::access=warn` an `error` read still carries its + /// filter summary, and never the search text. + #[test] + fn warn_only_error_lines_keep_the_filter_summary() { + let (conn, _rx) = + crate::connection::tests::test_conn_with_auth(crate::connection::AuthState::Failed); + let filters = [filter(serde_json::json!({ + "kinds": [9], "#h": [Uuid::nil().to_string()], "since": 10, + "search": "secret words", + }))]; + let (_, out) = capture_warn(|| { + ReadLog::req(&conn, "s", &filters).error("database_error"); + ReadLog::count(&conn, "c", &filters).error("database_error"); + }); + assert!(!out.raw().contains("secret"), "{}", out.raw()); + let lines = out.lines(); + assert_eq!(lines.len(), 2, "{lines:?}"); + for line in &lines { + assert_eq!(line["level"], "WARN", "{line}"); + assert_eq!(line["filters"], 1, "{line}"); + assert_eq!(line["kinds"], "9", "{line}"); + assert_eq!(line["channel_ids"], Uuid::nil().to_string(), "{line}"); + assert_eq!(line["since"], 10, "{line}"); + assert_eq!(line["search"], true, "{line}"); + } + } + + /// HTTP lines that go to WARN keep the read's summary under a + /// WARN-only filter, without the search text. + #[test] + fn warn_only_http_read_lines_keep_the_filter_summary() { + let filters = [filter(serde_json::json!({ + "kinds": [9], "#h": [Uuid::nil().to_string()], "since": 10, + "search": "secret words", + }))]; + let (_, out) = capture_warn(|| { + let failed = AccessSlot::default(); + failed.read(&filters); + failed.emit("/query", 500); + let aborted = AccessSlot::default(); + aborted.read(&filters); + aborted.abandon("/query"); + }); + assert!(!out.raw().contains("secret"), "{}", out.raw()); + let lines = out.lines(); + assert_eq!(lines.len(), 2, "{lines:?}"); + for line in &lines { + assert_eq!(line["level"], "WARN", "{line}"); + assert_eq!(line["filters"], 1, "{line}"); + assert_eq!(line["kinds"], "9", "{line}"); + assert!( + line["channel_ids"].is_string() && line.get("channel_count").is_none(), + "{line}" + ); + assert_eq!(line["since"], 10, "{line}"); + assert_eq!(line["search"], true, "{line}"); + } + } + + #[test] + fn refusal_budget_logs_sixteen_then_counts_the_rest() { + let budget = RefusalBudget::default(); + let logged = (0..20).filter(|_| budget.read()).count(); + assert_eq!(logged, 16); + assert_eq!(RefusalBudget::close(&budget.reads), 4); + assert_eq!(RefusalBudget::close(&budget.auths), 0); + } + + /// The first recorded close reason wins; a refusal with none closes as + /// `refused`, and a line dropped with neither as `handler_dropped`. + #[test] + fn close_line_keeps_the_first_reason_and_defaults_refusals() { + let open = || { + CloseLine::open( + Uuid::nil(), + CommunityId::from_uuid(Uuid::nil()), + "127.0.0.1:1".parse().unwrap(), + None, + ) + }; + let ((), out) = capture(|| { + let close = open(); + close.closed("auth_timeout"); + close.closed("server_closed"); + drop(close); + let refused = open(); + refused.refused("connection_limit"); + drop(refused); + drop(open()); + }); + let reasons: Vec<_> = out + .lines() + .iter() + .map(|l| l["close_reason"].clone()) + .collect(); + assert_eq!(reasons, ["auth_timeout", "refused", "handler_dropped"]); + } + + /// Refusals charged after `close` was written each log their own line, + /// so every refusal is either counted on `close` or logged, never both. + #[test] + fn refusals_after_close_log_their_own_lines() { + let (late, out) = capture(|| { + let close = CloseLine::open( + Uuid::nil(), + CommunityId::from_uuid(Uuid::nil()), + "127.0.0.1:1".parse().unwrap(), + None, + ); + let budget = Arc::clone(&close.refusals); + for _ in 0..(REFUSAL_LINES + 4) { + budget.read(); + budget.auth(); + } + drop(close); + let reads = (0..3).filter(|_| budget.read()).count(); + let auths = (0..3).filter(|_| budget.auth()).count(); + (reads, auths) + }); + assert_eq!(late, (3, 3), "late refusals must each log"); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["reads_suppressed"], 4, "{}", lines[0]); + assert_eq!(lines[0]["auth_suppressed"], 4, "{}", lines[0]); + } + + #[test] + fn summary_never_lists_malformed_tag_text() { + let s = FilterSummary::new(&[filter(serde_json::json!({ + "#h": ["secret plans for tuesday"], "#p": ["not a pubkey"] + }))]); + assert_eq!((s.channel_ids, s.channel_count), (None, Some(1))); + assert_eq!((s.p_tags, s.p_count), (None, Some(1))); + } + + #[test] + fn req_line_records_search_use_but_never_the_search_text() { + let needle = "zebra-crossing-7f3a"; + let filters = [filter(serde_json::json!({"kinds": [9], "search": needle}))]; + let ((), out) = capture(|| { + let mut log = ReadLog { + event: "req", + conn_id: Uuid::nil(), + community: CommunityId::from_uuid(Uuid::nil()), + pubkey: Some(PK_A.to_owned()), + sub_id: "sub".to_owned(), + summary: FilterSummary::new(&filters), + outcome: ReadOutcome::Aborted, + results: 0, + budget: None, + started: std::time::Instant::now(), + }; + for _ in 0..3 { + log.queued_one(); + } + log.served(); + }); + let raw = String::from_utf8(out.0.lock().unwrap().clone()).unwrap(); + assert!(!raw.contains(needle), "search text leaked: {raw}"); + let lines = out.lines(); + assert_eq!(lines.len(), 1); + let line = &lines[0]; + assert_eq!(line["event"], "req"); + assert_eq!(line["search"], true); + assert_eq!(line["outcome"], "served"); + assert_eq!(line["events_queued"], 3); + assert_eq!(line["pubkey"], PK_A); + assert_eq!(line["kinds"], "9"); + assert!(line.get("since").is_none() && line.get("reason").is_none()); + assert!(line.get("count").is_none()); + } + + #[test] + fn dropped_read_logs_as_aborted() { + let ((), out) = capture(|| { + let _log = ReadLog { + event: "count", + conn_id: Uuid::nil(), + community: CommunityId::from_uuid(Uuid::nil()), + pubkey: None, + sub_id: "c".to_owned(), + summary: FilterSummary::default(), + outcome: ReadOutcome::Aborted, + results: 0, + budget: None, + started: std::time::Instant::now(), + }; + }); + let line = &out.lines()[0]; + assert_eq!( + (&line["event"], &line["outcome"]), + (&"count".into(), &"aborted".into()) + ); + assert!( + line.get("count").is_none(), + "an uncounted COUNT has no count" + ); + assert!(line.get("pubkey").is_none()); + } + + /// A rejected write's reason is only its OK message's NIP-01 prefix. + #[test] + fn write_reason_is_the_ok_prefix_only() { + assert_eq!(ok_reason("invalid: bad signature"), "invalid"); + assert_eq!( + ok_reason("auth-required: not authenticated"), + "auth-required" + ); + assert_eq!(ok_reason("rate-limited"), "rate-limited"); + assert_eq!(ok_reason("something: secret"), "other"); + assert_eq!(ok_reason(""), "other"); + } + + /// Each answer logs its outcome and level; no OK logs `aborted`. + #[test] + fn write_lines_record_the_ok_answered() { + let (conn, _rx) = + crate::connection::tests::test_conn_with_auth(crate::connection::AuthState::Failed); + let event = nostr::EventBuilder::new(nostr::Kind::Custom(9), "secret words") + .sign_with_keys(&nostr::Keys::generate()) + .unwrap(); + let id = event.id.to_hex(); + let (_, out) = capture(|| { + WriteLog::new(&conn, &event).ok(&conn, &id, true, ""); + WriteLog::new(&conn, &event).ok(&conn, &id, false, "duplicate: already have it"); + WriteLog::new(&conn, &event).ok(&conn, &id, false, "error: internal error"); + drop(WriteLog::new(&conn, &event)); + WriteLog::refused(&conn, &event, "messages", true); + }); + assert!(!out.raw().contains("secret"), "{}", out.raw()); + let got: Vec = out + .lines() + .iter() + .map(|l| { + assert_eq!(l["event"], "write", "{l}"); + assert_eq!(l["kind"], 9, "{l}"); + assert_eq!(l["event_id"], id.as_str(), "{l}"); + assert!(l.get("ok_queued").is_none(), "{l}"); + format!("{}/{}/{}", l["outcome"], l["reason"], l["level"]) + }) + .collect(); + assert_eq!( + got, + [ + r#""accepted"/null/"INFO""#, + r#""rejected"/"duplicate"/"INFO""#, + r#""error"/"error"/"WARN""#, + r#""aborted"/null/"INFO""#, + r#""rejected"/"messages"/"INFO""#, + ] + ); + } + + /// Rejected writes past the refusal budget are only counted; accepted + /// writes are never capped. + #[test] + fn rejected_writes_have_a_refusal_budget() { + let (conn, mut rx) = + crate::connection::tests::test_conn_with_auth(crate::connection::AuthState::Failed); + let event = nostr::EventBuilder::new(nostr::Kind::Custom(9), "") + .sign_with_keys(&nostr::Keys::generate()) + .unwrap(); + let (_, out) = capture(|| { + for _ in 0..REFUSAL_LINES + 3 { + WriteLog::refused(&conn, &event, "messages", true); + WriteLog::new(&conn, &event).ok(&conn, "x", true, ""); + // Drain, so every OK is queued and only the cap is under test. + rx.try_recv().expect("OK queued"); + } + }); + let lines = out.lines(); + assert!( + lines.iter().all(|l| l.get("ok_queued").is_none()), + "{lines:?}" + ); + let count = |o: &str| lines.iter().filter(|l| l["outcome"] == o).count(); + assert_eq!(count("rejected"), REFUSAL_LINES as usize); + assert_eq!(count("accepted"), REFUSAL_LINES as usize + 3); + assert_eq!(RefusalBudget::close(&conn.refusal_budget.writes), 3); + } + + /// An OK the outbound channel could not take (full or closed) keeps the + /// relay's decision as `outcome` and adds `ok_queued=false`. + #[test] + fn write_lines_mark_an_ok_that_could_not_be_queued() { + let event = nostr::EventBuilder::new(nostr::Kind::Custom(9), "") + .sign_with_keys(&nostr::Keys::generate()) + .unwrap(); + let id = event.id.to_hex(); + + // Full: the test channel holds 4 frames and nothing drains it. + let (full, _rx) = + crate::connection::tests::test_conn_with_auth(crate::connection::AuthState::Failed); + while full.send(String::new()) {} + // Closed: the receiver is gone. + let (closed, rx) = + crate::connection::tests::test_conn_with_auth(crate::connection::AuthState::Failed); + drop(rx); + + let (_, out) = capture(|| { + WriteLog::new(&full, &event).ok(&full, &id, true, ""); + WriteLog::new(&closed, &event).ok(&closed, &id, false, "invalid: bad"); + WriteLog::refused(&closed, &event, "rate-limited", false); + }); + let got: Vec = out + .lines() + .iter() + .map(|l| format!("{}/{}/{}", l["outcome"], l["reason"], l["ok_queued"])) + .collect(); + assert_eq!( + got, + [ + r#""accepted"/null/false"#, + r#""rejected"/"invalid"/false"#, + r#""rejected"/"rate-limited"/false"#, + ] + ); + } + + /// Every read is measured under its type, outcome and reason, including + /// the refusals whose lines the budget suppresses. + /// Mutation: record after the budget check in `Drop`, or drop the + /// over-budget branch of `refused_read` → RED. + #[test] + fn every_read_is_measured_even_when_its_line_is_suppressed() { + let (conn, _rx) = + crate::connection::tests::test_conn_with_auth(crate::connection::AuthState::Failed); + let recorder = metrics_util::debugging::DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + metrics::with_local_recorder(&recorder, || { + // More refusals than the budget logs: the rest are only counted. + for _ in 0..REFUSAL_LINES + 4 { + ReadLog::refused_read("req", &conn, "r", &[], "not_admitted"); + } + // A handler denial past the budget: `Drop` suppresses its line. + ReadLog::req(&conn, "d", &[]).deny("auth_required"); + ReadLog::count(&conn, "c", &[]).error("database_error"); + ReadLog::sync(&conn, "s", &[]).served(); + drop(ReadLog::req(&conn, "a", &[])); + }); + let mut measured: Vec<(String, String, String, usize)> = snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, ..)| key.key().name() == "buzz_ws_read_seconds") + .map(|(key, _, _, value)| { + let metrics_util::debugging::DebugValue::Histogram(samples) = value else { + panic!("buzz_ws_read_seconds must be a histogram"); + }; + let label = |name: &str| { + key.key() + .labels() + .find(|l| l.key() == name) + .map(|l| l.value().to_owned()) + .unwrap_or_default() + }; + ( + label("type"), + label("outcome"), + label("reason"), + samples.len(), + ) + }) + .collect(); + measured.sort(); + let row = |t: &str, o: &str, r: &str, n| (t.to_owned(), o.to_owned(), r.to_owned(), n); + assert_eq!( + measured, + [ + row("count", "error", "database_error", 1), + row("req", "aborted", "none", 1), + row("req", "denied", "auth_required", 1), + row("req", "denied", "not_admitted", REFUSAL_LINES as usize + 4), + row("sync", "served", "none", 1), + ] + ); + } + + #[test] + fn auth_failure_is_warn_and_marks_the_claimed_key_unverified() { + let key = nostr::Keys::generate().public_key(); + let ((), out) = capture(|| { + AuthAttempt { + method: AuthMethod::Nip98, + community: None, + conn_id: None, + route: Some("/query"), + peer_addr: None, + client_ip: None, + pubkey: Some(key), + pubkey_verified: false, + } + .log(AuthResult::Failed("invalid_signature")); + }); + let line = &out.lines()[0]; + assert_eq!(line["level"], "WARN"); + assert_eq!(line["event"], "auth"); + assert_eq!(line["method"], "nip98"); + assert_eq!(line["outcome"], "failed"); + assert_eq!(line["reason"], "invalid_signature"); + assert_eq!(line["pubkey"], key.to_hex()); + assert_eq!(line["pubkey_verified"], false); + assert_eq!(line["route"], "/query"); + } + + #[test] + fn auth_success_is_info_without_a_reason() { + let ((), out) = capture(|| { + AuthAttempt { + method: AuthMethod::Nip42, + community: Some(CommunityId::from_uuid(Uuid::nil())), + conn_id: Some(Uuid::nil()), + route: None, + peer_addr: None, + client_ip: None, + pubkey: Some(nostr::Keys::generate().public_key()), + pubkey_verified: true, + } + .log(AuthResult::Success); + }); + let line = &out.lines()[0]; + assert_eq!( + (&line["level"], &line["outcome"]), + (&"INFO".into(), &"success".into()) + ); + assert_eq!(line["pubkey_verified"], true); + assert!(line.get("reason").is_none() && line.get("route").is_none()); + } + + #[test] + fn auth_line_logs_once_and_aborts_when_dropped_undecided() { + let attempt = || AuthAttempt::http(AuthMethod::Nip42, "audio", None, false); + let ((), out) = capture(|| { + let mut line = AuthLine::new(attempt()); + line.finish(AuthResult::Denied(crate::access::AuthReason::DenySet)); + line.finish(AuthResult::Success); + drop(AuthLine::new(attempt())); + }); + let outcomes: Vec<_> = out.lines().iter().map(|l| l["outcome"].clone()).collect(); + assert_eq!(outcomes, ["denied", "aborted"]); + } + + /// Lines the layer writes for `req` through a router with one protected + /// template, the excluded documents, and a fallback answering `fallback`. + async fn layer_lines( + state: Arc, + fallback: axum::http::StatusCode, + req: axum::http::Request, + ) -> Vec { + use axum::routing::get; + use tower::ServiceExt as _; + let ok = || async { "ok" }; + let router = axum::Router::new() + .route("/x/{id}", get(ok)) + .route("/", get(ok)) + .route("/info", get(ok)) + .route("/health", get(ok)) + .route("/.well-known/nostr.json", get(ok)) + .fallback(move || async move { fallback }) + .layer(axum::middleware::from_fn_with_state(state, http_access_log)); + let (guard, out) = capture_scoped(); + router.oneshot(req).await.expect("router oneshot"); + drop(guard); + out.lines() + } + + fn get_req(path: &str) -> axum::http::Request { + axum::http::Request::get(path) + .header("host", "relay.test") + .body(axum::body::Body::empty()) + .unwrap() + } + + /// A matched route no handler annotated still gets a line: its template, + /// no identity, and an undecided outcome. + #[tokio::test(flavor = "current_thread")] + async fn unannotated_matched_route_logs_an_empty_note() { + let state = crate::state::tests::test_state().await; + let lines = layer_lines( + state, + axum::http::StatusCode::NOT_FOUND, + get_req("/x/secret-id"), + ) + .await; + assert_eq!(lines.len(), 1, "{lines:?}"); + let line = &lines[0]; + assert_eq!(line["event"], HTTP_EVENT, "{line}"); + assert_eq!(line["route"], "/x/{id}", "{line}"); + assert_eq!(line["outcome"], "undecided", "{line}"); + assert_eq!(line["status"], 200, "{line}"); + assert!(line.get("pubkey").is_none(), "{line}"); + assert!(line["time_to_response_ms"].is_u64(), "{line}"); + assert!(!line.to_string().contains("secret-id"), "{line}"); + } + + /// Public documents and probes never get a line. + #[tokio::test(flavor = "current_thread")] + async fn excluded_routes_log_nothing() { + let state = crate::state::tests::test_state().await; + for path in ["/", "/info", "/health", "/.well-known/nostr.json"] { + let lines = layer_lines( + state.clone(), + axum::http::StatusCode::NOT_FOUND, + get_req(path), + ) + .await; + assert!(lines.is_empty(), "{path}: {lines:?}"); + } + } + + /// An unmatched request is logged at 400 and above as ``, + /// never with its path, and skipped below 400. + #[tokio::test(flavor = "current_thread")] + async fn unmatched_request_logs_only_an_error_without_its_path() { + let state = crate::state::tests::test_state().await; + let lines = layer_lines( + state.clone(), + axum::http::StatusCode::NOT_FOUND, + get_req("/invite/INVITECODE123/extra?token=TOKEN456"), + ) + .await; + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["route"], UNMATCHED_ROUTE, "{}", lines[0]); + assert_eq!(lines[0]["status"], 404, "{}", lines[0]); + let raw = lines[0].to_string(); + assert!( + !raw.contains("INVITECODE123") && !raw.contains("TOKEN456"), + "{raw}" + ); + + let lines = layer_lines(state, axum::http::StatusCode::OK, get_req("/anything")).await; + assert!(lines.is_empty(), "{lines:?}"); + } + + /// With a web bundle configured, SPA documents are skipped even when + /// the fallback answers an error, ahead of the unmatched rule. + #[tokio::test(flavor = "current_thread")] + async fn spa_document_logs_nothing_at_any_status() { + let mut state = (*crate::state::tests::test_state().await).clone(); + let mut config = (*state.config).clone(); + config.web_dir = Some(std::env::temp_dir()); + state.config = Arc::new(config); + let state = Arc::new(state); + for status in [ + axum::http::StatusCode::OK, + axum::http::StatusCode::NOT_FOUND, + ] { + for path in ["/assets/app.js", "/invite/INVITECODE123"] { + let lines = layer_lines(state.clone(), status, get_req(path)).await; + assert!(lines.is_empty(), "{path} {status}: {lines:?}"); + } + } + } + + /// The configured header's IP rides the `http` line; an unset setting, a + /// missing header or a non-IP value logs none, and a list or repeated + /// fields log the rightmost entry, with no fallback past an invalid one. + #[tokio::test(flavor = "current_thread")] + async fn http_line_logs_the_configured_client_ip() { + let base = crate::state::tests::test_state().await; + async fn ip( + base: &Arc, + setting: Option<&str>, + values: &[&str], + ) -> Option { + let mut state = (**base).clone(); + Arc::make_mut(&mut state.config).client_ip_header = setting.map(|s| s.parse().unwrap()); + let mut req = get_req("/x/1"); + for value in values { + req.headers_mut() + .append("x-real-ip", value.parse().unwrap()); + } + let lines = layer_lines(Arc::new(state), axum::http::StatusCode::NOT_FOUND, req).await; + assert_eq!(lines.len(), 1, "{lines:?}"); + lines[0].get("client_ip").cloned() + } + let on = Some("X-Real-IP"); + assert_eq!( + ip(&base, on, &["203.0.113.7"]).await, + Some("203.0.113.7".into()) + ); + assert_eq!(ip(&base, None, &["203.0.113.7"]).await, None); + assert_eq!(ip(&base, on, &[]).await, None); + assert_eq!(ip(&base, on, &["not-an-ip"]).await, None); + assert_eq!( + ip(&base, on, &["198.51.100.1, 10.0.0.2"]).await, + Some("10.0.0.2".into()) + ); + assert_eq!( + ip(&base, on, &["198.51.100.1", "10.0.0.2"]).await, + Some("10.0.0.2".into()) + ); + assert_eq!(ip(&base, on, &["198.51.100.1", "not-an-ip"]).await, None); + } + + /// A request dropped before its response is ready is logged once as + /// `request=aborted` by the layer itself. + #[tokio::test(flavor = "current_thread")] + async fn layer_logs_a_dropped_request_as_aborted() { + use axum::routing::get; + use tower::ServiceExt as _; + let state = crate::state::tests::test_state().await; + let router = axum::Router::new() + .route("/x/{id}", get(std::future::pending::<&'static str>)) + .layer(axum::middleware::from_fn_with_state(state, http_access_log)); + let (guard, out) = capture_scoped(); + let call = router.oneshot(get_req("/x/1")); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(20), call) + .await + .is_err() + ); + drop(guard); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["request"], "aborted", "{}", lines[0]); + assert_eq!(lines[0]["route"], "/x/{id}", "{}", lines[0]); + assert!(lines[0].get("status").is_none(), "{}", lines[0]); + } + + /// A refusal is final: a later admission cannot replace it, while a + /// later refusal replaces an admission. + #[test] + fn refusal_is_final_and_overrides_an_admission() { + let slot = AccessSlot::default(); + slot.finish(AuthResult::Denied(AuthReason::Banned)); + slot.finish(AuthResult::Success); + assert_eq!( + slot.note().decision, + Some(AuthResult::Denied(AuthReason::Banned)) + ); + + let slot = AccessSlot::default(); + slot.finish(AuthResult::Success); + slot.finish(AuthResult::Failed("nip98_replay")); + assert_eq!( + slot.note().decision, + Some(AuthResult::Failed("nip98_replay")) + ); + } +} diff --git a/crates/buzz-relay/src/api/admin/auth.rs b/crates/buzz-relay/src/api/admin/auth.rs index 89961eb1a95..c949f89eb7c 100644 --- a/crates/buzz-relay/src/api/admin/auth.rs +++ b/crates/buzz-relay/src/api/admin/auth.rs @@ -14,7 +14,7 @@ //! Every request carries `Authorization: Nostr `. After //! verifying the signature, timestamp, `u` tag, method tag, and (for //! body-bearing mutations) the `payload` sha256 tag, the authenticated pubkey -//! is resolved to an [`AdminPrincipal`] via [`resolve_admin_principal`]. +//! is resolved to an [`AdminPrincipal`] via [`lookup_admin_principal`]. //! //! ## Principal resolution — union with fallback B //! @@ -38,6 +38,7 @@ //! [`AdminAccess::operator`] refuse with 403; an anonymous caller is never given //! a principal. +use crate::access::{auth_error_code, AccessSlot, AuthMethod, AuthReason, AuthResult}; use axum::http::{header, HeaderMap, Method, Uri}; use base64::engine::general_purpose::STANDARD as BASE64; use base64::Engine as _; @@ -204,6 +205,7 @@ fn method_has_body(method: &str) -> bool { /// authentication or authorization failed. pub async fn authorize( state: &AppState, + slot: &AccessSlot, headers: &HeaderMap, path_and_query: &str, method: &str, @@ -215,42 +217,112 @@ pub async fn authorize( .as_ref() .ok_or_else(ApiError::not_found)?; + let full_path = format!("{ADMIN_API_PREFIX}{path_and_query}"); + authorize_at(state, slot, headers, config, &full_path, method, raw_body).await +} + +/// The admin decision, recorded on `slot`. With auth disabled the request +/// is network-trusted: it carries no key, and only the Host and Origin +/// checks can refuse it. +async fn authorize_at( + state: &AppState, + slot: &AccessSlot, + headers: &HeaderMap, + config: &AdminConfig, + full_path: &str, + method: &str, + raw_body: Option<&[u8]>, +) -> Result { + let decided = match config.auth { + AdminAuth::Nip98 => { + slot.method(AuthMethod::Nip98); + authorize_staff(state, slot, headers, config, full_path, method, raw_body).await + } + AdminAuth::Disabled => { + slot.method(AuthMethod::NetworkTrusted); + check_admin_origin(state, headers, config).map(|()| AdminAccess::NetworkTrusted) + } + }; + slot.finish(match &decided { + Ok(_) => AuthResult::Success, + Err((_, result)) => *result, + }); + decided.map_err(|(e, _)| e) +} + +/// An admin auth refusal and its access-log result. +type AdminRefusal = (ApiError, AuthResult); + +/// The NIP-98 admin decision. Records the key on `slot` once the signature +/// verifies; the caller records the decision. +async fn authorize_staff( + state: &AppState, + slot: &AccessSlot, + headers: &HeaderMap, + config: &AdminConfig, + full_path: &str, + method: &str, + raw_body: Option<&[u8]>, +) -> Result { // Credential check first: an unauthenticated caller learns nothing about // which Host or Origin the deployment expects. - let (access, nip98_event_id) = match &config.auth { - AdminAuth::Disabled => (AdminAccess::NetworkTrusted, None), - AdminAuth::Nip98 => { - let full_path = format!("{ADMIN_API_PREFIX}{path_and_query}"); - let (pubkey_bytes, event_id) = - authorize_nip98(config, headers, &full_path, method, raw_body).await?; - // Resolve the roster grant BEFORE claiming the replay ID: an - // unrostered-but-validly-signing key (e.g. any WARP-admitted laptop) - // must not be able to consume replay slots at request rate. Only a - // request that clears authorization claims its event ID. - let principal = resolve_admin_principal(state, pubkey_bytes).await?; - (AdminAccess::Staff(principal), Some(event_id)) + let (pubkey_bytes, event_id) = authorize_nip98(config, headers, full_path, method, raw_body) + .await + .map_err(|(e, code)| (e, AuthResult::Failed(code)))?; + if let Ok(pubkey) = nostr::PublicKey::from_slice(&pubkey_bytes) { + slot.attempt(AuthMethod::Nip98, Some(pubkey), true); + } + // Resolve the roster grant BEFORE claiming the replay ID: an + // unrostered-but-validly-signing key (e.g. any WARP-admitted laptop) + // must not be able to consume replay slots at request rate. Only a + // request that clears authorization claims its event ID. + let principal = match lookup_admin_principal(state, pubkey_bytes).await { + Ok(Some(principal)) => principal, + Ok(None) => { + return Err(( + ApiError::forbidden(), + AuthResult::Denied(crate::access::AuthReason::NotStaff), + )) + } + Err(e) => { + return Err(( + e, + AuthResult::Denied(crate::access::AuthReason::RosterUnavailable), + )) } }; + check_admin_origin(state, headers, config)?; + + // Claim the NIP-98 replay ID only after Host and Origin validation succeed, + // so a request rejected by either check does not burn the event ID — the + // caller can retry with the corrected header without a new signature. + claim_nip98_replay(state, &event_id).await?; + Ok(AdminAccess::Staff(principal)) +} +/// The admin Host and Origin checks. +fn check_admin_origin( + state: &AppState, + headers: &HeaderMap, + config: &AdminConfig, +) -> Result<(), AdminRefusal> { if !is_admin_host(state, headers) { - return Err(ApiError::forbidden()); + return Err(( + ApiError::forbidden(), + AuthResult::Denied(crate::access::AuthReason::AdminHostMismatch), + )); } if headers.get(header::ORIGIN).is_some_and(|origin| { origin .to_str() .map_or(true, |origin| !origin_matches_host(origin, &config.host)) }) { - return Err(ApiError::forbidden()); - } - - // Claim the NIP-98 replay ID only after Host and Origin validation succeed, - // so a request rejected by either check does not burn the event ID — the - // caller can retry with the corrected header without a new signature. - if let Some(event_id) = nip98_event_id { - claim_nip98_replay(state, &event_id).await?; + return Err(( + ApiError::forbidden(), + AuthResult::Denied(crate::access::AuthReason::OriginMismatch), + )); } - - Ok(access) + Ok(()) } /// [`authorize`] for a bodyless read, bound to the request's real method and @@ -258,11 +330,20 @@ pub async fn authorize( /// `"GET"` would reject a correctly signed `HEAD`. pub async fn authorize_read( state: &AppState, + slot: &AccessSlot, headers: &HeaderMap, method: &Method, uri: &Uri, ) -> Result { - authorize(state, headers, request_target(uri), method.as_str(), None).await + authorize( + state, + slot, + headers, + request_target(uri), + method.as_str(), + None, + ) + .await } /// [`authorize`] for a mutation, bound to the request's real method and full @@ -271,6 +352,7 @@ pub async fn authorize_read( /// contract: the buffered body bytes, or `None` only for a bodyless `DELETE`. pub async fn authorize_write( state: &AppState, + slot: &AccessSlot, headers: &HeaderMap, method: &Method, uri: &Uri, @@ -278,6 +360,7 @@ pub async fn authorize_write( ) -> Result { authorize( state, + slot, headers, request_target(uri), method.as_str(), @@ -292,27 +375,30 @@ fn request_target(uri: &Uri) -> &str { .map_or_else(|| uri.path(), |pq| pq.as_str()) } +/// True when `pubkey` holds the operator role (not moderator), with the same +/// precedence as [`lookup_admin_principal`]. A roster lookup failure is an +/// `Err`, never "not an operator". +pub(crate) async fn is_relay_operator( + state: &AppState, + pubkey: [u8; 32], +) -> Result { + Ok(lookup_admin_principal(state, pubkey) + .await? + .is_some_and(|p| p.role == AdminRole::Operator)) +} + /// Resolve a 32-byte pubkey to an `AdminPrincipal` using config + DB. /// /// Resolution order (config outranks DB): /// 1. Operator/Config if pubkey ∈ RELAY_OPERATOR_PUBKEYS /// 2. Operator/OwnerFallback if pubkey == RELAY_OWNER_PUBKEY AND RELAY_OPERATOR_PUBKEYS is empty /// 3. role from relay_operators DB row -/// 4. None → 403 +/// 4. None → not staff (403) /// /// A DB moderator row for a config-backed Operator is ignored (never demotes /// the config grant). -pub async fn resolve_admin_principal( - state: &AppState, - pubkey: [u8; 32], -) -> Result { - lookup_admin_principal(state, pubkey) - .await? - .ok_or_else(ApiError::forbidden) -} - -/// Effective staff grant for `pubkey`, same precedence as -/// [`resolve_admin_principal`]. `Ok(None)` means "not staff"; a roster lookup +/// +/// `Ok(None)` means "not staff"; a roster lookup /// failure is an `Err`, so callers fail closed instead of treating it as /// "not staff". pub async fn lookup_admin_principal( @@ -392,22 +478,26 @@ pub enum AdminAccess { impl AdminAccess { /// The act check: a write needs a signed staff member. Role-specific - /// checks run on the returned principal. - pub fn act(self) -> Result { + /// checks run on the returned principal. A refusal is recorded on `slot`. + pub fn act(self, slot: &AccessSlot) -> Result { match self { Self::Staff(principal) => Ok(principal), - Self::NetworkTrusted => Err(ApiError::forbidden_with_message( - "this endpoint requires BUZZ_ADMIN_AUTH=nip98", - )), + Self::NetworkTrusted => { + slot.finish(AuthResult::Denied(AuthReason::NotStaff)); + Err(ApiError::forbidden_with_message( + "this endpoint requires BUZZ_ADMIN_AUTH=nip98", + )) + } } } /// The operator check: roster routes need a signed Operator. - pub fn operator(self) -> Result { - let principal = self.act()?; + pub fn operator(self, slot: &AccessSlot) -> Result { + let principal = self.act(slot)?; if principal.role == AdminRole::Operator { Ok(principal) } else { + slot.finish(AuthResult::Denied(AuthReason::NotOperator)); Err(ApiError::forbidden_with_message( "staffing endpoints require operator role", )) @@ -434,13 +524,18 @@ async fn authorize_nip98( path: &str, method: &str, raw_body: Option<&[u8]>, -) -> Result<([u8; 32], nostr::EventId), ApiError> { - let unauth = ApiError::unauthorized; +) -> Result<([u8; 32], nostr::EventId), (ApiError, &'static str)> { + let unauth = || (ApiError::unauthorized(), "nip98_invalid"); // 1. Extract exactly one Authorization: Nostr header. let mut values = headers.get_all(header::AUTHORIZATION).iter(); let (Some(value), None) = (values.next(), values.next()) else { - return Err(unauth()); + let reason = if headers.contains_key(header::AUTHORIZATION) { + "duplicate_authorization" + } else { + "nip98_missing" + }; + return Err((ApiError::unauthorized(), reason)); }; let auth_str = value .to_str() @@ -478,8 +573,8 @@ async fn authorize_nip98( // 5. Verify signature, timestamp, u-tag, method-tag, and payload hash. // For GET/HEAD (no body), body is None so payload tag is optional. // For mutations, body bytes are provided so the payload hash is verified. - let pubkey = - buzz_auth::verify_nip98_event(&event_json, &url, method, raw_body).map_err(|_| unauth())?; + let pubkey = buzz_auth::verify_nip98_event(&event_json, &url, method, raw_body) + .map_err(|e| (ApiError::unauthorized(), auth_error_code(&e)))?; Ok(( pubkey.to_bytes(), @@ -489,9 +584,12 @@ async fn authorize_nip98( /// Atomically claim a verified NIP-98 event ID against the deployment-scoped /// replay guard. Called only after [`authorize_nip98`] verified the event and -/// [`resolve_admin_principal`] confirmed a roster grant, so an unrostered +/// [`lookup_admin_principal`] confirmed a roster grant, so an unrostered /// signer never consumes a slot. Redis failure fails closed. -async fn claim_nip98_replay(state: &AppState, event_id: &nostr::EventId) -> Result<(), ApiError> { +async fn claim_nip98_replay( + state: &AppState, + event_id: &nostr::EventId, +) -> Result<(), AdminRefusal> { let unauth = ApiError::unauthorized; match state .nip98_replay @@ -503,14 +601,17 @@ async fn claim_nip98_replay(state: &AppState, event_id: &nostr::EventId) -> Resu .await { Ok(true) => Ok(()), - Ok(false) => Err(unauth()), + Ok(false) => Err((unauth(), AuthResult::Failed("nip98_replay"))), Err(err) => { tracing::warn!( scope = ADMIN_REPLAY_SCOPE, error = %err, "admin NIP-98 replay guard failed; rejecting request fail-closed" ); - Err(unauth()) + Err(( + unauth(), + AuthResult::Denied(crate::access::AuthReason::ReplayCheckUnavailable), + )) } } } @@ -542,8 +643,9 @@ fn origin_matches_host(origin: &str, host: &str) -> bool { #[cfg(test)] mod tests { use super::{ - admin_api_origin, canonical_url, host_matches, method_has_body, nostr_credential, - origin_matches_host, + admin_api_origin, authorize, canonical_url, header, host_matches, method_has_body, + nostr_credential, origin_matches_host, AccessSlot, AdminAccess, AdminPrincipal, AdminRole, + AdminSource, AuthResult, ADMIN_API_PREFIX, BASE64, }; #[test] @@ -772,4 +874,198 @@ mod tests { let _ = m; // acknowledged } } + + // A rostered admin request dropped while its replay check is in flight + // still writes one `aborted` line. The real NIP-98, roster and Host + // checks pass first; the replay guard never answers. + #[tokio::test(flavor = "current_thread")] + async fn admin_request_dropped_during_replay_logs_one_aborted_line() { + use base64::Engine as _; + let keys = nostr::Keys::generate(); + let mut state = (*crate::state::tests::test_state().await).clone(); + let mut config = (*state.config).clone(); + config.admin = Some(crate::config::AdminConfig { + host: "admin.example.com".into(), + auth: crate::config::AdminAuth::Nip98, + web_dir: None, + }); + config.relay_operator_pubkeys = vec![keys.public_key().to_hex()]; + state.config = std::sync::Arc::new(config); + let replay = std::sync::Arc::new(crate::access::tests::StallingReplayGuard::default()); + state.nip98_replay = replay.clone(); + let url = format!("https://admin.example.com{ADMIN_API_PREFIX}/users"); + let event = nostr::EventBuilder::new(nostr::Kind::HttpAuth, "") + .tags([ + nostr::Tag::parse(["u", url.as_str()]).unwrap(), + nostr::Tag::parse(["method", "GET"]).unwrap(), + ]) + .sign_with_keys(&keys) + .unwrap(); + let mut headers = axum::http::HeaderMap::new(); + headers.insert(header::HOST, "admin.example.com".parse().unwrap()); + let credential = BASE64.encode(serde_json::to_string(&event).unwrap()); + headers.insert( + header::AUTHORIZATION, + format!("Nostr {credential}").parse().unwrap(), + ); + + let slot = crate::access::AccessSlot::default(); + let (guard, out) = crate::access::tests::capture_scoped(); + tokio::select! { + _ = authorize(&state, &slot, &headers, "/users", "GET", None) => { + panic!("the replay check must stall"); + } + () = replay.arrived.notified() => {} + } + slot.abandon(&format!("{ADMIN_API_PREFIX}/users")); + drop(guard); + crate::access::tests::assert_one_aborted_line(&out, &keys.public_key()); + } + + // A refused admin request logs exactly one access line with a fixed code, + // and the query string never reaches it. + #[tokio::test(flavor = "current_thread")] + async fn admin_refusal_logs_one_auth_line() { + let mut state = (*crate::state::tests::test_state().await).clone(); + let mut config = (*state.config).clone(); + config.admin = Some(crate::config::AdminConfig { + host: "admin.example.com".into(), + auth: crate::config::AdminAuth::Nip98, + web_dir: None, + }); + state.config = std::sync::Arc::new(config); + let slot = crate::access::AccessSlot::default(); + let (guard, out) = crate::access::tests::capture_scoped(); + let refused = crate::api::admin::auth::authorize( + &state, + &slot, + &axum::http::HeaderMap::new(), + "/users?q=secret", + "GET", + None, + ) + .await; + slot.emit("/api/admin/users", 401); + drop(guard); + assert!(refused.is_err()); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "failed"); + assert_eq!(lines[0]["reason"], "nip98_missing"); + assert!(!out.raw().contains("secret")); + } + + // With admin auth disabled, the network-trusted admission and the + // Host/Origin refusal each record their outcome on the request's line. + #[tokio::test(flavor = "current_thread")] + async fn disabled_admin_records_admission_and_refusal() { + let mut state = (*crate::state::tests::test_state().await).clone(); + let mut config = (*state.config).clone(); + config.admin = Some(crate::config::AdminConfig { + host: "admin.example.com".into(), + auth: crate::config::AdminAuth::Disabled, + web_dir: None, + }); + state.config = std::sync::Arc::new(config); + let cases = [ + ("admin.example.com", None, "success", None), + ( + "tenant.example.com", + None, + "denied", + Some("admin_host_mismatch"), + ), + ( + "admin.example.com", + Some("https://evil.example"), + "denied", + Some("origin_mismatch"), + ), + ]; + for (host, origin, outcome, reason) in cases { + let mut headers = axum::http::HeaderMap::new(); + headers.insert(header::HOST, host.parse().unwrap()); + if let Some(origin) = origin { + headers.insert(header::ORIGIN, origin.parse().unwrap()); + } + let slot = crate::access::AccessSlot::default(); + let (guard, out) = crate::access::tests::capture_scoped(); + let decided = authorize(&state, &slot, &headers, "/users", "GET", None).await; + slot.emit("/api/admin/users", if decided.is_ok() { 200 } else { 403 }); + drop(guard); + assert_eq!(decided.is_ok(), outcome == "success", "{host} {origin:?}"); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + let line = &lines[0]; + assert_eq!(line["method"], "network_trusted", "{line}"); + assert_eq!(line["outcome"], outcome, "{line}"); + assert_eq!( + line.get("reason").and_then(|r| r.as_str()), + reason, + "{line}" + ); + assert!(line.get("pubkey").is_none(), "{line}"); + } + } + + // A role check that refuses after `authorize` admitted logs `denied` + // with its fixed reason, not the earlier `success`. + #[test] + fn admin_role_refusal_logs_denied() { + let moderator = AdminAccess::Staff(AdminPrincipal { + pubkey: [7; 32], + role: AdminRole::Moderator, + source: AdminSource::Config, + }); + for (access, operator, reason) in [ + (AdminAccess::NetworkTrusted, false, "not_staff"), + (moderator, true, "not_operator"), + ] { + let slot = AccessSlot::default(); + slot.finish(AuthResult::Success); + let (guard, out) = crate::access::tests::capture_scoped(); + let refused = if operator { + access.operator(&slot) + } else { + access.act(&slot) + }; + slot.emit("/api/admin/users", 403); + drop(guard); + assert!(refused.is_err()); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "denied", "{reason}"); + assert_eq!(lines[0]["reason"], reason); + } + } + + // Two Authorization headers are a duplicate, not a missing credential. + #[tokio::test(flavor = "current_thread")] + async fn admin_duplicate_authorization_logs_duplicate() { + let mut state = (*crate::state::tests::test_state().await).clone(); + let mut config = (*state.config).clone(); + config.admin = Some(crate::config::AdminConfig { + host: "admin.example.com".into(), + auth: crate::config::AdminAuth::Nip98, + web_dir: None, + }); + state.config = std::sync::Arc::new(config); + let mut headers = axum::http::HeaderMap::new(); + headers.append(header::AUTHORIZATION, "Nostr a".parse().unwrap()); + headers.append(header::AUTHORIZATION, "Nostr b".parse().unwrap()); + let slot = AccessSlot::default(); + let (guard, out) = crate::access::tests::capture_scoped(); + let refused = authorize(&state, &slot, &headers, "/users", "GET", None).await; + slot.emit("/api/admin/users", 401); + drop(guard); + assert!(refused.is_err()); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "failed", "{}", lines[0]); + assert_eq!( + lines[0]["reason"], "duplicate_authorization", + "{}", + lines[0] + ); + } } diff --git a/crates/buzz-relay/src/api/admin/direct.rs b/crates/buzz-relay/src/api/admin/direct.rs index b262c7827ca..1dee1256168 100644 --- a/crates/buzz-relay/src/api/admin/direct.rs +++ b/crates/buzz-relay/src/api/admin/direct.rs @@ -40,8 +40,10 @@ enum Kind { Delete, } +#[allow(clippy::too_many_arguments)] // one Axum extractor per argument pub(super) async fn ban( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, @@ -49,11 +51,24 @@ pub(super) async fn ban( Query(q): Query, body: Bytes, ) -> Result<(StatusCode, Json), ApiError> { - direct_action(state, method, uri, headers, Kind::Ban, target, q, body).await + direct_action( + state, + slot, + method, + uri, + headers, + Kind::Ban, + target, + q, + body, + ) + .await } +#[allow(clippy::too_many_arguments)] // one Axum extractor per argument pub(super) async fn timeout( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, @@ -61,11 +76,24 @@ pub(super) async fn timeout( Query(q): Query, body: Bytes, ) -> Result<(StatusCode, Json), ApiError> { - direct_action(state, method, uri, headers, Kind::Timeout, target, q, body).await + direct_action( + state, + slot, + method, + uri, + headers, + Kind::Timeout, + target, + q, + body, + ) + .await } +#[allow(clippy::too_many_arguments)] // one Axum extractor per argument pub(super) async fn delete_event( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, @@ -73,7 +101,18 @@ pub(super) async fn delete_event( Query(q): Query, body: Bytes, ) -> Result<(StatusCode, Json), ApiError> { - direct_action(state, method, uri, headers, Kind::Delete, target, q, body).await + direct_action( + state, + slot, + method, + uri, + headers, + Kind::Delete, + target, + q, + body, + ) + .await } /// 409 `target_is_staff` when `target` is on the effective staff roster @@ -102,6 +141,7 @@ pub(super) fn enforcement_failed(action_id: Uuid, error: &str) -> ApiError { #[allow(clippy::too_many_arguments)] async fn direct_action( state: Arc, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, @@ -110,15 +150,15 @@ async fn direct_action( q: CommunityQuery, body_bytes: Bytes, ) -> Result<(StatusCode, Json), ApiError> { - let principal = authorize_write(&state, &headers, &method, &uri, Some(&body_bytes)) + let principal = authorize_write(&state, &slot, &headers, &method, &uri, Some(&body_bytes)) .await? - .act()?; + .act(&slot)?; let body: DirectBody = serde_json::from_slice(&body_bytes) .map_err(|_| ApiError::bad_request("invalid_body", "invalid JSON body"))?; let target = decode_hex_pubkey(&target_hex)?; let host = buzz_core::tenant::validate_community_host(&q.community_host) .map_err(|msg| ApiError::bad_request("invalid_community_host", msg))?; - let tenant = match crate::tenant::bind_community(&state.db, &host).await { + let tenant = match crate::tenant::bind_community(&*state, &host).await { Ok(t) => t, Err(crate::tenant::BindError::UnmappedHost) => { return Err(ApiError::bad_request( diff --git a/crates/buzz-relay/src/api/admin/mod.rs b/crates/buzz-relay/src/api/admin/mod.rs index b5cfa1ef490..8c0ed1b78f0 100644 --- a/crates/buzz-relay/src/api/admin/mod.rs +++ b/crates/buzz-relay/src/api/admin/mod.rs @@ -40,6 +40,7 @@ pub(crate) fn is_admin_host(state: &crate::state::AppState, headers: &HeaderMap) /// [`auth::admin_api_origin`]). Re-exported so the NIP-11 builder can derive /// the advertised origin without reaching into the private `auth` module. pub(crate) use auth::admin_api_origin; +pub(crate) use auth::is_relay_operator; /// Build the deployment-admin routes. /// @@ -165,12 +166,13 @@ struct ProbeResponse { async fn probe( State(state): State>, + slot: crate::access::AccessSlot, uri: Uri, method: Method, headers: HeaderMap, ) -> Result, ApiError> { let (auth_mode, role, source, can_act, can_staff) = - match authorize_read(&state, &headers, &method, &uri).await? { + match authorize_read(&state, &slot, &headers, &method, &uri).await? { AdminAccess::NetworkTrusted => ("disabled", None, None, false, false), AdminAccess::Staff(p) => { let can_staff = p.role == AdminRole::Operator; @@ -196,12 +198,13 @@ async fn probe( async fn reports( State(state): State>, + slot: crate::access::AccessSlot, uri: Uri, method: Method, headers: HeaderMap, Query(query): Query, ) -> Result>, ApiError> { - authorize_read(&state, &headers, &method, &uri).await?; + authorize_read(&state, &slot, &headers, &method, &uri).await?; validate( query.status.as_deref(), REPORT_STATUS_ALLOWLIST, @@ -240,12 +243,13 @@ async fn reports( async fn report_detail( State(state): State>, + slot: crate::access::AccessSlot, uri: Uri, method: Method, headers: HeaderMap, Path(id): Path, ) -> Result, ApiError> { - authorize_read(&state, &headers, &method, &uri).await?; + authorize_read(&state, &slot, &headers, &method, &uri).await?; state .db .admin_get_report(id) @@ -272,11 +276,12 @@ struct FeedbackSummary { async fn feedback( State(state): State>, + slot: crate::access::AccessSlot, uri: Uri, method: Method, headers: HeaderMap, ) -> Result>, ApiError> { - authorize_read(&state, &headers, &method, &uri).await?; + authorize_read(&state, &slot, &headers, &method, &uri).await?; let items = state .db .admin_list_feedback(100) @@ -301,12 +306,13 @@ async fn feedback( async fn feedback_detail( State(state): State>, + slot: crate::access::AccessSlot, uri: Uri, method: Method, headers: HeaderMap, Path(id): Path, ) -> Result, ApiError> { - authorize_read(&state, &headers, &method, &uri).await?; + authorize_read(&state, &slot, &headers, &method, &uri).await?; state .db .admin_get_feedback(id) @@ -317,13 +323,34 @@ async fn feedback_detail( async fn feedback_attachment( State(state): State>, + slot: crate::access::AccessSlot, uri: Uri, method: Method, headers: HeaderMap, Path((id, sha256)): Path<(Uuid, String)>, ) -> Result { - authorize_read(&state, &headers, &method, &uri).await?; - if !is_sha256(&sha256) { + authorize_read(&state, &slot, &headers, &method, &uri).await?; + // The request's access line carries the attachment read. + let served = serve_feedback_attachment_checked(&state, &headers, id, &sha256).await; + if let Ok((_, community_id)) = &served { + slot.in_community(*community_id); + slot.detail(crate::access::Detail { + feedback_id: Some(id), + attachment_sha256: Some(sha256), + ..Default::default() + }); + } + served.map(|(response, _)| response) +} + +/// The attachment `sha256` of feedback `id`, and the community it was read from. +async fn serve_feedback_attachment_checked( + state: &crate::state::AppState, + headers: &HeaderMap, + id: Uuid, + sha256: &str, +) -> Result<(Response, buzz_core::tenant::CommunityId), ApiError> { + if !is_sha256(sha256) { return Err(ApiError::not_found()); } @@ -342,14 +369,14 @@ async fn feedback_attachment( return Err(ApiError::not_found()); }; - if !feedback_references_hash(&feedback.tags, community_host, &sha256) { + if !feedback_references_hash(&feedback.tags, community_host, sha256) { return Err(ApiError::not_found()); } // Resolve the tenant from server-owned feedback provenance, then assert the // resolved row still agrees with the feedback FK. Client input never names // a community, host, object key, extension, or upstream URL. - let tenant = crate::tenant::bind_community(&state.db, community_host) + let tenant = crate::tenant::bind_community(state, community_host) .await .map_err(|_| ApiError::not_found())?; if tenant.community().as_uuid() != &community_id { @@ -362,19 +389,13 @@ async fn feedback_attachment( return Err(ApiError::not_found()); } - let response = crate::api::media::serve_feedback_attachment(&state, &tenant, &sha256, &headers) + let response = crate::api::media::serve_feedback_attachment(state, &tenant, sha256, headers) .await .map_err(|error| match error { buzz_media::MediaError::NotFound => ApiError::not_found(), _ => ApiError::internal(), })?; - tracing::info!( - feedback_id = %feedback.id, - community_id = %community_id, - attachment_sha256 = %sha256, - "admin feedback attachment read" - ); - Ok(response) + Ok((response, tenant.community())) } // ── Phase 2: Report resolution ──────────────────────────────────────────────── @@ -443,6 +464,7 @@ fn compute_timeout_until(secs: u64) -> Result, ApiError> { /// - delete/kick/ban/timeout: server-side enforcement state machine. async fn resolve_report( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, @@ -454,9 +476,9 @@ async fn resolve_report( resolve_report_with_enforcement, ResolutionError, }; - let principal = authorize_write(&state, &headers, &method, &uri, Some(&body_bytes)) + let principal = authorize_write(&state, &slot, &headers, &method, &uri, Some(&body_bytes)) .await? - .act()?; + .act(&slot)?; let body: ResolveReportBody = serde_json::from_slice(&body_bytes) .map_err(|_e| ApiError::bad_request("invalid_body", "invalid JSON body"))?; @@ -504,7 +526,7 @@ async fn resolve_report( }; // Bind tenant from server-owned report provenance (never from client input). - let tenant = crate::tenant::bind_community(&state.db, &report_detail.report.community_host) + let tenant = crate::tenant::bind_community(&*state, &report_detail.report.community_host) .await .map_err(|_| ApiError::internal())?; @@ -665,6 +687,7 @@ struct ReopenReportBody { /// records a durable `reopen` audit row. `409` if the report is not terminal. async fn reopen_report( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, @@ -673,9 +696,9 @@ async fn reopen_report( ) -> Result, ApiError> { use buzz_db::relay_admin_actions::ReopenResult; - let principal = authorize_write(&state, &headers, &method, &uri, Some(&body_bytes)) + let principal = authorize_write(&state, &slot, &headers, &method, &uri, Some(&body_bytes)) .await? - .act()?; + .act(&slot)?; let body: ReopenReportBody = serde_json::from_slice(&body_bytes) .map_err(|_| ApiError::bad_request("invalid_body", "invalid JSON body"))?; @@ -688,7 +711,7 @@ async fn reopen_report( .ok_or_else(ApiError::not_found)?; // Bind tenant from server-owned report provenance (never from client input). - let tenant = crate::tenant::bind_community(&state.db, &report_detail.report.community_host) + let tenant = crate::tenant::bind_community(&*state, &report_detail.report.community_host) .await .map_err(|_| ApiError::internal())?; @@ -744,15 +767,16 @@ struct CancelReportBody { /// `activeAction: null`. async fn cancel_report( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Path(report_id): Path, body_bytes: Bytes, ) -> Result, ApiError> { - let principal = authorize_write(&state, &headers, &method, &uri, Some(&body_bytes)) + let principal = authorize_write(&state, &slot, &headers, &method, &uri, Some(&body_bytes)) .await? - .act()?; + .act(&slot)?; let body: CancelReportBody = serde_json::from_slice(&body_bytes) .map_err(|_| ApiError::bad_request("invalid_body", "invalid JSON body"))?; @@ -765,7 +789,7 @@ async fn cancel_report( .ok_or_else(ApiError::not_found)?; // Bind tenant from server-owned report provenance (never from client input). - let tenant = crate::tenant::bind_community(&state.db, &report_detail.report.community_host) + let tenant = crate::tenant::bind_community(&*state, &report_detail.report.community_host) .await .map_err(|_| ApiError::internal())?; @@ -813,15 +837,16 @@ async fn cancel_report( /// Update product_feedback status. Requires nip98 auth. async fn update_feedback_status( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Path(id): Path, body_bytes: Bytes, ) -> Result, ApiError> { - let _principal = authorize_write(&state, &headers, &method, &uri, Some(&body_bytes)) + let _principal = authorize_write(&state, &slot, &headers, &method, &uri, Some(&body_bytes)) .await? - .act()?; + .act(&slot)?; #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -868,13 +893,14 @@ struct OperatorEntry { /// Requires nip98 auth + Operator role. async fn list_operators( State(state): State>, + slot: crate::access::AccessSlot, uri: Uri, method: Method, headers: HeaderMap, ) -> Result>, ApiError> { - authorize_read(&state, &headers, &method, &uri) + authorize_read(&state, &slot, &headers, &method, &uri) .await? - .operator()?; + .operator(&slot)?; let config = state .config @@ -943,15 +969,16 @@ struct UpsertOperatorBody { /// Requires nip98 auth + Operator role. async fn upsert_operator( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Path(pubkey_hex): Path, body_bytes: Bytes, ) -> Result, ApiError> { - let principal = authorize_write(&state, &headers, &method, &uri, Some(&body_bytes)) + let principal = authorize_write(&state, &slot, &headers, &method, &uri, Some(&body_bytes)) .await? - .operator()?; + .operator(&slot)?; // Canonicalize the path param once: validate it decodes to 32 bytes, then // lowercase it. Config-backed pubkeys are lowercased at parse, so the 409 @@ -1014,14 +1041,15 @@ async fn upsert_operator( /// Requires nip98 auth + Operator role. async fn delete_operator( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Path(pubkey_hex): Path, ) -> Result, ApiError> { - let principal = authorize_write(&state, &headers, &method, &uri, None) + let principal = authorize_write(&state, &slot, &headers, &method, &uri, None) .await? - .operator()?; + .operator(&slot)?; // Canonicalize the path param once (validate + lowercase) so the 409 check // and the DB delete use the same form config-backed pubkeys are stored in; @@ -1164,8 +1192,15 @@ async fn community_for_host( state: &crate::state::AppState, host: &str, ) -> Result { - match crate::tenant::bind_community(&state.db, host).await { - Ok(tenant) => Ok(tenant.community()), + Ok(tenant_for_host(state, host).await?.community()) +} + +async fn tenant_for_host( + state: &crate::state::AppState, + host: &str, +) -> Result { + match crate::tenant::bind_community(state, host).await { + Ok(tenant) => Ok(tenant), Err(crate::tenant::BindError::UnmappedHost) => Err(ApiError::bad_request( "unknown_community_host", "no community is served at this host", @@ -1201,12 +1236,13 @@ struct RestrictionsQuery { /// malformed. Returns 401 without a valid admin credential. async fn list_member_restrictions( State(state): State>, + slot: crate::access::AccessSlot, uri: Uri, method: Method, headers: HeaderMap, Query(query): Query, ) -> Result, ApiError> { - authorize_read(&state, &headers, &method, &uri).await?; + authorize_read(&state, &slot, &headers, &method, &uri).await?; let page_limit = limit(query.limit, 200, 200)?; let cursor = query.cursor.as_deref().map(decode_cursor).transpose()?; @@ -1238,18 +1274,19 @@ async fn list_member_restrictions( /// Requires nip98 auth. async fn unban_member( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Path(pubkey_hex): Path, Query(query): Query, ) -> Result { - let principal = authorize_write(&state, &headers, &method, &uri, None) + let principal = authorize_write(&state, &slot, &headers, &method, &uri, None) .await? - .act()?; + .act(&slot)?; let target_bytes = decode_hex_pubkey(&pubkey_hex)?; - let community = community_for_host(&state, &query.community_host).await?; + let tenant = tenant_for_host(&state, &query.community_host).await?; let actor_authority = match principal.role { AdminRole::Operator => "relay_operator", @@ -1259,7 +1296,7 @@ async fn unban_member( let lifted = state .db .unban_community_member_with_audit( - community, + tenant.community(), &target_bytes, &principal.pubkey, actor_authority, @@ -1268,6 +1305,7 @@ async fn unban_member( if !lifted { return Err(ApiError::conflict("no active ban for this member")); } + state.invalidate_restrictions(&tenant); Ok(axum::http::StatusCode::NO_CONTENT) } @@ -1279,18 +1317,19 @@ async fn unban_member( /// Requires nip98 auth. async fn untimeout_member( State(state): State>, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Path(pubkey_hex): Path, Query(query): Query, ) -> Result { - let principal = authorize_write(&state, &headers, &method, &uri, None) + let principal = authorize_write(&state, &slot, &headers, &method, &uri, None) .await? - .act()?; + .act(&slot)?; let target_bytes = decode_hex_pubkey(&pubkey_hex)?; - let community = community_for_host(&state, &query.community_host).await?; + let tenant = tenant_for_host(&state, &query.community_host).await?; let actor_authority = match principal.role { AdminRole::Operator => "relay_operator", @@ -1300,7 +1339,7 @@ async fn untimeout_member( let lifted = state .db .untimeout_community_member_with_audit( - community, + tenant.community(), &target_bytes, &principal.pubkey, actor_authority, @@ -1309,6 +1348,7 @@ async fn untimeout_member( if !lifted { return Err(ApiError::conflict("no active timeout for this member")); } + state.invalidate_restrictions(&tenant); Ok(axum::http::StatusCode::NO_CONTENT) } @@ -1503,9 +1543,7 @@ mod postgres_tests { }); let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1582,6 +1620,21 @@ mod postgres_tests { router(state).oneshot(request).await.expect("response") } + /// Sends an admin-relative request to its mounted path on the production + /// router, whose access layer writes the request's line. + async fn production_status_for( + state: Arc, + mut request: Request, + ) -> axum::response::Response { + *request.uri_mut() = format!("{ADMIN_API_PREFIX}{}", request.uri()) + .parse() + .expect("mounted uri"); + crate::router::build_router(state) + .oneshot(request) + .await + .expect("response") + } + #[tokio::test] async fn every_route_rejects_a_missing_credential_before_database_access() { let state = test_state().await; @@ -1718,8 +1771,10 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres — DB lookup returns 500 without a database"] async fn feedback_attachment_rejects_unknown_feedback() { - let response = status_for( - test_state().await, + let state = test_state().await; + let (_guard, out) = crate::access::tests::capture_scoped(); + let response = production_status_for( + state, status_request(authorized(&format!( "/feedback/{}/attachments/{HASH}", Uuid::nil() @@ -1727,6 +1782,106 @@ mod postgres_tests { ) .await; assert_eq!(response.status(), StatusCode::NOT_FOUND); + // The read's one access line: the login and the read's status. + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "success", "{}", lines[0]); + assert_eq!(lines[0]["status"], 404, "{}", lines[0]); + } + + /// A served attachment writes one access line carrying the feedback id, + /// attachment hash, community and final status, in both admin auth + /// modes; a network-trusted read carries no key. + mod external_infra_minio_tests { + use super::*; + + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres and MinIO"] + async fn served_attachment_writes_one_line_in_both_admin_modes() { + let signed = nip98_state(vec![test_operator_keys().public_key().to_hex()]).await; + let open = disabled_mode_state().await; + for (mode, state) in [("nip98", signed), ("network_trusted", open)] { + let host = format!("attach-{}.test", Uuid::new_v4().simple()); + state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community"); + let tenant = crate::tenant::bind_community(&state.db, &host) + .await + .expect("bind community"); + let bytes = format!("attachment bytes {}", Uuid::new_v4()).into_bytes(); + let sha256 = hex::encode(::digest(&bytes)); + state + .media_storage + .put(&format!("{sha256}.txt"), &bytes, "text/plain") + .await + .expect("put blob"); + let meta = buzz_media::BlobMeta { + dim: String::new(), + blurhash: String::new(), + thumb_url: String::new(), + ext: "txt".into(), + mime_type: "text/plain".into(), + size: bytes.len() as u64, + uploaded_at: 0, + duration_secs: None, + }; + state + .media_storage + .put_sidecar(&tenant, &sha256, &meta) + .await + .expect("put sidecar"); + let feedback_id = Uuid::new_v4(); + let tags = serde_json::json!([[ + "imeta", + format!("url /media/{sha256}.txt"), + format!("x {sha256}") + ]]); + sqlx::query( + "INSERT INTO product_feedback (id, community_id, event_id, submitter_pubkey, \ + category, body, tags, status, event_created_at, received_at) \ + VALUES ($1, $2, $3, $4, 'bug', 'see attachment', $5, 'new', now(), now())", + ) + .bind(feedback_id) + .bind(tenant.community().as_uuid()) + .bind([feedback_id.as_bytes().as_slice(), feedback_id.as_bytes()].concat()) + .bind(vec![9_u8; 32]) + .bind(&tags) + .execute(state.db.pool()) + .await + .expect("insert feedback"); + + let uri = format!("/feedback/{feedback_id}/attachments/{sha256}"); + let request = if mode == "nip98" { + authorized(&uri) + } else { + Request::builder() + .uri(&uri) + .header(header::HOST, "admin.example") + }; + let (guard, out) = crate::access::tests::capture_scoped(); + let response = production_status_for(state, status_request(request)).await; + let status = response.status(); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .expect("body"); + drop(guard); + assert_eq!(status, StatusCode::OK, "{mode}"); + assert_eq!(body.as_ref(), bytes.as_slice(), "{mode}"); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{mode}: {lines:?}"); + let line = &lines[0]; + assert_eq!(line["method"], mode, "{line}"); + assert_eq!(line["status"], 200, "{line}"); + assert_eq!(line["feedback_id"], feedback_id.to_string(), "{line}"); + assert_eq!(line["attachment_sha256"], sha256.as_str(), "{line}"); + assert_eq!(line["community"], tenant.community().to_string(), "{line}"); + if mode == "network_trusted" { + assert!(line.get("pubkey").is_none(), "{line}"); + } + } + } } #[tokio::test] @@ -2140,9 +2295,7 @@ mod postgres_tests { web_dir: None, }); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -2592,11 +2745,19 @@ mod postgres_tests { .expect("insert ban fixture for other community"); let state = nip98_state_with_real_pool(pool.clone()).await; + // Restriction rows this pod cached before the lift. + let cached_keys = [ + (community, target_pubkey.clone()), + (other_community, target_pubkey.clone()), + ]; + for key in cached_keys.clone() { + state.seed_restriction(key, buzz_db::moderation::RestrictionState::default()); + } let target_hex = hex::encode(&target_pubkey); let path = format!("/members/{target_hex}/ban?communityHost={host}"); let auth = make_nostr_auth_delete(&test_operator_keys(), &path); let response = status_for( - state, + Arc::clone(&state), Request::builder() .method("DELETE") .uri(&path) @@ -2612,6 +2773,12 @@ mod postgres_tests { StatusCode::NO_CONTENT, "unban of an active ban must return 204" ); + // The lift drops the community's cached rows (and, over Redis, every + // other pod's); another community's stay. + // Mutation: drop `invalidate_restrictions` from the handler → RED. + let [lifted, elsewhere] = cached_keys; + assert!(state.restriction_cache.entry(&lifted).is_none()); + assert!(state.restriction_cache.entry(&elsewhere).is_some()); // Ban must be cleared in the target community. let ban = db @@ -2721,11 +2888,19 @@ mod postgres_tests { .expect("insert timeout fixture for other community"); let state = nip98_state_with_real_pool(pool.clone()).await; + // Restriction rows this pod cached before the lift. + let cached_keys = [ + (community, target_pubkey.clone()), + (other_community, target_pubkey.clone()), + ]; + for key in cached_keys.clone() { + state.seed_restriction(key, buzz_db::moderation::RestrictionState::default()); + } let target_hex = hex::encode(&target_pubkey); let path = format!("/members/{target_hex}/timeout?communityHost={host}"); let auth = make_nostr_auth_delete(&test_operator_keys(), &path); let response = status_for( - state, + Arc::clone(&state), Request::builder() .method("DELETE") .uri(&path) @@ -2741,6 +2916,12 @@ mod postgres_tests { StatusCode::NO_CONTENT, "untimeout of an active timeout must return 204" ); + // The lift drops the community's cached rows (and, over Redis, every + // other pod's); another community's stay. + // Mutation: drop `invalidate_restrictions` from the handler → RED. + let [lifted, elsewhere] = cached_keys; + assert!(state.restriction_cache.entry(&lifted).is_none()); + assert!(state.restriction_cache.entry(&elsewhere).is_some()); // Timeout must be cleared in the target community. let restriction = db @@ -2934,7 +3115,7 @@ mod postgres_tests { let mut config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE] config.require_relay_membership = false; config.redis_url = "redis://127.0.0.1:1".to_string(); - // Populate relay_operator_pubkeys so resolve_admin_principal can grant + // Populate relay_operator_pubkeys so lookup_admin_principal can grant // Operator/Config to the test pubkeys without a DB lookup. config.relay_operator_pubkeys = pubkeys; // Ensure relay_operator_api_origin is set (required when pubkeys is non-empty). @@ -2948,9 +3129,7 @@ mod postgres_tests { }); let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -3442,9 +3621,7 @@ mod postgres_tests { }); let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -3520,9 +3697,7 @@ mod postgres_tests { .await .expect("connect to test DB"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -3647,9 +3822,7 @@ mod postgres_tests { drop(state); // not used let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -4116,9 +4289,7 @@ mod postgres_tests { }); let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -4189,9 +4360,7 @@ mod postgres_tests { }); let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -4259,9 +4428,7 @@ mod postgres_tests { }); let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -5352,7 +5519,7 @@ mod postgres_tests { // Kick needs a channel-scoped report. sqlx::query( "WITH ch AS (INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) \ - SELECT gen_random_uuid(), community_id, 'staff-guard', 'stream', 'open', $2 \ + SELECT gen_random_uuid(), community_id, 'staff-guard-' || $1::uuid::text, 'stream', 'open', $2 \ FROM moderation_reports WHERE id = $1 RETURNING id) \ UPDATE moderation_reports SET channel_id = (SELECT id FROM ch) WHERE id = $1", ) @@ -6061,9 +6228,7 @@ mod postgres_tests { web_dir: None, }); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -7124,7 +7289,7 @@ mod postgres_tests { let channel_id = uuid::Uuid::new_v4(); sqlx::query( r#"INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) - VALUES ($1, $2, 'event-report-ch', 'stream', 'open', $3)"#, + VALUES ($1, $2, 'event-report-ch-' || $1::uuid::text, 'stream', 'open', $3)"#, ) .bind(channel_id) .bind(community_id) @@ -7887,7 +8052,7 @@ mod postgres_tests { let _tenant = e2e_tenant(community_id, "worker-midflight-purge.example"); state .membership_cache - .insert((cid, channel_id, author.clone()), true); + .seed_member((cid, channel_id, author.clone()), true); let conn_id = uuid::Uuid::new_v4(); let (tx, _rx) = tokio::sync::mpsc::channel(1); let (ctrl_tx, _ctrl_rx) = tokio::sync::mpsc::channel(1); @@ -7999,7 +8164,7 @@ mod postgres_tests { assert!( state .membership_cache - .get(&(cid, channel_id, author.clone())) + .cached_member(&(cid, channel_id, author.clone())) .is_none(), "crash-recovery must clear membership cache after purged-event kick re-drive" ); @@ -9466,6 +9631,190 @@ mod postgres_tests { // ── Kick live side effects: crash-recovery and re-add race ──────────────── + /// A channel deleted between a committed kick and its recovery leaves no + /// roster to refresh. Recovery must treat that as convergence and finalize, + /// without running the removal again. + #[tokio::test] + #[ignore = "requires Postgres — a deleted channel does not strand a committed kick"] + async fn crash_recovery_finalizes_kick_after_channel_deleted() { + let pool = e2e_pool().await; + let (community_id, host) = e2e_community(&pool, "kick-recovery-deleted").await; + let cid = buzz_core::CommunityId::from_uuid(community_id); + let target = vec![0xAAu8; 32]; + let actor = vec![0xBBu8; 32]; + + // Seed channel + member. + let channel_id = uuid::Uuid::new_v4(); + sqlx::query( + r#"INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) + VALUES ($1, $2, 'recovery-deleted-ch', 'stream', 'open', $3)"#, + ) + .bind(channel_id) + .bind(community_id) + .bind(&actor) + .execute(&pool) + .await + .expect("create channel"); + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey, role) VALUES ($1, $2, $3, 'member')", + ) + .bind(community_id) + .bind(channel_id) + .bind(&target) + .execute(&pool) + .await + .expect("add member"); + + let report_id = e2e_report_pubkey(&pool, community_id, &target).await; + + // Claim → enforcing → lease → kick + commit marker (simulates process + // that committed the kick but crashed before live side effects ran). + let action_id = match buzz_db::relay_admin_actions::claim_report( + &pool, + cid, + report_id, + uuid::Uuid::new_v4(), + &actor, + "operator", + "kick", + None, + None, + "resolve:kick", + "relay_operator", + Some(&target), + None, + Some(channel_id), + ) + .await + .expect("claim") + { + buzz_db::relay_admin_actions::ClaimResult::Claimed(a) => a.id, + other => panic!("expected Claimed, got {other:?}"), + }; + let _ = buzz_db::relay_admin_actions::begin_enforcing(&pool, action_id) + .await + .expect("begin_enforcing"); + let lease_until = chrono::Utc::now() + chrono::Duration::seconds(60); + let lease_token = + match buzz_db::relay_admin_actions::acquire_action_lease(&pool, action_id, lease_until) + .await + .expect("acquire lease") + { + buzz_db::relay_admin_actions::LeaseResult::Acquired(t) => t, + other => panic!("expected Acquired, got {other:?}"), + }; + let kick_result = buzz_db::relay_admin_actions::execute_kick_with_marker( + &pool, + action_id, + lease_token, + cid, + channel_id, + &target, + &actor, + ) + .await + .expect("execute_kick_with_marker"); + assert!( + matches!( + kick_result, + buzz_db::relay_admin_actions::KickWithMarkerResult::Removed + ), + "kick must commit before the simulated crash" + ); + + // Expire the lease so the recovery worker can re-claim. + sqlx::query( + "UPDATE relay_admin_actions SET action_lease_expires_at = $2, action_lease_token = NULL WHERE id = $1", + ) + .bind(action_id) + .bind(chrono::Utc::now() - chrono::Duration::seconds(300)) + .execute(&pool) + .await + .expect("expire lease"); + + let removed_at = || async { + sqlx::query_scalar::<_, Option>>( + "SELECT removed_at FROM channel_members WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3", + ) + .bind(community_id) + .bind(channel_id) + .bind(&target) + .fetch_one(&pool) + .await + .expect("member row") + }; + let removed_before = removed_at().await.expect("kick removed the member"); + + // Discovery published before the delete, which is stale once the + // channel is gone; recovery must clean it up before the notice. + let state = state_from_pool(pool.clone()).await; + let tenant = e2e_tenant(community_id, &host); + crate::handlers::side_effects::emit_group_discovery_events(&tenant, &state, channel_id) + .await + .expect("seed discovery"); + let live_discovery = || async { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM events WHERE community_id = $1 AND channel_id = $2 \ + AND kind IN (39000, 39001, 39002) AND deleted_at IS NULL", + ) + .bind(community_id) + .bind(channel_id) + .fetch_one(&pool) + .await + .expect("count discovery") + }; + assert!(live_discovery().await > 0, "stale discovery seeded"); + assert!( + buzz_db::channel::soft_delete_channel(&pool, cid, channel_id) + .await + .expect("delete channel") + ); + let mut barrier = crate::handlers::side_effects::notice_barrier::install(&target); + let batch = buzz_db::relay_admin_actions::claim_stranded_action_batch( + &pool, + "e2e-kick-recovery-deleted", + chrono::Utc::now() + chrono::Duration::seconds(120), + 1000, + ) + .await + .expect("claim_stranded_action_batch"); + let claim = batch + .into_iter() + .find(|c| c.record.id == action_id) + .expect("stranded action must appear in batch"); + let recovery = tokio::spawn({ + let state = state.clone(); + async move { crate::handlers::admin_action_worker::recover_one(&state, claim).await } + }); + let (noticed, release) = + tokio::time::timeout(std::time::Duration::from_secs(10), barrier.next()) + .await + .expect("recovery sent no removal notice") + .expect("barrier open"); + assert_eq!(noticed, channel_id); + assert_eq!( + live_discovery().await, + 0, + "removal notice sent before discovery cleanup" + ); + release.send(()).expect("recovery waiting"); + recovery.await.expect("recovery task"); + + let final_rec = buzz_db::relay_admin_actions::get_action(&pool, action_id) + .await + .expect("get_action") + .expect("record must still exist"); + assert_eq!( + final_rec.state, "succeeded", + "recovery must finalize the kick" + ); + assert_eq!( + removed_at().await, + Some(removed_before), + "recovery must not run the removal again" + ); + } + /// Recovery seam: commit kick marker, simulate crash, re-drive via the real /// recovery worker entry point and assert all three live side effects fire: /// membership cache cleared, channel subscription evicted, workflow disabled. @@ -9578,7 +9927,7 @@ mod postgres_tests { state .membership_cache - .insert((cid, channel_id, target.clone()), true); + .seed_member((cid, channel_id, target.clone()), true); let conn_id = uuid::Uuid::new_v4(); let (tx, _rx) = tokio::sync::mpsc::channel(1); @@ -9638,7 +9987,7 @@ mod postgres_tests { assert!( state .membership_cache - .get(&(cid, channel_id, target.clone())) + .cached_member(&(cid, channel_id, target.clone())) .is_some(), "pre-condition: membership cache entry must exist before recovery" ); @@ -9680,7 +10029,7 @@ mod postgres_tests { assert!( state .membership_cache - .get(&(cid, channel_id, target.clone())) + .cached_member(&(cid, channel_id, target.clone())) .is_none(), "crash-recovery re-drive must clear the membership cache" ); @@ -10726,7 +11075,7 @@ mod postgres_tests { state .membership_cache - .insert((cid, channel_id, target.clone()), true); + .seed_member((cid, channel_id, target.clone()), true); let conn_id = uuid::Uuid::new_v4(); let (tx, _rx) = tokio::sync::mpsc::channel(1); @@ -10774,7 +11123,7 @@ mod postgres_tests { assert!( state .membership_cache - .get(&(cid, channel_id, target.clone())) + .cached_member(&(cid, channel_id, target.clone())) .is_some(), "pre-condition: membership cache entry must exist" ); @@ -10840,7 +11189,7 @@ mod postgres_tests { assert!( state .membership_cache - .get(&(cid, channel_id, target.clone())) + .cached_member(&(cid, channel_id, target.clone())) .is_none(), "recovery must clear the membership cache for legacy kick row" ); @@ -10990,7 +11339,7 @@ mod postgres_tests { state .membership_cache - .insert((cid, channel_id, target.clone()), true); + .seed_member((cid, channel_id, target.clone()), true); let conn_id = uuid::Uuid::new_v4(); let (tx, _rx) = tokio::sync::mpsc::channel(1); @@ -11084,7 +11433,7 @@ mod postgres_tests { assert!( state .membership_cache - .get(&(cid, channel_id, target.clone())) + .cached_member(&(cid, channel_id, target.clone())) .is_none(), "recovery must clear the membership cache for legacy kick row" ); @@ -11183,12 +11532,12 @@ mod postgres_tests { // 1. Seed the membership cache. state .membership_cache - .insert((cid, channel_id, target_pubkey.clone()), true); + .seed_member((cid, channel_id, target_pubkey.clone()), true); assert!( state .membership_cache - .get(&(cid, channel_id, target_pubkey.clone())) + .cached_member(&(cid, channel_id, target_pubkey.clone())) .is_some(), "pre-condition: membership cache entry must exist before kick side effects" ); @@ -11246,7 +11595,7 @@ mod postgres_tests { assert!( state .membership_cache - .get(&(cid, channel_id, target_pubkey.clone())) + .cached_member(&(cid, channel_id, target_pubkey.clone())) .is_none(), "membership cache must not contain a stale entry after kick side effects" ); @@ -11686,6 +12035,43 @@ mod postgres_tests { assert_eq!(live, 0); } + /// An artifact revision is not admin-deletable: open NIP-AR syncs would + /// get no live signal (they see `op=delete` and kind 9005). The action + /// fails terminally and the head stays. Mutation: drop the kind check in + /// `execute_delete_with_marker` → 200 and the head is gone → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn direct_delete_refuses_artifact_revisions() { + let (pool, community, host, state) = direct_fixture().await; + let id = seed_signed_event(&pool, community, &test_operator_keys()).await; + sqlx::query("UPDATE events SET kind = 45010 WHERE community_id = $1") + .bind(community.as_uuid()) + .execute(&pool) + .await + .unwrap(); + let path = format!("/events/{id}/delete?communityHost={host}"); + let (status, body) = direct_post( + &state, + &path, + serde_json::json!({ "requestId": Uuid::new_v4() }), + ) + .await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}"); + assert!( + body.to_string() + .contains("artifact revisions cannot be deleted"), + "{body}" + ); + let live: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM events WHERE community_id = $1 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(live, 1); + } + /// F1: attempt B passes the stored-action lookup, attempt A (same request) /// accepts and deletes, then B validates against a gone event. B must /// replay A (200), and a B carrying a different intent must get 409 — @@ -11815,7 +12201,7 @@ mod postgres_tests { // Retarget to the staff-authored event, channel-scoped so kick is valid. sqlx::query( "WITH ch AS (INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by) \ - VALUES (gen_random_uuid(), $2, 'staff-guard', 'stream', 'open', $3) RETURNING id) \ + VALUES (gen_random_uuid(), $2, 'staff-guard-' || $1::uuid::text, 'stream', 'open', $3) RETURNING id) \ UPDATE moderation_reports SET channel_id = (SELECT id FROM ch), target_kind = 'event', \ target_pubkey = NULL, target_event_id = $4 WHERE id = $1", ) @@ -12262,7 +12648,10 @@ mod postgres_tests { } /// A staff ban closes the target's open socket like a kind-9040 ban; a - /// staff timeout leaves the target connected. + /// staff timeout leaves the target connected. Both drop the community's + /// cached restriction rows, so the next request rereads the restriction. + /// Mutation: drop `invalidate_restrictions` from the enforcement + /// convergence point → RED. #[tokio::test] #[ignore = "requires Postgres"] async fn direct_ban_disconnects_target_and_timeout_does_not() { @@ -12270,6 +12659,19 @@ mod postgres_tests { let (banned, timed_out) = ([0x41u8; 32], [0x42u8; 32]); let banned_socket = live_socket(&state, community, &banned); let timed_out_socket = live_socket(&state, community, &timed_out); + let cached = |target: [u8; 32]| { + state + .restriction_cache + .entry(&(community, target.to_vec())) + .is_some() + }; + let seed = |target: [u8; 32]| { + state.seed_restriction( + (community, target.to_vec()), + buzz_db::moderation::RestrictionState::default(), + ) + }; + seed(timed_out); let (status, body) = direct_post( &state, @@ -12285,6 +12687,8 @@ mod postgres_tests { !timed_out_socket.is_cancelled(), "timeout must not disconnect" ); + assert!(!cached(timed_out), "timeout must drop the cached row"); + seed(banned); let (status, body) = direct_post( &state, @@ -12297,6 +12701,7 @@ mod postgres_tests { banned_socket.is_cancelled(), "ban must close the target's socket" ); + assert!(!cached(banned), "ban must drop the cached row"); assert!( !timed_out_socket.is_cancelled(), "ban is scoped to its target" diff --git a/crates/buzz-relay/src/api/admin/reads.rs b/crates/buzz-relay/src/api/admin/reads.rs index 6cb3e586353..8e88cadbf06 100644 --- a/crates/buzz-relay/src/api/admin/reads.rs +++ b/crates/buzz-relay/src/api/admin/reads.rs @@ -60,12 +60,13 @@ fn decode_community_cursor(token: &str) -> Result { /// `limit` is 1–100, default 50. pub(super) async fn communities( State(state): AppStateRef, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Query(query): Query, ) -> Result, ApiError> { - authorize_read(&state, &headers, &method, &uri).await?; + authorize_read(&state, &slot, &headers, &method, &uri).await?; let limit = limit(query.limit, 50, 100)?; let after = query .cursor @@ -116,12 +117,13 @@ pub(super) struct MemberSearchPage { /// `limit` is 1–50, default 20. pub(super) async fn search_members( State(state): AppStateRef, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Query(query): Query, ) -> Result, ApiError> { - authorize_read(&state, &headers, &method, &uri).await?; + authorize_read(&state, &slot, &headers, &method, &uri).await?; let q = query.q.trim(); if q.is_empty() || q.chars().count() > 100 { return Err(ApiError::bad_request( @@ -180,13 +182,14 @@ async fn is_staff(state: &AppState, pubkey: &[u8]) -> Result { /// community. pub(super) async fn lookup_member( State(state): AppStateRef, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Path(pubkey_hex): Path, Query(query): Query, ) -> Result, ApiError> { - let access = authorize_read(&state, &headers, &method, &uri).await?; + let access = authorize_read(&state, &slot, &headers, &method, &uri).await?; let pubkey = decode_hex_pubkey(&pubkey_hex)?; let pubkey_hex = hex::encode(&pubkey); let community = community_for_host(&state, &query.community_host).await?; @@ -230,13 +233,14 @@ fn event_not_found() -> ApiError { /// delete preview. Anything else is [`event_not_found`]. pub(super) async fn event_preview( State(state): AppStateRef, + slot: crate::access::AccessSlot, method: Method, uri: Uri, headers: HeaderMap, Path(id_hex): Path, Query(query): Query, ) -> Result, ApiError> { - authorize_read(&state, &headers, &method, &uri).await?; + authorize_read(&state, &slot, &headers, &method, &uri).await?; let id = hex::decode(&id_hex) .ok() .filter(|id| id.len() == 32) diff --git a/crates/buzz-relay/src/api/artifact.rs b/crates/buzz-relay/src/api/artifact.rs index bfe636c9086..7284563be8b 100644 --- a/crates/buzz-relay/src/api/artifact.rs +++ b/crates/buzz-relay/src/api/artifact.rs @@ -8,28 +8,39 @@ use serde_json::Value; use std::sync::Arc; /// Serve explicit artifact queries; `None` leaves the request to the generic -/// path (including existing extensions such as `#buzz-channel`). +/// path (including existing extensions such as `#buzz-channel`). `routed` +/// runs once the request is known to be an artifact read, before any of its +/// work awaits, so a request dropped mid-read is still described. pub(super) async fn query( state: &Arc, tenant: &TenantContext, reader: &nostr::PublicKey, filters: &[Value], count: bool, + routed: impl FnOnce(), ) -> Option, (StatusCode, Json)>> { - let mut artifact = false; + let mut artifact = Ok(false); for filter in filters { match route_filter(filter) { FilterRoute::Generic => {} - FilterRoute::Artifact => artifact = true, + FilterRoute::Artifact => artifact = Ok(true), FilterRoute::Rejected(reason) => { - return Some(Err(api_error(StatusCode::BAD_REQUEST, reason))) + artifact = Err(reason); + break; } } } - if !artifact { - return None; + match artifact { + Ok(false) => None, + Ok(true) => { + routed(); + Some(execute(state, tenant, reader, filters, count).await) + } + Err(reason) => { + routed(); + Some(Err(api_error(StatusCode::BAD_REQUEST, reason))) + } } - Some(execute(state, tenant, reader, filters, count).await) } async fn execute( @@ -47,6 +58,15 @@ async fn execute( "artifact queries require exactly one filter", )); } + if filters[0].get("artifact").and_then(Value::as_str) == Some("incremental") { + if count { + return Err(api_error( + StatusCode::BAD_REQUEST, + "incremental requires /query", + )); + } + return super::artifact_sync::query(state, tenant, reader, &filters[0]).await; + } let query = buzz_core::artifact::parse_query(&filters[0]) .map_err(|e| api_error(StatusCode::BAD_REQUEST, e))?; // The query's statement_timeout is the enforced execution budget. diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests.rs index 82d57dd2f19..2519510cf4c 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests.rs @@ -120,7 +120,7 @@ impl Fixture { .await .unwrap(); let status = response.status(); - let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) + let bytes = axum::body::to_bytes(response.into_body(), 8 * 1024 * 1024) .await .unwrap(); (status, serde_json::from_slice(&bytes).unwrap()) @@ -486,3 +486,6 @@ async fn generic_d_lookup_matches_before_limit() { expected.sort(); assert_eq!(ids, expected, "{body}"); } + +#[path = "artifact_postgres_tests/sync_postgres_tests.rs"] +mod sync_postgres_tests; diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs new file mode 100644 index 00000000000..89f08e9338d --- /dev/null +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_access_postgres_tests.rs @@ -0,0 +1,631 @@ +use super::*; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_redaction_and_query_exit_return_removals() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let id = Uuid::new_v4(); + let first = f.revision(id, "create", None); + let first = EventBuilder::new(Kind::Custom(45010), first.content.clone()) + .tags( + first + .tags + .iter() + .cloned() + .chain([Tag::parse(["project", "alpha"]).unwrap()]), + ) + .sign_with_keys(&f.owner) + .unwrap(); + accept(&f, &first).await; + let scope = json!({"artifact":"current","#type":["buzz.task"],"#project":["alpha"]}); + let (_, page) = f + .request("/query", json!([{"artifact":"incremental","query":scope}])) + .await; + assert_eq!(page["changes"][0]["type"], "upsert"); + let changed = f.revision(id, "update", Some(&first)); + accept(&f, &changed).await; + let (status, delta) = f + .request( + "/query", + json!([{"artifact":"incremental","query":scope,"checkpoint":page["checkpoint"]}]), + ) + .await; + assert!(status.is_success(), "{status}: {delta}"); + assert_eq!( + delta["changes"], + json!([{ "type":"remove","artifactId":id }]) + ); + let before = sync(&f, None).await; + assert!(buzz_db::event::soft_delete_event_and_update_thread( + &f.pool, + f.community, + changed.id.as_bytes(), + None, + None + ) + .await + .unwrap()); + let after = sync(&f, Some(&before["checkpoint"])).await; + assert_eq!( + after["changes"], + json!([{ "type":"remove","artifactId":id }]) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_rejoin_replays_old_heads_without_resetting_on_task_edits() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let id = Uuid::new_v4(); + let first = f.revision_as(&f.owner, f.private, id, "create", None); + accept(&f, &first).await; + sqlx::query("UPDATE artifact_heads SET modified_at='2000-01-01' WHERE community_id=$1") + .bind(f.community.as_uuid()) + .execute(&f.pool) + .await + .unwrap(); + buzz_db::channel_members::add_member( + &f.pool, + f.community, + f.private, + f.peer.public_key().as_bytes(), + buzz_db::channel_members::MemberRole::Member, + Some(f.owner.public_key().as_bytes()), + ) + .await + .unwrap(); + let (_, page) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + buzz_db::channel_members::remove_member( + &f.pool, + f.community, + f.private, + f.peer.public_key().as_bytes(), + f.owner.public_key().as_bytes(), + ) + .await + .unwrap(); + buzz_db::channel_members::add_member( + &f.pool, + f.community, + f.private, + f.peer.public_key().as_bytes(), + buzz_db::channel_members::MemberRole::Member, + Some(f.owner.public_key().as_bytes()), + ) + .await + .unwrap(); + let (status, delta) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":page["checkpoint"]}]), + ) + .await; + assert!(status.is_success(), "{status}: {delta}"); + assert_eq!(delta["changes"][0]["event"]["id"], first.id.to_hex()); + let changed = f.revision_as(&f.owner, f.private, id, "update", Some(&first)); + accept(&f, &changed).await; + let (status, delta) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":delta["checkpoint"]}]), + ) + .await; + assert!(status.is_success(), "{status}: {delta}"); + assert_eq!(delta["changes"][0]["event"]["id"], changed.id.to_hex()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_ignores_unchanged_visibility_and_resets_on_ttl_changes() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let permanent_id = Uuid::new_v4(); + let permanent = f.revision(permanent_id, "create", None); + accept(&f, &permanent).await; + let first = sync(&f, None).await; + buzz_db::channel::update_channel( + &f.pool, + f.community, + f.home, + buzz_db::channel::ChannelUpdate { + visibility: Some("open".into()), + name: Some("renamed".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + let renamed = sync(&f, Some(&first["checkpoint"])).await; + assert!(renamed["checkpoint"].is_string()); + buzz_db::channel::update_channel( + &f.pool, + f.community, + f.private, + buzz_db::channel::ChannelUpdate { + ttl_seconds: Some(Some(3600)), + ..Default::default() + }, + ) + .await + .unwrap(); + let (status, reset) = f + .request( + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":renamed["checkpoint"]}]), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(reset["reason"], "policy_changed"); + let next = sync(&f, None).await; + assert!(next["checkpoint"].is_string()); + let expiring_id = Uuid::new_v4(); + let expiring = f.revision_as(&f.owner, f.private, expiring_id, "create", None); + accept(&f, &expiring).await; + for checkpoint in [None, Some(&next["checkpoint"])] { + let page = sync(&f, checkpoint).await; + assert_eq!(page["changes"].as_array().unwrap().len(), 1); + assert_eq!(page["changes"][0]["artifactId"], permanent_id.to_string()); + assert_eq!(page["changes"][0]["type"], "upsert"); + assert!(page["checkpoint"].is_string()); + } + let (status, current) = f + .request( + "/query", + json!([{ + "artifact":"incremental","action":"current","query":query(), + "artifactIds":[permanent_id,expiring_id] + }]), + ) + .await; + assert!(status.is_success(), "{status}: {current}"); + assert_eq!(current["changes"][0]["type"], "upsert"); + assert_eq!( + current["changes"][1], + json!({"type":"remove","artifactId":expiring_id}) + ); + let (status, named) = f + .request( + "/query", + json!([{ + "artifact":"incremental","query":{"artifact":"current","#h":[f.private]} + }]), + ) + .await; + assert!(status.is_success(), "{status}: {named}"); + assert_eq!(named["changes"], json!([])); + let moved = f.revision_as(&f.owner, f.private, permanent_id, "move", Some(&permanent)); + accept(&f, &moved).await; + let delta = sync(&f, Some(&next["checkpoint"])).await; + assert_eq!( + delta["changes"], + json!([{"type":"remove","artifactId":permanent_id}]) + ); + let (status, scoped) = f + .request( + "/query", + json!([{ + "artifact":"incremental","query":{"artifact":"current","#h":[f.home]}, + }]), + ) + .await; + assert!(status.is_success(), "{status}: {scoped}"); + assert_eq!(scoped["changes"], json!([])); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_shrinks_large_pages_and_current_batches_fail_explicitly() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let mut ids = Vec::new(); + for _ in 0..40 { + let id = Uuid::new_v4(); + let base = f.revision(id, "create", None); + let event = EventBuilder::new(Kind::Custom(45010), "x".repeat(260_000)) + .tags(base.tags.clone()) + .sign_with_keys(&f.owner) + .unwrap(); + accept(&f, &event).await; + ids.push(id); + } + let first = sync(&f, None).await; + assert_eq!(first["changes"].as_array().unwrap().len(), 20); + assert!(first["nextCursor"].is_string()); + let (status, last) = f + .request( + "/query", + json!([{"artifact":"incremental","query":query(),"cursor":first["nextCursor"]}]), + ) + .await; + assert!(status.is_success(), "{status}: {last}"); + assert_eq!(last["changes"].as_array().unwrap().len(), 20); + assert!(last["checkpoint"].is_string()); + let (status, body) = f + .request( + "/query", + json!([{"artifact":"incremental","action":"current","query":query(),"artifactIds":ids}]), + ) + .await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); + assert_eq!(body["code"], "incremental_limit"); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_http_reads_and_capability_are_available() { + use tower::ServiceExt; + let _guard = SERIAL.lock().await; + let f = fixture().await; + let response = crate::router::build_router(f.state.clone()) + .oneshot( + axum::http::Request::builder() + .uri("/info") + .header("host", &f.host) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert!(response.status().is_success()); + let bytes = axum::body::to_bytes(response.into_body(), 1024 * 1024) + .await + .unwrap(); + let info: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + info["artifacts"]["sync"], + json!({"version":1,"max_events":4096}) + ); + assert_eq!( + info["artifacts"]["incremental"], + json!({"version":1,"overlapSeconds":120, + "pageRows":100,"currentRows":100,"responseBytes":8388608, + "permanentChannelsOnly":true,"checkpointLifetimeSeconds":2592000}) + ); + let (status, _) = f + .request( + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + assert_eq!(status, StatusCode::OK); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn incremental_resets_when_a_move_source_loses_access() { + let _guard = SERIAL.lock().await; + for delete_channel in [false, true] { + let f = fixture().await; + let id = Uuid::new_v4(); + let first = f.revision(id, "create", None); + accept(&f, &first).await; + let (_, read) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + let moved = f.revision_as(&f.owner, f.private, id, "move", Some(&first)); + accept(&f, &moved).await; + let heads: i64 = sqlx::query_scalar( + "SELECT count(*) FROM artifact_heads WHERE community_id=$1 AND channel_id=$2", + ) + .bind(f.community.as_uuid()) + .bind(f.home) + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!(heads, 0); + if delete_channel { + assert!( + buzz_db::channel::soft_delete_channel(&f.pool, f.community, f.home) + .await + .unwrap() + ); + } else { + buzz_db::channel::update_channel( + &f.pool, + f.community, + f.home, + buzz_db::channel::ChannelUpdate { + visibility: Some("private".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + } + let (status, delta) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":read["checkpoint"]}]), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(delta["reason"], "policy_changed"); + assert!(!delta.to_string().contains(&f.home.to_string())); + let (status, current) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","action":"current","query":query(),"artifactIds":[id]}]), + ) + .await; + assert!(status.is_success()); + assert_eq!( + current["changes"], + json!([{"type":"remove","artifactId":id}]) + ); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_policy_update_can_pass_a_channel_key_share() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let mut tx = f.pool.begin().await.unwrap(); + sqlx::query("SELECT id FROM channels WHERE community_id=$1 AND id=$2 FOR KEY SHARE") + .bind(f.community.as_uuid()) + .bind(f.home) + .fetch_one(&mut *tx) + .await + .unwrap(); + tokio::time::timeout( + std::time::Duration::from_secs(2), + buzz_db::channel::update_channel( + &f.pool, + f.community, + f.home, + buzz_db::channel::ChannelUpdate { + visibility: Some("private".into()), + ..Default::default() + }, + ), + ) + .await + .expect("policy update must permit a foreign-key reader") + .unwrap(); + tx.rollback().await.unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_progress_replays_queries_with_escaped_values() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let scope = json!({"artifact":"current","#type":["buzz.task"],"#project":vec!["\u{1}".repeat(4096);15]}); + let (status, first) = f + .request("/query", json!([{"artifact":"incremental","query":scope}])) + .await; + assert!(status.is_success(), "{status}: {first}"); + assert!(first["checkpoint"].as_str().unwrap().len() < 200_000); + let (status, next) = f + .request( + "/query", + json!([{"artifact":"incremental","query":scope,"checkpoint":first["checkpoint"]}]), + ) + .await; + assert!(status.is_success(), "{status}: {next}"); + assert_eq!(next["changes"], json!([])); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_current_intersects_known_ids_with_query_scope() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let included = Uuid::new_v4(); + let excluded = Uuid::new_v4(); + let event = f.revision(included, "create", None); + accept(&f, &event).await; + accept(&f, &f.revision(excluded, "create", None)).await; + let (status, body) = f + .request( + "/query", + json!([{"artifact":"incremental","action":"current", + "query":{"artifact":"current","#type":["buzz.task"],"#d":[included]}, + "artifactIds":[included,excluded]}]), + ) + .await; + assert!(status.is_success(), "{status}: {body}"); + assert_eq!(body["changes"][0]["artifactId"], included.to_string()); + assert_eq!(body["changes"][0]["event"]["id"], event.id.to_hex()); + assert_eq!( + body["changes"][1], + json!({"type":"remove","artifactId":excluded}) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn incremental_unlisted_channels_require_membership_or_named_scope() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let id = Uuid::new_v4(); + let event = f.revision(id, "create", None); + accept(&f, &event).await; + let (_, before) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + assert_eq!(before["changes"][0]["event"]["id"], event.id.to_hex()); + buzz_db::channel::update_channel( + &f.pool, + f.community, + f.home, + buzz_db::channel::ChannelUpdate { + unlisted: Some(true), + ..Default::default() + }, + ) + .await + .unwrap(); + let (status, reset) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":before["checkpoint"]}]), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(reset["reason"], "policy_changed"); + for (scope, visible) in [ + (query(), false), + ( + json!({"artifact":"current","#type":["buzz.task"],"#h":[f.home]}), + true, + ), + ] { + let (status, page) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":scope}]), + ) + .await; + assert!(status.is_success(), "{page}"); + assert_eq!( + page["changes"].as_array().unwrap().len(), + usize::from(visible) + ); + let (status, current) = f.request_as(&f.peer, "/query", json!([{"artifact":"incremental","action":"current","query":scope,"artifactIds":[id]}])).await; + assert!(status.is_success(), "{current}"); + assert_eq!( + current["changes"][0]["type"], + if visible { "upsert" } else { "remove" } + ); + } + assert_eq!( + sync(&f, None).await["changes"][0]["event"]["id"], + event.id.to_hex() + ); + buzz_db::channel::update_channel( + &f.pool, + f.community, + f.home, + buzz_db::channel::ChannelUpdate { + unlisted: Some(false), + ..Default::default() + }, + ) + .await + .unwrap(); + let (_, listed) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + assert_eq!(listed["changes"][0]["event"]["id"], event.id.to_hex()); +} + +/// An incremental poll's access line counts its changes, removals included: +/// an empty poll is DEBUG and a poll with changes is INFO. Mutation: count only array responses in `query_events` → the +/// empty poll has no `result_count` and logs INFO → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn incremental_poll_access_level_follows_its_change_count() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + accept(&f, &f.revision(Uuid::new_v4(), "create", None)).await; + let poll = |types: &str| json!([{"artifact":"incremental","query":{"artifact":"current","#type":[types]}}]); + let line = |out: &crate::access::tests::Captured| { + let lines = out.lines(); + assert_eq!(lines.len(), 1, "one access line: {lines:?}"); + lines[0].clone() + }; + + let (_capture, out) = crate::access::tests::capture_scoped(); + let (status, body) = f.request("/query", poll("buzz.none")).await; + assert!(status.is_success(), "{status}: {body}"); + let empty = line(&out); + assert_eq!( + (&empty["level"], &empty["result_count"]), + (&"DEBUG".into(), &0.into()), + "{empty}" + ); + + let (_capture, out) = crate::access::tests::capture_scoped(); + let (status, body) = f.request("/query", poll("buzz.task")).await; + assert!(status.is_success(), "{status}: {body}"); + let served = line(&out); + assert_eq!( + (&served["level"], &served["result_count"]), + (&"INFO".into(), &1.into()), + "{served}" + ); +} + +/// A wrapped incremental read dropped during its database work still +/// writes its one WARN aborted line with the standard filter summary, and +/// without its artifact predicates. Mutation: record the artifact summary +/// after `artifact::query` returns → the line has no `kinds` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn dropped_incremental_read_keeps_its_filter_summary() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let marker = "private-predicate-marker"; + let body = json!([{"artifact":"incremental","query":{ + "artifact":"current","kinds":[45010],"#h":[f.home],"#project":[marker]}}]); + let mut lock = f.pool.begin().await.unwrap(); + sqlx::query("LOCK TABLE artifact_heads IN ACCESS EXCLUSIVE MODE") + .execute(&mut *lock) + .await + .unwrap(); + let blocker_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *lock) + .await + .unwrap(); + let (capture, out) = crate::access::tests::capture_access_only(tracing::Level::WARN); + let mut request = Box::pin(f.request("/query", body)); + // Poll the request until its candidate read waits on the lock. + loop { + tokio::select! { + _ = &mut request => panic!("the read must wait on the locked table"), + () = tokio::time::sleep(std::time::Duration::from_millis(20)) => {} + } + let blocked: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE $1=ANY(pg_blocking_pids(pid)))", + ) + .bind(blocker_pid) + .fetch_one(&f.pool) + .await + .unwrap(); + if blocked { + break; + } + } + drop(request); + drop(capture); + lock.rollback().await.unwrap(); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "exactly one access line: {lines:?}"); + let line = &lines[0]; + assert_eq!( + (&line["request"], &line["level"]), + (&"aborted".into(), &"WARN".into()), + "{line}" + ); + assert_eq!(line["route"], "/query", "{line}"); + assert_eq!(line["kinds"], "45010", "{line}"); + assert_eq!(line["channel_ids"], f.home.to_string(), "{line}"); + assert!(!out.raw().contains(marker), "{}", out.raw()); +} diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_cursor_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_cursor_postgres_tests.rs new file mode 100644 index 00000000000..eab9488eb2a --- /dev/null +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_cursor_postgres_tests.rs @@ -0,0 +1,231 @@ +use super::*; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_move_cursor_hides_private_and_redacted_revision_ids() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let (_, empty) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + let mut current = std::collections::HashMap::new(); + let mut private_ids = Vec::new(); + for _ in 0..101 { + let id = Uuid::new_v4(); + let created = f.revision(id, "create", None); + accept(&f, &created).await; + let moved = f.revision_as(&f.owner, f.private, id, "move", Some(&created)); + accept(&f, &moved).await; + private_ids.push(moved.id.to_hex()); + current.insert(id, moved); + } + let (&id, previous) = current.iter().next().unwrap(); + let back = f.revision(id, "move", Some(previous)); + accept(&f, &back).await; + let moved = f.revision_as(&f.owner, f.private, id, "move", Some(&back)); + accept(&f, &moved).await; + private_ids.push(moved.id.to_hex()); + current.insert(id, moved); + let stamp: chrono::DateTime = sqlx::query_scalar("SELECT clock_timestamp()") + .fetch_one(&f.pool) + .await + .unwrap(); + sqlx::query("UPDATE artifact_revisions SET modified_at=$2 WHERE community_id=$1") + .bind(f.community.as_uuid()) + .bind(stamp) + .execute(&f.pool) + .await + .unwrap(); + for redacted in [false, true] { + let (status, first) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":empty["checkpoint"]}]), + ) + .await; + assert!(status.is_success(), "{status}: {first}"); + let cursor = first["nextCursor"].as_str().unwrap(); + let payload = cursor.split_once('.').unwrap().0; + let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload) + .unwrap(); + let decoded = String::from_utf8(decoded).unwrap(); + for private_id in &private_ids { + assert!( + !decoded.contains(private_id), + "cursor exposes a private revision ID (redacted={redacted})" + ); + } + assert_eq!(first["changes"].as_array().unwrap().len(), 100); + let (status, last) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"cursor":cursor}]), + ) + .await; + assert!(status.is_success(), "{status}: {last}"); + assert!(last["checkpoint"].is_string()); + let mut ids = std::collections::HashSet::new(); + for change in first["changes"] + .as_array() + .unwrap() + .iter() + .chain(last["changes"].as_array().unwrap()) + { + assert_eq!(change["type"], "remove"); + assert!(ids.insert(change["artifactId"].as_str().unwrap().to_owned())); + } + assert_eq!(ids.len(), 101); + if !redacted { + let boundary = first["changes"].as_array().unwrap().last().unwrap()["artifactId"] + .as_str() + .unwrap() + .parse::() + .unwrap(); + assert!(buzz_db::event::soft_delete_event_and_update_thread( + &f.pool, + f.community, + current[&boundary].id.as_bytes(), + None, + None + ) + .await + .unwrap()); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_channel_scope_limits_candidates_and_keeps_source_removals() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + buzz_db::channel::update_channel( + &f.pool, + f.community, + f.home, + buzz_db::channel::ChannelUpdate { + visibility: Some("private".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + for _ in 0..101 { + accept( + &f, + &f.revision_as(&f.owner, f.private, Uuid::new_v4(), "create", None), + ) + .await; + } + let deleted_id = Uuid::new_v4(); + let deleted = f.revision(deleted_id, "create", None); + accept(&f, &deleted).await; + accept(&f, &f.revision(deleted_id, "delete", Some(&deleted))).await; + let id = Uuid::new_v4(); + let created = f.revision(id, "create", None); + accept(&f, &created).await; + let scoped_query = json!({"artifact":"current","#type":["buzz.task"],"#h":[f.home]}); + let (status, initial) = f + .request( + "/query", + json!([{ + "artifact":"incremental","query":scoped_query + }]), + ) + .await; + assert!(status.is_success(), "{status}: {initial}"); + assert_eq!(initial["changes"].as_array().unwrap().len(), 1); + assert_eq!(initial["changes"][0]["event"]["id"], created.id.to_hex()); + assert!(initial["nextCursor"].is_null()); + assert!(initial["checkpoint"].is_string()); + let moved = f.revision_as(&f.owner, f.private, id, "move", Some(&created)); + accept(&f, &moved).await; + let (status, delta) = f + .request( + "/query", + json!([{ + "artifact":"incremental","query":scoped_query,"checkpoint":initial["checkpoint"] + }]), + ) + .await; + assert!(status.is_success(), "{status}: {delta}"); + assert!(delta["changes"] + .as_array() + .unwrap() + .contains(&json!({"type":"remove","artifactId":id}))); + assert!(!delta.to_string().contains(&f.private.to_string())); + let restored = f.revision(id, "move", Some(&moved)); + accept(&f, &restored).await; + for channel in [f.home, f.private] { + sqlx::query("INSERT INTO channel_members(community_id,channel_id,pubkey,role) VALUES($1,$2,$3,'owner')") + .bind(f.community.as_uuid()).bind(channel).bind(f.peer.public_key().as_bytes().as_slice()) + .execute(&f.pool).await.unwrap(); + } + buzz_db::channel_members::remove_member( + &f.pool, + f.community, + f.private, + f.owner.public_key().as_bytes(), + f.owner.public_key().as_bytes(), + ) + .await + .unwrap(); + let (status, returned) = f + .request( + "/query", + json!([{ + "artifact":"incremental","query":scoped_query,"checkpoint":delta["checkpoint"] + }]), + ) + .await; + assert!(status.is_success(), "{status}: {returned}"); + assert!(returned["changes"] + .as_array() + .unwrap() + .iter() + .any(|c| c["event"]["id"] == restored.id.to_hex())); + assert!(returned["changes"] + .as_array() + .unwrap() + .iter() + .all(|c| c["type"] != "removeChannel")); + buzz_db::channel_members::remove_member( + &f.pool, + f.community, + f.home, + f.owner.public_key().as_bytes(), + f.owner.public_key().as_bytes(), + ) + .await + .unwrap(); + let (status, removed) = f + .request( + "/query", + json!([{ + "artifact":"incremental","query":scoped_query,"checkpoint":returned["checkpoint"] + }]), + ) + .await; + assert!(status.is_success(), "{status}: {removed}"); + assert_eq!( + removed["changes"], + json!([{"type":"removeChannel","channelId":f.home}]) + ); + let (status, invalid_scope) = f + .request( + "/query", + json!([{ + "artifact":"incremental","query":{"artifact":"current","#h":["not-a-uuid"]} + }]), + ) + .await; + assert!(status.is_success(), "{status}: {invalid_scope}"); + assert_eq!(invalid_scope["changes"], json!([])); +} diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_policy_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_policy_postgres_tests.rs new file mode 100644 index 00000000000..c3cc3d9f1d4 --- /dev/null +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_policy_postgres_tests.rs @@ -0,0 +1,79 @@ +use super::*; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn incremental_resets_for_first_artifact_during_channel_transition() { + let _guard = SERIAL.lock().await; + for delete_channel in [false, true] { + let f = fixture().await; + let mut blocker = f.pool.begin().await.unwrap(); + let blocker_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *blocker) + .await + .unwrap(); + sqlx::query("SELECT id FROM communities WHERE id=$1 FOR NO KEY UPDATE") + .bind(f.community.as_uuid()) + .fetch_one(&mut *blocker) + .await + .unwrap(); + let pool = f.pool.clone(); + let community = f.community; + let home = f.home; + let transition = tokio::spawn(async move { + if delete_channel { + assert!( + buzz_db::channel::soft_delete_channel(&pool, community, home) + .await + .unwrap() + ); + } else { + buzz_db::channel::update_channel( + &pool, + community, + home, + buzz_db::channel::ChannelUpdate { + visibility: Some("private".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + } + }); + tokio::time::timeout(std::time::Duration::from_secs(2), async { + loop { + assert!(!transition.is_finished(), "an empty channel must still advance the recovery marker"); + let blocked: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE $1=ANY(pg_blocking_pids(pid)) AND query LIKE 'UPDATE communities SET artifact_policy_modified_at=%')") + .bind(blocker_pid).fetch_one(&f.pool).await.unwrap(); + if blocked { break; } + tokio::task::yield_now().await; + } + }).await.expect("channel transition reaches the recovery marker"); + let id = Uuid::new_v4(); + let event = f.revision(id, "create", None); + tokio::time::timeout(std::time::Duration::from_secs(2), accept(&f, &event)) + .await + .expect("first artifact commits while the channel transition is uncommitted"); + let (status, first) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + assert!(status.is_success(), "{status}: {first}"); + assert_eq!(first["changes"][0]["event"]["id"], event.id.to_hex()); + blocker.commit().await.unwrap(); + transition.await.unwrap(); + let (status, next) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":first["checkpoint"]}]), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(next["reason"], "policy_changed"); + assert!(!next.to_string().contains(&f.home.to_string())); + } +} diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs new file mode 100644 index 00000000000..db76a358c54 --- /dev/null +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs @@ -0,0 +1,333 @@ +use super::*; +use axum::http::StatusCode; +#[path = "sync_access_postgres_tests.rs"] +mod access_postgres_tests; +#[path = "sync_cursor_postgres_tests.rs"] +mod cursor_postgres_tests; +#[path = "sync_policy_postgres_tests.rs"] +mod policy_postgres_tests; +#[path = "sync_scale_postgres_tests.rs"] +mod scale_postgres_tests; + +async fn fixture() -> Fixture { + Fixture::new().await +} +static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +fn query() -> Value { + json!({"artifact":"current","#type":["buzz.task"]}) +} +async fn sync(f: &Fixture, checkpoint: Option<&Value>) -> Value { + let mut request = json!({"artifact":"incremental","query":query()}); + if let Some(checkpoint) = checkpoint { + request["checkpoint"] = checkpoint.clone(); + } + let (status, body) = f.request("/query", json!([request])).await; + assert!(status.is_success(), "{status}: {body}"); + body +} +async fn accept(f: &Fixture, event: &Event) { + let envelope = buzz_core::artifact::validate(event).unwrap(); + let source = if envelope.op == buzz_core::artifact::ArtifactOp::Move { + f.state + .db + .artifact_home(f.community, envelope.id) + .await + .unwrap() + } else { + None + }; + assert!(matches!( + f.state + .db + .accept_artifact( + f.community, + event, + &envelope, + source, + &f.state.relay_keypair + ) + .await + .unwrap(), + buzz_db::artifact::ArtifactOutcome::Accepted(_) + )); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_recovers_late_commit_and_returns_explicit_deletion() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let first = sync(&f, None).await; + assert_eq!(first["changes"], json!([])); + let id = Uuid::new_v4(); + let event = f.revision(id, "create", None); + accept(&f, &event).await; + // Model a stamp assigned before the first read, followed by a later commit. + sqlx::query("UPDATE artifact_heads SET modified_at=$1::timestamptz-interval '119 seconds' WHERE community_id=$2 AND artifact_id=$3") + .bind(first["startedAt"].as_str().unwrap()).bind(f.community.as_uuid()).bind(id).execute(&f.pool).await.unwrap(); + let second = sync(&f, Some(&first["checkpoint"])).await; + assert!(second["changes"] + .as_array() + .unwrap() + .iter() + .any(|c| c["event"]["id"] == event.id.to_hex())); + let deleted = f.revision(id, "delete", Some(&event)); + accept(&f, &deleted).await; + let third = sync(&f, Some(&second["checkpoint"])).await; + assert!(third["changes"] + .as_array() + .unwrap() + .iter() + .any(|c| c == &json!({"type":"remove","artifactId":id}))); + assert_eq!(third["overlapSeconds"], 120); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_pages_equal_timestamps_and_replays_the_same_cursor() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + for _ in 0..103 { + accept(&f, &f.revision(Uuid::new_v4(), "create", None)).await; + } + sqlx::query("UPDATE artifact_heads SET modified_at='2000-01-01' WHERE community_id=$1") + .bind(f.community.as_uuid()) + .execute(&f.pool) + .await + .unwrap(); + let first = sync(&f, None).await; + assert_eq!(first["changes"].as_array().unwrap().len(), 100); + assert!(first["checkpoint"].is_null()); + let request = json!([{"artifact":"incremental","query":query(),"cursor":first["nextCursor"]}]); + let (status, last) = f.request("/query", request.clone()).await; + assert!(status.is_success(), "{status}: {last}"); + assert_eq!(last["changes"].as_array().unwrap().len(), 3); + assert!(last["nextCursor"].is_null()); + assert!(last["checkpoint"].is_string()); + let (_, replay) = f.request("/query", request).await; + assert_eq!(last, replay); + let ids = first["changes"] + .as_array() + .unwrap() + .iter() + .chain(last["changes"].as_array().unwrap()) + .map(|c| c["artifactId"].as_str().unwrap()) + .collect::>(); + assert_eq!(ids.len(), 103); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_current_has_uniform_unavailable_and_rejects_duplicate_ids() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let id = Uuid::new_v4(); + let event = f.revision_as(&f.owner, f.private, id, "create", None); + accept(&f, &event).await; + let missing = Uuid::new_v4(); + let body = json!([{"artifact":"incremental","action":"current","query":query(),"artifactIds":[id,missing,"local-only"]}]); + let (status, body) = f.request_as(&f.peer, "/query", body).await; + assert!(status.is_success(), "{status}: {body}"); + assert_eq!( + body["changes"], + json!([ + {"type":"remove","artifactId":id},{"type":"remove","artifactId":missing},{"type":"remove","artifactId":"local-only"} + ]) + ); + let (status, _) = f + .request( + "/query", + json!([{"artifact":"incremental","action":"current","query":query(),"artifactIds":[id,id]}]), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, body) = f + .request( + "/query", + json!([{"artifact":"incremental","action":"current","query":query(),"artifactIds":[id]}]), + ) + .await; + assert!(status.is_success(), "{status}: {body}"); + assert_eq!(body["changes"][0]["event"]["id"], event.id.to_hex()); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_grant_finds_old_heads_and_removal_names_only_own_membership() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let id = Uuid::new_v4(); + let event = f.revision_as(&f.owner, f.private, id, "create", None); + accept(&f, &event).await; + sqlx::query("UPDATE artifact_heads SET modified_at='2000-01-01' WHERE community_id=$1") + .bind(f.community.as_uuid()) + .execute(&f.pool) + .await + .unwrap(); + let (_, first) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + assert_eq!(first["changes"], json!([])); + buzz_db::channel_members::add_member( + &f.pool, + f.community, + f.private, + f.peer.public_key().as_bytes(), + buzz_db::channel_members::MemberRole::Member, + Some(f.owner.public_key().as_bytes()), + ) + .await + .unwrap(); + let (_, granted) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":first["checkpoint"]}]), + ) + .await; + assert!( + granted["changes"] + .as_array() + .unwrap() + .iter() + .any(|c| c["event"]["id"] == event.id.to_hex()), + "{granted}" + ); + buzz_db::channel_members::remove_member( + &f.pool, + f.community, + f.private, + f.peer.public_key().as_bytes(), + f.owner.public_key().as_bytes(), + ) + .await + .unwrap(); + let (_, removed) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":granted["checkpoint"]}]), + ) + .await; + assert_eq!( + removed["changes"], + json!([{ "type":"removeChannel","channelId":f.private }]) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_move_to_hidden_destination_removes_the_source_view() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let id = Uuid::new_v4(); + let first = f.revision(id, "create", None); + accept(&f, &first).await; + let (_, read) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query()}]), + ) + .await; + let moved = f.revision_as(&f.owner, f.private, id, "move", Some(&first)); + accept(&f, &moved).await; + let (_, delta) = f + .request_as( + &f.peer, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":read["checkpoint"]}]), + ) + .await; + assert_eq!( + delta["changes"], + json!([{ "type":"remove","artifactId":id }]) + ); + assert!(!delta.to_string().contains(&f.private.to_string())); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_policy_changes_reset_without_hidden_channel_ids() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + for _ in 0..101 { + accept(&f, &f.revision(Uuid::new_v4(), "create", None)).await; + } + let first = sync(&f, None).await; + assert!(first["nextCursor"].is_string()); + buzz_db::channel::update_channel( + &f.pool, + f.community, + f.home, + buzz_db::channel::ChannelUpdate { + visibility: Some("private".into()), + ..Default::default() + }, + ) + .await + .unwrap(); + let (status, body) = f + .request( + "/query", + json!([{"artifact":"incremental","query":query(),"cursor":first["nextCursor"]}]), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!( + body, + json!({"code":"incremental_reset","error":"incremental_reset","reason":"policy_changed"}) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_progress_binds_reader_query_and_community() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let first = sync(&f, None).await; + for (reader, scope) in [ + (&f.peer, query()), + ( + &f.owner, + json!({"artifact":"current","#type":["other.task"]}), + ), + ] { + let (status, _) = f + .request_as( + reader, + "/query", + json!([{"artifact":"incremental","query":scope,"checkpoint":first["checkpoint"]}]), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } + let mut other = fixture().await; + Arc::make_mut(&mut other.state).relay_keypair = f.state.relay_keypair.clone(); + let (status, _) = other + .request_as( + &f.owner, + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":first["checkpoint"]}]), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let expired = crate::api::artifact_sync::expired_checkpoint_for_test( + &f.state, + first["checkpoint"].as_str().unwrap(), + ) + .unwrap(); + let (status, body) = f + .request( + "/query", + json!([{"artifact":"incremental","query":query(),"checkpoint":expired}]), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(body["reason"], "checkpoint_expired"); +} diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_scale_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_scale_postgres_tests.rs new file mode 100644 index 00000000000..aa7ace8828a --- /dev/null +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_scale_postgres_tests.rs @@ -0,0 +1,131 @@ +use super::*; +use base64::Engine; +use sha2::Digest; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn sync_downloads_ten_thousand_tasks_with_sixty_thousand_memberships() { + let _guard = SERIAL.lock().await; + let f = fixture().await; + let homes = (0..60_001) + .map(|n| if n == 0 { f.home } else { Uuid::new_v4() }) + .collect::>(); + for chunk in homes[1..].chunks(500) { + sqlx::query("INSERT INTO channels(community_id,id,name,visibility,channel_type,created_by,archived_at) SELECT $1,id,id::text,'private','stream',$2,'2000-01-01' FROM unnest($3::uuid[]) id") + .bind(f.community.as_uuid()).bind(f.owner.public_key().as_bytes().as_slice()).bind(chunk).execute(&f.pool).await.unwrap(); + sqlx::query("INSERT INTO channel_members(community_id,channel_id,pubkey,role,sync_modified_at) SELECT $1,id,$2,'owner','2000-01-01' FROM unnest($3::uuid[]) id") + .bind(f.community.as_uuid()).bind(f.owner.public_key().as_bytes().as_slice()).bind(chunk).execute(&f.pool).await.unwrap(); + } + sqlx::query("UPDATE channel_members SET sync_modified_at='2000-01-01' WHERE community_id=$1 AND channel_id=ANY($2)") + .bind(f.community.as_uuid()).bind(vec![f.home,f.private]).execute(&f.pool).await.unwrap(); + sqlx::query("UPDATE channels SET archived_at=NULL WHERE community_id=$1 AND id=ANY($2)") + .bind(f.community.as_uuid()) + .bind(&homes[..10_000]) + .execute(&f.pool) + .await + .unwrap(); + let mut event_bytes = 0; + for chunk in homes[..10_050].chunks(500) { + let values=chunk.iter().map(|home| { + let id=Uuid::new_v4(); + let base=f.revision_as(&f.owner,*home,id,"create",None); + let event=EventBuilder::new(Kind::Custom(45010),json!({"notes":"x".repeat(4400)}).to_string()) + .tags(base.tags.clone()).sign_with_keys(&f.owner).unwrap(); + event_bytes=serde_json::to_vec(&event).unwrap().len(); + json!({"id":event.id.to_hex(),"artifact_id":id,"tags":event.tags,"content":event.content,"sig":event.sig.to_string(),"created_at":event.created_at.as_secs(),"channel_id":home}) + }).collect::>(); + sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id) SELECT $1,decode(x.id,'hex'),$2,to_timestamp(x.created_at),45010,x.tags,x.content,decode(x.sig,'hex'),x.channel_id FROM jsonb_to_recordset($3) x(id text,tags jsonb,content text,sig text,created_at bigint,channel_id uuid)") + .bind(f.community.as_uuid()).bind(f.owner.public_key().as_bytes().as_slice()).bind(json!(values)).execute(&f.pool).await.unwrap(); + sqlx::query("INSERT INTO artifact_heads(community_id,artifact_id,event_id,channel_id,artifact_type,modified_at) SELECT $1,x.artifact_id,decode(x.id,'hex'),x.channel_id,'buzz.task','2000-01-01' FROM jsonb_to_recordset($2) x(id text,artifact_id uuid,channel_id uuid)") + .bind(f.community.as_uuid()).bind(json!(values)).execute(&f.pool).await.unwrap(); + } + sqlx::raw_sql("ANALYZE artifact_heads; ANALYZE channel_members; ANALYZE channels") + .execute(&f.pool) + .await + .unwrap(); + let mut other = (*bridge_handler_test_state().await.unwrap()).clone(); + let config = Arc::make_mut(&mut other.config); + config.require_auth_token = true; + other.relay_keypair = f.state.relay_keypair.clone(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/query", listener.local_addr().unwrap()); + let router = crate::router::build_router(Arc::new(other)); + let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(10)) + .build() + .unwrap(); + let started = std::time::Instant::now(); + let mut page = sync(&f, None).await; + let mut ids = std::collections::HashSet::new(); + let mut pages = 0; + loop { + pages += 1; + for change in page["changes"].as_array().unwrap() { + assert_eq!(change["type"], "upsert"); + ids.insert(change["artifactId"].as_str().unwrap().to_owned()); + } + if page["nextCursor"].is_null() { + break; + } + let (status, next) = signed_query( + &f, + &client, + &url, + json!([{"artifact":"incremental","query":query(),"cursor":page["nextCursor"]}]), + ) + .await; + assert!(status.is_success(), "{status}: {next}"); + page = next; + } + let cold = started.elapsed(); + assert_eq!(ids.len(), 10_050); + assert_eq!(pages, 101); + let warm = std::time::Instant::now(); + let (status, delta) = signed_query( + &f, + &client, + &url, + json!([{"artifact":"incremental","query":query(),"checkpoint":page["checkpoint"]}]), + ) + .await; + assert!(status.is_success(), "{status}: {delta}"); + assert_eq!(delta["changes"], json!([])); + assert!(delta["checkpoint"].is_string()); + eprintln!("10,050 tasks; 60,002 memberships; {event_bytes}-byte events; {pages} cold pages: {cold:?}; empty warm sync: {:?}",warm.elapsed()); + server.abort(); +} + +async fn signed_query( + f: &Fixture, + client: &reqwest::Client, + url: &str, + body: Value, +) -> (StatusCode, Value) { + let bytes = serde_json::to_vec(&body).unwrap(); + let auth = EventBuilder::new(Kind::Custom(27235), "") + .tags([ + Tag::parse(["u", &format!("https://{}/query", f.host)]).unwrap(), + Tag::parse(["method", "POST"]).unwrap(), + Tag::parse(["payload", &hex::encode(sha2::Sha256::digest(&bytes))]).unwrap(), + Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), + ]) + .sign_with_keys(&f.owner) + .unwrap(); + let authorization = format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD.encode(serde_json::to_vec(&auth).unwrap()) + ); + let response = client + .post(url) + .header("host", &f.host) + .header("content-type", "application/json") + .header("authorization", authorization) + .body(bytes) + .send() + .await + .unwrap(); + let status = StatusCode::from_u16(response.status().as_u16()).unwrap(); + let body = serde_json::from_slice(&response.bytes().await.unwrap()).unwrap(); + (status, body) +} diff --git a/crates/buzz-relay/src/api/artifact_sync.rs b/crates/buzz-relay/src/api/artifact_sync.rs new file mode 100644 index 00000000000..8b50f748939 --- /dev/null +++ b/crates/buzz-relay/src/api/artifact_sync.rs @@ -0,0 +1,389 @@ +//! Incremental reads with signed progress and bounded current-identity reads. +use crate::state::AppState; +use axum::{http::StatusCode, Json}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; +use buzz_core::{ + artifact::{ArtifactQuery, ArtifactView}, + TenantContext, +}; +use buzz_db::artifact_sync::{Candidate, Position, PAGE_ROWS}; +use chrono::{DateTime, Duration, Utc}; +use hmac::{Hmac, KeyInit, Mac}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; +use uuid::Uuid; + +const OVERLAP: i64 = 120; +const CHECKPOINT_DAYS: i64 = 30; +const RESPONSE_BYTES: usize = 8_388_608; +static WORK: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4); +type Response = Result, (StatusCode, Json)>; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +struct Request { + artifact: String, + query: Value, + action: Option, + checkpoint: Option, + cursor: Option, + artifact_ids: Option>, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Token { + version: u8, + community: Uuid, + reader: String, + query: String, + at: DateTime, + policy: DateTime, + since: Option>, + position: Option, + cursor: bool, +} + +fn error(status: StatusCode, code: &str) -> (StatusCode, Json) { + (status, Json(json!({"error":code,"code":code}))) +} +fn invalid() -> (StatusCode, Json) { + error(StatusCode::BAD_REQUEST, "incremental_invalid") +} +fn unavailable() -> (StatusCode, Json) { + error(StatusCode::SERVICE_UNAVAILABLE, "incremental_unavailable") +} +fn limit() -> (StatusCode, Json) { + error(StatusCode::PAYLOAD_TOO_LARGE, "incremental_limit") +} +fn reset(reason: &str) -> (StatusCode, Json) { + ( + StatusCode::CONFLICT, + Json(json!({"error":"incremental_reset","code":"incremental_reset","reason":reason})), + ) +} +fn db_error(e: buzz_db::DbError) -> (StatusCode, Json) { + match e { + buzz_db::DbError::ArtifactSyncLimit => limit(), + error => { + tracing::warn!(%error,"incremental artifact read failed"); + unavailable() + } + } +} + +/// Bounds advertised to clients that use the incremental protocol. +pub(crate) fn capability() -> Value { + json!({"version":1,"overlapSeconds":OVERLAP,"pageRows":PAGE_ROWS, + "currentRows":PAGE_ROWS,"responseBytes":RESPONSE_BYTES,"permanentChannelsOnly":true, + "checkpointLifetimeSeconds":CHECKPOINT_DAYS*86400}) +} + +fn mac(state: &AppState) -> Result, (StatusCode, Json)> { + let mut digest = Sha256::new(); + digest.update(b"buzz-artifact-incremental-v1\0"); + digest.update(state.relay_keypair.secret_key().as_secret_bytes()); + Hmac::::new_from_slice(&digest.finalize()).map_err(|_| unavailable()) +} +fn encode(state: &AppState, token: &Token) -> Result)> { + let data = serde_json::to_vec(token).map_err(|_| unavailable())?; + let mut signature = mac(state)?; + signature.update(&data); + let encoded = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(&data), + URL_SAFE_NO_PAD.encode(signature.finalize().into_bytes()) + ); + if encoded.len() > 200_000 { + return Err(invalid()); + } + Ok(encoded) +} +fn decode(state: &AppState, value: &str) -> Result)> { + if value.len() > 200_000 { + return Err(invalid()); + } + let (data, signature) = value.split_once('.').ok_or_else(invalid)?; + let data = URL_SAFE_NO_PAD.decode(data).map_err(|_| invalid())?; + let signature = URL_SAFE_NO_PAD.decode(signature).map_err(|_| invalid())?; + let mut check = mac(state)?; + check.update(&data); + check.verify_slice(&signature).map_err(|_| invalid())?; + serde_json::from_slice(&data).map_err(|_| invalid()) +} + +/// Execute one incremental read without a manifest or server-side cursor state. +#[tracing::instrument(skip_all, fields(community_id = %tenant.community(), reader = %reader))] +pub(super) async fn query( + state: &Arc, + tenant: &TenantContext, + reader: &nostr::PublicKey, + filter: &Value, +) -> Response { + let _permit = WORK.try_acquire().map_err(|_| unavailable())?; + tokio::time::timeout( + std::time::Duration::from_secs(8), + execute(state, tenant, reader, filter), + ) + .await + .map_err(|_| unavailable())? +} + +async fn execute( + state: &Arc, + tenant: &TenantContext, + reader: &nostr::PublicKey, + filter: &Value, +) -> Response { + let request: Request = serde_json::from_value(filter.clone()).map_err(|_| invalid())?; + if request.artifact != "incremental" + || request.query.get("limit").is_some() + || request.query.get("offset").is_some() + { + return Err(invalid()); + } + let parsed = buzz_core::artifact::parse_query(&request.query).map_err(|_| invalid())?; + let query_binding = URL_SAFE_NO_PAD.encode(Sha256::digest( + serde_json::to_vec(&request.query).map_err(|_| invalid())?, + )); + if parsed.view != ArtifactView::Current { + return Err(invalid()); + } + let (now, policy) = state + .db + .artifact_sync_boundary(tenant.community()) + .await + .map_err(db_error)?; + if request.action.as_deref() == Some("current") { + if request.checkpoint.is_some() || request.cursor.is_some() { + return Err(invalid()); + } + let ids = request.artifact_ids.ok_or_else(invalid)?; + if ids.is_empty() + || ids.len() > PAGE_ROWS + || ids.iter().any(|id| id.is_empty() || id.len() > 256) + || ids.iter().collect::>().len() != ids.len() + { + return Err(invalid()); + } + let valid = ids + .iter() + .filter_map(|id| buzz_core::artifact::canonical_uuid(id).ok()) + .collect::>(); + let resolved = current(state, tenant, reader, &parsed, &valid).await?; + let resolved = resolved + .into_iter() + .filter_map(|value| { + value + .get("artifactId") + .and_then(Value::as_str) + .map(|id| (id.to_owned(), value.clone())) + }) + .collect::>(); + let changes = ids + .iter() + .map(|id| { + resolved + .get(id) + .cloned() + .unwrap_or_else(|| json!({"type":"remove","artifactId":id})) + }) + .collect::>(); + let response = json!({"version":1,"startedAt":now,"changes":changes}); + if serde_json::to_vec(&response) + .map_err(|_| unavailable())? + .len() + > RESPONSE_BYTES + { + return Err(limit()); + } + return Ok(Json(response)); + } + if request.action.is_some() + || request.artifact_ids.is_some() + || (request.checkpoint.is_some() && request.cursor.is_some()) + { + return Err(invalid()); + } + let encoded = request.cursor.as_ref().or(request.checkpoint.as_ref()); + let mut token = if let Some(encoded) = encoded { + let previous = decode(state, encoded)?; + if previous.version != 1 + || previous.community != *tenant.community().as_uuid() + || previous.reader != reader.to_hex() + || previous.query != query_binding + || previous.cursor != request.cursor.is_some() + || previous.at > now + { + return Err(invalid()); + } + if previous.at < now - Duration::days(CHECKPOINT_DAYS) { + return Err(reset("checkpoint_expired")); + } + if previous.policy != policy { + return Err(reset("policy_changed")); + } + if previous.cursor { + previous + } else { + Token { + since: Some(previous.at - Duration::seconds(OVERLAP)), + at: now, + position: None, + cursor: true, + ..previous + } + } + } else { + Token { + version: 1, + community: *tenant.community().as_uuid(), + reader: reader.to_hex(), + query: query_binding, + at: now, + policy, + since: None, + position: None, + cursor: true, + } + }; + let candidates = state + .db + .artifact_sync_candidates( + tenant.community(), + reader.as_bytes(), + token.since, + token.at, + token.position.as_ref(), + &parsed, + ) + .await + .map_err(db_error)?; + let mut selected = candidates.len().min(PAGE_ROWS); + let resolved = loop { + let ids = candidates[..selected] + .iter() + .filter_map(|c| c.artifact_id) + .collect::>() + .into_iter() + .collect::>(); + match current(state, tenant, reader, &parsed, &ids).await { + Err((StatusCode::PAYLOAD_TOO_LARGE, _)) if selected > 1 => selected /= 2, + result => break result?, + } + }; + let more = candidates.len() > selected; + let candidates = &candidates[..selected]; + let resolved = resolved + .into_iter() + .filter_map(|value| { + value + .get("artifactId") + .and_then(Value::as_str) + .map(|id| (id.to_owned(), value.clone())) + }) + .collect::>(); + let mut changes = Vec::new(); + let mut size = 0; + let mut processed = 0; + let mut emitted = HashSet::new(); + for candidate in candidates { + let change = change(candidate, &resolved)?; + let key = change.to_string(); + if !emitted.insert(key) { + token.position = Some(candidate.position.clone()); + processed += 1; + continue; + } + let bytes = serde_json::to_vec(&change) + .map_err(|_| unavailable())? + .len(); + // Leave room for the signed continuation and response fields. + if size + bytes > RESPONSE_BYTES - 262_144 { + if processed == 0 { + return Err(limit()); + } + break; + } + size += bytes; + changes.push(change); + token.position = Some(candidate.position.clone()); + processed += 1; + } + let (_, final_policy) = state + .db + .artifact_sync_boundary(tenant.community()) + .await + .map_err(db_error)?; + if final_policy != token.policy { + return Err(reset("policy_changed")); + } + let more = more || processed < candidates.len(); + let (cursor, checkpoint) = if more { + (Some(encode(state, &token)?), None) + } else { + token.cursor = false; + token.position = None; + token.since = None; + (None, Some(encode(state, &token)?)) + }; + Ok(Json( + json!({"version":1,"startedAt":token.at,"overlapSeconds":OVERLAP, + "changes":changes,"nextCursor":cursor,"checkpoint":checkpoint}), + )) +} + +async fn current( + state: &AppState, + tenant: &TenantContext, + reader: &nostr::PublicKey, + query: &ArtifactQuery, + ids: &[Uuid], +) -> Result, (StatusCode, Json)> { + let events = state + .db + .artifact_sync_current(tenant.community(), reader.as_bytes(), query, ids) + .await + .map_err(db_error)?; + let mut by_id = HashMap::new(); + for stored in events { + let env = buzz_core::artifact::validate(&stored.event).map_err(|_| unavailable())?; + by_id.insert(env.id, stored.event); + } + Ok(ids + .iter() + .map(|id| match by_id.remove(id) { + Some(event) => json!({"type":"upsert","artifactId":id,"event":event}), + None => json!({"type":"remove","artifactId":id}), + }) + .collect()) +} + +fn change( + candidate: &Candidate, + resolved: &HashMap, +) -> Result)> { + if let Some(channel) = candidate.removed_channel { + return Ok(json!({"type":"removeChannel","channelId":channel})); + } + let id = candidate.artifact_id.ok_or_else(unavailable)?; + resolved + .get(&id.to_string()) + .cloned() + .ok_or_else(unavailable) +} + +#[cfg(test)] +pub(super) fn expired_checkpoint_for_test( + state: &AppState, + value: &str, +) -> Result)> { + let mut token = decode(state, value)?; + token.at -= Duration::days(31); + encode(state, &token) +} diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index d5420096efd..2986c35cfbd 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -3,7 +3,10 @@ //! These endpoints provide HTTP access to the relay's Nostr protocol, //! authenticated via NIP-98 signed events. +mod effective_edit; +mod membership_snapshot; mod read_state_snapshot; +pub(crate) mod search_slots; use std::sync::Arc; @@ -18,16 +21,22 @@ use serde_json::Value; use buzz_auth::{LimitType, Nip98ReplayGuard, DEFAULT_REPLAY_TTL_SECS}; use buzz_core::TenantContext; +use crate::access::{AccessSlot, AuthResult}; use crate::handlers::ingest::{IngestAuth, IngestError}; use crate::nip_fi_http::{admit_nip_fi_http_on_state, Nip98Proof}; use crate::state::AppState; -use super::relay_members::MembershipRefusal; -use super::{api_error, db_read_error, internal_error, not_found, parse_query_or_400}; +use super::{ + api_error, db_read_error, internal_error, not_found, parse_query_or_400, search_read_error, +}; mod thread_roots; mod thread_window; +#[cfg(test)] +#[path = "bridge/workflow_webhook_postgres_tests.rs"] +mod workflow_webhook_postgres_tests; + /// Authenticate a relay-owned JSON `POST` endpoint for a community member. /// /// Binds the community from the request host, runs NIP-FI admission over a @@ -36,6 +45,7 @@ mod thread_window; #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers pub(crate) async fn authenticate_member_post( state: &Arc, + slot: &AccessSlot, headers: &HeaderMap, path: &str, body: &[u8], @@ -56,7 +66,9 @@ pub(crate) async fn authenticate_member_post( let admission = admit_nip_fi_http_on_state( state, headers, + slot, make_nip98_closure_for_admission( + slot.clone(), headers.clone(), "POST", expected_url, @@ -66,30 +78,168 @@ pub(crate) async fn authenticate_member_post( ), ) .await?; - let pubkey = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let (event_id_bytes, signed_created_at) = admission.into_extra(); - - enforce_http_admission(state, &tenant, &pubkey) - .await - .map_err(|e| e.into_response())?; - check_nip98_replay(state, &tenant, event_id_bytes) + let mut caller = ProvenCaller::new(admission, slot, &tenant); + caller + .rate_limit_and_replay(state, &tenant) .await - .map_err(|e| e.into_response())?; - super::relay_members::enforce_relay_membership( + .map_err(IntoResponse::into_response)?; + let membership = super::relay_members::enforce_relay_membership( state, &tenant, - &pubkey.to_bytes(), + &caller.pubkey.to_bytes(), super::relay_members::extract_auth_tag_header(headers), - signed_created_at, - token_owner, + caller.signed_at, + caller.token_owner, ) - .await - .map_err(|e| e.into_response())?; + .await; + caller + .admit_member(membership) + .map_err(IntoResponse::into_response)?; + let pubkey = caller.pubkey; Ok((tenant, pubkey)) } +/// A caller whose NIP-98 proof (and enterprise assertion, when enforced) +/// passed, before the shared rate limit, replay guard and relay membership +/// decide whether it is admitted, recorded on the request's access note. +pub(crate) struct ProvenCaller { + pub(crate) pubkey: nostr::PublicKey, + event_id_bytes: [u8; 32], + pub(crate) signed_at: Option, + /// The owner named by a verified agent token (Enforce only). + pub(crate) token_owner: Option, + slot: AccessSlot, +} + +impl ProvenCaller { + /// The caller from a NIP-98 admission whose proof closure returned the + /// proof's event id and its signed `created_at`. + pub(crate) fn new( + admission: crate::nip_fi_http::NipFiAdmission<([u8; 32], Option)>, + slot: &AccessSlot, + tenant: &TenantContext, + ) -> Self { + slot.in_community(tenant.community()); + let (pubkey, token_owner) = (*admission.proven_pubkey(), admission.token_owner()); + let (event_id_bytes, signed_at) = admission.into_extra(); + Self { + pubkey, + event_id_bytes, + signed_at, + token_owner, + slot: slot.clone(), + } + } + + /// Record the filters the request reads. + pub(crate) fn read(&self, filters: &[nostr::Filter]) { + self.slot.read(filters); + } + + /// Record what an artifact read covered. Only the standard dimensions + /// of each raw filter are summarized; every other predicate (artifact + /// or client-defined tags) only narrows the read, so it is dropped + /// before parsing and cannot cancel the summary. A filter whose standard + /// dimensions do not parse leaves the line without a summary. An + /// incremental read is summarized by the query it wraps. Skipped below + /// WARN, the level a failed or aborted request logs at. + fn read_artifact(&self, raw: &[Value]) { + const SUMMARIZED: [&str; 9] = [ + "kinds", "authors", "ids", "#h", "#p", "since", "until", "limit", "search", + ]; + if !tracing::enabled!(target: crate::access::TARGET, tracing::Level::WARN) { + return; + } + let standard = |v: &Value| -> Value { + let v = match v.get("artifact").and_then(Value::as_str) { + Some("incremental") => v.get("query").unwrap_or(v), + _ => v, + }; + let mut kept = serde_json::Map::new(); + if let Some(obj) = v.as_object() { + for key in SUMMARIZED { + if let Some(x) = obj.get(key) { + kept.insert(key.to_owned(), x.clone()); + } + } + } + Value::Object(kept) + }; + if let Ok(filters) = raw + .iter() + .map(|v| serde_json::from_value::(standard(v))) + .collect::, _>>() + { + self.slot.read(&filters); + } + } + + /// Record what the request did. + pub(crate) fn complete(&self, detail: crate::access::Detail) { + self.slot.detail(detail); + } + + /// The shared API rate limit, then the replay guard. A refusal is logged. + pub(crate) async fn rate_limit_and_replay( + &mut self, + state: &AppState, + tenant: &TenantContext, + ) -> Result<(), (StatusCode, Json)> { + self.slot.gate( + enforce_http_admission(state, tenant, &self.pubkey).await, + admission_refusal, + )?; + self.replay(state, tenant).await + } + + /// The replay guard alone, for routes outside the shared rate limit. + pub(crate) async fn replay( + &mut self, + state: &AppState, + tenant: &TenantContext, + ) -> Result<(), (StatusCode, Json)> { + self.slot + .gate( + check_nip98_replay(state, tenant, self.event_id_bytes).await, + ReplayRejection::auth_result, + ) + .map_err(Into::into) + } + + /// The result of an intermediate admission step: logs only a refusal. + pub(crate) fn check( + &mut self, + step: Result, + refusal: impl FnOnce(&E) -> AuthResult, + ) -> Result { + self.slot.gate(step, refusal) + } + + /// The result of the route's last admission step (relay membership and + /// ban): logs the request's final auth decision either way. + pub(crate) fn admit( + &mut self, + last_step: Result, + refusal: impl FnOnce(&E) -> AuthResult, + ) -> Result { + let admitted = self.slot.gate(last_step, refusal)?; + self.slot.finish(AuthResult::Success); + Ok(admitted) + } + + /// [`Self::admit`] for the relay membership and ban check. + pub(crate) fn admit_member( + &mut self, + membership: Result, + ) -> Result { + self.admit( + membership, + super::relay_members::MembershipRefusal::auth_result, + ) + } +} + pub(crate) async fn enforce_http_admission( state: &AppState, tenant: &TenantContext, @@ -156,16 +306,18 @@ type BridgeAuthResult = Result)>; /// (explicitly-named exempt paths), or the `pub(crate)` form below for /// git-settings and other crate-local specialized handlers. pub(crate) fn verify_bridge_auth( + slot: &AccessSlot, headers: &HeaderMap, method: &str, url: &str, body: Option<&[u8]>, require_auth_token: bool, ) -> BridgeAuthResult { - verify_bridge_auth_with_options(headers, method, url, body, require_auth_token, false) + verify_bridge_auth_with_options(slot, headers, method, url, body, require_auth_token, false) } pub(crate) fn verify_bridge_auth_with_options( + slot: &AccessSlot, headers: &HeaderMap, method: &str, url: &str, @@ -173,6 +325,63 @@ pub(crate) fn verify_bridge_auth_with_options( require_auth_token: bool, require_payload: bool, ) -> BridgeAuthResult { + check_bridge_proof( + headers, + method, + url, + body, + require_auth_token, + require_payload, + ) + .map_err(|rejected| { + slot.attempt(crate::access::AuthMethod::Nip98, rejected.claimed, false); + slot.finish(crate::access::AuthResult::Failed(rejected.reason)); + api_error(StatusCode::UNAUTHORIZED, &rejected.message) + }) +} + +/// [`verify_bridge_auth_with_options`] without the access line, for shadow +/// observation re-checking a proof the request's real admission also checks. +pub(crate) fn bridge_strict_proof( + headers: &HeaderMap, + method: &str, + url: &str, + body: Option<&[u8]>, + require_payload: bool, +) -> Result<(), ()> { + check_bridge_proof(headers, method, url, body, true, require_payload) + .map(drop) + .map_err(drop) +} + +/// Why a bridge proof was rejected: a fixed `reason` code for the access log, +/// the pubkey the proof claimed (unverified), and the client-facing message. +struct BridgeRejection { + reason: &'static str, + claimed: Option, + message: String, +} + +fn rejected( + reason: &'static str, + claimed: Option, + message: impl Into, +) -> BridgeRejection { + BridgeRejection { + reason, + claimed, + message: message.into(), + } +} + +fn check_bridge_proof( + headers: &HeaderMap, + method: &str, + url: &str, + body: Option<&[u8]>, + require_auth_token: bool, + require_payload: bool, +) -> Result { // Try NIP-98 first (Authorization: Nostr ) // // Cardinality is enforced at the NIP-FI admission boundary @@ -188,14 +397,15 @@ pub(crate) fn verify_bridge_auth_with_options( use base64::engine::general_purpose::STANDARD as BASE64; let bytes = BASE64 .decode(auth_str) - .map_err(|_| api_error(StatusCode::UNAUTHORIZED, "invalid base64 in Nostr auth"))?; + .map_err(|_| rejected("invalid_encoding", None, "invalid base64 in Nostr auth"))?; String::from_utf8(bytes) - .map_err(|_| api_error(StatusCode::UNAUTHORIZED, "invalid UTF-8 in Nostr auth"))? + .map_err(|_| rejected("invalid_encoding", None, "invalid UTF-8 in Nostr auth"))? }; let event: nostr::Event = serde_json::from_str(&event_json) - .map_err(|_| api_error(StatusCode::UNAUTHORIZED, "invalid NIP-98 event JSON"))?; + .map_err(|_| rejected("invalid_event", None, "invalid NIP-98 event JSON"))?; let event_id_bytes = event.id.to_bytes(); + let claimed = Some(event.pubkey); if require_payload && !event @@ -203,14 +413,21 @@ pub(crate) fn verify_bridge_auth_with_options( .iter() .any(|tag| tag.kind() == nostr::TagKind::Payload) { - return Err(api_error( - StatusCode::UNAUTHORIZED, + return Err(rejected( + "missing_payload", + claimed, "NIP-98: missing payload tag", )); } - let pubkey = buzz_auth::verify_nip98_event(&event_json, url, method, body) - .map_err(|e| api_error(StatusCode::UNAUTHORIZED, &format!("NIP-98: {e}")))?; + let pubkey = + buzz_auth::verify_nip98_event(&event_json, url, method, body).map_err(|e| { + rejected( + crate::access::auth_error_code(&e), + claimed, + format!("NIP-98: {e}"), + ) + })?; return Ok(VerifiedBridgeAuth { pubkey, @@ -223,7 +440,7 @@ pub(crate) fn verify_bridge_auth_with_options( if !require_auth_token { if let Some(hex_val) = headers.get("x-pubkey").and_then(|v| v.to_str().ok()) { let pubkey = nostr::PublicKey::from_hex(hex_val) - .map_err(|_| api_error(StatusCode::UNAUTHORIZED, "invalid X-Pubkey hex"))?; + .map_err(|_| rejected("invalid_x_pubkey", None, "invalid X-Pubkey hex"))?; // Zero event ID — no replay detection needed for dev mode return Ok(VerifiedBridgeAuth { pubkey, @@ -233,7 +450,7 @@ pub(crate) fn verify_bridge_auth_with_options( } } - Err(api_error(StatusCode::UNAUTHORIZED, "missing Nostr auth")) + Err(rejected("missing_auth", None, "missing Nostr auth")) } // ── NIP-FI Authority boundary ───────────────────────────────────────────────── @@ -270,6 +487,7 @@ pub(crate) fn verify_bridge_auth_with_options( #[allow(clippy::result_large_err)] #[allow(clippy::type_complexity)] // The return type IS the admission closure contract; a type alias cannot name impl Trait pub(crate) fn make_nip98_closure_for_admission( + slot: AccessSlot, headers: HeaderMap, method: &'static str, url: String, @@ -280,6 +498,7 @@ pub(crate) fn make_nip98_closure_for_admission( { move || { verify_bridge_auth_with_options( + &slot, &headers, method, &url, @@ -298,13 +517,14 @@ pub(crate) fn make_nip98_closure_for_admission( /// structurally outside the NIP-FI state machine. This function makes the /// exemption nameable and greppable. [FI-TRACE-AUTHORITY-EXEMPT] pub(crate) fn verify_nip98_exempt_invite_claim( + slot: &AccessSlot, headers: &HeaderMap, method: &str, url: &str, body: Option<&[u8]>, ) -> BridgeAuthResult { verify_bridge_auth_with_options( - headers, method, url, body, + slot, headers, method, url, body, true, // invite-claim always requires NIP-98; no X-Pubkey dev fallback true, // POST bodies must be covered by a payload tag ) @@ -315,12 +535,14 @@ pub(crate) fn verify_nip98_exempt_invite_claim( /// Operator endpoints use a separate auth origin and are structurally outside /// the per-tenant NIP-FI state machine. [FI-TRACE-AUTHORITY-EXEMPT] pub(crate) fn verify_nip98_exempt_operator( + slot: &AccessSlot, headers: &HeaderMap, method: &str, url: &str, body: Option<&[u8]>, ) -> BridgeAuthResult { verify_bridge_auth_with_options( + slot, headers, method, url, @@ -330,7 +552,9 @@ pub(crate) fn verify_nip98_exempt_operator( ) } -/// Check NIP-98 replay and record the event ID atomically. +/// Check NIP-98 replay and record the event ID atomically. Logs nothing: +/// replay is never the last admission step on its own, so the caller records +/// the request's final decision on its [`AccessSlot`](crate::access::AccessSlot). /// /// The correctness boundary is the shared, community-scoped Redis seen-set on /// `AppState`, not process-local memory. Any Redis/guard error fails closed: @@ -340,15 +564,58 @@ pub(crate) async fn check_nip98_replay( state: &AppState, tenant: &TenantContext, event_id_bytes: [u8; 32], -) -> Result<(), (StatusCode, Json)> { +) -> Result<(), ReplayRejection> { check_nip98_replay_with_guard(state.nip98_replay.as_ref(), tenant, event_id_bytes).await } +/// Why the replay check refused a proof. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum ReplayRejection { + Replayed, + Unavailable, +} + +impl ReplayRejection { + /// The access-log result for this refusal. + pub(crate) fn auth_result(&self) -> crate::access::AuthResult { + match self { + Self::Replayed => crate::access::AuthResult::Failed("nip98_replay"), + Self::Unavailable => { + crate::access::AuthResult::Denied(crate::access::AuthReason::ReplayCheckUnavailable) + } + } + } +} + +impl From for (StatusCode, Json) { + fn from(rejection: ReplayRejection) -> Self { + let message = match rejection { + ReplayRejection::Replayed => "NIP-98: replay detected", + ReplayRejection::Unavailable => "NIP-98: replay check unavailable", + }; + api_error(StatusCode::UNAUTHORIZED, message) + } +} + +impl IntoResponse for ReplayRejection { + fn into_response(self) -> Response { + <(StatusCode, Json)>::from(self).into_response() + } +} + +/// The access-log result for a refusal from [`enforce_http_admission`]. +pub(crate) fn admission_refusal(e: &(StatusCode, Json)) -> crate::access::AuthResult { + crate::access::AuthResult::Denied(match e.0 { + StatusCode::TOO_MANY_REQUESTS => crate::access::AuthReason::QuotaExceeded, + _ => crate::access::AuthReason::AdmissionUnavailable, + }) +} + async fn check_nip98_replay_with_guard( replay_guard: &dyn Nip98ReplayGuard, tenant: &TenantContext, event_id_bytes: [u8; 32], -) -> Result<(), (StatusCode, Json)> { +) -> Result<(), ReplayRejection> { // Skip replay detection for dev-mode X-Pubkey auth (zero hash). if event_id_bytes == [0u8; 32] { return Ok(()); @@ -360,20 +627,14 @@ async fn check_nip98_replay_with_guard( .await { Ok(true) => Ok(()), - Ok(false) => Err(api_error( - StatusCode::UNAUTHORIZED, - "NIP-98: replay detected", - )), + Ok(false) => Err(ReplayRejection::Replayed), Err(e) => { tracing::warn!( community = %tenant.community(), error = %e, "NIP-98 replay guard failed; rejecting request fail-closed" ); - Err(api_error( - StatusCode::UNAUTHORIZED, - "NIP-98: replay check unavailable", - )) + Err(ReplayRejection::Unavailable) } } } @@ -451,7 +712,7 @@ fn extract_channel_from_filter(filter: &nostr::Filter) -> Option { // Nostr filter JSON. nostr::Filter silently drops unknown fields during // deserialization, so we extract them from the raw JSON Value first. -const BRIDGE_FEED_MAX_LIMIT: i64 = 100; +const BRIDGE_FEED_MAX_LIMIT: u32 = 100; const BRIDGE_THREAD_MAX_LIMIT: u32 = 500; /// The `before_id` extension field, with "present but malformed" kept distinct @@ -804,11 +1065,12 @@ async fn handle_channel_window_filter( } }; - let limit = filter - .limit - .map(|l| (l as u32).min(BRIDGE_WINDOW_MAX_LIMIT)) - .unwrap_or(BRIDGE_WINDOW_DEFAULT_LIMIT) - .max(1); + let limit = buzz_core::filter::clamp_limit( + filter.limit, + BRIDGE_WINDOW_DEFAULT_LIMIT, + BRIDGE_WINDOW_MAX_LIMIT, + ) + .max(1); let kind_filter: Option> = filter .kinds .as_ref() @@ -824,7 +1086,7 @@ async fn handle_channel_window_filter( kind_filter.as_deref(), ) .await - .map_err(|e| internal_error(&format!("channel window error: {e}")))?; + .map_err(|e| db_read_error("channel window error", &e))?; // 1. Rows, in keyset order. let mut row_ids_hex = Vec::with_capacity(window.rows.len()); @@ -949,32 +1211,32 @@ fn event_in_accessible_channel(se: &buzz_core::StoredEvent, accessible: &[uuid:: } } -/// Hard cap on the `reason` field logged for a rejected `/events` request. -/// -/// The reject message can embed event-controlled content (e.g. a submitted -/// channel's `visibility`/`channel_type` tag values, or a raw tag pubkey) — -/// attacker-controlled text that must never reach Datadog unbounded. -const REJECT_REASON_MAX_BYTES: usize = 256; - -/// Truncate `s` to at most `max_bytes`, cutting at the nearest UTF-8 character -/// boundary so a multi-byte codepoint straddling the cutoff is never split. -/// Bounds attacker-controlled text before it enters a structured log line — -/// the line's size must stay bounded regardless of the triggering input size. -fn truncate_reason(s: &str, max_bytes: usize) -> &str { - if s.len() <= max_bytes { - return s; - } - let mut end = max_bytes; - while !s.is_char_boundary(end) { - end -= 1; - } - &s[..end] +/// The fixed code logged for a rejected `/events` write: the NIP-01 prefix +/// that leads the rejection message (`invalid`, `blocked`, ...), never the +/// text after it, which can quote event-controlled tag values. +fn reject_code(msg: &str) -> &'static str { + const PREFIXES: [&str; 8] = [ + "invalid", + "blocked", + "restricted", + "duplicate", + "pow", + "rate-limited", + "auth-required", + "error", + ]; + let prefix = msg.split([':', ' ']).next().unwrap_or_default(); + PREFIXES + .into_iter() + .find(|p| *p == prefix) + .unwrap_or("rejected") } /// Submit a signed Nostr event via HTTP bridge (NIP-98 auth). #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers pub async fn submit_event( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result { @@ -997,107 +1259,46 @@ pub async fn submit_event( // In NIP-FI enforce/deny-protected mode, a real NIP-98 event is mandatory — // the X-Pubkey dev-mode fallback must never satisfy the pairing requirement. // [NIP-FI.md:594-607, FI-TRACE-HTTP-INGRESS] - let nip_fi_active = state.config.nip_fi.mode.restricts(); + let nip_fi_active = crate::nip_fi_policy::mode(&state, &headers) + .await + .restricts(); // POST /events carries an authorization-relevant body (the event determines // resource, effect, and state change), so a payload tag is required in // NIP-FI enforce mode. [NIP-FI.md:619-637] - let nip_fi_enforce = state.config.nip_fi.mode.enforces(); + let nip_fi_enforce = crate::nip_fi_policy::mode(&state, &headers) + .await + .enforces(); // NIP-FI admission: NIP-98 extraction runs inside the closure, followed by // assertion verify → pair → deny-map in fixed order. The proven pubkey is // only available through the returned NipFiAdmission. [FI-TRACE-AUTHORITY-UNIFORM] + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "bridge", || { - verify_bridge_auth_with_options(&headers, "POST", &url, Some(&body), true, true).map(drop) + bridge_strict_proof(&headers, "POST", &url, Some(&body), true) }) .await; - let admission = admit_nip_fi_http_on_state(&state, &headers, || { - verify_bridge_auth_with_options( - &headers, - "POST", - &url, - Some(&body), - state.config.require_auth_token || nip_fi_active, - nip_fi_enforce, - ) - .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) - .map_err(|e| e.into_response()) + let admission = admit_nip_fi_http_on_state(&state, &headers, &slot, || { + proof + .record(verify_bridge_auth_with_options( + &slot, + &headers, + "POST", + &url, + Some(&body), + state.config.require_auth_token || nip_fi_active, + nip_fi_enforce, + )) + .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) + .map_err(|e| e.into_response()) }) .await?; - let pubkey = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let (event_id_bytes, signed_created_at) = admission.into_extra(); - let pubkey_hex = pubkey.to_hex(); + let mut caller = ProvenCaller::new(admission, &slot, &tenant); // Everything after auth — admission, replay, membership, parse, ingest — - // runs inside the helper. The thin wrapper here owns the single terminal - // attribution line so it fires for every outcome, including admission/ - // replay/membership failures that previously returned before any log fired. - let outcome = submit_event_authed( - &state, - &tenant, - &headers, - &body, - pubkey, - event_id_bytes, - signed_created_at, - token_owner, - ) - .await; - - match &outcome { - SubmitOutcome::Ok { accepted, kind, .. } => { - tracing::info!( - pubkey = %pubkey_hex, - route = "/events", - status = 200u16, - accepted, - kind, - "HTTP bridge request" - ); - } - SubmitOutcome::ParseFail { - category, - line, - column, - .. - } => { - tracing::warn!( - pubkey = %pubkey_hex, - route = "/events", - status = 400u16, - accepted = false, - category, - line, - column, - "HTTP bridge request" - ); - } - SubmitOutcome::Rejected { - kind, - reason, - response, - } => { - tracing::warn!( - pubkey = %pubkey_hex, - route = "/events", - status = response.0.as_u16(), - accepted = false, - kind, - reason = %reason, - "HTTP bridge request" - ); - } - SubmitOutcome::Err { status, .. } => { - tracing::warn!( - pubkey = %pubkey_hex, - route = "/events", - status = status.as_u16(), - accepted = false, - "HTTP bridge request" - ); - } - } - + // runs inside the helper; the caller's access line is the request's one + // line, covering every outcome including a refused login. + let outcome = submit_event_authed(&state, &tenant, &headers, &body, &mut caller).await; + caller.complete(outcome.fields()); Ok(outcome.into_response().into_response()) } @@ -1110,6 +1311,7 @@ enum SubmitOutcome { Ok { accepted: bool, kind: u32, + event_id: String, response: Json, }, /// JSON parse failure before ingest — log category/line/column, not msg. @@ -1125,23 +1327,61 @@ enum SubmitOutcome { /// The logged `status` reflects the actual response status carried in `response`. Rejected { kind: u32, - reason: String, + reason: &'static str, response: (StatusCode, Json), }, /// Any other error (admission, replay, membership, auth, internal) — /// only the HTTP status is logged; the response body is returned as-is. - Err { - status: StatusCode, - response: MembershipRefusal, - }, + Err { response: Response }, } impl SubmitOutcome { - fn into_response(self) -> Result, MembershipRefusal> { + /// What the request's access line records about this outcome. + fn fields(&self) -> crate::access::Detail { + use crate::access::Detail; + match self { + SubmitOutcome::Ok { + accepted, + kind, + event_id, + .. + } => Detail { + accepted: Some(*accepted), + kind: Some(*kind), + event_id: Some(event_id.clone()), + ..Detail::default() + }, + SubmitOutcome::ParseFail { + category, + line, + column, + .. + } => Detail { + accepted: Some(false), + category: Some(category), + line: Some(*line), + column: Some(*column), + ..Detail::default() + }, + SubmitOutcome::Rejected { kind, reason, .. } => Detail { + accepted: Some(false), + kind: Some(*kind), + reject_reason: Some(reason), + ..Detail::default() + }, + SubmitOutcome::Err { .. } => Detail { + accepted: Some(false), + ..Detail::default() + }, + } + } + + #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers + fn into_response(self) -> Result, Response> { match self { SubmitOutcome::Ok { response, .. } => Ok(response), - SubmitOutcome::ParseFail { response, .. } => Err(response.into()), - SubmitOutcome::Rejected { response, .. } => Err(response.into()), + SubmitOutcome::ParseFail { response, .. } => Err(response.into_response()), + SubmitOutcome::Rejected { response, .. } => Err(response.into_response()), SubmitOutcome::Err { response, .. } => Err(response), } } @@ -1157,25 +1397,17 @@ async fn submit_event_authed( tenant: &TenantContext, headers: &HeaderMap, body: &[u8], - pubkey: nostr::PublicKey, - event_id_bytes: [u8; 32], - signed_auth_created_at: Option, - token_owner: Option, + caller: &mut ProvenCaller, ) -> SubmitOutcome { // Admission and replay checks fire before body parse — a 429 or replay // reject on a malformed body must still be attributed. - if let Err(e) = enforce_http_admission(state, tenant, &pubkey).await { + if let Err(e) = caller.rate_limit_and_replay(state, tenant).await { return SubmitOutcome::Err { - status: e.0, - response: e.into(), - }; - } - if let Err(e) = check_nip98_replay(state, tenant, event_id_bytes).await { - return SubmitOutcome::Err { - status: e.0, - response: e.into(), + response: e.into_response(), }; } + let (pubkey, signed_auth_created_at, token_owner) = + (caller.pubkey, caller.signed_at, caller.token_owner); let pubkey_bytes = pubkey.to_bytes().to_vec(); let event: nostr::Event = match serde_json::from_slice(body) { @@ -1206,31 +1438,17 @@ async fn submit_event_authed( let is_typing = kind_u32 == buzz_core::kind::KIND_TYPING_INDICATOR; // Enforce relay membership (with NIP-OA fallback via x-auth-tag header). - // Typing pulses arrive every few seconds per working agent, so their ban - // check uses the same short-TTL cache as their write-restriction check. let auth_tag = super::relay_members::extract_auth_tag_header(headers); - let membership = if is_typing { - super::relay_members::enforce_relay_membership_ephemeral( - state, - tenant, - &pubkey_bytes, - auth_tag, - signed_auth_created_at, - token_owner, - ) - .await - } else { - super::relay_members::enforce_relay_membership( - state, - tenant, - &pubkey_bytes, - auth_tag, - signed_auth_created_at, - token_owner, - ) - .await - }; - let nip_oa_owner = match membership { + let membership = super::relay_members::enforce_relay_membership( + state, + tenant, + &pubkey_bytes, + auth_tag, + signed_auth_created_at, + token_owner, + ) + .await; + let nip_oa_owner = match caller.admit_member(membership) { Ok(owner) => owner.or_else(|| { if !state.config.require_relay_membership { super::relay_members::extract_nip_oa_owner( @@ -1244,8 +1462,7 @@ async fn submit_event_authed( }), Err(e) => { return SubmitOutcome::Err { - status: e.status(), - response: e, + response: e.into_response(), }; } }; @@ -1278,18 +1495,26 @@ async fn submit_event_authed( // token-less request, keeps its existing response. let result = match result { Err(IngestError::Ban { refusal, .. }) if token_owner.is_some() => { + use crate::handlers::{auth::BanSource, ingest::BanRefusal}; crate::handlers::ingest::reject_with_transport("http", "auth"); - let refusal = MembershipRefusal::NipFi(match refusal { - crate::handlers::ingest::BanRefusal::Banned => { - buzz_auth::DenialClass::AuthorizationDenied + let class = match refusal { + BanRefusal::Banned(_) => buzz_auth::DenialClass::AuthorizationDenied, + BanRefusal::Unavailable => buzz_auth::DenialClass::AuthorizationUnavailable, + }; + // An owner-decided late refusal is the request's verdict, not its + // earlier admit. The agent's own ban is not its owner's, as at + // every other seam. + match refusal { + BanRefusal::Banned(BanSource::Owner) => { + crate::nip_fi_http::owner_refused(class, "owner_banned"); } - crate::handlers::ingest::BanRefusal::Unavailable => { - buzz_auth::DenialClass::AuthorizationUnavailable + BanRefusal::Unavailable => { + crate::nip_fi_http::owner_refused(class, "owner_ban_unavailable"); } - }); + BanRefusal::Banned(BanSource::Own) => {} + } return SubmitOutcome::Err { - status: refusal.status(), - response: refusal, + response: crate::nip_fi_core::http_denial(class), }; } other => other.map_err(IngestError::into_legacy), @@ -1298,22 +1523,21 @@ async fn submit_event_authed( match result { Ok(result) => { let response = Json(serde_json::json!({ - "event_id": result.event_id, + "event_id": &result.event_id, "accepted": result.accepted, "message": result.message, })); SubmitOutcome::Ok { accepted: result.accepted, kind: kind_u32, + event_id: result.event_id, response, } } Err(IngestError::Rejected(msg)) => { - // `msg` can embed event-controlled content (e.g. a channel - // create's raw `visibility`/`channel_type` tag values, or a raw - // tag pubkey) — truncate before logging, but return the full msg - // in the HTTP response body (unchanged from prior behaviour). - let reason = truncate_reason(&msg, REJECT_REASON_MAX_BYTES).to_owned(); + // `msg` can quote event-controlled tag values: the log gets only + // its fixed prefix code, the response body the full message. + let reason = reject_code(&msg); crate::handlers::ingest::reject_with_transport("http", "invalid"); SubmitOutcome::Rejected { kind: kind_u32, @@ -1326,7 +1550,7 @@ async fn submit_event_authed( // CLI's reconciliation branch (which gates on `status == 409`) is // reachable against the live relay. The message body is unchanged; // the desktop TypeScript layer matches on message text, not status. - let reason = truncate_reason(&msg, REJECT_REASON_MAX_BYTES).to_owned(); + let reason = "canvas_conflict"; crate::handlers::ingest::reject_with_transport("http", "invalid"); SubmitOutcome::Rejected { kind: kind_u32, @@ -1338,8 +1562,7 @@ async fn submit_event_authed( crate::handlers::ingest::reject_with_transport("http", "auth"); let e = api_error(StatusCode::FORBIDDEN, &msg); SubmitOutcome::Err { - status: e.0, - response: e.into(), + response: e.into_response(), } } // `into_legacy` never returns `Ban`; it would fail closed here. @@ -1347,16 +1570,14 @@ async fn submit_event_authed( crate::handlers::ingest::reject_with_transport("http", "error"); let e = internal_error("ban refusal reached the legacy mapping"); SubmitOutcome::Err { - status: e.0, - response: e.into(), + response: e.into_response(), } } Err(IngestError::Internal(msg)) => { crate::handlers::ingest::reject_with_transport("http", "error"); let e = internal_error(&msg); SubmitOutcome::Err { - status: e.0, - response: e.into(), + response: e.into_response(), } } } @@ -1368,6 +1589,7 @@ async fn submit_event_authed( #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers pub async fn query_events( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result { @@ -1390,71 +1612,60 @@ pub async fn query_events( let url = nip98_expected_url(&state.config.relay_url, &tenant, "/query"); // In NIP-FI enforce/deny-protected mode, a real NIP-98 event is mandatory. // [NIP-FI.md:594-607, FI-TRACE-HTTP-INGRESS] - let nip_fi_active = state.config.nip_fi.mode.restricts(); + let nip_fi_active = crate::nip_fi_policy::mode(&state, &headers) + .await + .restricts(); // POST /query carries an authorization-relevant body (filter selects the // resources returned), so a payload tag is required in enforce mode. // [NIP-FI.md:619-637] - let nip_fi_enforce = state.config.nip_fi.mode.enforces(); + let nip_fi_enforce = crate::nip_fi_policy::mode(&state, &headers) + .await + .enforces(); + + // This authority surface always needs payload-bound NIP-98, including dev. + // Detect before admission, and before Filter can drop the extension key. + let compact_membership = serde_json::from_slice::>(&body) + .is_ok_and(|filters| membership_snapshot::requested(&filters)); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "bridge", || { - verify_bridge_auth_with_options(&headers, "POST", &url, Some(&body), true, true).map(drop) + bridge_strict_proof(&headers, "POST", &url, Some(&body), true) }) .await; - let admission = admit_nip_fi_http_on_state(&state, &headers, || { - verify_bridge_auth_with_options( - &headers, - "POST", - &url, - Some(&body), - state.config.require_auth_token || nip_fi_active, - nip_fi_enforce, - ) - .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) - .map_err(|e| e.into_response()) + let admission = admit_nip_fi_http_on_state(&state, &headers, &slot, || { + proof + .record(verify_bridge_auth_with_options( + &slot, + &headers, + "POST", + &url, + Some(&body), + state.config.require_auth_token || nip_fi_active || compact_membership, + nip_fi_enforce || compact_membership, + )) + .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) + .map_err(|e| e.into_response()) }) .await?; - let pubkey = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let (event_id_bytes, signed_created_at) = admission.into_extra(); - let pubkey_hex = pubkey.to_hex(); + let mut caller = ProvenCaller::new(admission, &slot, &tenant); // Admission, replay, membership, and filter execution all run inside the - // helper. The single terminal attribution line fires here from the Result - // so every outcome — including admission/replay/membership failures that - // previously returned before any log — is attributed. - let result = query_events_authed( - &state, - &tenant, - &headers, - &body, - pubkey, - event_id_bytes, - signed_created_at, - token_owner, - ) - .await; - match &result { - Ok(Json(Value::Array(events))) => { - tracing::info!( - pubkey = %pubkey_hex, - route = "/query", - status = 200u16, - result_count = events.len(), - "HTTP bridge request" - ); - } - Ok(_) => { - tracing::info!(pubkey = %pubkey_hex, route = "/query", status = 200u16, "HTTP bridge request"); - } - Err(refusal) => { - tracing::warn!( - pubkey = %pubkey_hex, - route = "/query", - status = refusal.status().as_u16(), - "HTTP bridge request" - ); - } + // helper; the caller's access line is the request's one line, covering + // every outcome including a refused login. + let result = query_events_authed(&state, &tenant, &headers, &body, &mut caller).await; + // A generic or artifact read returns its events; an incremental read + // returns `{changes: [...]}`, removals included. + let returned = match &result { + Ok(Json(Value::Array(events))) => Some(events.len()), + Ok(Json(value)) => value.get("changes").and_then(Value::as_array).map(Vec::len), + Err(_) => None, + }; + if let Some(n) = returned { + caller.complete(crate::access::Detail { + result_count: Some(n as u64), + ..Default::default() + }); } Ok(result.into_response()) } @@ -1463,32 +1674,38 @@ pub async fn query_events( /// Handles admission, replay, membership, and all filter paths so the thin /// wrapper above can emit exactly one terminal attribution line from the Result. #[allow(clippy::too_many_arguments)] +#[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn query_events_authed( state: &Arc, tenant: &TenantContext, headers: &HeaderMap, body: &[u8], - pubkey: nostr::PublicKey, - event_id_bytes: [u8; 32], - signed_auth_created_at: Option, - token_owner: Option, -) -> Result, MembershipRefusal> { - enforce_http_admission(state, tenant, &pubkey).await?; - check_nip98_replay(state, tenant, event_id_bytes).await?; + caller: &mut ProvenCaller, +) -> Result, Response> { + caller + .rate_limit_and_replay(state, tenant) + .await + .map_err(IntoResponse::into_response)?; + let pubkey = caller.pubkey; let pubkey_bytes = pubkey.to_bytes().to_vec(); let auth_tag = super::relay_members::extract_auth_tag_header(headers); - super::relay_members::enforce_relay_membership( + let membership = super::relay_members::enforce_relay_membership( state, tenant, &pubkey_bytes, auth_tag, - signed_auth_created_at, - token_owner, + caller.signed_at, + caller.token_owner, ) - .await?; + .await; + caller + .admit_member(membership) + .map_err(IntoResponse::into_response)?; - Ok(query_member_events(state, tenant, body, pubkey).await?) + query_member_events(state, tenant, body, caller) + .await + .map_err(IntoResponse::into_response) } /// The rest of [`query_events_authed`], once the caller is admitted as a relay member. @@ -1496,14 +1713,28 @@ async fn query_member_events( state: &Arc, tenant: &TenantContext, body: &[u8], - pubkey: nostr::PublicKey, + caller: &ProvenCaller, ) -> Result, (StatusCode, Json)> { + let pubkey = caller.pubkey; let pubkey_bytes = pubkey.to_bytes().to_vec(); // Two-pass parse: preserve raw JSON for custom extension fields (before_id, // depth_limit, feed_types) that nostr::Filter silently drops. let raw_filters: Vec = serde_json::from_slice(body) .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid filters: {e}")))?; - if let Some(result) = super::artifact::query(state, tenant, &pubkey, &raw_filters, false).await + if membership_snapshot::requested(&raw_filters) { + caller.read_artifact(&raw_filters); + return membership_snapshot::query( + state, + tenant, + &pubkey, + caller.event_id_bytes, + &raw_filters, + ) + .await; + } + let routed = || caller.read_artifact(&raw_filters); + if let Some(result) = + super::artifact::query(state, tenant, &pubkey, &raw_filters, false, routed).await { return result; } @@ -1513,6 +1744,7 @@ async fn query_member_events( .map(|v| serde_json::from_value(v.clone())) .collect::>() .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid filters: {e}")))?; + caller.read(&filters); crate::handlers::req::extract_channel_ids_from_filters_limited(&filters) .map_err(|()| api_error(StatusCode::BAD_REQUEST, "too many explicit channels"))?; @@ -1558,6 +1790,9 @@ async fn query_member_events( })? .map(|events| Json(Value::Array(events))); } + if effective_edit::requested(&raw_filters) { + return effective_edit::query(state, tenant, &pubkey, &raw_filters).await; + } if read_state_snapshot::requested(&raw_filters) { return read_state_snapshot::query(state, tenant, &pubkey, &raw_filters).await; } @@ -1598,7 +1833,7 @@ async fn query_member_events( "mixed search and non-search filters not supported", )); } - return handle_bridge_search( + let search = handle_bridge_search( state, &raw_filters, &filters, @@ -1607,8 +1842,12 @@ async fn query_member_events( tenant, &authed_pubkey_hex, &pubkey_bytes, - ) - .await; + ); + return state + .search_slots + .run(tenant.community(), pubkey.to_bytes(), search) + .await + .unwrap_or_else(|superseded| Err(superseded.into())); } if let Some(presence_result) = @@ -1677,10 +1916,11 @@ async fn query_member_events( None => continue, }; - let limit = filter - .limit - .map(|l| (l as i64).min(BRIDGE_FEED_MAX_LIMIT)) - .unwrap_or(20); + let limit = i64::from(buzz_core::filter::clamp_limit( + filter.limit, + 20, + BRIDGE_FEED_MAX_LIMIT, + )); let since = filter .since .and_then(|s| chrono::DateTime::from_timestamp(s.as_secs() as i64, 0)); @@ -1713,7 +1953,7 @@ async fn query_member_events( remaining, ) .await - .map_err(|e| internal_error(&format!("feed mentions error: {e}")))?, + .map_err(|e| db_read_error("feed mentions error", &e))?, "needs_action" => state .db .query_feed_needs_action_routed( @@ -1725,7 +1965,7 @@ async fn query_member_events( remaining, ) .await - .map_err(|e| internal_error(&format!("feed needs_action error: {e}")))?, + .map_err(|e| db_read_error("feed needs_action error", &e))?, "activity" => state .db .query_feed_activity_routed( @@ -1736,7 +1976,7 @@ async fn query_member_events( remaining, ) .await - .map_err(|e| internal_error(&format!("feed activity error: {e}")))?, + .map_err(|e| db_read_error("feed activity error", &e))?, _ => continue, }; for se in type_events { @@ -1795,10 +2035,7 @@ async fn query_member_events( } } - let limit = filter - .limit - .unwrap_or(100) - .min(BRIDGE_THREAD_MAX_LIMIT as usize) as u32; + let limit = buzz_core::filter::clamp_limit(filter.limit, 100, BRIDGE_THREAD_MAX_LIMIT); let thread_cursor = extract_thread_cursor(raw); let thread_replies = state .db @@ -1810,7 +2047,7 @@ async fn query_member_events( thread_cursor.as_deref(), ) .await - .map_err(|e| internal_error(&format!("thread query error: {e}")))?; + .map_err(|e| db_read_error("thread query error", &e))?; let mut thread_row_ids = Vec::with_capacity(thread_replies.len() + 1); thread_row_ids.push(root_hex.to_string()); @@ -2063,6 +2300,7 @@ pub(crate) async fn repair_requested_channel_access( #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers pub async fn count_events( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result { @@ -2084,69 +2322,48 @@ pub async fn count_events( let url = nip98_expected_url(&state.config.relay_url, &tenant, "/count"); // In NIP-FI enforce/deny-protected mode, a real NIP-98 event is mandatory. // [NIP-FI.md:594-607, FI-TRACE-HTTP-INGRESS] - let nip_fi_active = state.config.nip_fi.mode.restricts(); + let nip_fi_active = crate::nip_fi_policy::mode(&state, &headers) + .await + .restricts(); // POST /count carries an authorization-relevant body (filter selects what // is counted), so a payload tag is required in enforce mode. // [NIP-FI.md:619-637] - let nip_fi_enforce = state.config.nip_fi.mode.enforces(); + let nip_fi_enforce = crate::nip_fi_policy::mode(&state, &headers) + .await + .enforces(); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "bridge", || { - verify_bridge_auth_with_options(&headers, "POST", &url, Some(&body), true, true).map(drop) + bridge_strict_proof(&headers, "POST", &url, Some(&body), true) }) .await; - let admission = admit_nip_fi_http_on_state(&state, &headers, || { - verify_bridge_auth_with_options( - &headers, - "POST", - &url, - Some(&body), - state.config.require_auth_token || nip_fi_active, - nip_fi_enforce, - ) - .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) - .map_err(|e| e.into_response()) + let admission = admit_nip_fi_http_on_state(&state, &headers, &slot, || { + proof + .record(verify_bridge_auth_with_options( + &slot, + &headers, + "POST", + &url, + Some(&body), + state.config.require_auth_token || nip_fi_active, + nip_fi_enforce, + )) + .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) + .map_err(|e| e.into_response()) }) .await?; - let pubkey = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let (event_id_bytes, signed_created_at) = admission.into_extra(); - let pubkey_hex = pubkey.to_hex(); + let mut caller = ProvenCaller::new(admission, &slot, &tenant); // Admission, replay, membership, and count execution all run inside the - // helper. The single terminal attribution line fires here from the Result - // so every outcome — including admission/replay/membership failures that - // previously returned before any log — is attributed. - let result = count_events_authed( - &state, - &tenant, - &headers, - &body, - pubkey, - event_id_bytes, - signed_created_at, - token_owner, - ) - .await; - match &result { - Ok(Json(value)) => { - let count = value.get("count").and_then(Value::as_u64); - tracing::info!( - pubkey = %pubkey_hex, - route = "/count", - status = 200u16, - result_count = count, - "HTTP bridge request" - ); - } - Err(refusal) => { - tracing::warn!( - pubkey = %pubkey_hex, - route = "/count", - status = refusal.status().as_u16(), - "HTTP bridge request" - ); - } + // helper; the caller's access line is the request's one line, covering + // every outcome including a refused login. + let result = count_events_authed(&state, &tenant, &headers, &body, &mut caller).await; + if let Ok(Json(value)) = &result { + caller.complete(crate::access::Detail { + result_count: value.get("count").and_then(Value::as_u64), + ..Default::default() + }); } Ok(result.into_response()) } @@ -2155,32 +2372,38 @@ pub async fn count_events( /// Handles admission, replay, membership, and count execution so the thin /// wrapper above can emit exactly one terminal attribution line from the Result. #[allow(clippy::too_many_arguments)] +#[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn count_events_authed( state: &Arc, tenant: &TenantContext, headers: &HeaderMap, body: &[u8], - pubkey: nostr::PublicKey, - event_id_bytes: [u8; 32], - signed_auth_created_at: Option, - token_owner: Option, -) -> Result, MembershipRefusal> { - enforce_http_admission(state, tenant, &pubkey).await?; - check_nip98_replay(state, tenant, event_id_bytes).await?; + caller: &mut ProvenCaller, +) -> Result, Response> { + caller + .rate_limit_and_replay(state, tenant) + .await + .map_err(IntoResponse::into_response)?; + let pubkey = caller.pubkey; let pubkey_bytes = pubkey.to_bytes().to_vec(); let auth_tag = super::relay_members::extract_auth_tag_header(headers); - super::relay_members::enforce_relay_membership( + let membership = super::relay_members::enforce_relay_membership( state, tenant, &pubkey_bytes, auth_tag, - signed_auth_created_at, - token_owner, + caller.signed_at, + caller.token_owner, ) - .await?; + .await; + caller + .admit_member(membership) + .map_err(IntoResponse::into_response)?; - Ok(count_member_events(state, tenant, body, pubkey).await?) + count_member_events(state, tenant, body, caller) + .await + .map_err(IntoResponse::into_response) } /// The rest of [`count_events_authed`], once the caller is admitted as a relay member. @@ -2188,16 +2411,19 @@ async fn count_member_events( state: &Arc, tenant: &TenantContext, body: &[u8], - pubkey: nostr::PublicKey, + caller: &ProvenCaller, ) -> Result, (StatusCode, Json)> { + let pubkey = caller.pubkey; let pubkey_bytes = pubkey.to_bytes().to_vec(); let raw: Vec = serde_json::from_slice(body) .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid filters: {e}")))?; - if let Some(result) = super::artifact::query(state, tenant, &pubkey, &raw, true).await { + let routed = || caller.read_artifact(&raw); + if let Some(result) = super::artifact::query(state, tenant, &pubkey, &raw, true, routed).await { return result; } let filters: Vec = serde_json::from_slice(body) .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid filters: {e}")))?; + caller.read(&filters); crate::handlers::req::extract_channel_ids_from_filters_limited(&filters) .map_err(|()| api_error(StatusCode::BAD_REQUEST, "too many explicit channels"))?; @@ -2333,7 +2559,7 @@ async fn count_member_events( } else { // Fallback: query + post-filter for non-pushable constraints. let mut q = query; - crate::handlers::req::apply_count_fallback_limit(&mut q); + crate::handlers::req::prepare_count_fallback(&mut q); match state .db .query_events_routed_bounded("bridge_count_fallback", &q) @@ -2406,7 +2632,7 @@ async fn count_member_events( } } else { // Fallback: query a bounded candidate set + post-filter. - crate::handlers::req::apply_count_fallback_limit(&mut query); + crate::handlers::req::prepare_count_fallback(&mut query); match state .db .query_events_routed_bounded("bridge_count_fallback", &query) @@ -2505,7 +2731,7 @@ async fn handle_bridge_search( _ => continue, }; - let limit = filter.limit.unwrap_or(100).min(500) as u32; + let limit = buzz_core::filter::clamp_limit(filter.limit, 100, 500); if limit == 0 { continue; } @@ -2578,20 +2804,23 @@ async fn handle_bridge_search( .search .search(&search_query) .await - .map_err(|e| internal_error(&format!("search error: {e}")))?; + .map_err(|e| search_read_error("search error", &e))?; - // Fetch full events from DB by ID. Hit ids are already raw 32-byte + // Fetch full events by exact hit keys. Hit ids are already raw 32-byte // arrays from the FTS layer — no hex decode. - let hit_ids: Vec<[u8; 32]> = search_result.hits.into_iter().map(|h| h.event_id).collect(); + let hit_keys: Vec<_> = search_result + .hits + .iter() + .map(|h| (h.event_id, h.created_at)) + .collect(); - if hit_ids.is_empty() { + if hit_keys.is_empty() { continue; } - let id_refs: Vec<&[u8]> = hit_ids.iter().map(|b| b.as_slice()).collect(); let stored_events = state .db - .get_events_by_ids_routed("bridge_search_hydrate", tenant.community(), &id_refs) + .get_events_by_ids_at_routed("bridge_search_hydrate", tenant.community(), &hit_keys) .await .map_err(|e| db_read_error("search fetch error", &e))?; @@ -2601,7 +2830,7 @@ async fn handle_bridge_search( .map(|ev| (ev.event.id.to_bytes(), ev)) .collect(); - for id_array in &hit_ids { + for (id_array, _) in &hit_keys { let stored = match event_map.get(id_array) { Some(ev) => ev, None => continue, @@ -2642,7 +2871,9 @@ pub struct WebhookQuery { /// Webhook trigger endpoint. No user auth — the webhook secret authenticates the caller. /// /// Prefers `X-Webhook-Secret` header over `?secret=` query param (headers aren't logged -/// by most proxies). Returns 202 Accepted; execution is async. +/// by most proxies). Returns 202 Accepted; execution is async. Immediately +/// before the `workflow_runs` insert, the owner authority gate also rejects an +/// owner banned from the host-bound community. pub async fn workflow_webhook( State(state): State>, Path(id_str): Path, @@ -2664,7 +2895,7 @@ pub async fn workflow_webhook( .get(axum::http::header::HOST) .and_then(|v| v.to_str().ok()) .unwrap_or(""); - let tenant = crate::tenant::bind_community(&state.db, raw_host) + let tenant = crate::tenant::bind_community(&*state, raw_host) .await .map_err(|_| not_found("workflow not found"))?; let community_id = tenant.community(); @@ -2736,9 +2967,10 @@ pub async fn workflow_webhook( // executes with the workflow **owner's** standing authority — so the // secret alone is insufficient. Immediately before run creation, reject // disabled/inactive workflows and recheck the owner's current channel - // membership (and role, for exfiltration-capable definitions). Fail - // closed with the same generic 404 as the lookups above so a - // revoked-owner workflow is indistinguishable from a nonexistent one. + // membership (and role, for exfiltration-capable definitions) and that + // the owner is not banned. Fail closed with the same generic 404 as the + // lookups above so a revoked-owner workflow is indistinguishable from a + // nonexistent one. if !workflow.enabled || workflow.status != buzz_db::workflow::WorkflowStatus::Active { return Err(not_found("workflow not found")); } @@ -2754,7 +2986,13 @@ pub async fn workflow_webhook( let run_id = state .db - .create_workflow_run(community_id, id, None, trigger_ctx_json.as_ref()) + .create_workflow_run( + community_id, + id, + None, + trigger_ctx_json.as_ref(), + &buzz_db::workflow::RunCause::Webhook, + ) .await .map_err(|e| super::internal_error(&format!("db error: {e}")))?; @@ -2788,14 +3026,12 @@ pub async fn workflow_webhook( } }; - let result = buzz_workflow::executor::execute_from_step( + let result = buzz_workflow::executor::execute_run( &engine, community_id, run_id, &def, &trigger_ctx_clone, - 0, - None, ) .await; engine @@ -2927,6 +3163,7 @@ async fn synthesize_presence( #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn authorize_moderation_read( state: &Arc, + slot: &AccessSlot, headers: &HeaderMap, path: &str, raw_query: Option<&str>, @@ -2949,47 +3186,54 @@ async fn authorize_moderation_read( // In NIP-FI enforce/deny-protected mode a real NIP-98 event is mandatory — // the X-Pubkey dev-mode fallback must never satisfy the pairing requirement. // [NIP-FI.md:594-607, FI-TRACE-HTTP-INGRESS] - let nip_fi_active = state.config.nip_fi.mode.restricts(); + let nip_fi_active = crate::nip_fi_policy::mode(state, headers).await.restricts(); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] + let proof = crate::nip_fi_shadow::EnforcedProof::new(state, headers, "bridge"); crate::nip_fi_shadow::observe_strict_proof(state, headers, "bridge", || { - verify_bridge_auth(headers, "GET", &url, None, true).map(drop) + bridge_strict_proof(headers, "GET", &url, None, false) }) .await; - let admission = admit_nip_fi_http_on_state(state, headers, || { - verify_bridge_auth( - headers, - "GET", - &url, - None, - state.config.require_auth_token || nip_fi_active, - ) - .map(|auth| auth.proof(auth.event_id_bytes)) - .map_err(|e| e.into_response()) + let admission = admit_nip_fi_http_on_state(state, headers, slot, || { + proof + .record(verify_bridge_auth( + slot, + headers, + "GET", + &url, + None, + state.config.require_auth_token || nip_fi_active, + )) + .map(|auth| auth.proof((auth.event_id_bytes, None))) + .map_err(|e| e.into_response()) }) .await?; - let pubkey = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let event_id_bytes = admission.into_extra(); - - check_nip98_replay(state, &tenant, event_id_bytes) + let mut caller = ProvenCaller::new(admission, slot, &tenant); + caller + .replay(state, &tenant) .await - .map_err(|e| e.into_response())?; - let pubkey_bytes = pubkey.to_bytes().to_vec(); + .map_err(IntoResponse::into_response)?; + let pubkey_bytes = caller.pubkey.to_bytes().to_vec(); // Membership and community ban, same step as the other NIP-98 routes. - super::relay_members::enforce_relay_membership( + let membership = super::relay_members::enforce_relay_membership( state, &tenant, &pubkey_bytes, super::relay_members::extract_auth_tag_header(headers), None, - token_owner, + caller.token_owner, ) - .await - .map_err(|e| e.into_response())?; + .await; + caller + .check( + membership, + super::relay_members::MembershipRefusal::auth_result, + ) + .map_err(IntoResponse::into_response)?; - crate::handlers::moderation_authz::authorize_moderation_action( + // Moderator authority is this route's last admission step. + let moderator = crate::handlers::moderation_authz::authorize_moderation_action( &tenant, state, &pubkey_bytes, @@ -2997,8 +3241,8 @@ async fn authorize_moderation_read( crate::handlers::moderation_authz::ModerationTarget::None, crate::handlers::moderation_authz::ModerationAction::ViewQueue, ) - .await - .map_err(|_| { + .await; + caller.admit(moderator, moderation_refusal).map_err(|_| { api_error( StatusCode::FORBIDDEN, "restricted: moderator access required", @@ -3009,6 +3253,16 @@ async fn authorize_moderation_read( Ok(tenant) } +/// A moderation authority refusal: a failed role lookup is unavailable, +/// anything else is a real role refusal. +fn moderation_refusal(e: &anyhow::Error) -> AuthResult { + AuthResult::Denied(if e.is::() { + crate::access::AuthReason::AuthorizationUnavailable + } else { + crate::access::AuthReason::NotModerator + }) +} + /// Cap on rows returned by a single moderation read. const MODERATION_READ_LIMIT: i64 = 500; @@ -3029,11 +3283,13 @@ fn clamp_limit(requested: Option) -> i64 { /// `GET /moderation/reports` — the moderation queue (NIP-98 + mod-authz). pub async fn moderation_reports( State(state): State>, + slot: AccessSlot, headers: HeaderMap, RawQuery(raw_query): RawQuery, ) -> Response { let tenant = match authorize_moderation_read( &state, + &slot, &headers, "/moderation/reports", raw_query.as_deref(), @@ -3069,11 +3325,13 @@ pub async fn moderation_reports( /// `GET /moderation/audit` — the moderation audit log (NIP-98 + mod-authz). pub async fn moderation_audit( State(state): State>, + slot: AccessSlot, headers: HeaderMap, RawQuery(raw_query): RawQuery, ) -> Response { let tenant = match authorize_moderation_read( &state, + &slot, &headers, "/moderation/audit", raw_query.as_deref(), @@ -3104,10 +3362,13 @@ pub async fn moderation_audit( /// `GET /moderation/restricted` — currently banned/timed-out members. pub async fn moderation_restricted( State(state): State>, + slot: AccessSlot, headers: HeaderMap, ) -> Response { let tenant = - match authorize_moderation_read(&state, &headers, "/moderation/restricted", None).await { + match authorize_moderation_read(&state, &slot, &headers, "/moderation/restricted", None) + .await + { Ok(t) => t, Err(r) => return r, }; @@ -3173,6 +3434,26 @@ fn ban_json(b: &buzz_db::moderation::BanRecord) -> Value { }) } +#[cfg(test)] +mod moderation_refusal_tests { + // A failed role lookup logs `authorization_unavailable`; a real role + // refusal logs `not_moderator`. + #[test] + fn moderation_lookup_failure_is_unavailable() { + use crate::access::{AuthReason, AuthResult}; + let lookup = anyhow::Error::from(buzz_db::DbError::NotFound("pool".into())); + assert_eq!( + super::moderation_refusal(&lookup), + AuthResult::Denied(AuthReason::AuthorizationUnavailable) + ); + let refused = anyhow::anyhow!("moderator access required"); + assert_eq!( + super::moderation_refusal(&refused), + AuthResult::Denied(AuthReason::NotModerator) + ); + } +} + #[cfg(test)] #[path = "artifact_postgres_tests.rs"] mod artifact_postgres_tests; @@ -3187,11 +3468,9 @@ pub(crate) mod postgres_tests { use nostr::{Alphabet, EventBuilder, Keys, Kind, SingleLetterTag, Tag}; use std::sync::Mutex; - fn redis_pool() -> deadpool_redis::Pool { + fn redis_pool() -> buzz_pubsub::RedisConnection { let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); - deadpool_redis::Config::from_url(url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("create redis pool") + buzz_pubsub::redis_connection(&url).expect("create redis pool") } fn fresh_tenant(host: &str) -> TenantContext { @@ -3201,6 +3480,40 @@ pub(crate) mod postgres_tests { ) } + /// An artifact read's summary survives a WARN-only filter on a failed + /// request, without the search text or the artifact-only predicates. + #[test] + fn warn_only_artifact_read_lines_keep_the_filter_summary() { + let raw = [serde_json::json!({ + "kinds": [9], "#h": [uuid::Uuid::nil().to_string()], "since": 10, + "search": "secret words", "#x": ["artifact"], + })]; + let (_, out) = crate::access::tests::capture_warn(|| { + let caller = ProvenCaller { + pubkey: Keys::generate().public_key(), + event_id_bytes: fresh_nip98_event_id_bytes(), + signed_at: None, + token_owner: None, + slot: AccessSlot::default(), + }; + caller.read_artifact(&raw); + caller.slot.emit("/query", 500); + }); + assert!(!out.raw().contains("secret"), "{}", out.raw()); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + let line = &lines[0]; + assert_eq!(line["level"], "WARN", "{line}"); + assert_eq!(line["filters"], 1, "{line}"); + assert_eq!(line["kinds"], "9", "{line}"); + assert!( + line["channel_ids"].is_string() && line.get("channel_count").is_none(), + "{line}" + ); + assert_eq!(line["since"], 10, "{line}"); + assert_eq!(line["search"], true, "{line}"); + } + fn fresh_nip98_event_id_bytes() -> [u8; 32] { EventBuilder::new(Kind::HttpAuth, "") .sign_with_keys(&Keys::generate()) @@ -3252,9 +3565,8 @@ pub(crate) mod postgres_tests { use buzz_core::kind::KIND_PRESENCE_SNAPSHOT; // Pool at a closed port: get_presence_bulk's connection attempt fails. - let dead_pool = deadpool_redis::Config::from_url("redis://127.0.0.1:1") - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("pool builds lazily"); + let dead_pool = + buzz_pubsub::redis_connection("redis://127.0.0.1:1").expect("pool builds lazily"); let pubsub = buzz_pubsub::PubSubManager::new("redis://127.0.0.1:1", dead_pool) .await .expect("PubSubManager::new performs no IO"); @@ -3449,10 +3761,10 @@ pub(crate) mod postgres_tests { .await .expect("first pod should claim fresh NIP-98 event id"); - let (status, _) = check_nip98_replay_with_guard(&pod_b, &tenant_a, event_id_bytes) + let rejection = check_nip98_replay_with_guard(&pod_b, &tenant_a, event_id_bytes) .await .expect_err("second pod must reject same-community replay"); - assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(rejection, ReplayRejection::Replayed); check_nip98_replay_with_guard(&pod_b, &tenant_b, event_id_bytes) .await @@ -3474,10 +3786,78 @@ pub(crate) mod postgres_tests { .await .expect("first claim on a fresh event id must succeed"); - let (status, _) = check_nip98_replay_with_guard(&pod, &tenant, event_id_bytes) + let rejection = check_nip98_replay_with_guard(&pod, &tenant, event_id_bytes) .await .expect_err("same-pod replay of the same id+community must reject"); - assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_eq!(rejection, ReplayRejection::Replayed); + } + + /// Replay guard returning a fixed answer, for access-line tests. + struct FixedReplayGuard(Option); + + impl Nip98ReplayGuard for FixedReplayGuard { + fn try_mark_in_scope<'a>( + &'a self, + _scope: &'a str, + _event_id: &'a nostr::EventId, + _ttl_secs: u64, + ) -> std::pin::Pin< + Box> + Send + 'a>, + > { + let answer = self.0; + Box::pin(async move { + answer.ok_or_else(|| buzz_auth::AuthError::Internal("simulated outage".into())) + }) + } + } + + /// Drive one request's note through the replay step the way + /// [`ProvenCaller`] does, then write its line as the layer would. + async fn replay_auth_lines(answer: Option) -> Vec { + let (_guard, out) = crate::access::tests::capture_scoped(); + let tenant = fresh_tenant("relay-a.example"); + let slot = AccessSlot::default(); + slot.attempt( + crate::access::AuthMethod::Nip98, + Some(Keys::generate().public_key()), + true, + ); + slot.in_community(tenant.community()); + let checked = slot.gate( + check_nip98_replay_with_guard( + &FixedReplayGuard(answer), + &tenant, + fresh_nip98_event_id_bytes(), + ) + .await, + ReplayRejection::auth_result, + ); + assert!(out.lines().is_empty(), "only the layer writes the line"); + slot.emit("/query", if checked.is_ok() { 200 } else { 401 }); + out.lines() + } + + /// Replay never decides success on its own: a refusal is final, and a + /// pass leaves the decision to the later admission steps (here none + /// run, so the line stays `undecided`). + #[tokio::test(flavor = "current_thread")] + async fn nip98_replay_check_logs_only_its_refusal() { + for (answer, outcome, reason) in [ + (Some(true), "undecided", None), + (Some(false), "failed", Some("nip98_replay")), + (None, "denied", Some("replay_check_unavailable")), + ] { + let lines = replay_auth_lines(answer).await; + assert_eq!(lines.len(), 1, "{answer:?}: {lines:?}"); + let line = &lines[0]; + assert_eq!(line["event"], "http"); + assert_eq!(line["method"], "nip98"); + assert_eq!(line["outcome"], outcome); + assert_eq!(line["reason"].as_str(), reason); + assert_eq!(line["route"], "/query"); + assert!(line["community"].is_string()); + assert!(!line.to_string().contains("simulated outage")); + } } mod external_infra_redis_tests { @@ -3531,9 +3911,11 @@ pub(crate) mod postgres_tests { let tenant = fresh_tenant("relay-a.example"); let event_id_bytes = fresh_nip98_event_id_bytes(); - let (status, body) = check_nip98_replay_with_guard(&guard, &tenant, event_id_bytes) + let rejection = check_nip98_replay_with_guard(&guard, &tenant, event_id_bytes) .await .expect_err("guard error MUST fail closed, never admit"); + assert_eq!(rejection, ReplayRejection::Unavailable); + let (status, body) = <(StatusCode, Json)>::from(rejection); assert_eq!( status, StatusCode::UNAUTHORIZED, @@ -3605,11 +3987,18 @@ pub(crate) mod postgres_tests { let tenant_b = fresh_tenant("host-b.example"); let expected_url = nip98_expected_url(config_relay_url, &tenant_b, "/events"); - let (status, body) = verify_bridge_auth(&headers, "POST", &expected_url, Some(b""), true) - .expect_err( - "cross-host NIP-98 event MUST be rejected — row 44: `u` URL host \ + let (status, body) = verify_bridge_auth( + &crate::access::AccessSlot::default(), + &headers, + "POST", + &expected_url, + Some(b""), + true, + ) + .expect_err( + "cross-host NIP-98 event MUST be rejected — row 44: `u` URL host \ must match req.community", - ); + ); assert_eq!( status, StatusCode::UNAUTHORIZED, @@ -3634,6 +4023,7 @@ pub(crate) mod postgres_tests { let headers = nip98_auth_headers(&event_json); let (status, body) = verify_bridge_auth_with_options( + &crate::access::AccessSlot::default(), &headers, "POST", signed_url, @@ -3675,8 +4065,15 @@ pub(crate) mod postgres_tests { pubkey, signed_created_at, .. - } = verify_bridge_auth(&headers, "POST", &expected_url, Some(b""), true) - .expect("matching-host NIP-98 event must verify"); + } = verify_bridge_auth( + &crate::access::AccessSlot::default(), + &headers, + "POST", + &expected_url, + Some(b""), + true, + ) + .expect("matching-host NIP-98 event must verify"); assert_eq!( pubkey, keys.public_key(), @@ -3727,9 +4124,15 @@ pub(crate) mod postgres_tests { Some("limit=20&status=open"), ); - let VerifiedBridgeAuth { pubkey, .. } = - verify_bridge_auth(&headers, "GET", &expected_url, None, true) - .expect("query-bearing moderation read must verify against the same query"); + let VerifiedBridgeAuth { pubkey, .. } = verify_bridge_auth( + &crate::access::AccessSlot::default(), + &headers, + "GET", + &expected_url, + None, + true, + ) + .expect("query-bearing moderation read must verify against the same query"); assert_eq!(pubkey, keys.public_key()); } @@ -3753,8 +4156,15 @@ pub(crate) mod postgres_tests { None, ); - let (status, body) = verify_bridge_auth(&headers, "GET", &bare_url, None, true) - .expect_err("query-signed event MUST NOT match a bare-path expected URL"); + let (status, body) = verify_bridge_auth( + &crate::access::AccessSlot::default(), + &headers, + "GET", + &bare_url, + None, + true, + ) + .expect_err("query-signed event MUST NOT match a bare-path expected URL"); assert_eq!(status, StatusCode::UNAUTHORIZED); let msg = body .get("error") @@ -3784,9 +4194,15 @@ pub(crate) mod postgres_tests { Some("limit=20"), ); - let VerifiedBridgeAuth { pubkey, .. } = - verify_bridge_auth(&headers, "GET", &expected_url, None, true) - .expect("audit query-bearing read must verify"); + let VerifiedBridgeAuth { pubkey, .. } = verify_bridge_auth( + &crate::access::AccessSlot::default(), + &headers, + "GET", + &expected_url, + None, + true, + ) + .expect("audit query-bearing read must verify"); assert_eq!(pubkey, keys.public_key()); } @@ -3809,9 +4225,15 @@ pub(crate) mod postgres_tests { ); assert_eq!(expected_url, "https://host-a.example/moderation/restricted"); - let VerifiedBridgeAuth { pubkey, .. } = - verify_bridge_auth(&headers, "GET", &expected_url, None, true) - .expect("query-less restricted read must verify against the bare path"); + let VerifiedBridgeAuth { pubkey, .. } = verify_bridge_auth( + &crate::access::AccessSlot::default(), + &headers, + "GET", + &expected_url, + None, + true, + ) + .expect("query-less restricted read must verify against the bare path"); assert_eq!(pubkey, keys.public_key()); } @@ -4491,46 +4913,16 @@ pub(crate) mod postgres_tests { ); } - // ────────────────────────────────────────────────────────────────────────── - // truncate_reason regression tests - // - // Required by T1: prove a near-limit malformed input cannot produce a - // near-limit log payload. No infrastructure needed — pure unit tests. - // ────────────────────────────────────────────────────────────────────────── - - /// Near-limit ASCII input (1 MiB) must be capped at exactly `max_bytes`. - #[test] - fn truncate_reason_large_ascii_input_is_bounded() { - let big = "a".repeat(1024 * 1024); // 1 MiB - let result = truncate_reason(&big, 256); - assert_eq!(result.len(), 256); - assert!(result.is_ascii()); - } - - /// A multi-byte codepoint that straddles the byte boundary must not be - /// split: the output must end at the last complete codepoint before the - /// cap, keeping the slice valid UTF-8. - #[test] - fn truncate_reason_multibyte_codepoint_at_boundary_is_not_split() { - // Build a string of 255 ASCII bytes followed by a 3-byte codepoint (€, U+20AC). - // Naïve cutoff at byte 256 would land inside the 3-byte sequence. - let mut s = "a".repeat(255); - s.push('€'); // 3 bytes: 0xE2 0x82 0xAC — spans bytes 255..258 - assert_eq!(s.len(), 258); - - let result = truncate_reason(&s, 256); - // Must end before the multi-byte codepoint. - assert_eq!(result.len(), 255); - assert_eq!(result, "a".repeat(255)); - assert!(std::str::from_utf8(result.as_bytes()).is_ok()); - } - - /// Short input well under the cap must be returned unchanged. #[test] - fn truncate_reason_short_input_returned_unchanged() { - let s = "invalid: kind 24620 rejected"; - let result = truncate_reason(s, 256); - assert_eq!(result, s); + fn reject_code_keeps_only_a_known_prefix() { + assert_eq!(reject_code("invalid: visibility SECRET"), "invalid"); + assert_eq!(reject_code("invalid visibility: SECRET"), "invalid"); + assert_eq!( + reject_code("restricted: community writes are fenced"), + "restricted" + ); + assert_eq!(reject_code("SECRET: invalid"), "rejected"); + assert_eq!(reject_code("no prefix SECRET"), "rejected"); } // ────────────────────────────────────────────────────────────────────────── @@ -4600,9 +4992,7 @@ pub(crate) mod postgres_tests { let pool = sqlx::PgPool::connect(database_url).await.ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -5142,9 +5532,8 @@ pub(crate) mod postgres_tests { // ────────────────────────────────────────────────────────────────────────── // Log-capture helpers and attribution-invariant tests // - // These tests assert that exactly ONE "HTTP bridge request" log line - // appears per authed request, pinning the W1 single-terminal-log invariant - // and the E1 no-double-log rule. + // These tests assert that exactly ONE access line, carrying both the + // login and the request's outcome, appears per authed request. // // Infrastructure: same `#[ignore = "requires Postgres"]` + current_thread // runtime discipline as the HTTP-counter tests above. @@ -5205,21 +5594,28 @@ pub(crate) mod postgres_tests { (status, captured) } - /// Count lines that contain the terminal attribution marker. + /// The access lines in `log`; each must carry the login and a status. fn count_attribution_lines(log: &str) -> usize { - log.lines() - .filter(|l| l.contains("HTTP bridge request")) - .count() + let lines: Vec<_> = log + .lines() + .filter(|l| l.contains(crate::access::TARGET)) + .collect(); + for line in &lines { + assert!( + line.contains("event=\"http\"") && line.contains("status="), + "the request's one line carries its login and status: {line}" + ); + } + lines.len() } /// T3a — exactly-once invariant, pre-parse 400 arm (invalid JSON). /// /// An authenticated client that submits a non-JSON body must produce - /// exactly ONE "HTTP bridge request" log line. This pins W1 (early exits - /// are attributed) and E1 (no double line even for the parse-fail arm). + /// exactly ONE access line, carrying its login and its 400 status. /// - /// Discriminating: if the attribution log is removed from the ParseFail - /// arm in submit_event, this test fails. + /// Discriminating: if `submit_event` stops completing the caller's line + /// with the outcome, or logs the login separately, this test fails. #[test] #[ignore = "requires Postgres"] fn submit_event_invalid_json_emits_exactly_one_attribution_line() { @@ -5257,6 +5653,7 @@ pub(crate) mod postgres_tests { n, 1, "expected exactly 1 attribution line for invalid-JSON arm, got {n};\nlog:\n{log}" ); + assert!(log.contains("status=400"), "log:\n{log}"); assert!( log.contains(&pubkey_hex[..16]), "attribution line must carry the pubkey;\nlog:\n{log}" @@ -5266,8 +5663,8 @@ pub(crate) mod postgres_tests { /// T3b — exactly-once invariant, post-parse IngestError::Rejected arm (relay-only kind). /// /// An authenticated client that submits a relay-only-kind event (kind 13534) - /// must produce exactly ONE "HTTP bridge request" log line — not two - /// (the old code emitted both an info! attribution and a warn! reason line). + /// must produce exactly ONE access line, carrying its login and its 400 + /// status, not a separate login line and request line. /// /// Discriminating: if two log lines are emitted (old double-log bug), this /// test fails. @@ -5317,6 +5714,7 @@ pub(crate) mod postgres_tests { n, 1, "expected exactly 1 attribution line for IngestError::Rejected arm, got {n};\nlog:\n{log}" ); + assert!(log.contains("status=400"), "log:\n{log}"); assert!( log.contains(&pubkey_hex[..16]), "attribution line must carry the pubkey;\nlog:\n{log}" @@ -5390,9 +5788,7 @@ pub(crate) mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -5503,9 +5899,7 @@ pub(crate) mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -5551,9 +5945,7 @@ pub(crate) mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -5686,6 +6078,583 @@ pub(crate) mod postgres_tests { (status, resp_headers, resp_body) } + // ── HTTP auth access lines: one line, at the final decision ───────────── + + const QUERY_BODY: &[u8] = br#"[{"kinds":[1],"limit":1}]"#; + + /// `state` with a community at a fresh host, and that host. + async fn with_community(state: &crate::state::AppState) -> String { + let host = format!("auth-line-{}.local", uuid::Uuid::new_v4().simple()); + state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community"); + host + } + + /// POST a NIP-98-signed `/query` through the full router; returns the + /// status and the request's access auth lines. + async fn signed_query_auth_lines( + state: Arc, + host: &str, + keys: &Keys, + ) -> (axum::http::StatusCode, Vec) { + let headers = + make_nip98_headers(keys, &format!("https://{host}/query"), "POST", QUERY_BODY); + let (_guard, out) = crate::access::tests::capture_scoped(); + let status = oneshot_request(state, "POST", "/query", host, headers, QUERY_BODY).await; + let lines = out + .lines() + .into_iter() + .filter(|line| line["event"] == "http") + .collect(); + (status, lines) + } + + fn assert_one_auth_line( + lines: &[serde_json::Value], + outcome: &str, + reason: Option<&str>, + ) -> serde_json::Value { + assert_eq!(lines.len(), 1, "exactly one access line: {lines:?}"); + let line = &lines[0]; + assert_eq!(line["outcome"], outcome, "{line}"); + match reason { + Some(reason) => assert_eq!(line["reason"], reason, "{line}"), + None => assert!(line.get("reason").is_none(), "{line}"), + } + assert_eq!(line["route"], "/query"); + line.clone() + } + + /// The same signed `/query` sent twice: the second is refused by the + /// replay check inside `ProvenCaller`, and that refusal is its one line. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn replayed_query_logs_one_failed_line() { + /// Admits each event id once, like the Redis guard. + struct SeenOnce(std::sync::Mutex>); + impl Nip98ReplayGuard for SeenOnce { + fn try_mark_in_scope<'a>( + &'a self, + scope: &'a str, + event_id: &'a nostr::EventId, + _ttl_secs: u64, + ) -> std::pin::Pin< + Box< + dyn std::future::Future> + + Send + + 'a, + >, + > { + let fresh = self + .0 + .lock() + .expect("seen set") + .insert(format!("{scope}:{event_id}")); + Box::pin(async move { Ok(fresh) }) + } + } + let mut state = (*nip_fi_off_test_state().await.expect("local Postgres")).clone(); + state.nip98_replay = Arc::new(SeenOnce(Default::default())); + let state = Arc::new(state); + let host = with_community(&state).await; + let keys = Keys::generate(); + let headers = + make_nip98_headers(&keys, &format!("https://{host}/query"), "POST", QUERY_BODY); + let (_guard, out) = crate::access::tests::capture_scoped(); + for expected in [ + axum::http::StatusCode::OK, + axum::http::StatusCode::UNAUTHORIZED, + ] { + let status = oneshot_request( + Arc::clone(&state), + "POST", + "/query", + &host, + headers.clone(), + QUERY_BODY, + ) + .await; + assert_eq!(status, expected); + } + let lines: Vec<_> = out + .lines() + .into_iter() + .filter(|line| line["event"] == "http") + .collect(); + assert_eq!(lines.len(), 2, "one line per request: {lines:?}"); + assert_eq!(lines[0]["outcome"], "success", "{lines:?}"); + assert_one_auth_line(&lines[1..], "failed", Some("nip98_replay")); + assert_eq!( + lines[1]["status"], 401, + "a refused login keeps its status: {lines:?}" + ); + } + + /// A served `/query` that returns nothing writes one DEBUG access line: the login, the route's + /// status and result count, and the filter summary, and no separate + /// bridge line. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn query_writes_one_line_with_login_outcome_and_filters() { + let state = nip_fi_off_test_state().await.expect("local Postgres"); + let host = with_community(&state).await; + let keys = Keys::generate(); + let headers = + make_nip98_headers(&keys, &format!("https://{host}/query"), "POST", QUERY_BODY); + let (_guard, out) = crate::access::tests::capture_scoped(); + let status = oneshot_request(state, "POST", "/query", &host, headers, QUERY_BODY).await; + assert_eq!(status, axum::http::StatusCode::OK); + assert!(!out.raw().contains("HTTP bridge request"), "{}", out.raw()); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "one line per request: {lines:?}"); + let line = &lines[0]; + assert_eq!(line["level"], "DEBUG", "{line}"); + assert_eq!(line["event"], "http", "{line}"); + assert_eq!(line["outcome"], "success", "{line}"); + assert!(line.get("reason").is_none(), "{line}"); + assert_eq!(line["method"], "nip98", "{line}"); + assert_eq!(line["pubkey"], keys.public_key().to_hex(), "{line}"); + assert_eq!(line["pubkey_verified"], true, "{line}"); + assert_eq!(line["route"], "/query", "{line}"); + assert_eq!(line["status"], 200, "{line}"); + assert_eq!(line["result_count"], 0, "{line}"); + assert_eq!( + (&line["kinds"], &line["limit"]), + (&"1".into(), &1.into()), + "{line}" + ); + assert_eq!(line["authors"], "*", "an open dimension is `*`: {line}"); + } + + /// Every HTTP line names its verb itself, since the `http.request` span + /// is absent under an access-only filter and when a request is dropped + /// (Tower enters the span only while polling). + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn http_lines_carry_the_verb_without_the_span() { + use crate::access::tests::{assert_one_aborted_line, capture_access_only}; + use tracing::Level; + let state = nip_fi_off_test_state().await.expect("local Postgres"); + let host = with_community(&state).await; + let community = crate::tenant::bind_community(&state.db, &host) + .await + .expect("bind community") + .community(); + let keys = Keys::generate(); + + // A served, non-empty read under an access-only INFO filter. + let event = EventBuilder::new(Kind::TextNote, "") + .sign_with_keys(&keys) + .expect("sign event"); + state + .db + .insert_event(community, &event, None) + .await + .expect("insert event"); + let body = format!( + r#"[{{"kinds":[1],"authors":["{}"]}}]"#, + keys.public_key().to_hex() + ); + let headers = make_nip98_headers( + &keys, + &format!("https://{host}/query"), + "POST", + body.as_bytes(), + ); + let (guard, out) = capture_access_only(Level::INFO); + let status = oneshot_request( + Arc::clone(&state), + "POST", + "/query", + &host, + headers, + body.as_bytes(), + ) + .await; + drop(guard); + assert_eq!(status, axum::http::StatusCode::OK); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "exactly one access line: {lines:?}"); + let line = &lines[0]; + assert_eq!( + (&line["level"], &line["result_count"]), + (&"INFO".into(), &1.into()), + "{line}" + ); + assert_eq!(line["http_method"], "POST", "{line}"); + assert_eq!(line["pubkey"], keys.public_key().to_hex(), "{line}"); + assert!(!out.raw().contains("http.request"), "{}", out.raw()); + + // A refusal under an access-only WARN filter. + let mut members_only = (*state).clone(); + Arc::make_mut(&mut members_only.config).require_relay_membership = true; + let outsider = Keys::generate(); + let headers = make_nip98_headers( + &outsider, + &format!("https://{host}/query"), + "POST", + QUERY_BODY, + ); + let (guard, out) = capture_access_only(Level::WARN); + let status = oneshot_request( + Arc::new(members_only), + "POST", + "/query", + &host, + headers, + QUERY_BODY, + ) + .await; + drop(guard); + assert_eq!(status, axum::http::StatusCode::FORBIDDEN); + let line = assert_one_auth_line(&out.lines(), "denied", Some("not_relay_member")); + assert_eq!(line["level"], "WARN", "{line}"); + assert_eq!(line["http_method"], "POST", "{line}"); + assert_eq!(line["pubkey"], outsider.public_key().to_hex(), "{line}"); + + // A request dropped mid-replay, with every target on. + let mut stalled = (*state).clone(); + let replay = Arc::new(crate::access::tests::StallingReplayGuard::default()); + stalled.nip98_replay = replay.clone(); + let headers = + make_nip98_headers(&keys, &format!("https://{host}/query"), "POST", QUERY_BODY); + let (guard, out) = crate::access::tests::capture_scoped(); + tokio::select! { + _ = oneshot_request(Arc::new(stalled), "POST", "/query", &host, headers, QUERY_BODY) => { + panic!("the replay check must stall"); + } + () = replay.arrived.notified() => {} + } + drop(guard); + let line = assert_one_aborted_line(&out, &keys.public_key()); + assert_eq!(line["http_method"], "POST", "{line}"); + assert_eq!(line["route"], "/query", "{line}"); + } + + /// POST `body` to `route` signed by `keys` for `signed_url`, and return + /// the status and every access line the request wrote. + async fn post_access_lines( + state: Arc, + host: &str, + route: &str, + signed_url: &str, + keys: &Keys, + body: &[u8], + ) -> (axum::http::StatusCode, Vec, String) { + let headers = make_nip98_headers(keys, signed_url, "POST", body); + let (_guard, out) = crate::access::tests::capture_scoped(); + let status = oneshot_request(state, "POST", route, host, headers, body).await; + (status, out.lines(), out.raw()) + } + + /// A refused `/events` write logs a fixed code; the event's own tag + /// values, which the rejection message quotes, appear nowhere. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn rejected_write_logs_a_fixed_code_never_tag_text() { + let state = nip_fi_off_test_state().await.expect("local Postgres"); + let host = with_community(&state).await; + let keys = Keys::generate(); + for (tag, marker) in [ + ("visibility", "LEAKMARKERVISIBILITY7f3a"), + ("channel_type", "LEAKMARKERCHANNELTYPE9c1d"), + ] { + let event = nostr::EventBuilder::new(nostr::Kind::Custom(9007), "") + .tags([ + nostr::Tag::parse(["name", "marker-test"]).unwrap(), + nostr::Tag::parse([tag, marker]).unwrap(), + ]) + .sign_with_keys(&keys) + .unwrap(); + let body = serde_json::to_vec(&event).unwrap(); + let url = format!("https://{host}/events"); + let (status, lines, raw) = + post_access_lines(Arc::clone(&state), &host, "/events", &url, &keys, &body).await; + assert_eq!(status, axum::http::StatusCode::BAD_REQUEST, "{raw}"); + assert!(!raw.contains(marker), "tag text leaked into logs: {raw}"); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["reject_reason"], "invalid", "{}", lines[0]); + assert_eq!(lines[0]["accepted"], false, "{}", lines[0]); + } + } + + /// A served artifact `/query` and `/count` record which kinds, channel + /// and limit they read, like any other read. A client-defined tag the + /// plain filter parser rejects (`#1`) narrows the read but must not cancel + /// its summary, and its value is never logged. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn artifact_reads_log_their_filter_summary() { + let state = nip_fi_off_test_state().await.expect("local Postgres"); + let host = with_community(&state).await; + let keys = Keys::generate(); + let channel = uuid::Uuid::new_v4().to_string(); + let marker = "CUSTOMTAGMARKER4b2e"; + let plain = serde_json::json!({"artifact": "current", "kinds": [45010], "#h": [channel], "limit": 1}); + let mut custom = plain.clone(); + custom["#1"] = serde_json::json!([marker]); + for filter in [plain, custom] { + let body = serde_json::to_vec(&[filter]).unwrap(); + for route in ["/query", "/count"] { + let url = format!("https://{host}{route}"); + let (status, lines, raw) = + post_access_lines(Arc::clone(&state), &host, route, &url, &keys, &body).await; + assert_eq!(status, axum::http::StatusCode::OK, "{raw}"); + assert_eq!(lines.len(), 1, "{lines:?}"); + let line = &lines[0]; + assert_eq!(line["route"], route, "{line}"); + assert_eq!(line["kinds"], "45010", "{line}"); + assert_eq!(line["channel_ids"], channel.as_str(), "{line}"); + assert_eq!(line["limit"], 1, "{line}"); + assert_eq!(line["filters"], 1, "{line}"); + assert!(!raw.contains(marker), "custom tag value logged: {raw}"); + } + } + } + + /// Assert `lines` is one refusal for `route` carrying `status`, the + /// status the client actually received. + fn assert_one_refusal( + lines: &[serde_json::Value], + route: &str, + status: axum::http::StatusCode, + ) { + assert_eq!(lines.len(), 1, "one line per refused request: {lines:?}"); + let line = &lines[0]; + assert_eq!(line["route"], route, "{line}"); + assert_eq!(line["status"], status.as_u16(), "{line}"); + assert_eq!(line["level"], "WARN", "{line}"); + assert_ne!(line["outcome"], "success", "{line}"); + } + + /// Off mode: a proof signed for another URL is refused 401, and its one + /// line says so. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn off_mode_bad_proof_logs_route_and_status() { + let state = nip_fi_off_test_state().await.expect("local Postgres"); + let host = with_community(&state).await; + let wrong = format!("https://{host}/elsewhere"); + let (status, lines, _) = post_access_lines( + state, + &host, + "/query", + &wrong, + &Keys::generate(), + QUERY_BODY, + ) + .await; + assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED); + assert_one_refusal(&lines, "/query", status); + } + + /// Enforce mode: a missing assertion (refused by the router guard) and a + /// bad proof beside a valid assertion (refused by the handler's + /// admission, which remaps the proof's 401) each log the status sent. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn enforce_mode_refusals_log_route_and_final_status() { + let keys = Keys::generate(); + + let state = nip_fi_enforce_test_state().await.expect("local Postgres"); + let host = with_community(&state).await; + let url = format!("https://{host}/query"); + let (status, lines, _) = + post_access_lines(state, &host, "/query", &url, &keys, QUERY_BODY).await; + assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED); + assert_one_refusal(&lines, "/query", status); + assert_eq!(lines[0]["reason"], "assertion_missing", "{}", lines[0]); + + let state = nip_fi_enforce_test_state_with_verifier() + .await + .expect("local Postgres"); + let host = with_community(&state).await; + let headers = same_key_nip98_and_assertion_headers( + &keys, + &format!("https://{host}/elsewhere"), + "POST", + QUERY_BODY, + ); + let (_guard, out) = crate::access::tests::capture_scoped(); + let status = oneshot_request(state, "POST", "/query", &host, headers, QUERY_BODY).await; + assert!(status.is_client_error(), "{status}"); + let lines = out.lines(); + assert_one_refusal(&lines, "/query", status); + assert_eq!(lines[0]["method"], "nip98", "{}", lines[0]); + } + + /// DenyProtected: the unconditional 503 logs its route and status. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn deny_protected_refusal_logs_route_and_status() { + let state = nip_fi_deny_protected_test_state() + .await + .expect("local Postgres"); + let host = with_community(&state).await; + let url = format!("https://{host}/query"); + let (status, lines, _) = + post_access_lines(state, &host, "/query", &url, &Keys::generate(), QUERY_BODY).await; + assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE); + assert_one_refusal(&lines, "/query", status); + } + + /// A valid proof from a banned identity is refused by the ban check + /// after replay: one `denied` line, never a `success`. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn banned_query_logs_one_denied_line() { + let state = nip_fi_off_test_state().await.expect("local Postgres"); + let host = with_community(&state).await; + let tenant = crate::tenant::bind_community(&state.db, &host) + .await + .expect("bind community"); + let keys = Keys::generate(); + sqlx::query( + "INSERT INTO community_bans (community_id, pubkey, banned, actor_pubkey) \ + VALUES ($1, $2, true, $2)", + ) + .bind(tenant.community().as_uuid()) + .bind(keys.public_key().to_bytes().as_slice()) + .execute(state.db.pool()) + .await + .expect("ban"); + let (status, lines) = signed_query_auth_lines(state, &host, &keys).await; + assert_eq!(status, axum::http::StatusCode::FORBIDDEN); + assert_one_auth_line(&lines, "denied", Some("banned")); + } + + /// On a members-only relay a valid proof from a nonmember is refused by + /// the membership check: one `denied` line. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn nonmember_query_logs_one_denied_line() { + let mut state = (*nip_fi_off_test_state().await.expect("local Postgres")).clone(); + Arc::make_mut(&mut state.config).require_relay_membership = true; + let host = with_community(&state).await; + let (status, lines) = + signed_query_auth_lines(Arc::new(state), &host, &Keys::generate()).await; + assert_eq!(status, axum::http::StatusCode::FORBIDDEN); + assert_one_auth_line(&lines, "denied", Some("not_relay_member")); + } + + /// The shared API rate limit refuses before replay: one `denied` line + /// for an exhausted quota and for an unreachable limiter. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres and Redis"] + async fn rate_limited_query_logs_one_denied_line() { + let base = nip_fi_off_test_state().await.expect("local Postgres"); + let host = with_community(&base).await; + + let mut quota = (*base).clone(); + let mut auth_config = quota.config.auth.clone(); + auth_config.rate_limits.human_api_calls_per_min = 0; + quota.auth = Arc::new(buzz_auth::AuthService::new(auth_config)); + let (status, lines) = + signed_query_auth_lines(Arc::new(quota), &host, &Keys::generate()).await; + assert_eq!(status, axum::http::StatusCode::TOO_MANY_REQUESTS); + assert_one_auth_line(&lines, "denied", Some("quota_exceeded")); + + let mut unavailable = (*base).clone(); + let dead = buzz_pubsub::redis_connection("redis://127.0.0.1:1").expect("redis pool"); + unavailable.admission_rate_limiter = + Arc::new(buzz_pubsub::rate_limiter::RedisRateLimiter::new(dead)); + let (status, lines) = + signed_query_auth_lines(Arc::new(unavailable), &host, &Keys::generate()).await; + assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE); + assert_one_auth_line(&lines, "denied", Some("admission_unavailable")); + } + + /// The outer assertion guard refuses before any handler runs, so it logs + /// the refusal itself: a missing assertion in Enforce and every request + /// in DenyProtected. In Shadow it refuses nothing and logs nothing, so the + /// handler's own line is the request's only one. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn assertion_guard_logs_its_refusals_and_shadow_logs_nothing() { + let enforce = nip_fi_enforce_test_state().await.expect("local Postgres"); + let host = with_community(&enforce).await; + let keys = Keys::generate(); + + let (status, lines) = signed_query_auth_lines(enforce.clone(), &host, &keys).await; + assert_eq!(status, axum::http::StatusCode::UNAUTHORIZED); + let line = assert_one_auth_line(&lines, "failed", Some("assertion_missing")); + assert_eq!(line["method"], "nip_fi"); + + let mut deny = (*enforce).clone(); + Arc::make_mut(&mut deny.config).nip_fi.mode = buzz_auth::NipFiMode::DenyProtected; + let (status, lines) = signed_query_auth_lines(Arc::new(deny), &host, &keys).await; + assert_eq!(status, axum::http::StatusCode::SERVICE_UNAVAILABLE); + assert_one_auth_line(&lines, "denied", Some("authorization_unavailable")); + + let mut shadow = (*enforce).clone(); + Arc::make_mut(&mut shadow.config).nip_fi.mode = buzz_auth::NipFiMode::Shadow; + let (status, lines) = signed_query_auth_lines(Arc::new(shadow), &host, &keys).await; + assert_eq!(status, axum::http::StatusCode::OK); + let line = assert_one_auth_line(&lines, "success", None); + assert_eq!(line["method"], "nip98"); + } + + /// A failed workflow-deletion write reaches the HTTP ERROR log as a fixed + /// kind: a database error quoting the event's content never appears. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn failed_workflow_deletion_logs_no_database_error_text() { + let state = nip_fi_off_test_state().await.expect("local Postgres"); + let host = with_community(&state).await; + let marker = format!("wfdel-marker-{}", uuid::Uuid::new_v4().simple()); + // A row trigger that fails with the inserted content as its message, + // for marker events only. + for sql in [ + "CREATE OR REPLACE FUNCTION access_log_test_fail() RETURNS trigger \ + LANGUAGE plpgsql AS $$BEGIN RAISE EXCEPTION '%', NEW.content; END$$", + "DROP TRIGGER IF EXISTS access_log_test_fail ON events", + "CREATE TRIGGER access_log_test_fail BEFORE INSERT ON events FOR EACH ROW \ + WHEN (NEW.content LIKE 'wfdel-marker-%') EXECUTE FUNCTION access_log_test_fail()", + ] { + sqlx::query(sql) + .execute(state.db.pool()) + .await + .expect("install trigger"); + } + + let keys = Keys::generate(); + let coordinate = format!( + "30620:{}:{}", + keys.public_key().to_hex(), + uuid::Uuid::new_v4() + ); + let event = nostr::EventBuilder::new(nostr::Kind::EventDeletion, &marker) + .tag(nostr::Tag::parse(["a", &coordinate]).unwrap()) + .sign_with_keys(&keys) + .unwrap(); + let body = nostr::JsonUtil::as_json(&event).into_bytes(); + let headers = make_nip98_headers(&keys, &format!("https://{host}/events"), "POST", &body); + let (guard, out) = crate::access::tests::capture_scoped(); + // Catch a panic in the request so the shared trigger is removed first. + let status = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe( + oneshot_request(Arc::clone(&state), "POST", "/events", &host, headers, &body), + )) + .await; + drop(guard); + sqlx::query("DROP TRIGGER IF EXISTS access_log_test_fail ON events") + .execute(state.db.pool()) + .await + .expect("remove trigger"); + let status = status.unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + + assert_eq!(status, axum::http::StatusCode::INTERNAL_SERVER_ERROR); + let raw = out.raw(); + let error = raw + .lines() + .find(|line| line.contains("\"level\":\"ERROR\"")) + .unwrap_or_else(|| panic!("an ERROR line: {raw}")); + assert!(error.contains("workflow deletion write failed"), "{error}"); + assert!(!raw.contains(&marker), "marker leaked: {raw}"); + } + // ── F4: bridge POST /events — enforce mode, no assertion → 401 ────────── // // Exercises the OUTER assertion guard in `router.rs` (not the per-handler @@ -6233,6 +7202,103 @@ pub(crate) mod postgres_tests { ); } + // ── Profile name search — verified names, end to end ─────────────────── + // + // Where the community advertises verified profiles, a member finds a + // person by a name only their relay-signed kind:30382 carries, and gets + // their kind:0 and that kind:30382. Without the advertisement, the same + // query finds nobody. + #[test] + #[ignore = "requires Postgres"] + fn profile_search_matches_verified_names_where_advertised() { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("current_thread runtime"); + + let Some(unadvertised) = rt.block_on(nip_fi_enforce_test_state_with_verifier()) else { + panic!("local Postgres not reachable"); + }; + let mut advertised = (*unadvertised).clone(); + let mut config = (*advertised.config).clone(); + config.relay_private_key = Some(advertised.relay_keypair.secret_key().to_secret_hex()); + config.nip_fi.profile_policies = vec![buzz_db::verified_profiles::ProfilePolicy { + issuer: "https://issuer.test".to_owned(), + label: Some("Example".to_owned()), + refresh_seconds: 3600, + }]; + advertised.config = Arc::new(config); + let advertised = Arc::new(advertised); + + let host = format!( + "nip-fi-verified-search-{}.local", + uuid::Uuid::new_v4().simple() + ); + let community = rt + .block_on(advertised.db.ensure_configured_community(&host)) + .expect("ensure community") + .id; + let subject = Keys::generate(); + let profile = nostr::EventBuilder::new(nostr::Kind::Metadata, r#"{"name":"Fake"}"#) + .sign_with_keys(&subject) + .expect("sign profile"); + rt.block_on( + advertised + .db + .replace_addressable_event(community, &profile, None), + ) + .expect("store profile"); + let now = chrono::Utc::now(); + let verified = rt + .block_on(advertised.db.publish_verified_profile( + buzz_db::verified_profiles::ProfileAdmission { + community, + issuer: "https://issuer.test", + pubkey: &subject.public_key().to_hex(), + issued_at: now, + admitted_at: now, + display_name: "fname", + username: "fname", + full_name: Some("Fake Name"), + label: "Example", + refresh_seconds: 3600, + membership_required: false, + }, + &advertised.relay_keypair, + )) + .expect("publish verified profile") + .expect("verified profile written"); + + let search = |state: &Arc| { + let keys = Keys::generate(); + let body = br#"{"query":"name"}"#; + let url = format!("https://{host}{}", crate::api::profiles::SEARCH_PATH); + let headers = same_key_nip98_and_assertion_headers(&keys, &url, "POST", body); + let (status, _resp_headers, resp) = rt.block_on(oneshot_request_full( + Arc::clone(state), + "POST", + crate::api::profiles::SEARCH_PATH, + &host, + headers, + body, + )); + assert_eq!( + status, + axum::http::StatusCode::OK, + "body: {:?}", + String::from_utf8_lossy(&resp) + ); + serde_json::from_slice::>(&resp) + .expect("response is a JSON array of events") + }; + + let events = search(&advertised); + assert_eq!(events, vec![profile, verified]); + assert_eq!(events[1].pubkey, advertised.relay_keypair.public_key()); + assert!(events.iter().all(|event| event.verify().is_ok())); + assert!(search(&unadvertised).is_empty()); + } + // ── Moderation reports — Enforce mode, same-key admission → reaches handler ─ // // Positive control: a valid NIP-FI assertion + same-key NIP-98 on the @@ -6744,7 +7810,13 @@ pub(crate) mod postgres_tests { format!("Nostr {}", B64.encode(event.as_json().as_bytes())) }; - for owner_banned in [true, false] { + // (case, the owner refusal reason it gives every route) + for (case, reason) in [ + ("owner_banned", Some("owner_banned")), + ("conflict", Some("not_stored_owner")), + ("clear", None), + ] { + let owner_banned = reason.is_some(); let host = format!("owner-routes-{}.local", uuid::Uuid::new_v4().simple()); let community = state .db @@ -6767,7 +7839,22 @@ pub(crate) mod postgres_tests { .map(|write| write.outcome) .expect("add member"); } - if owner_banned { + if case == "conflict" { + let other = Keys::generate().public_key(); + for key in [agent.public_key(), other] { + state + .db + .ensure_user(community, key.as_bytes()) + .await + .expect("ensure user"); + } + assert!(state + .db + .set_agent_owner(community, agent.public_key().as_bytes(), other.as_bytes()) + .await + .expect("seed another stored owner")); + } + if case == "owner_banned" { let owner_bytes = owner.public_key().to_bytes(); state .db @@ -6930,8 +8017,30 @@ pub(crate) mod postgres_tests { .parse() .expect("assertion header"), ); - let (status, headers, body) = - oneshot_request_full(state.clone(), method, &path, &host, headers, &body).await; + let ((status, headers, body), records, lines) = + crate::nip_fi_shadow::tests::enforce_records_during(oneshot_request_full( + state.clone(), + method, + &path, + &host, + headers, + &body, + )) + .await; + // One request, one enforce verdict, whatever its path and + // however many owner rechecks it runs. + let expected = if owner_banned { + "http owner/denied" + } else { + "http admit/admit" + }; + assert_eq!(records, [expected], "{case} {method} {path}: {lines:?}"); + if let Some(reason) = reason { + assert!( + lines.len() == 1 && lines[0].contains(&format!("reason=\"{reason}\"")), + "{case} {method} {path}: {lines:?}" + ); + } let denied = status == StatusCode::FORBIDDEN && headers .get(header::CONTENT_TYPE) @@ -6958,7 +8067,7 @@ pub(crate) mod postgres_tests { use crate::nip_fi_test_hooks::http_ban_recheck_hook::arm; use axum::http::{header, StatusCode}; - for case in ["banned", "unavailable"] { + for case in ["banned", "owner_banned", "unavailable"] { for route in ["buzz_v1", "git_settings"] { let fixture = nip_fi_enforce_test_state().await.expect("local Postgres"); let mut state = (*fixture).clone(); @@ -6998,6 +8107,10 @@ pub(crate) mod postgres_tests { db.ban_community_member(community, &agent_bytes, &owner_bytes, None, None) .await .expect("ban agent"); + } else if case == "owner_banned" { + db.ban_community_member(community, &owner_bytes, &owner_bytes, None, None) + .await + .expect("ban owner"); } else { db.pool().close().await; } @@ -7016,12 +8129,35 @@ pub(crate) mod postgres_tests { .parse() .expect("assertion header"), ); - let (status, headers, body) = - oneshot_request_full(state.clone(), "GET", &path, &host, headers, b"").await; + let ((status, headers, body), records, lines) = + crate::nip_fi_shadow::tests::enforce_records_during(oneshot_request_full( + state.clone(), + "GET", + &path, + &host, + headers, + b"", + )) + .await; refuse.await.expect("refusal task"); + // The reread's refusal is the request's one verdict: an + // unreadable ban state is the owner step's, as shadow records + // it; the agent's own ban is not an owner refusal. + let (expected, reason) = match case { + "banned" => ("http admit/admit", None), + "owner_banned" => ("http owner/denied", Some("owner_banned")), + _ => ("http owner/unavailable", Some("owner_ban_unavailable")), + }; + assert_eq!(records, [expected], "{case} {route}: {lines:?}"); + if let Some(reason) = reason { + assert!( + lines.len() == 1 && lines[0].contains(&format!("reason=\"{reason}\"")), + "{case} {route}: {lines:?}" + ); + } let (expected_status, expected_body) = match case { - "banned" => (StatusCode::FORBIDDEN, "authorization denied\n"), + "banned" | "owner_banned" => (StatusCode::FORBIDDEN, "authorization denied\n"), _ => ( StatusCode::SERVICE_UNAVAILABLE, "authorization unavailable\n", @@ -7066,15 +8202,17 @@ pub(crate) mod postgres_tests { // (check, kind, refusal, token): refusal is "banned", "unavailable" // or "timeout"; token-less rows publish as the member owner. let mut cases = Vec::new(); + // `who`: whose row a ban lands on, the agent's, its owner's or both. for check in ["write", "typing", "moderation", "relay_admin"] { - for refusal in ["banned", "unavailable"] { - cases.push((check, refusal, true)); + for who in ["agent", "owner", "both"] { + cases.push((check, "banned", who, true)); } - cases.push((check, "banned", false)); + cases.push((check, "unavailable", "agent", true)); + cases.push((check, "banned", "agent", false)); } - cases.push(("write", "timeout", true)); + cases.push(("write", "timeout", "agent", true)); - for (check, refusal, token) in cases { + for (check, refusal, who, token) in cases { let fixture = nip_fi_enforce_test_state().await.expect("local Postgres"); let mut state = (*fixture).clone(); let config = Arc::make_mut(&mut state.config); @@ -7135,17 +8273,25 @@ pub(crate) mod postgres_tests { let state = state.clone(); let target = author.public_key().to_bytes(); let actor = owner.public_key().to_bytes(); + // Without a token the author is the owner, so `agent` bans it. + let banned = match who { + "agent" => vec![target], + "owner" => vec![actor], + _ => vec![target, actor], + }; tokio::spawn(async move { arrived.await.expect("ban check reached"); if refusal == "banned" { - state - .db - .ban_community_member(community, &target, &actor, None, None) - .await - .expect("ban"); - state.invalidate_restriction_cache(community, &target); + for key in banned { + state + .db + .ban_community_member(community, &key, &actor, None, None) + .await + .expect("ban"); + } + state.invalidate_restrictions_local(community); } else { - state.invalidate_restriction_cache(community, &target); + state.invalidate_restrictions_local(community); state.db.pool().close().await; } release.notify_one(); @@ -7181,8 +8327,16 @@ pub(crate) mod postgres_tests { .expect("assertion header"), ); } - let (status, headers, body) = - oneshot_request_full(state.clone(), "POST", "/events", &host, headers, &body).await; + let ((status, headers, body), records, _) = + crate::nip_fi_shadow::tests::enforce_records_during(oneshot_request_full( + state.clone(), + "POST", + "/events", + &host, + headers, + &body, + )) + .await; if let Some(refuse) = refuse { tokio::time::timeout(std::time::Duration::from_secs(10), refuse) .await @@ -7194,7 +8348,19 @@ pub(crate) mod postgres_tests { let content_type = headers[header::CONTENT_TYPE].to_str().unwrap_or_default(); let body = std::str::from_utf8(&body).expect("utf-8 body"); - let case = format!("{check} {refusal} token={token}"); + let case = format!("{check} {refusal} {who} token={token}"); + // A late owner-decided token refusal is the request's one verdict, + // never an admit. The agent's own ban, alone or with its owner's, + // is not its owner's refusal, as at every other seam. + let expected = match (refusal, who, token) { + ("banned", "owner", true) => Some("http owner/denied"), + ("banned", _, true) => Some("http admit/admit"), + ("unavailable", _, true) => Some("http owner/unavailable"), + _ => None, + }; + if let Some(expected) = expected { + assert_eq!(records, [expected], "{case}"); + } match (refusal, token) { ("banned", true) => assert_eq!( (status, content_type, body), @@ -7887,9 +9053,7 @@ pub(crate) mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -8128,9 +9292,7 @@ pub(crate) mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -8269,9 +9431,7 @@ pub(crate) mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -8870,9 +10030,7 @@ pub(crate) mod postgres_tests { db.fence().force_open_for_tests(chrono::Utc::now()); db.set_replica_read_max_age_for_tests(Some(std::time::Duration::from_secs(5))); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -9001,6 +10159,9 @@ pub(crate) mod postgres_tests { admin: sqlx::PgPool, writer: sqlx::PgPool, replica: sqlx::PgPool, + /// The production search pool options on the writer, with a 300ms + /// session `statement_timeout` they must keep (it is tighter). + search: sqlx::PgPool, names: [String; 2], state: Arc, host: String, @@ -9039,7 +10200,17 @@ pub(crate) mod postgres_tests { .await .expect("replica statement_timeout"); } - let pool = sqlx::PgPool::connect(&format!("{base}/{name}")) + // The replica gets a short acquire timeout, like production's + // reader pool, so a shed read against a held-full replica fails + // fast instead of waiting out sqlx's 30s default. + let options = sqlx::postgres::PgPoolOptions::new(); + let options = if role == "r" { + options.acquire_timeout(std::time::Duration::from_secs(1)) + } else { + options + }; + let pool = options + .connect(&format!("{base}/{name}")) .await .expect("connect scratch"); buzz_db::migration::run_migrations(&pool) @@ -9075,6 +10246,16 @@ pub(crate) mod postgres_tests { } let replica = pools.pop().expect("replica"); let writer = pools.pop().expect("writer"); + let search_url = format!("{base}/{}", names[0]); + let search = buzz_search::pool_options() + .connect_with( + search_url + .parse::() + .expect("search url") + .options([("statement_timeout", "300ms")]), + ) + .await + .expect("search pool"); let mut config = crate::config::Config::from_env().expect("config"); config.redis_url = @@ -9085,9 +10266,7 @@ pub(crate) mod postgres_tests { let mut db = buzz_db::Db::from_pools(writer.clone(), replica.clone()); db.fence().force_open_for_tests(chrono::Utc::now()); db.set_replica_read_max_age_for_tests(Some(std::time::Duration::from_secs(5))); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -9100,7 +10279,7 @@ pub(crate) mod postgres_tests { buzz_audit::AuditService::new(writer.clone()), pubsub, buzz_auth::AuthService::new(config.auth.clone()), - buzz_search::SearchService::new(writer.clone()), + buzz_search::SearchService::new(search.clone()), Arc::new(buzz_workflow::WorkflowEngine::new( db, buzz_workflow::WorkflowConfig::default(), @@ -9113,6 +10292,7 @@ pub(crate) mod postgres_tests { admin, writer, replica, + search, names: [names[0].clone(), names[1].clone()], state: Arc::new(state), host, @@ -9151,20 +10331,49 @@ pub(crate) mod postgres_tests { } async fn http(&self, uri: &str, filter: &serde_json::Value) -> (StatusCode, Value) { + let body = serde_json::to_vec(&[filter]).expect("json"); + self.post(uri, body, axum::http::HeaderMap::new()).await + } + + /// `POST /profiles/search` for `needle`, NIP-98 signed by the reader. + async fn profile_search(&self) -> (StatusCode, Value) { + let path = super::super::profiles::SEARCH_PATH; + let body = serde_json::to_vec(&serde_json::json!({"query": "needle"})).expect("json"); + let url = super::nip98_expected_url( + &self.state.config.relay_url, + &TenantContext::resolved(self.community, self.host.clone()), + path, + ); + let auth = make_nip98_headers(&self.reader, &url, "POST", &body); + self.post(path, body, auth).await + } + + async fn post( + &self, + uri: &str, + body: Vec, + headers: axum::http::HeaderMap, + ) -> (StatusCode, Value) { use axum::body::Body; use axum::http::{header, Request}; use tower::ServiceExt; + // Keep the deliberately divergent replica selected for each + // cancellation probe, independent of earlier probes' elapsed time. + self.state + .db + .fence() + .force_open_for_tests(chrono::Utc::now()); + let mut request = Request::builder() + .method("POST") + .uri(uri) + .header(header::HOST, &self.host) + .header("x-pubkey", self.reader.public_key().to_hex()) + .header("content-type", "application/json"); + if let Some(map) = request.headers_mut() { + map.extend(headers); + } let resp = crate::router::build_router(self.state.clone()) - .oneshot( - Request::builder() - .method("POST") - .uri(uri) - .header(header::HOST, &self.host) - .header("x-pubkey", self.reader.public_key().to_hex()) - .header("content-type", "application/json") - .body(Body::from(serde_json::to_vec(&[filter]).expect("json"))) - .expect("request"), - ) + .oneshot(request.body(Body::from(body)).expect("request")) .await .expect("oneshot"); let status = resp.status(); @@ -9183,6 +10392,10 @@ pub(crate) mod postgres_tests { F: FnOnce(Arc) -> Fut, Fut: std::future::Future, { + self.state + .db + .fence() + .force_open_for_tests(chrono::Utc::now()); let (conn, mut send_rx) = self.ws_conn(); drive(conn).await; match send_rx.try_recv().expect("handler sent a frame") { @@ -9198,10 +10411,22 @@ pub(crate) mod postgres_tests { Arc, tokio::sync::mpsc::Receiver, ) { - let (send_tx, send_rx) = tokio::sync::mpsc::channel(64); + self.ws_conn_with_capacity(64) + } + + /// A connection whose writer queue holds `capacity` frames. + fn ws_conn_with_capacity( + &self, + capacity: usize, + ) -> ( + Arc, + tokio::sync::mpsc::Receiver, + ) { + let (send_tx, send_rx) = tokio::sync::mpsc::channel(capacity); let (ctrl_tx, _ctrl_rx) = tokio::sync::mpsc::channel(4); let cancel = tokio_util::sync::CancellationToken::new(); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: uuid::Uuid::new_v4(), tenant: TenantContext::resolved(self.community, self.host.clone()), remote_addr: "127.0.0.1:1234".parse().expect("addr"), @@ -9250,6 +10475,7 @@ pub(crate) mod postgres_tests { async fn drop(self) { drop(self.state); + self.search.close().await; for (pool, name) in [ (self.writer, &self.names[0]), (self.replica, &self.names[1]), @@ -9351,6 +10577,207 @@ pub(crate) mod postgres_tests { fx.drop().await; } + /// A shed history read answers 503 `database unavailable` on every + /// bridge `/query` branch that serves one: channel window, the three + /// feeds, legacy thread replies and search hydration. A WS search whose + /// hydration is shed closes with the retryable `error: database error` + /// instead of an EOSE that would read as "no matches". A saturated reader + /// (every connection checked out, none idle) rejects history reads + /// instead of moving them to the writer, the same `PoolTimedOut` as a + /// full history gate. Mutations: map any of these branches through + /// `internal_error`, or let a failed WS hydration fall through to EOSE + /// → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn shed_history_read_maps_to_503_on_every_bridge_branch() { + let fx = cancel_fixture().await; + let h = [&fx.channel]; + let cases = [ + ( + "channel window", + serde_json::json!({"kinds": [9], "#h": h, "top_level": true}), + ), + ( + "feed mentions", + serde_json::json!({"kinds": [9], "feed_types": ["mentions"]}), + ), + ( + "feed needs_action", + serde_json::json!({"kinds": [9], "feed_types": ["needs_action"]}), + ), + ( + "feed activity", + serde_json::json!({"kinds": [9], "feed_types": ["activity"]}), + ), + ( + "thread replies", + serde_json::json!({"kinds": [9], "#e": [&fx.root], "depth_limit": 1}), + ), + ("search hydrate", fx.search_filter()), + ]; + for (branch, filter) in &cases { + let (status, body) = fx.http("/query", filter).await; + assert_eq!(status, StatusCode::OK, "healthy {branch}: {body}"); + } + let frame = fx.ws_search().await; + assert!(frame.contains("root needle"), "healthy WS search: {frame}"); + + let mut held = Vec::new(); + for _ in 0..fx.replica.options().get_max_connections() { + held.push(fx.replica.acquire().await.expect("hold reader connection")); + } + for (branch, filter) in &cases { + let (status, body) = fx.http("/query", filter).await; + assert_eq!( + (status, body["error"].as_str()), + ( + StatusCode::SERVICE_UNAVAILABLE, + Some(super::super::DATABASE_UNAVAILABLE) + ), + "shed {branch}: {body}" + ); + } + assert_eq!( + fx.ws_search().await, + format!( + r#"["CLOSED","s","{}"]"#, + crate::handlers::req::DATABASE_ERROR_CLOSED + ), + "shed WS search hydration" + ); + + drop(held); + fx.drop().await; + } + + /// The search itself (not its hydrate) cancelled by the search pool's + /// statement timeout answers with the timeout contract on every search + /// caller: HTTP `/query` and `/profiles/search` 503 `query timed out`, WS + /// CLOSED `error: query timed out`. The ordinary-error control (42P01) + /// keeps the generic 500 and the retryable `error: search failed`. + /// Mutations: drop the 57014 check in any caller, or map every search + /// error to the timeout → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn search_statement_timeout_maps_to_timeout_contract() { + use crate::handlers::req::{QUERY_TIMED_OUT_CLOSED, SEARCH_FAILED_CLOSED}; + let fx = cancel_fixture().await; + let closed = |reason: &str| format!(r#"["CLOSED","s","{reason}"]"#); + + // Healthy controls. + let (status, body) = fx.http("/query", &fx.search_filter()).await; + assert_eq!(status, StatusCode::OK, "healthy HTTP search: {body}"); + assert!( + body.to_string().contains("root needle"), + "search hit: {body}" + ); + let (status, body) = fx.profile_search().await; + assert_eq!(status, StatusCode::OK, "healthy profile search: {body}"); + let frame = fx.ws_search().await; + assert!(frame.contains("root needle"), "healthy WS search: {frame}"); + + // `events` locked on the search pool's database: the search waits past + // its 300ms `statement_timeout` and is cancelled with 57014. + let mut locker = fx.writer.begin().await.expect("begin locker"); + sqlx::query("LOCK TABLE events IN ACCESS EXCLUSIVE MODE") + .execute(&mut *locker) + .await + .expect("lock search events"); + let timed_out = ( + StatusCode::SERVICE_UNAVAILABLE, + Some(super::super::QUERY_TIMED_OUT), + ); + let (status, body) = fx.http("/query", &fx.search_filter()).await; + assert_eq!((status, body["error"].as_str()), timed_out, "HTTP search"); + let (status, body) = fx.profile_search().await; + assert_eq!( + (status, body["error"].as_str()), + timed_out, + "HTTP profile search" + ); + assert_eq!( + fx.ws_search().await, + closed(QUERY_TIMED_OUT_CLOSED), + "WS search" + ); + locker.rollback().await.expect("unlock"); + + // Ordinary-error controls: `events` gone → 42P01. Not a timeout. + for pool in [&fx.writer, &fx.replica] { + sqlx::query("ALTER TABLE events RENAME TO events_gone") + .execute(pool) + .await + .expect("rename events"); + } + let failed = ( + StatusCode::INTERNAL_SERVER_ERROR, + Some("internal server error"), + ); + let (status, body) = fx.http("/query", &fx.search_filter()).await; + assert_eq!( + (status, body["error"].as_str()), + failed, + "HTTP search ordinary error" + ); + let (status, body) = fx.profile_search().await; + assert_eq!( + (status, body["error"].as_str()), + failed, + "HTTP profile search ordinary error" + ); + assert_eq!( + fx.ws_search().await, + closed(SEARCH_FAILED_CLOSED), + "WS search ordinary error" + ); + + fx.drop().await; + } + + /// A history read that queues one event and then fails to enqueue the + /// next logs `aborted` with the event it already queued, not zero. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn aborted_history_read_logs_events_already_queued() { + let fx = cancel_fixture().await; + let channel: uuid::Uuid = fx.channel.parse().expect("channel uuid"); + let author = Keys::generate(); + for text in ["second", "third"] { + let event = EventBuilder::new(Kind::Custom(9), text) + .tag(Tag::parse(["h", &fx.channel]).expect("h")) + .sign_with_keys(&author) + .expect("sign"); + for pool in [&fx.writer, &fx.replica] { + buzz_db::Db::from_pool(pool.clone()) + .insert_event(fx.community, &event, Some(channel)) + .await + .expect("insert event"); + } + } + // The queue holds one frame and nobody drains it: the first EVENT is + // queued and the second enqueue fails, ending the read. + let (conn, _rx) = fx.ws_conn_with_capacity(1); + let filter: nostr::Filter = + serde_json::from_value(serde_json::json!({"kinds": [9], "#h": [&fx.channel]})) + .expect("filter"); + let (guard, out) = crate::access::tests::capture_scoped(); + crate::handlers::req::handle_req( + "p".into(), + vec![filter], + vec![None], + conn, + fx.state.clone(), + ) + .await; + drop(guard); + let lines = out.lines(); + let reads: Vec<_> = lines.iter().filter(|l| l["event"] == "req").collect(); + assert_eq!(reads.len(), 1, "one access line per REQ: {lines:?}"); + assert_eq!(reads[0]["outcome"], "aborted"); + assert_eq!(reads[0]["events_queued"], 1); + fx.drop().await; + } + /// A search REQ reusing a live subscription's ID retires it (NIP-01 /// replacement) before its hydrate is cancelled, so the timeout CLOSED /// leaves nothing registered under the ID. @@ -9403,7 +10830,10 @@ pub(crate) mod postgres_tests { .expect("lock replica events"); let search: nostr::Filter = serde_json::from_value(fx.search_filter()).expect("search filter"); - let live_owner = *conn.subscriptions.lock().await.get("x").expect("x owned"); + // `before_search_query` runs after the claim and before the query, so + // the live entry must already be gone there: the timeout CLOSED, + // which also retires it, has not happened yet. + let (arrived, release) = crate::nip_fi_test_hooks::search_query_hook::arm(fx.community); let task = tokio::spawn(handle_req( "x".into(), vec![search], @@ -9411,11 +10841,10 @@ pub(crate) mod postgres_tests { conn.clone(), fx.state.clone(), )); - // Once search has claimed `x` its hydrate blocks on the lock. The old - // live fan-out must already be retired then, not only at final cleanup. - while conn.subscriptions.lock().await.get("x") == Some(&live_owner) { - tokio::task::yield_now().await; - } + tokio::time::timeout(std::time::Duration::from_secs(10), arrived) + .await + .expect("search reaches its query") + .expect("hook armed"); assert!( fx.state .sub_registry @@ -9424,6 +10853,8 @@ pub(crate) mod postgres_tests { "accepting search must retire live fan-out" ); assert_eq!(fx.state.pubsub.topic_refcount(&tenant, topic).await, 0); + assert!(rx.is_empty(), "nothing sent before the query"); + release.notify_one(); task.await.expect("search task"); locker.rollback().await.expect("unlock"); @@ -9448,6 +10879,135 @@ pub(crate) mod postgres_tests { fx.drop().await; } + /// A failed history read ends the REQ with CLOSED, never EOSE: EOSE would + /// tell a resuming client it holds every stored event, so its next REQ would + /// skip the history that failed. A statement timeout keeps its terminal + /// `query timed out` reason; any other DB error gets the retryable + /// `database error`. Either CLOSED retires the subscription, and once the DB + /// recovers a reconnect with the same REQ replays the missed event. + /// Mutations: send EOSE on the non-timeout error again, or map every error + /// to `database error` → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn failed_history_read_closes_and_reconnect_replays_the_history() { + use crate::handlers::req::handle_req; + let fx = cancel_fixture().await; + let frames = |rx: &mut tokio::sync::mpsc::Receiver| { + std::iter::from_fn(|| rx.try_recv().ok()) + .map(|msg| match msg { + axum::extract::ws::Message::Text(t) => t.to_string(), + other => panic!("expected text frame, got {other:?}"), + }) + .collect::>() + }; + let req = || -> nostr::Filter { + serde_json::from_value(serde_json::json!({"kinds": [9], "#h": [&fx.channel]})) + .expect("history filter") + }; + let channel: uuid::Uuid = fx.channel.parse().expect("channel uuid"); + let topic = buzz_pubsub::EventTopic::Channel(channel); + let tenant = TenantContext::resolved(fx.community, fx.host.clone()); + let fails_and_retires = |sub: &'static str, reason: &'static str, logged: &'static str| { + let state = fx.state.clone(); + let (conn, mut rx) = fx.ws_conn(); + let tenant = tenant.clone(); + let channel = fx.channel.clone(); + async move { + let (_guard, out) = crate::access::tests::capture_scoped(); + handle_req( + sub.into(), + vec![req()], + vec![None], + conn.clone(), + state.clone(), + ) + .await; + // The read line is a WARN error that keeps its filter summary. + let lines = out.lines(); + let line = lines + .iter() + .find(|l| l["event"] == "req") + .unwrap_or_else(|| panic!("no req line: {lines:?}")); + assert_eq!(line["level"], "WARN", "{line}"); + assert_eq!(line["outcome"], "error", "{line}"); + assert_eq!(line["reason"], logged, "{line}"); + assert_eq!(line["kinds"], "9", "{line}"); + assert_eq!(line["channel_ids"], channel, "{line}"); + assert_eq!( + frames(&mut rx), + vec![format!(r#"["CLOSED","{sub}","{reason}"]"#)], + "a failed history read must CLOSE with {reason:?}, not EOSE" + ); + assert!(conn.subscriptions.lock().await.is_empty(), "conn map"); + assert!( + state.sub_registry.get_filters(conn.conn_id, sub).is_none(), + "CLOSED must retire the fan-out registration" + ); + assert_eq!(state.pubsub.topic_refcount(&tenant, topic).await, 0); + } + }; + + // A replica lock outlasting its 300ms `statement_timeout`: the read is + // cancelled with 57014, which keeps the terminal timeout reason. + let mut locker = fx.replica.begin().await.expect("begin locker"); + sqlx::query("LOCK TABLE events IN ACCESS EXCLUSIVE MODE") + .execute(&mut *locker) + .await + .expect("lock replica events"); + fails_and_retires( + "t", + crate::handlers::req::QUERY_TIMED_OUT_CLOSED, + "query_timed_out", + ) + .await; + locker.rollback().await.expect("unlock"); + + // `events` gone on both pools: the history read fails with 42P01 on the + // replica and again on the writer re-run. Not a statement timeout. + let rename = |from: &'static str, to: &'static str| { + let pools = [fx.writer.clone(), fx.replica.clone()]; + async move { + for pool in pools { + sqlx::query(sqlx::AssertSqlSafe(format!( + "ALTER TABLE {from} RENAME TO {to}" + ))) + .execute(&pool) + .await + .expect("rename events"); + } + } + }; + rename("events", "events_gone").await; + fails_and_retires( + "h", + crate::handlers::req::DATABASE_ERROR_CLOSED, + "database_error", + ) + .await; + + // The DB recovers and the client reconnects with the same REQ. + rename("events_gone", "events").await; + let (conn, mut rx) = fx.ws_conn(); + handle_req( + "h".into(), + vec![req()], + vec![None], + conn.clone(), + fx.state.clone(), + ) + .await; + let replay = frames(&mut rx); + assert_eq!(replay.len(), 2, "event then EOSE: {replay:?}"); + assert!( + replay[0].starts_with(r#"["EVENT","h","#) && replay[0].contains(&fx.root), + "the reconnect must replay the missed event: {replay:?}" + ); + assert_eq!(replay[1], r#"["EOSE","h"]"#); + + drop(conn); + fx.drop().await; + } + /// HTTP agents reach `materialize_nip_oa_owner` on every request. Once the /// owner link is confirmed in `observer_owner_cache` the call writes /// nothing: the link is set once and never cleared. @@ -9524,6 +11084,7 @@ pub(crate) mod postgres_tests { "CREATE SCHEMA {schema}; \ CREATE TABLE {schema}.users (LIKE public.users INCLUDING ALL); \ CREATE TABLE {schema}.community_bans (LIKE public.community_bans INCLUDING ALL); \ + CREATE TABLE {schema}.relay_invites (LIKE public.relay_invites INCLUDING ALL); \ CREATE TABLE {schema}.relay_members (LIKE public.relay_members INCLUDING ALL); \ CREATE TABLE {schema}.join_policy_acceptances \ (LIKE public.join_policy_acceptances INCLUDING ALL); \ @@ -9611,10 +11172,13 @@ pub(crate) mod postgres_tests { &tenant, &headers, serde_json::to_vec(&event).expect("event json").as_slice(), - agent.public_key(), - fresh_nip98_event_id_bytes(), - Some(nostr::Timestamp::now().as_secs()), - None, + &mut ProvenCaller { + pubkey: agent.public_key(), + event_id_bytes: fresh_nip98_event_id_bytes(), + signed_at: Some(nostr::Timestamp::now().as_secs()), + token_owner: None, + slot: AccessSlot::default(), + }, ) .await; assert!( @@ -9630,12 +11194,6 @@ pub(crate) mod postgres_tests { "{action}: the HTTP request recorded the owner" ); - sqlx::raw_sql(sqlx::AssertSqlSafe(format!( - "ALTER TABLE {schema}.users RENAME TO users_unavailable" - ))) - .execute(&admin) - .await - .expect("break the owner-to-agent lookup"); let owner_hex = owner.public_key().to_hex(); match action { "ban" => state @@ -9675,6 +11233,12 @@ pub(crate) mod postgres_tests { .expect("removal commits"); } } + sqlx::raw_sql(sqlx::AssertSqlSafe(format!( + "ALTER TABLE {schema}.users RENAME TO users_unavailable" + ))) + .execute(&admin) + .await + .expect("break the owner-to-agent lookup"); let revoked = state .revoke_live_access( &tenant, diff --git a/crates/buzz-relay/src/api/bridge/effective_edit.rs b/crates/buzz-relay/src/api/bridge/effective_edit.rs new file mode 100644 index 00000000000..b7c84284ff4 --- /dev/null +++ b/crates/buzz-relay/src/api/bridge/effective_edit.rs @@ -0,0 +1,88 @@ +//! Explicit, versioned effective-edit lookup; generic #e matching stays exact. +use crate::{ + api::{api_error, db_read_error}, + state::AppState, +}; +use axum::{http::StatusCode, Json}; +use buzz_core::TenantContext; +use nostr::{EventId, PublicKey}; +use serde_json::{json, Value}; +use uuid::Uuid; + +pub(super) fn requested(filters: &[Value]) -> bool { + filters.iter().any(|f| f.get("effective_edit").is_some()) +} + +fn request(filters: &[Value]) -> Result<(Uuid, EventId), &'static str> { + let filter = filters.first().ok_or("missing effective_edit filter")?; + let channel = filter["#h"][0] + .as_str() + .and_then(|v| Uuid::parse_str(v).ok()) + .ok_or("invalid channel")?; + let target = filter["ids"][0] + .as_str() + .and_then(|v| EventId::from_hex(v).ok()) + .ok_or("invalid target")?; + if filters + != [ + json!({"kinds":buzz_core::media::EDIT_GOVERNED_KINDS, "ids":[target.to_hex()], "#h":[channel.to_string()], "effective_edit":1, "consistency":"strong"}), + ] + { + return Err("effective_edit requires one exact version-1 original-message filter with strong consistency"); + } + Ok((channel, target)) +} + +pub(super) async fn query( + state: &AppState, + tenant: &TenantContext, + reader: &PublicKey, + filters: &[Value], +) -> Result, (StatusCode, Json)> { + let (channel, target) = + request(filters).map_err(|message| api_error(StatusCode::BAD_REQUEST, message))?; + let snapshot = state + .db + .message_edit_state( + tenant.community(), + channel, + target.as_bytes(), + reader.as_bytes(), + ) + .await + .map_err(|error| db_read_error("effective edit lookup", &error))? + .filter(|snapshot| { + crate::handlers::req::event_visible_to_reader(&snapshot.original, reader.as_bytes()) + && snapshot.edit.as_ref().is_none_or(|edit| { + crate::handlers::req::event_visible_to_reader(edit, reader.as_bytes()) + }) + }) + .ok_or_else(|| api_error(StatusCode::NOT_FOUND, "message not found"))?; + Ok(Json( + json!({"effective_edit":1, "original":snapshot.original, "edit":snapshot.edit}), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exact_versioned_shape_is_required() { + let channel = Uuid::new_v4(); + let valid = json!({"kinds":[9,40002,40008,45001,45003],"ids":["a".repeat(64)],"#h":[channel.to_string()],"effective_edit":1,"consistency":"strong"}); + assert!(request(std::slice::from_ref(&valid)).is_ok()); + for (key, value) in [ + ("effective_edit", json!(2)), + ("consistency", json!("eventual")), + ("#h", json!([])), + ("ids", json!([])), + ("kinds", json!([40003])), + ("limit", json!(1)), + ] { + let mut invalid = valid.clone(); + invalid[key] = value; + assert!(request(&[invalid]).is_err(), "{key}"); + } + assert!(request(&[valid.clone(), valid]).is_err()); + } +} diff --git a/crates/buzz-relay/src/api/bridge/membership_snapshot.rs b/crates/buzz-relay/src/api/bridge/membership_snapshot.rs new file mode 100644 index 00000000000..f440680b740 --- /dev/null +++ b/crates/buzz-relay/src/api/bridge/membership_snapshot.rs @@ -0,0 +1,249 @@ +//! Opt-in NIP-CL compact discovery; ordinary arrays never assert completeness. + +use axum::{http::StatusCode, Json}; +use buzz_core::{ + kind::{KIND_MEMBERSHIP_PUBLIC, KIND_MEMBERSHIP_SNAPSHOT}, + TenantContext, +}; +use buzz_db::membership_snapshot::{valid_public_types, valid_types, MAX_RESPONSE_BYTES}; +use serde::Serialize; +use serde_json::{json, Value}; + +use crate::{api::api_error, state::AppState}; + +pub(super) fn requested(filters: &[Value]) -> bool { + filters + .iter() + .any(|f| f.get("membership_snapshot").is_some() || f.get("membership_public").is_some()) +} + +fn types( + filters: &[Value], + viewer: &nostr::PublicKey, + public: bool, +) -> Result, &'static str> { + let types: Vec = filters + .first() + .and_then(|f| f.get("#t")) + .and_then(|v| serde_json::from_value(v.clone()).ok()) + .filter(|types: &Vec| valid_types(types) && (!public || valid_public_types(types))) + .ok_or("compact membership requires a sorted unique nonempty supported type set")?; + let expected = json!({ + "kinds": [if public { KIND_MEMBERSHIP_PUBLIC } else { KIND_MEMBERSHIP_SNAPSHOT }], + "#p": [viewer.to_hex()], + "#t": types, + (if public { "membership_public" } else { "membership_snapshot" }): 1, + }); + if filters != [expected] { + return Err( + "compact membership requires one exact version-1 filter for its mode and subject", + ); + } + Ok(types) +} + +#[derive(Serialize)] +struct Content<'a> { + version: u8, + community_id: uuid::Uuid, + host: &'a str, + viewer: String, + request_id: String, + types: &'a [String], + complete: bool, + snapshot_id: &'a str, + channels: &'a [buzz_db::membership_snapshot::ViewerMembership], +} + +pub(super) async fn query( + state: &AppState, + tenant: &TenantContext, + viewer: &nostr::PublicKey, + request_id: [u8; 32], + filters: &[Value], +) -> Result, (StatusCode, Json)> { + let public = filters.iter().any(|f| f.get("membership_public").is_some()); + if public + && filters + .iter() + .any(|f| f.get("membership_snapshot").is_some()) + { + return Err(api_error( + StatusCode::BAD_REQUEST, + "membership modes cannot be mixed", + )); + } + for filter in filters { + for (key, kind) in [ + ("membership_public", KIND_MEMBERSHIP_PUBLIC), + ("membership_snapshot", KIND_MEMBERSHIP_SNAPSHOT), + ] { + if filter.get(key).is_some() && filter.get("kinds") != Some(&json!([kind])) { + return Err(api_error( + StatusCode::BAD_REQUEST, + "membership mode does not match response kind", + )); + } + } + } + let mode = if public { + "membership_public" + } else { + "membership_snapshot" + }; + if !(if public { + state.config.membership_public_enabled + } else { + state.config.membership_snapshot_enabled + }) { + return Err(api_error( + StatusCode::NOT_FOUND, + &format!("{mode} unsupported"), + )); + } + // Even dev mode must provide real NIP-98 for this new authority surface. + if request_id == [0; 32] { + return Err(api_error( + StatusCode::UNAUTHORIZED, + &format!("{mode} requires NIP-98"), + )); + } + let subject = if public { + let subject = filters + .first() + .and_then(|f| f.get("#p")) + .and_then(Value::as_array) + .filter(|p| p.len() == 1) + .and_then(|p| p[0].as_str()) + .filter(|p| { + p.len() == 64 + && p.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) + .and_then(|p| nostr::PublicKey::from_hex(p).ok()) + .ok_or_else(|| { + api_error( + StatusCode::BAD_REQUEST, + "membership_public requires one lowercase subject key", + ) + })?; + subject + } else { + *viewer + }; + let types = types(filters, &subject, public) + .map_err(|reason| api_error(StatusCode::BAD_REQUEST, reason))?; + let snapshot = tokio::time::timeout(std::time::Duration::from_secs(10), async { + if public { + state + .db + .public_memberships(tenant.community(), &subject, &types) + .await + } else { + state + .db + .membership_snapshot(tenant.community(), viewer, &types) + .await + } + }) + .await + .map_err(|_| { + api_error( + StatusCode::SERVICE_UNAVAILABLE, + &format!("{mode} timed out"), + ) + })? + .map_err(|error| match error { + buzz_db::DbError::MembershipSnapshotTooLarge => api_error( + StatusCode::PAYLOAD_TOO_LARGE, + &format!("{mode} exceeds limit"), + ), + _ => { + tracing::error!(mode, error_kind = %error.kind(), "membership projection failed"); + api_error( + StatusCode::SERVICE_UNAVAILABLE, + &format!("{mode} unavailable"), + ) + } + })?; + let started = std::time::Instant::now(); + let content = Content { + version: 1, + community_id: *tenant.community().as_uuid(), + host: tenant.host(), + viewer: viewer.to_hex(), + request_id: hex::encode(request_id), + types: &types, + complete: true, + snapshot_id: &snapshot.snapshot_id, + channels: &snapshot.channels, + }; + let serialized = if public { + serde_json::to_string(&json!({ + "version": 1, "scope": "public", "community_id": content.community_id, + "host": content.host, "requester": viewer.to_hex(), "subject": subject.to_hex(), + "request_id": content.request_id, "types": content.types, "complete": true, + "snapshot_id": content.snapshot_id, "channels": content.channels, + })) + } else { + serde_json::to_string(&content) + } + .map_err(|_| { + api_error( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("{mode} encoding failed"), + ) + })?; + let tags = [ + ["d".to_string(), content.request_id], + ["p".to_string(), subject.to_hex()], + ] + .into_iter() + .map(nostr::Tag::parse) + .collect::, _>>() + .map_err(|_| { + api_error( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("{mode} tags failed"), + ) + })?; + let event = nostr::EventBuilder::new( + nostr::Kind::Custom(if public { + KIND_MEMBERSHIP_PUBLIC + } else { + KIND_MEMBERSHIP_SNAPSHOT + } as u16), + serialized, + ) + .tags(tags) + .sign_with_keys(&state.relay_keypair) + .map_err(|_| { + api_error( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("{mode} signing failed"), + ) + })?; + let envelope = json!({(mode):1, "event":event}); + let bytes = serde_json::to_vec(&envelope) + .map_err(|_| { + api_error( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("{mode} encoding failed"), + ) + })? + .len(); + if bytes > MAX_RESPONSE_BYTES { + return Err(api_error( + StatusCode::PAYLOAD_TOO_LARGE, + &format!("{mode} exceeds limit"), + )); + } + metrics::histogram!("buzz_membership_snapshot_encode_sign_seconds", "mode" => mode) + .record(started.elapsed().as_secs_f64()); + metrics::histogram!("buzz_membership_snapshot_response_bytes", "mode" => mode) + .record(bytes as f64); + Ok(Json(envelope)) +} + +#[cfg(test)] +mod postgres_tests; diff --git a/crates/buzz-relay/src/api/bridge/membership_snapshot/postgres_tests.rs b/crates/buzz-relay/src/api/bridge/membership_snapshot/postgres_tests.rs new file mode 100644 index 00000000000..838581ebcd8 --- /dev/null +++ b/crates/buzz-relay/src/api/bridge/membership_snapshot/postgres_tests.rs @@ -0,0 +1,603 @@ +use super::*; +use axum::{ + body::{to_bytes, Body}, + http::Request, +}; +use base64::Engine; +use nostr::{EventBuilder, Keys, Kind, Tag}; +use sha2::{Digest, Sha256}; +use std::sync::Arc; +use tower::ServiceExt; + +fn filter(viewer: &Keys) -> Value { + json!([{"kinds":[39008],"#p":[viewer.public_key().to_hex()], + "#t":["dm","forum","stream","system","workflow"],"membership_snapshot":1}]) +} + +fn proof(key: &Keys, host: &str, body: &Value, payload: bool) -> (String, nostr::Event) { + proof_at(key, host, "/query", body, payload) +} + +fn proof_at( + key: &Keys, + host: &str, + path: &str, + body: &Value, + payload: bool, +) -> (String, nostr::Event) { + let mut tags = vec![ + Tag::parse(["u", &format!("https://{host}{path}")]).unwrap(), + Tag::parse(["method", "POST"]).unwrap(), + Tag::parse(["nonce", &uuid::Uuid::new_v4().to_string()]).unwrap(), + ]; + if payload { + tags.push( + Tag::parse([ + "payload", + &hex::encode(Sha256::digest(serde_json::to_vec(body).unwrap())), + ]) + .unwrap(), + ); + } + let event = EventBuilder::new(Kind::Custom(27235), "") + .tags(tags) + .sign_with_keys(key) + .unwrap(); + ( + format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD.encode(serde_json::to_vec(&event).unwrap()) + ), + event, + ) +} + +async fn post( + state: Arc, + host: &str, + body: Value, + auth: Option, + owner_tag: Option, +) -> (StatusCode, Value) { + let mut request = Request::builder() + .method("POST") + .uri("/query") + .header("host", host); + if let Some(auth) = auth { + request = request.header("authorization", auth); + } + if let Some(tag) = owner_tag { + request = request.header("x-auth-tag", tag); + } + let response = crate::router::build_router(state) + .oneshot( + request + .body(Body::from(serde_json::to_vec(&body).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = to_bytes(response.into_body(), 3 * 1024 * 1024) + .await + .unwrap(); + (status, serde_json::from_slice(&bytes).unwrap()) +} + +async fn setup() -> (Arc, String, buzz_core::CommunityId, Keys) { + let fixture = super::super::postgres_tests::bridge_handler_test_state() + .await + .expect("isolated Postgres/Redis fixture"); + let host = format!("membership-{}.local", uuid::Uuid::new_v4().simple()); + let community = fixture + .db + .ensure_configured_community(&host) + .await + .unwrap() + .id; + let mut state = (*fixture).clone(); + Arc::make_mut(&mut state.config).membership_snapshot_enabled = true; + state.nip98_replay = Arc::new(buzz_pubsub::RedisNip98ReplayGuard::new( + state.redis_pool.clone(), + )); + (Arc::new(state), host, community, Keys::generate()) +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn membership_snapshot_router_signature_scope_strict_auth_replay_and_owner_substitution() { + let (state, host, community, viewer) = setup().await; + let channel = state + .db + .create_channel( + community, + "private", + buzz_db::channel::ChannelType::Stream, + buzz_db::channel::ChannelVisibility::Private, + None, + &viewer.public_key().to_bytes(), + None, + ) + .await + .unwrap(); + let body = filter(&viewer); + assert_eq!( + post(state.clone(), &host, body.clone(), None, None).await.0, + StatusCode::UNAUTHORIZED + ); + for (signed_host, payload, submitted) in [ + ("wrong.local", true, body.clone()), + (host.as_str(), false, body.clone()), + (host.as_str(), true, json!([])), + ] { + let (auth, _) = proof(&viewer, signed_host, &body, payload); + assert_eq!( + post(state.clone(), &host, submitted, Some(auth), None) + .await + .0, + StatusCode::UNAUTHORIZED + ); + } + let (auth, event) = proof(&viewer, &host, &body, true); + let (status, response) = + post(state.clone(), &host, body.clone(), Some(auth.clone()), None).await; + assert_eq!(status, StatusCode::OK, "{response}"); + assert_eq!(response["membership_snapshot"], 1); + let signed: nostr::Event = serde_json::from_value(response["event"].clone()).unwrap(); + signed.verify().unwrap(); + assert_eq!(signed.pubkey, state.relay_keypair.public_key()); + assert_eq!(signed.kind, Kind::Custom(39008)); + assert!(signed + .content + .starts_with("{\"version\":1,\"community_id\":")); + let content: Value = serde_json::from_str(&signed.content).unwrap(); + assert_eq!(content["request_id"], event.id.to_hex()); + assert!(signed + .tags + .iter() + .any(|t| t.as_slice() == ["d", event.id.to_hex().as_str()])); + + assert_eq!(content["viewer"], viewer.public_key().to_hex()); + assert_eq!(content["community_id"], community.as_uuid().to_string()); + assert_eq!(content["host"], host); + assert_eq!(content["types"], body[0]["#t"]); + assert_eq!(content["complete"], true); + assert_eq!( + content["channels"], + json!([{"id":channel.id,"role":"owner","channel_type":"stream","visibility":"private","archived":false}]) + ); + assert!(serde_json::to_vec(&response).unwrap().len() < 2000); + assert_eq!( + post(state.clone(), &host, body.clone(), Some(auth), None) + .await + .0, + StatusCode::UNAUTHORIZED + ); + let (auth, _) = proof(&viewer, &host, &body, true); + assert_eq!( + post(state.clone(), &host, body.clone(), Some(auth), None) + .await + .0, + StatusCode::OK + ); + // Real NIP-OA owner admission never changes the projection's viewer. + let agent = Keys::generate(); + let mut enforced = (*state).clone(); + Arc::make_mut(&mut enforced.config).require_relay_membership = true; + Arc::make_mut(&mut enforced.config).allow_nip_oa_auth = true; + let _ = enforced + .db + .add_relay_member( + community, + &viewer.public_key().to_hex(), + "owner", + None, + &enforced.relay_keypair, + ) + .await + .unwrap(); + let tag = buzz_sdk::nip_oa::compute_auth_tag(&viewer, &agent.public_key(), "").unwrap(); + let enforced = Arc::new(enforced); + let (auth, _) = proof(&agent, &host, &body, true); + assert_eq!( + post(enforced.clone(), &host, body, Some(auth), Some(tag.clone())) + .await + .0, + StatusCode::BAD_REQUEST + ); + let own = filter(&agent); + let (auth, _) = proof(&agent, &host, &own, true); + let (status, own_response) = post(enforced, &host, own, Some(auth), Some(tag)).await; + assert_eq!(status, StatusCode::OK, "{own_response}"); + let own_content: Value = + serde_json::from_str(own_response["event"]["content"].as_str().unwrap()).unwrap(); + assert_eq!(own_content["channels"], json!([])); + assert_eq!(own_content["viewer"], agent.public_key().to_hex()); + let other_host = format!("other-{}.local", uuid::Uuid::new_v4().simple()); + state + .db + .ensure_configured_community(&other_host) + .await + .unwrap(); + let own = filter(&viewer); + let (auth, _) = proof(&viewer, &other_host, &own, true); + let (status, other) = post(state.clone(), &other_host, own, Some(auth), None).await; + assert_eq!(status, StatusCode::OK, "{other}"); + let other: Value = serde_json::from_str(other["event"]["content"].as_str().unwrap()).unwrap(); + assert_ne!(other["community_id"], content["community_id"]); + assert_eq!(other["channels"], json!([])); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn membership_snapshot_router_disabled_malformed_and_legacy_roster_compatibility() { + let (state, host, community, viewer) = setup().await; + let capability = crate::nip11::nip11_document(&state, &host) + .await + .unwrap() + .membership_snapshot + .unwrap(); + assert_eq!(capability["version"], 1); + assert_eq!(capability["community_id"], community.as_uuid().to_string()); + assert_eq!( + capability["max_channels"], + buzz_db::membership_snapshot::MAX_CHANNELS + ); + assert_eq!(capability["max_response_bytes"], MAX_RESPONSE_BYTES); + let body = filter(&viewer); + let mut disabled = (*state).clone(); + Arc::make_mut(&mut disabled.config).membership_snapshot_enabled = false; + assert!(crate::nip11::nip11_document(&disabled, &host) + .await + .unwrap() + .membership_snapshot + .is_none()); + let (auth, _) = proof(&viewer, &host, &body, true); + let (status, response) = post(Arc::new(disabled), &host, body.clone(), Some(auth), None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(response, json!({"error":"membership_snapshot unsupported"})); + let mut malformed = vec![]; + for (key, value) in [ + ("membership_snapshot", json!(2)), + ("#p", json!([Keys::generate().public_key().to_hex()])), + ("#t", json!(["system", "stream"])), + ("#t", json!(["unknown"])), + ("#t", json!([])), + ("#t", json!(["dm", "dm"])), + ("limit", json!(1)), + ("artifact", json!("incremental")), + ("read_state_snapshot", json!(1)), + ] { + let mut changed = body.clone(); + changed[0][key] = value; + malformed.push(changed); + } + malformed.push(json!([body[0], body[0]])); + for bad in malformed { + let (auth, _) = proof(&viewer, &host, &bad, true); + let (status, error) = post(state.clone(), &host, bad, Some(auth), None).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{error}"); + assert!(error.get("event").is_none()); + } + let channel = state + .db + .create_channel( + community, + "legacy", + buzz_db::channel::ChannelType::Stream, + buzz_db::channel::ChannelVisibility::Private, + None, + &viewer.public_key().to_bytes(), + None, + ) + .await + .unwrap(); + // Ordinary legacy reads and full signatures are unchanged on the new relay. + let roster = EventBuilder::new(Kind::Custom(39002), "") + .tags([ + Tag::identifier(channel.id.to_string()), + Tag::parse(["t", "stream"]).unwrap(), + Tag::parse(["p", &viewer.public_key().to_hex(), "", "owner"]).unwrap(), + ]) + .sign_with_keys(&state.relay_keypair) + .unwrap(); + state + .db + .replace_addressable_event(community, &roster, Some(channel.id)) + .await + .unwrap(); + let legacy = json!([{"kinds":[39002],"#p":[viewer.public_key().to_hex()]}]); + let (auth, _) = proof(&viewer, &host, &legacy, true); + let (status, events) = post(state.clone(), &host, legacy, Some(auth), None).await; + assert_eq!(status, StatusCode::OK, "{events}"); + assert_eq!(events, json!([roster])); + // The relay-only gate is exercised through the real ingest boundary. + for kind in [39008, 39009] { + let forged = EventBuilder::new(Kind::Custom(kind), "{}") + .tags([Tag::identifier(viewer.public_key().to_hex())]) + .sign_with_keys(&viewer) + .unwrap(); + let forged = serde_json::to_value(forged).unwrap(); + let (auth, _) = proof_at(&viewer, &host, "/events", &forged, true); + let response = crate::router::build_router(state.clone()) + .oneshot( + Request::builder() + .method("POST") + .uri("/events") + .header("host", &host) + .header("authorization", auth) + .body(Body::from(serde_json::to_vec(&forged).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + assert!(!response.status().is_success()); + // Ordinary reads never synthesize a compact snapshot (old-relay wire shape). + let ordinary = json!([{"kinds":[kind],"#p":[viewer.public_key().to_hex()]}]); + let (auth, _) = proof(&viewer, &host, &ordinary, true); + let (status, events) = post(state.clone(), &host, ordinary, Some(auth), None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(events, json!([])); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn membership_snapshot_router_scale_overflow_and_backend_failure_never_complete_partial() { + for public in [false, true] { + let (state, host, community, viewer) = setup().await; + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let ids: Vec = (0..4097).map(|_| uuid::Uuid::new_v4()).collect(); + // 468 memberships first: the query and signing path must handle an ordinary + // large account without pagination or full roster demand. + sqlx::query( + "INSERT INTO channels (community_id,id,name,created_by) + SELECT $1,id,id::text,$3 FROM unnest($2::uuid[]) id", + ) + .bind(community.as_uuid()) + .bind(&ids) + .bind(viewer.public_key().to_bytes().to_vec()) + .execute(&pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO channel_members (community_id,channel_id,pubkey) + SELECT $1,id,$3 FROM unnest($2::uuid[]) id", + ) + .bind(community.as_uuid()) + .bind(&ids[..468]) + .bind(viewer.public_key().to_bytes().to_vec()) + .execute(&pool) + .await + .unwrap(); + let mut enabled = (*state).clone(); + Arc::make_mut(&mut enabled.config).membership_public_enabled = public; + let state = Arc::new(enabled); + let body = if public { + json!([{"kinds":[39009],"#p":[viewer.public_key().to_hex()],"#t":["stream"],"membership_public":1}]) + } else { + filter(&viewer) + }; + let started = std::time::Instant::now(); + let (auth, _) = proof(&viewer, &host, &body, true); + let (status, response) = post(state.clone(), &host, body.clone(), Some(auth), None).await; + assert_eq!(status, StatusCode::OK, "{response}"); + let signed: nostr::Event = serde_json::from_value(response["event"].clone()).unwrap(); + signed.verify().unwrap(); + let content: Value = serde_json::from_str(&signed.content).unwrap(); + assert_eq!(content["channels"].as_array().unwrap().len(), 468); + let bytes = serde_json::to_vec(&response).unwrap().len(); + println!( + "468-channel signed HTTP envelope bytes={bytes}, router_ms={}", + started.elapsed().as_secs_f64() * 1000.0 + ); + assert!(bytes < 100_000); + sqlx::query( + "INSERT INTO channel_members (community_id,channel_id,pubkey) + SELECT $1,id,$3 FROM unnest($2::uuid[]) id", + ) + .bind(community.as_uuid()) + .bind(&ids[468..]) + .bind(viewer.public_key().to_bytes().to_vec()) + .execute(&pool) + .await + .unwrap(); + let (auth, _) = proof(&viewer, &host, &body, true); + let (status, error) = post(state.clone(), &host, body.clone(), Some(auth), None).await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE, "{error}"); + assert!(error.get("event").is_none()); + sqlx::query("ALTER TABLE channel_members RENAME TO membership_snapshot_unavailable") + .execute(&pool) + .await + .unwrap(); + let (auth, _) = proof(&viewer, &host, &body, true); + let (status, error) = post(state, &host, body, Some(auth), None).await; + sqlx::query("ALTER TABLE membership_snapshot_unavailable RENAME TO channel_members") + .execute(&pool) + .await + .unwrap(); + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{error}"); + assert!(error.get("event").is_none()); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn public_memberships_router_bindings_scope_flags_and_strict_filters() { + let (state, host, community, requester) = setup().await; + let subject = Keys::generate(); + let channel = state + .db + .create_channel( + community, + "public", + buzz_db::channel::ChannelType::Stream, + buzz_db::channel::ChannelVisibility::Open, + None, + &subject.public_key().to_bytes(), + None, + ) + .await + .unwrap(); + let body = json!([{"kinds":[39009],"#p":[subject.public_key().to_hex()],"#t":["forum","stream","workflow"],"membership_public":1}]); + assert!(crate::nip11::nip11_document(&state, &host) + .await + .unwrap() + .membership_public + .is_none()); + let (auth, _) = proof(&requester, &host, &body, true); + let (status, error) = post(state.clone(), &host, body.clone(), Some(auth), None).await; + assert_eq!(status, StatusCode::NOT_FOUND); + assert_eq!(error, json!({"error":"membership_public unsupported"})); + let mut enabled = (*state).clone(); + Arc::make_mut(&mut enabled.config).membership_public_enabled = true; + Arc::make_mut(&mut enabled.config).membership_snapshot_enabled = false; + let state = Arc::new(enabled); + let info = crate::nip11::nip11_document(&state, &host).await.unwrap(); + assert!(info.membership_snapshot.is_none()); + assert_eq!(info.membership_public.unwrap()["kind"], 39009); + assert!(crate::nip11::nip11_document(&state, "unknown.local") + .await + .is_err()); + assert_eq!( + post(state.clone(), &host, body.clone(), None, None).await.0, + StatusCode::UNAUTHORIZED + ); + for (signed_host, payload, submitted) in [ + ("wrong.local", true, body.clone()), + (host.as_str(), false, body.clone()), + (host.as_str(), true, json!([])), + ] { + let (auth, _) = proof(&requester, signed_host, &body, payload); + assert_eq!( + post(state.clone(), &host, submitted, Some(auth), None) + .await + .0, + StatusCode::UNAUTHORIZED + ); + } + let (auth, event) = proof(&requester, &host, &body, true); + let (status, response) = + post(state.clone(), &host, body.clone(), Some(auth.clone()), None).await; + assert_eq!(status, StatusCode::OK, "{response}"); + assert_eq!(response["membership_public"], 1); + assert!(response.get("membership_snapshot").is_none()); + let signed: nostr::Event = serde_json::from_value(response["event"].clone()).unwrap(); + signed.verify().unwrap(); + assert_eq!(signed.kind, Kind::Custom(39009)); + assert_eq!(signed.pubkey, state.relay_keypair.public_key()); + assert_eq!( + signed + .tags + .iter() + .map(|t| t.as_slice().to_vec()) + .collect::>(), + vec![ + vec!["d".to_string(), event.id.to_hex()], + vec!["p".to_string(), subject.public_key().to_hex()] + ] + ); + let content: Value = serde_json::from_str(&signed.content).unwrap(); + assert_eq!(content["scope"], "public"); + assert_eq!(content["requester"], requester.public_key().to_hex()); + assert_eq!(content["subject"], subject.public_key().to_hex()); + assert_eq!(content["request_id"], event.id.to_hex()); + assert_eq!(content["community_id"], community.as_uuid().to_string()); + assert_eq!(content["host"], host); + assert_eq!(content["types"], body[0]["#t"]); + assert_eq!(content["complete"], true); + assert_eq!( + content["channels"], + json!([{"id":channel.id,"role":"owner","channel_type":"stream","visibility":"open","archived":false}]) + ); + assert_eq!( + post(state.clone(), &host, body.clone(), Some(auth), None) + .await + .0, + StatusCode::UNAUTHORIZED + ); + for (key, value) in [ + ("kinds", json!([39008])), + ("membership_public", json!(2)), + ("membership_snapshot", json!(1)), + ("#t", json!(["dm", "stream"])), + ("#t", json!(["system"])), + ("#t", json!(["stream", "forum"])), + ("#t", json!(["stream", "stream"])), + ("#t", json!([])), + ( + "#p", + json!([ + requester.public_key().to_hex(), + subject.public_key().to_hex() + ]), + ), + ("#p", json!([subject.public_key().to_hex().to_uppercase()])), + ("limit", json!(1)), + ] { + let mut bad = body.clone(); + bad[0][key] = value; + let (auth, _) = proof(&requester, &host, &bad, true); + assert_eq!( + post(state.clone(), &host, bad.clone(), Some(auth), None) + .await + .0, + StatusCode::BAD_REQUEST, + "{bad}" + ); + } + let ordinary = json!([{"kinds":[39009],"#p":[subject.public_key().to_hex()]}]); + let (auth, _) = proof(&requester, &host, &ordinary, true); + assert_eq!( + post(state, &host, ordinary, Some(auth), None).await.1, + json!([]) + ); +} + +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn public_memberships_share_requester_quota_across_subjects_and_fail_closed() { + let (base, host, _, requester) = setup().await; + let mut quota = (*base).clone(); + Arc::make_mut(&mut quota.config).membership_public_enabled = true; + let mut config = quota.config.auth.clone(); + config.rate_limits.human_api_calls_per_min = 1; + quota.auth = Arc::new(buzz_auth::AuthService::new(config)); + let state = Arc::new(quota); + let body = |subject: &Keys| json!([{"kinds":[39009],"#p":[subject.public_key().to_hex()],"#t":["stream"],"membership_public":1}]); + for (subject, expected) in [ + (Keys::generate(), StatusCode::OK), + (Keys::generate(), StatusCode::TOO_MANY_REQUESTS), + ] { + let body = body(&subject); + let (auth, _) = proof(&requester, &host, &body, true); + let (status, response) = post(state.clone(), &host, body, Some(auth), None).await; + assert_eq!(status, expected, "{response}"); + if status == StatusCode::TOO_MANY_REQUESTS { + assert!(response["error"] + .as_str() + .unwrap() + .starts_with("rate-limited: quota exceeded; retry in ")); + assert!(response.get("event").is_none()); + } + } + let other = Keys::generate(); + let body = body(&requester); + let (auth, _) = proof(&other, &host, &body, true); + assert_eq!( + post(state.clone(), &host, body.clone(), Some(auth), None) + .await + .0, + StatusCode::OK + ); + let mut unavailable = (*state).clone(); + let dead = buzz_pubsub::redis_connection("redis://127.0.0.1:1").unwrap(); + unavailable.admission_rate_limiter = + Arc::new(buzz_pubsub::rate_limiter::RedisRateLimiter::new(dead)); + let (auth, _) = proof(&Keys::generate(), &host, &body, true); + let (status, error) = post(Arc::new(unavailable), &host, body, Some(auth), None).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert!(error.get("event").is_none()); +} diff --git a/crates/buzz-relay/src/api/bridge/read_state_snapshot.rs b/crates/buzz-relay/src/api/bridge/read_state_snapshot.rs index 8ec3fe3ab95..e2bb8e2a311 100644 --- a/crates/buzz-relay/src/api/bridge/read_state_snapshot.rs +++ b/crates/buzz-relay/src/api/bridge/read_state_snapshot.rs @@ -255,15 +255,14 @@ mod postgres_tests { assert_eq!(body["community_id"], community.as_uuid().to_string()); assert_eq!(body["pubkey"], key.public_key().to_hex()); assert_eq!(body["events"], json!([event])); - let info = crate::nip11::nip11_document(&state, &host).await; + let info = crate::nip11::nip11_document(&state, &host).await.unwrap(); assert_eq!( info.read_state_snapshot.as_ref().unwrap()["community_id"], body["community_id"] ); assert!(crate::nip11::nip11_document(&state, "unmapped.invalid") .await - .read_state_snapshot - .is_none()); + .is_err()); let (_, other_body) = request(state.clone(), &other_host, Some(&key), filter(&key)).await; assert_eq!( other_body["community_id"], @@ -353,7 +352,7 @@ mod postgres_tests { #[ignore = "requires Postgres"] async fn read_state_snapshot_router_advertised_event_array_byte_boundary() { let (state, host, community, key) = setup().await; - let info = crate::nip11::nip11_document(&state, &host).await; + let info = crate::nip11::nip11_document(&state, &host).await.unwrap(); let descriptor = info.read_state_snapshot.unwrap(); let budget = descriptor["max_event_array_bytes"].as_u64().unwrap() as usize; assert_eq!(budget, buzz_db::read_state::MAX_SNAPSHOT_BYTES); diff --git a/crates/buzz-relay/src/api/bridge/search_slots.rs b/crates/buzz-relay/src/api/bridge/search_slots.rs new file mode 100644 index 00000000000..39a64b20d65 --- /dev/null +++ b/crates/buzz-relay/src/api/bridge/search_slots.rs @@ -0,0 +1,247 @@ +//! Per-user cap on bridge searches in flight. +//! +//! Typeahead starts a search on almost every keystroke. The client aborts the +//! previous request, but an abort that never reaches the relay (an +//! intermediary that keeps the upstream request open) leaves every one of +//! them running. Each `(community, pubkey)` may have [`PER_USER`] searches in +//! flight; the next one supersedes the oldest, whose request then fails with +//! [`Superseded`] (409, never 429: clients read 429 as relay-wide +//! back-pressure and hold all their relay traffic). Dropping the superseded search cancels its statement on +//! the server (see `buzz_search::cancel`). +//! +//! Newest wins rather than rejecting the newcomer: the newest keystroke is +//! the one the user is waiting for. The cap is above one so that sessions +//! sharing a pubkey (several agent sessions, parallel people and message +//! search) keep their parallel searches. + +use std::collections::{HashMap, VecDeque}; +use std::future::Future; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use axum::http::StatusCode; +use axum::Json; +use buzz_core::CommunityId; +use tokio_util::sync::CancellationToken; + +use crate::api::api_error; + +/// Bridge searches one `(community, pubkey)` may have in flight. +pub(crate) const PER_USER: usize = 4; + +type Key = (CommunityId, [u8; 32]); + +/// A search gave way to a newer one from the same user. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct Superseded; + +/// Body of a superseded search's response. +const SUPERSEDED: &str = "search superseded by a newer search"; + +/// 409, not 429: desktop and the CLI treat any 429 (and any `rate-limited:` +/// body) as relay-wide back-pressure, so a 429 here would stall every relay +/// request the client makes, or retry the search it just replaced. +impl From for (StatusCode, Json) { + fn from(_: Superseded) -> Self { + api_error(StatusCode::CONFLICT, SUPERSEDED) + } +} + +/// In-flight bridge searches per user, oldest first. +#[derive(Default)] +pub(crate) struct SearchSlots { + in_flight: Mutex>>, + next_id: AtomicU64, +} + +impl SearchSlots { + /// Run `search` in one of `key`'s slots. Returns `Err(Superseded)`, and + /// drops `search`, if [`PER_USER`] newer searches from `key` start first. + pub(crate) async fn run( + &self, + community: CommunityId, + pubkey: [u8; 32], + search: F, + ) -> Result { + let slot = self.claim((community, pubkey)); + // Polled first: a search that finishes as it is superseded still + // returns its result. + tokio::select! { + biased; + output = search => Ok(output), + () = slot.superseded.cancelled() => Err(Superseded), + } + } + + fn claim(&self, key: Key) -> Slot<'_> { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + let superseded = CancellationToken::new(); + let mut in_flight = self.lock(); + let queue = in_flight.entry(key).or_default(); + queue.push_back((id, superseded.clone())); + if queue.len() > PER_USER { + if let Some((_, oldest)) = queue.pop_front() { + oldest.cancel(); + } + } + Slot { + slots: self, + key, + id, + superseded, + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, HashMap>> { + // A panic while holding this lock leaves the map consistent: every + // critical section is a single push, pop or retain. + self.in_flight + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + #[cfg(test)] + fn users(&self) -> usize { + self.lock().len() + } +} + +/// One search's place in its user's queue; leaving it (finished, failed, +/// dropped or superseded) frees the place. +struct Slot<'a> { + slots: &'a SearchSlots, + key: Key, + id: u64, + superseded: CancellationToken, +} + +impl Drop for Slot<'_> { + fn drop(&mut self) { + let mut in_flight = self.slots.lock(); + if let Some(queue) = in_flight.get_mut(&self.key) { + // By id: a superseded slot is already gone, and must not remove + // the newer search that took its place. + queue.retain(|(id, _)| *id != self.id); + if queue.is_empty() { + in_flight.remove(&self.key); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::pin::pin; + use std::task::{Context, Poll}; + + fn user(n: u8) -> (CommunityId, [u8; 32]) { + (CommunityId::from_uuid(uuid::Uuid::from_u128(1)), [n; 32]) + } + + /// Poll `fut` once. + fn poll_once(fut: std::pin::Pin<&mut F>) -> Poll { + fut.poll(&mut Context::from_waker(std::task::Waker::noop())) + } + + #[tokio::test] + async fn the_search_past_the_cap_supersedes_the_oldest() { + let slots = SearchSlots::default(); + let (community, me) = user(1); + let (_, other) = user(2); + let mut held = Vec::new(); + for _ in 0..PER_USER { + held.push(Box::pin(slots.run( + community, + me, + std::future::pending::<()>(), + ))); + } + let mut theirs = pin!(slots.run(community, other, std::future::pending::<()>())); + for search in &mut held { + assert!(poll_once(search.as_mut()).is_pending()); + } + assert!(poll_once(theirs.as_mut()).is_pending()); + + let mut newest = pin!(slots.run(community, me, std::future::pending::<()>())); + assert!(poll_once(newest.as_mut()).is_pending()); + assert_eq!(poll_once(held[0].as_mut()), Poll::Ready(Err(Superseded))); + for search in &mut held[1..] { + assert!( + poll_once(search.as_mut()).is_pending(), + "only the oldest gives way" + ); + } + assert!( + poll_once(theirs.as_mut()).is_pending(), + "other users keep their searches" + ); + assert!(poll_once(newest.as_mut()).is_pending()); + } + + #[tokio::test] + async fn a_finished_search_frees_its_slot() { + let slots = SearchSlots::default(); + let (community, me) = user(1); + assert_eq!(slots.run(community, me, async { 7 }).await, Ok(7)); + let mut held = Vec::new(); + for _ in 0..PER_USER { + let mut search = Box::pin(slots.run(community, me, std::future::pending::<()>())); + assert!(poll_once(search.as_mut()).is_pending()); + held.push(search); + } + // A dropped search frees its slot too, so the next one displaces no one. + drop(held.pop()); + let mut next = pin!(slots.run(community, me, std::future::pending::<()>())); + assert!(poll_once(next.as_mut()).is_pending()); + for search in &mut held { + assert!(poll_once(search.as_mut()).is_pending()); + } + } + + #[tokio::test] + async fn a_superseded_search_leaves_its_successor_in_place() { + let slots = SearchSlots::default(); + let (community, me) = user(1); + let mut oldest = Box::pin(slots.run(community, me, std::future::pending::<()>())); + assert!(poll_once(oldest.as_mut()).is_pending()); + let mut rest = Vec::new(); + for _ in 0..PER_USER { + let mut search = Box::pin(slots.run(community, me, std::future::pending::<()>())); + assert!(poll_once(search.as_mut()).is_pending()); + rest.push(search); + } + assert_eq!(poll_once(oldest.as_mut()), Poll::Ready(Err(Superseded))); + drop(oldest); + // Still exactly PER_USER in flight: one more displaces the oldest survivor. + let mut next = pin!(slots.run(community, me, std::future::pending::<()>())); + assert!(poll_once(next.as_mut()).is_pending()); + assert_eq!(poll_once(rest[0].as_mut()), Poll::Ready(Err(Superseded))); + for search in &mut rest[1..] { + assert!(poll_once(search.as_mut()).is_pending()); + } + } + + #[test] + fn a_superseded_search_is_a_conflict_not_back_pressure() { + let (status, Json(body)) = Superseded.into(); + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!( + body, + serde_json::json!({ "error": "search superseded by a newer search" }) + ); + } + + #[tokio::test] + async fn no_entry_outlives_its_searches() { + let slots = SearchSlots::default(); + for n in 0..3 { + let (community, pubkey) = user(n); + let mut search = Box::pin(slots.run(community, pubkey, std::future::pending::<()>())); + assert!(poll_once(search.as_mut()).is_pending()); + assert_eq!(slots.users(), 1); + drop(search); + assert_eq!(slots.users(), 0); + } + } +} diff --git a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs index 02ef106cdae..35318b0c614 100644 --- a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs +++ b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs @@ -180,8 +180,13 @@ impl Fixture { } } -async fn production_db(mut config: buzz_db::DbConfig) -> buzz_db::Db { - config.database_url = crate::test_support::database_url(); +async fn production_db(config: buzz_db::DbConfig) -> buzz_db::Db { + production_db_at(crate::test_support::database_url(), config).await +} + +/// [`production_db`] at another URL, such as a proxy in front of the test database. +async fn production_db_at(database_url: String, mut config: buzz_db::DbConfig) -> buzz_db::Db { + config.database_url = database_url; config.max_connections = 5; buzz_db::Db::new(&config).await.unwrap() } @@ -593,3 +598,44 @@ async fn private_deletions_reach_only_their_signer_through_windows_and_id_reads( assert_eq!(ids(&body, Some(5)).len(), usize::from(visible), "{body}"); } } + +/// A deletion stored before deletions applied atomically can sit beside a +/// target that is still live. Neither window may serve that reaction or edit +/// without the deletion that cancels it, and no resend can repair the row once +/// it is older than the ingest timestamp window. The fixtures store each +/// deletion without soft-deleting its target, the state such a write left. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn torn_deletions_still_cancel_live_targets_in_both_windows() { + let f = Fixture::new().await; + let reply = f.reply(0).await; + let reaction = f.aux(7, &f.root, Some(f.channel)).await; + let edit = f.aux(40003, &f.root, Some(f.channel)).await; + let reply_reaction = f.aux(7, &reply, Some(f.channel)).await; + let reaction_deletion = f.aux(5, &reaction, None).await; + let edit_deletion = f.aux(9005, &edit, Some(f.channel)).await; + let reply_reaction_deletion = f.aux(5, &reply_reaction, None).await; + + let window = json!({"top_level":true,"#h":[f.channel],"kinds":[9],"include_aux":true}); + let legacy = json!({"#h":[f.channel],"#e":[f.root.id.to_hex()],"kinds":[9], + "depth_limit":2147483647,"include_aux":true}); + let mut pairs = vec![(&reaction, &reaction_deletion), (&edit, &edit_deletion)]; + for (filter, path) in [(&window, "channel window"), (&legacy, "legacy thread")] { + if path == "legacy thread" { + pairs.push((&reply_reaction, &reply_reaction_deletion)); + } + let page = f.query(filter).await; + let all = ids(&page, None); + for (target, deletion) in &pairs { + assert!( + all.contains(&target.id.to_hex().as_str()), + "{path}: fixture target must still be live: {page}" + ); + assert!( + all.contains(&deletion.id.to_hex().as_str()), + "{path}: live kind {} served without its deletion: {page}", + target.kind.as_u16() + ); + } + } +} diff --git a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests/failure_postgres_tests.rs b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests/failure_postgres_tests.rs index c7f7e7bf925..3f67c7d0ea5 100644 --- a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests/failure_postgres_tests.rs +++ b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests/failure_postgres_tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::test_support::PausingProxy; use std::{ future::Future, sync::atomic::{AtomicUsize, Ordering}, @@ -9,23 +10,30 @@ use tracing_subscriber::{layer::Context, prelude::*, registry::LookupSpan, Layer // Pause the HTTP future after the first real auxiliary page completes. This // observes a production span rather than replacing the database or closure. -struct AuxPages(Arc); +// The first page's span close also pauses the proxy the request's database +// connects through. That runs inside the request's poll, before the second +// page's query is written, so the second page stays pending however fast the +// database answers. +struct AuxPages(Arc, Arc); impl Layer for AuxPages where S: tracing::Subscriber + for<'a> LookupSpan<'a>, { fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { - if ctx.span(&id).unwrap().metadata().name() == "thread_window_aux" { - self.0.fetch_add(1, Ordering::SeqCst); + if ctx.span(&id).unwrap().metadata().name() == "thread_window_aux" + && self.0.fetch_add(1, Ordering::SeqCst) == 0 + { + self.1.set_paused(true); } } } async fn pause_after_aux_page( request: F, + proxy: Arc, ) -> std::pin::Pin>> { let pages = Arc::new(AtomicUsize::new(0)); - let subscriber = tracing_subscriber::registry().with(AuxPages(pages.clone())); + let subscriber = tracing_subscriber::registry().with(AuxPages(pages.clone(), proxy)); let mut request = Box::pin(request.with_subscriber(subscriber)); tokio::time::timeout( Duration::from_secs(5), @@ -51,6 +59,23 @@ async fn pause_after_aux_page( request } +// State for the paused request alone, whose production writer connects through +// a proxy so `AuxPages` can hold its second writer page. The test still reads +// through the fixture's direct `state.db` while the request is held; through +// the proxy, that read would deadlock. +async fn proxied_state(f: &Fixture) -> (Arc, Arc) { + let database_url = crate::test_support::database_url(); + let options: sqlx::postgres::PgConnectOptions = database_url.parse().unwrap(); + let proxy = + Arc::new(PausingProxy::spawn(options.get_host().to_owned(), options.get_port()).await); + let mut url = url::Url::parse(&database_url).unwrap(); + url.set_host(Some("127.0.0.1")).unwrap(); + url.set_port(Some(proxy.port)).unwrap(); + let mut state = (*f.state).clone(); + state.db = production_db_at(url.into(), buzz_db::DbConfig::default()).await; + (Arc::new(state), proxy) +} + #[tokio::test] #[ignore = "requires Postgres"] async fn thread_window_bridge_restarts_both_aux_hops_after_replica_failure() { @@ -63,9 +88,17 @@ async fn thread_window_bridge_restarts_both_aux_hops_after_replica_failure() { let reader_name = format!("tw-reader-{}", Uuid::new_v4()); let options: sqlx::postgres::PgConnectOptions = crate::test_support::database_url().parse().unwrap(); + // The replica reads through a proxy that holds the second aux page. + let proxy = + Arc::new(PausingProxy::spawn(options.get_host().to_owned(), options.get_port()).await); let reader = sqlx::postgres::PgPoolOptions::new() .max_connections(1) - .connect_with(options.application_name(&reader_name)) + .connect_with( + options + .host("127.0.0.1") + .port(proxy.port) + .application_name(&reader_name), + ) .await .unwrap(); let db = buzz_db::Db::from_pools(f.pool.clone(), reader.clone()); @@ -75,7 +108,8 @@ async fn thread_window_bridge_restarts_both_aux_hops_after_replica_failure() { let mut filter = f.filter(); filter["until"] = json!(f.root.created_at.as_secs() + 1); filter["before_id"] = json!("00".repeat(32)); - let request = pause_after_aux_page(f.post(&f.keys, "/query", json!([filter]))).await; + let request = + pause_after_aux_page(f.post(&f.keys, "/query", json!([filter])), proxy.clone()).await; let held: i64 = sqlx::query_scalar("SELECT count(*) FROM pg_stat_activity WHERE application_name=$1 AND xact_start IS NOT NULL") .bind(&reader_name).fetch_one(&f.pool).await.unwrap(); assert_eq!(held, 1, "must actually hold the proved replica transaction"); @@ -87,6 +121,9 @@ async fn thread_window_bridge_restarts_both_aux_hops_after_replica_failure() { .execute(&f.pool) .await .unwrap(); + // Deliver the termination, so the held page fails and the closure + // restarts on the writer. + proxy.set_paused(false); let (status, body) = request.await; assert_eq!(status, StatusCode::OK, "{body}"); assert_eq!(f.bounds(&body, &filter)["has_more"], false); @@ -194,7 +231,12 @@ async fn assert_aux_access_change(grant: bool) { "pre-transition visibility control" ); - let request = pause_after_aux_page(f.post(&f.keys, "/query", json!([filter]))).await; + let (state, proxy) = proxied_state(&f).await; + let request = pause_after_aux_page( + post(state, &f.host, &f.keys, "/query", json!([filter])), + proxy.clone(), + ) + .await; set_access(&f, aux_channel, grant).await; let current = f .state @@ -207,6 +249,7 @@ async fn assert_aux_access_change(grant: bool) { "requested channel stays authorized" ); assert_eq!(current.contains(&aux_channel), grant); + proxy.set_paused(false); let (status, interrupted) = request.await; assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{interrupted}"); assert_eq!( @@ -331,8 +374,14 @@ async fn thread_window_batch_discards_earlier_windows_after_revocation() { let (status, before) = f.post(&f.keys, "/query", batch.clone()).await; assert_eq!(status, StatusCode::OK, "{before}"); assert_eq!(ids(&before, Some(39007)).len(), 2); - let request = pause_after_aux_page(f.post(&f.keys, "/query", batch.clone())).await; + let (state, proxy) = proxied_state(&f).await; + let request = pause_after_aux_page( + post(state, &f.host, &f.keys, "/query", batch.clone()), + proxy.clone(), + ) + .await; set_access(&f, f.channel, false).await; + proxy.set_paused(false); let (status, body) = request.await; assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{body}"); assert_eq!( diff --git a/crates/buzz-relay/src/api/bridge/workflow_webhook_postgres_tests.rs b/crates/buzz-relay/src/api/bridge/workflow_webhook_postgres_tests.rs new file mode 100644 index 00000000000..ad22536291e --- /dev/null +++ b/crates/buzz-relay/src/api/bridge/workflow_webhook_postgres_tests.rs @@ -0,0 +1,357 @@ +use std::sync::Arc; + +use axum::{ + body::Bytes, + extract::{Path, Query, State}, + http::{header, HeaderMap, HeaderValue, StatusCode}, + Json, +}; +use serde_json::{json, Value}; +use sqlx::PgPool; +use uuid::Uuid; + +use super::{workflow_webhook, WebhookQuery}; +use crate::{ + config::Config, + state::{AppState, AuditShutdownHandle}, + test_support::database_url, +}; + +async fn app_state(db: buzz_db::Db, pool: &PgPool) -> (Arc, AuditShutdownHandle) { + let mut config = Config::for_test(); + config.database_url = database_url(); + config.redis_url = + std::env::var("REDIS_URL").expect("REDIS_URL must point to the isolated test Redis"); + config.relay_url = "wss://workflow-webhook-test.invalid".to_owned(); + config.require_auth_token = false; + config.require_relay_membership = false; + + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("create Redis pool"); + let pubsub = Arc::new( + buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) + .await + .expect("create pubsub manager"), + ); + let audit = buzz_audit::AuditService::new(pool.clone()); + let auth = buzz_auth::AuthService::new(config.auth.clone()); + let search = buzz_search::SearchService::new(pool.clone()); + let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new( + db.clone(), + buzz_workflow::WorkflowConfig::default(), + )); + let media_storage = buzz_media::MediaStorage::new(&config.media).expect("create media storage"); + + let (state, audit_shutdown) = AppState::new( + config, + db, + redis_pool, + audit, + pubsub, + auth, + search, + workflow_engine, + nostr::Keys::generate(), + media_storage, + ); + (Arc::new(state), audit_shutdown) +} + +async fn seed_community(pool: &PgPool, community_id: Uuid, host: &str) { + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community_id) + .bind(host) + .execute(pool) + .await + .expect("insert community"); +} + +struct WebhookWorkflowSeed<'a> { + community_id: Uuid, + workflow_id: Uuid, + channel_id: Uuid, + owner_pubkey: &'a [u8], + owner_role: &'a str, + name: &'a str, + secret: &'a str, + steps: Value, +} + +async fn seed_webhook_workflow(pool: &PgPool, seed: WebhookWorkflowSeed<'_>) { + sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2)") + .bind(seed.community_id) + .bind(seed.owner_pubkey) + .execute(pool) + .await + .expect("insert workflow owner"); + sqlx::query( + "INSERT INTO channels (community_id, id, name, created_by) VALUES ($1, $2, $3, $4)", + ) + .bind(seed.community_id) + .bind(seed.channel_id) + .bind(format!("workflow-{}", seed.name)) + .bind(seed.owner_pubkey) + .execute(pool) + .await + .expect("insert workflow channel"); + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey, role) \ + VALUES ($1, $2, $3, $4::member_role)", + ) + .bind(seed.community_id) + .bind(seed.channel_id) + .bind(seed.owner_pubkey) + .bind(seed.owner_role) + .execute(pool) + .await + .expect("insert workflow owner membership"); + + let definition = json!({ + "name": seed.name, + "trigger": {"on": "webhook"}, + "steps": seed.steps, + "_webhook_secret": seed.secret + }); + sqlx::query( + "INSERT INTO workflows \ + (community_id, id, name, owner_pubkey, channel_id, definition, definition_hash) \ + VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)", + ) + .bind(seed.community_id) + .bind(seed.workflow_id) + .bind(seed.name) + .bind(seed.owner_pubkey) + .bind(seed.channel_id) + .bind(definition.to_string()) + .bind(vec![0u8; 32]) + .execute(pool) + .await + .expect("insert workflow"); +} + +async fn post_webhook( + state: &Arc, + workflow_id: Uuid, + host: &str, + secret: &str, +) -> (StatusCode, Value) { + let mut headers = HeaderMap::new(); + headers.insert( + header::HOST, + HeaderValue::from_bytes(host.as_bytes()).expect("host header"), + ); + headers.insert( + "x-webhook-secret", + HeaderValue::from_bytes(secret.as_bytes()).expect("secret header"), + ); + + match workflow_webhook( + State(Arc::clone(state)), + Path(workflow_id.to_string()), + Query(WebhookQuery { secret: None }), + headers, + Bytes::new(), + ) + .await + { + Ok((status, Json(body))) | Err((status, Json(body))) => (status, body), + } +} + +async fn workflow_run_count(pool: &PgPool, community_id: Uuid, workflow_id: Uuid) -> i64 { + sqlx::query_scalar( + "SELECT COUNT(*) FROM workflow_runs WHERE community_id = $1 AND workflow_id = $2", + ) + .bind(community_id) + .bind(workflow_id) + .fetch_one(pool) + .await + .expect("count workflow runs") +} + +#[tokio::test] +#[ignore = "requires PostgreSQL and Redis"] +async fn webhook_admission_enforces_owner_ban_tenant_scope_and_lookup_failure() { + let pool = PgPool::connect(&database_url()) + .await + .expect("connect to isolated PostgreSQL test database"); + let db = buzz_db::Db::from_pool(pool.clone()); + + let community_a = Uuid::new_v4(); + let community_b = Uuid::new_v4(); + let host_a = format!("webhook-a-{}.test", Uuid::new_v4().simple()); + let host_b = format!("webhook-b-{}.test", Uuid::new_v4().simple()); + let owner_pubkey = [0x31; 32]; + let actor_pubkey = [0x52; 32]; + let member_pubkey = [0x73; 32]; + let workflow_id = Uuid::new_v4(); + let channel_id = Uuid::new_v4(); + let secret = format!("webhook-secret-{}", Uuid::new_v4().simple()); + + seed_community(&pool, community_a, &host_a).await; + seed_community(&pool, community_b, &host_b).await; + // Deliberately reuse workflow and channel IDs across tenants. The webhook + // request host must choose which community's owner restriction applies. + let delay_step = || { + json!([{ + "id": "hold", + "action": "delay", + "duration": "1s" + }]) + }; + seed_webhook_workflow( + &pool, + WebhookWorkflowSeed { + community_id: community_a, + workflow_id, + channel_id, + owner_pubkey: &owner_pubkey, + owner_role: "owner", + name: "owner-workflow-a", + secret: &secret, + steps: delay_step(), + }, + ) + .await; + seed_webhook_workflow( + &pool, + WebhookWorkflowSeed { + community_id: community_b, + workflow_id, + channel_id, + owner_pubkey: &owner_pubkey, + owner_role: "owner", + name: "owner-workflow-b", + secret: &secret, + steps: delay_step(), + }, + ) + .await; + + let member_workflow_id = Uuid::new_v4(); + let member_channel_id = Uuid::new_v4(); + seed_webhook_workflow( + &pool, + WebhookWorkflowSeed { + community_id: community_a, + workflow_id: member_workflow_id, + channel_id: member_channel_id, + owner_pubkey: &member_pubkey, + owner_role: "member", + name: "member-exfiltration-workflow", + secret: &secret, + steps: json!([{ + "id": "send", + "action": "call_webhook", + "url": "https://workflow-webhook-test.invalid" + }]), + }, + ) + .await; + + let (state, audit_shutdown) = app_state(db.clone(), &pool).await; + + let (status, body) = post_webhook(&state, workflow_id, &host_a, "wrong-secret").await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "the secret remains required and is denied generically" + ); + assert_eq!(body["error"], "workflow not found"); + assert_eq!(workflow_run_count(&pool, community_a, workflow_id).await, 0); + + let (status, _) = post_webhook(&state, workflow_id, &host_a, &secret).await; + assert_eq!( + status, + StatusCode::ACCEPTED, + "an unbanned owner is admitted" + ); + assert_eq!(workflow_run_count(&pool, community_a, workflow_id).await, 1); + + db.ban_community_member( + buzz_core::CommunityId::from_uuid(community_a), + &owner_pubkey, + &actor_pubkey, + None, + None, + ) + .await + .expect("ban workflow owner"); + let (status, body) = post_webhook(&state, workflow_id, &host_a, &secret).await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "a banned owner is denied generically" + ); + assert_eq!(body["error"], "workflow not found"); + assert_eq!( + workflow_run_count(&pool, community_a, workflow_id).await, + 1, + "denial must not enqueue a workflow run" + ); + + let (status, _) = post_webhook(&state, workflow_id, &host_b, &secret).await; + assert_eq!( + status, + StatusCode::ACCEPTED, + "a ban in community A must not block the same owner in community B" + ); + assert_eq!(workflow_run_count(&pool, community_b, workflow_id).await, 1); + + assert!(db + .unban_community_member( + buzz_core::CommunityId::from_uuid(community_a), + &owner_pubkey, + &actor_pubkey, + ) + .await + .expect("unban workflow owner")); + let (status, _) = post_webhook(&state, workflow_id, &host_a, &secret).await; + assert_eq!( + status, + StatusCode::ACCEPTED, + "an explicitly unbanned owner is admitted" + ); + assert_eq!(workflow_run_count(&pool, community_a, workflow_id).await, 2); + + let (status, _) = post_webhook(&state, member_workflow_id, &host_a, &secret).await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "the existing elevated-role check still rejects member-owned exfiltration workflows" + ); + assert_eq!( + workflow_run_count(&pool, community_a, member_workflow_id).await, + 0, + "role denial must not enqueue a workflow run" + ); + + audit_shutdown + .drain(std::time::Duration::from_secs(1)) + .await; + drop(state); + + let (failing_db, admin_pool, schema) = + crate::test_support::restriction_lookup_failing_db().await; + let (failing_state, failing_audit_shutdown) = app_state(failing_db, &pool).await; + let (status, body) = post_webhook(&failing_state, workflow_id, &host_a, &secret).await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "restriction lookup failure denies admission" + ); + assert_eq!(body["error"], "workflow not found"); + assert_eq!( + workflow_run_count(&pool, community_a, workflow_id).await, + 2, + "a failed restriction lookup must not enqueue a workflow run" + ); + failing_audit_shutdown + .drain(std::time::Duration::from_secs(1)) + .await; + drop(failing_state); + + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("DROP SCHEMA {schema} CASCADE"))) + .execute(&admin_pool) + .await + .expect("drop restriction lookup failure schema"); +} diff --git a/crates/buzz-relay/src/api/buzz_v1/auth.rs b/crates/buzz-relay/src/api/buzz_v1/auth.rs index 920221d8567..934ba304ef3 100644 --- a/crates/buzz-relay/src/api/buzz_v1/auth.rs +++ b/crates/buzz-relay/src/api/buzz_v1/auth.rs @@ -85,6 +85,7 @@ pub(super) struct Principal { pub(super) async fn authorize( state: &Arc, + slot: &crate::access::AccessSlot, headers: &HeaderMap, uri: &Uri, method: &'static str, @@ -100,10 +101,13 @@ pub(super) async fn authorize( let url = bridge::nip98_expected_url(&state.config.relay_url, &tenant, path); // Private state always requires cryptographic identity, even on a dev relay. // NIP-FI admission owns NIP-98 extraction, assertion pairing and deny map. + let mode = crate::nip_fi_policy::mode(state, headers).await; let admission = crate::nip_fi_http::admit_nip_fi_http_on_state( state, headers, + slot, bridge::make_nip98_closure_for_admission( + slot.clone(), headers.clone(), method, url, @@ -114,37 +118,51 @@ pub(super) async fn authorize( ) .await .map_err(|response| { - if state.config.nip_fi.mode.restricts() { + if mode.restricts() { // Preserve the shared NIP-FI wire contract, not just its status. Error::Admission(Box::new(response)) } else { bridge_error((response.status(), Json(Value::Null))) } })?; - let actor = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let (event_id, signed_at) = admission.into_extra(); - bridge::enforce_http_admission(state, &tenant, &actor) - .await - .map_err(bridge_error)?; - bridge::check_nip98_replay(state, &tenant, event_id) + let mut caller = bridge::ProvenCaller::new(admission, slot, &tenant); + caller + .rate_limit_and_replay(state, &tenant) .await .map_err(bridge_error)?; let principal = Principal { tenant, - actor, - signed_at, - token_owner, + actor: caller.pubkey, + signed_at: caller.signed_at, + token_owner: caller.token_owner, }; - recheck(state, headers, &principal).await?; + caller + .admit( + admission_checks(state, headers, &principal).await, + |(_, refusal)| *refusal, + ) + .map_err(|(error, _)| error)?; Ok(principal) } +/// Re-run the per-request admission checks for an authorized principal. pub(super) async fn recheck( state: &AppState, headers: &HeaderMap, principal: &Principal, ) -> Result<(), Error> { + admission_checks(state, headers, principal) + .await + .map_err(|(error, _)| error) +} + +/// Relay membership, then community ban. A refusal carries its access-log +/// result alongside the response error. +async fn admission_checks( + state: &AppState, + headers: &HeaderMap, + principal: &Principal, +) -> Result<(), (Error, crate::access::AuthResult)> { relay_members::enforce_relay_membership( state, &principal.tenant, @@ -154,16 +172,23 @@ pub(super) async fn recheck( principal.token_owner, ) .await - .map_err(|refusal| match refusal { - relay_members::MembershipRefusal::Api(refusal) => bridge_error(refusal), - // Preserve the shared NIP-FI wire contract, as admission does. - refusal => Error::Admission(Box::new(refusal.into_response())), + .map_err(|refusal| { + let result = refusal.auth_result(); + let error = match refusal { + relay_members::MembershipRefusal::Api(_, refusal) => bridge_error(refusal), + // Preserve the shared NIP-FI wire contract, as admission does. + refusal => Error::Admission(Box::new(refusal.into_response())), + }; + (error, result) })?; // A verified agent token gets only NIP-FI's fixed denial here too, so a // ban or outage between the two reads never shows which step refused it. - let refuse = |class, legacy: Error| match principal.token_owner { - Some(_) => Error::Admission(Box::new(crate::nip_fi_core::http_denial(class))), - None => legacy, + let refuse = |class, legacy: Error, reason| { + let error = match principal.token_owner { + Some(_) => Error::Admission(Box::new(crate::nip_fi_core::http_denial(class))), + None => legacy, + }; + (error, crate::access::AuthResult::Denied(reason)) }; #[cfg(test)] crate::nip_fi_test_hooks::before_http_ban_recheck(principal.tenant.community()).await; @@ -171,11 +196,25 @@ pub(super) async fn recheck( .db .moderation_restriction_state(principal.tenant.community(), &principal.actor.to_bytes()) .await - .map_err(|_| refuse(DenialClass::AuthorizationUnavailable, Error::unavailable()))?; + .map_err(|_| { + crate::nip_fi_http::owner_refused( + DenialClass::AuthorizationUnavailable, + "owner_ban_unavailable", + ); + refuse( + DenialClass::AuthorizationUnavailable, + Error::unavailable(), + crate::access::AuthReason::BanCheckUnavailable, + ) + })?; if restrictions.banned { + if !restrictions.own_banned { + crate::nip_fi_http::owner_refused(DenialClass::AuthorizationDenied, "owner_banned"); + } return Err(refuse( DenialClass::AuthorizationDenied, Error::new(StatusCode::FORBIDDEN, "forbidden"), + crate::access::AuthReason::Banned, )); } // Timeouts block posting conversation content, not personal reading. diff --git a/crates/buzz-relay/src/api/buzz_v1/handlers.rs b/crates/buzz-relay/src/api/buzz_v1/handlers.rs index f3dbf095654..c6c24d79b40 100644 --- a/crates/buzz-relay/src/api/buzz_v1/handlers.rs +++ b/crates/buzz-relay/src/api/buzz_v1/handlers.rs @@ -35,12 +35,13 @@ pub(super) struct SidebarQuery { pub(super) async fn sidebar( State(state): State>, + slot: crate::access::AccessSlot, headers: HeaderMap, OriginalUri(uri): OriginalUri, query: Result, axum::extract::rejection::QueryRejection>, ) -> Result { tokio::time::timeout(Duration::from_secs(8), async { - let principal = auth::authorize(&state, &headers, &uri, "GET", None).await?; + let principal = auth::authorize(&state, &slot, &headers, &uri, "GET", None).await?; let Query(query) = query.map_err(|_| Error::invalid())?; if query .limit @@ -139,6 +140,7 @@ struct Batch { pub(super) async fn write( State(state): State>, + slot: crate::access::AccessSlot, headers: HeaderMap, OriginalUri(uri): OriginalUri, body: Bytes, @@ -146,7 +148,7 @@ pub(super) async fn write( if body.len() > 64 * 1024 { return Err(Error::invalid()); } - let principal = auth::authorize(&state, &headers, &uri, "POST", Some(&body)).await?; + let principal = auth::authorize(&state, &slot, &headers, &uri, "POST", Some(&body)).await?; let batch: Batch = serde_json::from_slice(&body).map_err(|_| Error::invalid())?; if batch.intents.is_empty() || batch.intents.len() > MAX_INTENTS { return Err(Error::invalid()); diff --git a/crates/buzz-relay/src/api/buzz_v1/postgres_tests.rs b/crates/buzz-relay/src/api/buzz_v1/postgres_tests.rs index 8c235e90d89..0fd441e7e5d 100644 --- a/crates/buzz-relay/src/api/buzz_v1/postgres_tests.rs +++ b/crates/buzz-relay/src/api/buzz_v1/postgres_tests.rs @@ -438,11 +438,17 @@ async fn accessory_write_revocation_is_terminal_before_persistence() { .parse() .unwrap(), ); - let principal = - super::auth::authorize(&state, &headers, &path.parse().unwrap(), "POST", Some(body)) - .await - .ok() - .expect("admitted before revoke"); + let principal = super::auth::authorize( + &state, + &crate::access::AccessSlot::default(), + &headers, + &path.parse().unwrap(), + "POST", + Some(body), + ) + .await + .ok() + .expect("admitted before revoke"); state .db .remove_relay_member( @@ -497,6 +503,14 @@ async fn accessory_discovery_is_host_bound_and_opt_in() { ) .await .unwrap(); + if !known_host { + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert_eq!( + response.headers()[axum::http::header::CACHE_CONTROL], + "no-store" + ); + continue; + } assert_eq!(response.status(), StatusCode::OK); let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap(); let doc: Value = serde_json::from_slice(&bytes).unwrap(); diff --git a/crates/buzz-relay/src/api/gifs.rs b/crates/buzz-relay/src/api/gifs.rs index c1d087dfce0..f77b2678078 100644 --- a/crates/buzz-relay/src/api/gifs.rs +++ b/crates/buzz-relay/src/api/gifs.rs @@ -217,15 +217,19 @@ fn successful_search_payload(upstream: &Value) -> Result>, + slot: crate::access::AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Response { - search_inner(state, headers, body).await.into_response() + search_inner(state, slot, headers, body) + .await + .into_response() } #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn search_inner( state: Arc, + slot: crate::access::AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, Response> { @@ -233,7 +237,7 @@ async fn search_inner( // check (including provider availability) so the denial contract wins over // config or request-validation errors. [FI-TRACE-HTTP-INGRESS] let (tenant, pubkey) = - bridge::authenticate_member_post(&state, &headers, SEARCH_PATH, &body).await?; + bridge::authenticate_member_post(&state, &slot, &headers, SEARCH_PATH, &body).await?; let Some(config) = state.config.klipy.as_ref() else { return Err( @@ -294,21 +298,25 @@ async fn search_inner( /// Report a selected GIF to KLIPY so the provider can update Recents. pub async fn share( State(state): State>, + slot: crate::access::AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Response { - share_inner(state, headers, body).await.into_response() + share_inner(state, slot, headers, body) + .await + .into_response() } #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn share_inner( state: Arc, + slot: crate::access::AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result { // Admission first: NIP-98 + NIP-FI must fire before provider availability // check. [FI-TRACE-HTTP-INGRESS] - bridge::authenticate_member_post(&state, &headers, SHARE_PATH, &body).await?; + bridge::authenticate_member_post(&state, &slot, &headers, SHARE_PATH, &body).await?; let Some(config) = state.config.klipy.as_ref() else { return Err( @@ -360,9 +368,8 @@ mod tests { .connect_lazy("postgres://buzz:buzz_dev@127.0.0.1:1/buzz") // sadscan:disable np.postgres.1 .expect("lazy test database pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("lazy test Redis pool"); + let redis_pool = + buzz_pubsub::redis_connection(&config.redis_url).expect("lazy test Redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await diff --git a/crates/buzz-relay/src/api/git/cas_publish.rs b/crates/buzz-relay/src/api/git/cas_publish.rs index 50bb36d818c..438c16a4f78 100644 --- a/crates/buzz-relay/src/api/git/cas_publish.rs +++ b/crates/buzz-relay/src/api/git/cas_publish.rs @@ -1,30 +1,34 @@ -//! Push commit point — content-addressed pack + manifest CAS (§Push step 2–7). +//! Push commit point — content-addressed pack + manifest CAS (§Push steps 3–7 +//! of `docs/git-on-object-storage.md`). //! -//! Pure async function over the spec's commit primitives. Given the post- -//! receive-pack repository workspace and the object-store client, this: +//! This module holds the two halves of what happens after `git receive-pack` +//! returns. //! -//! 1. Reads the current pointer → `(e, d_before)` (§Push step 3). -//! 2. Fetches `m_before` via `get_verified(d_before)` (§Push step 3) — -//! digest-verified so a corrupt manifest fails closed, not silently. -//! 3. Snapshots refs + HEAD off the workspace (the receive-pack's published -//! state, by which point the pre-receive hook has enforced fast-forward / -//! branch-protection against the parent's refs). -//! 4. Normally captures the new objects as a delta pack via `git pack-objects +//! **Deciding (§Push step 3).** [`snapshot_workspace`] reads the refs and HEAD +//! that receive-pack left in the workspace, and [`push_disposition`] compares +//! them with the refs the workspace was hydrated from. Only a push that +//! changed refs is published. +//! +//! **Publishing (§Push steps 4–7).** [`cas_publish`] takes that snapshot and +//! the [`ParentState`] the workspace was hydrated from. It never re-reads the +//! pointer before the conditional write. It: +//! +//! 1. Normally captures the new objects as a delta pack via `git pack-objects //! --revs --stdout` over `(refs_after) --not (refs_before-tips)` (§Push -//! step 1–2). Before the manifest reaches its pack cap, compaction instead +//! step 4). Before the manifest reaches its pack cap, compaction instead //! captures the complete `refs_after` closure into bounded replacement //! packs. Empty output for a ref-less repository is allowed. -//! 5. `put_pack` (content-addressed, create-only, idempotent — §Push step 2). +//! 2. `put_pack` (content-addressed, create-only, idempotent — §Push step 5). //! The key is derived from `sha256(bytes)` by the store layer. -//! 6. Composes `m_after`: normal pushes use parent packs ∪ new pack; +//! 3. Composes `m_after`: normal pushes use parent packs ∪ new pack; //! compaction replaces the pack list with the newly captured full closure. -//! Both retain the parent digest and post-push refs (§Push step 5). -//! 7. `put_manifest` (content-addressed, create-only, idempotent — §Push -//! step 6). -//! 8. `put_pointer(IfMatch(e) | IfNoneMatchStar)` — the CAS (§Push step 7). +//! Both retain the parent digest and post-push refs. `put_manifest` +//! (content-addressed, create-only, idempotent — §Push step 6). +//! 4. `put_pointer(IfMatch(e) | IfNoneMatchStar)` — the CAS (§Push step 7), +//! with `e` taken from the `ParentState`. //! - `Won` → return `CasSuccess { manifest, manifest_key }`. The caller -//! then derives kind:30618 against `m_after` (Sami's -//! `manifest_event::build_ref_state_event`) and constructs the +//! then derives kind:30618 against `m_after` +//! (`manifest_event::build_ref_state_event`) and constructs the //! success response — the *fence* in §Push step 8. //! - `LostRace` → re-read the pointer to fetch the winner's manifest, //! then return `CasError::Conflict { winner_manifest, @@ -32,11 +36,11 @@ //! the caller's diagnostic + future cache; the loser's ephemeral //! tempdir dies on scope exit, so there's no disk to reconcile. //! **No retry.** The losing push's receive-pack output was derived -//! against the now-superseded parent; reusing it would violate -//! `Inv_RefDerivedFromParent` (§Mechanized Verification). The client -//! re-runs `git push`, which re-hydrates and re-runs receive-pack -//! against the advanced state — that is the only safe retry, and -//! `git`'s own machinery already does it. +//! against the now-superseded parent, so nothing computed from it may +//! be published (the model's seeded error `stale-base` is that +//! mistake; see §Mechanized Verification). The client re-runs +//! `git push`, which re-hydrates and re-runs receive-pack against the +//! advanced state. //! //! ## Fence positioning //! @@ -47,11 +51,9 @@ //! //! ## What this function deliberately does *not* do //! -//! - **No retry on `LostRace`.** Per spec §Push step 7 "GOTO 3 (retry) or -//! respond non-ff": both arms are safe; we take the non-ff arm because -//! reusing receive-pack's output against a moved parent isn't safe and -//! re-hydrating from inside the handler is expensive. Sami's TLA-action -//! guidance is explicit: retry would change the TLA action. +//! - **No retry on `LostRace`.** See above: re-using receive-pack's output +//! against a moved parent is unsafe, and re-hydrating from inside the +//! handler is expensive. //! - **No kind:30618 emission.** That is the *derived* publication after a //! successful CAS. Caller passes `m_after` into //! `manifest_event::build_ref_state_event` *after* this returns `Ok`. @@ -59,7 +61,7 @@ //! CAS, never the commit." //! - **No advisory lock.** Spec §Push, "No advisory lock in v1": writer //! serialization is the CAS. Adding a per-repo mutex would hide the -//! exact contention `Inv_NoFork` proves safe. +//! exact contention the refinement check (`Inv_NoFork`) covers. use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; @@ -72,8 +74,8 @@ use tokio::process::Command; use tracing::{debug, warn}; use crate::api::git::manifest::{ - pointer_key, Manifest, ManifestError, MANIFEST_VERSION, MAX_MANIFEST_PACKS, MAX_MANIFEST_REFS, - PACK_COMPACTION_THRESHOLD, + next_published_at, pointer_key, Manifest, ManifestError, MANIFEST_VERSION, MAX_MANIFEST_PACKS, + MAX_MANIFEST_REFS, PACK_COMPACTION_THRESHOLD, }; use crate::api::git::store::{CasOutcome, ETag, GitStore, Precond, StoreError}; use buzz_core::TenantContext; @@ -196,7 +198,7 @@ pub struct CasSuccess { pub manifest_key: String, } -/// Resolved view of the pre-push pointer (§Push step 3 output). +/// Resolved view of the pre-push pointer (§Push step 1 output). /// /// **The CAS write is predicated on `if_match`** — the caller must load /// this *before* running receive-pack against the hydrated workspace, and @@ -239,6 +241,7 @@ impl ParentState { refs: BTreeMap::new(), packs: Vec::new(), parent: None, + published_at: None, }, } } @@ -260,16 +263,112 @@ impl ParentState { } } -/// Read `refs/*` + symbolic-HEAD from the workspace. +/// Ref state of a workspace: every ref and the symbolic HEAD. /// -/// HEAD is the symref target (e.g. `refs/heads/main`), unprefixed — the -/// manifest stores published ref state, not protocol formatting. Detached -/// HEAD or no HEAD yields an empty string. -async fn snapshot_workspace_state( - repo_path: &Path, - scratch_dir: &Path, -) -> Result<(BTreeMap, String), CasError> { +/// This is the relay's only evidence of what `git receive-pack` did. Both the +/// decision whether to publish ([`push_disposition`]) and the published +/// manifest ([`cas_publish`]) are computed from one value of this type, so +/// they cannot disagree about what the push changed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WorkspaceState { + /// Every ref in the workspace, mapped to the object id it names. + pub refs: BTreeMap, + /// The symbolic-ref target of `HEAD` (for example `refs/heads/main`), or + /// an empty string when `HEAD` is detached or missing. + pub head: String, +} + +/// What a finished `git receive-pack` run obliges the relay to do. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PushDisposition { + /// The workspace refs equal the refs it was hydrated from. There is + /// nothing to publish; the client is answered with git's own output. + RelayOnly, + /// The workspace refs changed and git exited normally. The change must + /// be published before the client is told anything. + Publish, + /// The workspace refs changed but git exited abnormally. Its report to + /// the client may be incomplete, so nothing is published and the request + /// fails. + Abort, +} + +/// Decide what to do with a finished push from the refs it left behind. +/// +/// The decision compares the workspace refs with the refs the workspace was +/// hydrated from. It does not read git's report-status stream, for two +/// reasons. A client chooses whether that stream exists, and git exits zero +/// both for a request that carries no commands and for one a hook declined, so +/// the stream cannot show that a push was authorized. And a push that updates +/// one ref and is refused another reports both outcomes, so an `ng` line does +/// not show that nothing changed. +/// +/// The decision is sound under one assumption about git: `receive-pack` +/// changes a ref only by applying a command the client submitted, and only +/// after the pre-receive hook accepted the whole command list. Then changed +/// refs imply an accepted push. Unchanged refs imply that any `ok` git +/// reported belongs to a command that asked for the value the ref already +/// had, which is true of the published state the workspace was hydrated +/// from, so git's report can be passed on as it is. +/// `docs/spec/GitOnObjectStore.tla` states this as `Disposition` and checks +/// it against the legacy rule. +pub fn push_disposition( + exited_ok: bool, + parent_refs: &BTreeMap, + workspace_refs: &BTreeMap, +) -> PushDisposition { + if workspace_refs == parent_refs { + PushDisposition::RelayOnly + } else if exited_ok { + PushDisposition::Publish + } else { + PushDisposition::Abort + } +} + +/// Parse `git for-each-ref --format='%(refname) %(objectname)'` output. +/// +/// Every line must be a ref name, one space, and a 40-hex object id. Anything +/// else is an error: a line that is skipped would publish a manifest without +/// that ref, which deletes the ref for every later reader. +fn parse_ref_snapshot(stdout: &[u8]) -> Result, CasError> { + let text = std::str::from_utf8(stdout) + .map_err(|e| CasError::PackCapture(format!("for-each-ref output is not UTF-8: {e}")))?; + let mut refs = BTreeMap::new(); + for line in text.lines() { + let well_formed = line.split_once(' ').filter(|(name, oid)| { + !name.is_empty() && oid.len() == 40 && oid.chars().all(|c| c.is_ascii_hexdigit()) + }); + let Some((name, oid)) = well_formed else { + return Err(CasError::PackCapture(format!( + "for-each-ref returned a malformed line: {line:?}" + ))); + }; + if refs.len() >= MAX_MANIFEST_REFS && !refs.contains_key(name) { + return Err(CasError::ResourceLimit(format!( + "workspace contains more than {MAX_MANIFEST_REFS} refs" + ))); + } + refs.insert(name.to_string(), oid.to_string()); + } + Ok(refs) +} + +/// Directory for the temporary files of a publication. +/// +/// Hydrated repositories are direct children of the configured Git scratch +/// root. Reusing that parent keeps temporary files on the mounted scratch +/// volume without another path argument. +fn scratch_dir_of(repo_path: &Path) -> Result<&Path, CasError> { + repo_path + .parent() + .ok_or_else(|| CasError::PackCapture("repository path has no scratch parent".into())) +} + +/// Read every ref and the symbolic HEAD from the workspace at `repo_path`. +pub async fn snapshot_workspace(repo_path: &Path) -> Result { const MAX_REF_SNAPSHOT_BYTES: u64 = 4 * 1024 * 1024; + let scratch_dir = scratch_dir_of(repo_path)?; let refs_stdout_tmp = tempfile::NamedTempFile::new_in(scratch_dir) .map_err(|e| CasError::PackCapture(format!("for-each-ref stdout tempfile: {e}")))?; @@ -313,26 +412,7 @@ async fn snapshot_workspace_state( .await .map_err(|e| CasError::PackCapture(format!("for-each-ref stdout read: {e}")))?; - let mut refs = BTreeMap::new(); - for line in std::str::from_utf8(&refs_stdout) - .unwrap_or_default() - .lines() - { - let mut parts = line.splitn(2, ' '); - let (Some(name), Some(oid)) = (parts.next(), parts.next()) else { - continue; - }; - if oid.len() != 40 || !oid.chars().all(|c| c.is_ascii_hexdigit()) { - warn!(ref_name = %name, oid = %oid, "for-each-ref returned malformed oid; skipping"); - continue; - } - if refs.len() >= MAX_MANIFEST_REFS && !refs.contains_key(name) { - return Err(CasError::ResourceLimit(format!( - "workspace contains more than {MAX_MANIFEST_REFS} refs" - ))); - } - refs.insert(name.to_string(), oid.to_string()); - } + let refs = parse_ref_snapshot(&refs_stdout)?; let mut head_cmd = Command::new("git"); head_cmd @@ -349,7 +429,7 @@ async fn snapshot_workspace_state( String::new() }; - Ok((refs, head)) + Ok(WorkspaceState { refs, head }) } fn resolve_published_head( @@ -925,6 +1005,7 @@ fn compose_after( refs, packs, parent: parent_digest, + published_at: None, } } @@ -942,6 +1023,7 @@ fn compose_compacted_after( refs, packs: compacted_pack_keys, parent: parent_digest, + published_at: None, } } @@ -977,14 +1059,16 @@ fn record_compaction( } } -/// The function the §Push step 2–7 protocol distills to. +/// The function the §Push step 4–7 protocol distills to. /// /// **Caller contract — `Inv_RefDerivedFromParent` is structural.** The /// `parent_state` you pass in must be the same one the workspace was /// hydrated from. Concretely: `hydrate::hydrate_for_write(store, ctx, owner, /// repo)` returns `(HydratedRepo, ParentState)` from a single pointer /// observation → `install_hook(repo.path())` → run `receive-pack` -/// against the workspace → call this with the **same `parent_state`**. +/// against the workspace → [`snapshot_workspace`] → call this with the +/// **same `parent_state`** and that snapshot, and only when +/// [`push_disposition`] returned [`PushDisposition::Publish`]. /// The CAS predicate is `parent_state.if_match`, so a concurrent writer /// that advanced the pointer between hydrate and CAS reliably surfaces /// as `CasError::Conflict { winner_manifest, .. }` (412 → HTTP 409). The @@ -994,6 +1078,7 @@ fn record_compaction( /// at step 7 is the *only* writer serialization (`Inv_NoFork`). No /// advisory lock — adding one would hide exactly the interleavings the /// model proves safe. +#[allow(clippy::too_many_arguments)] // the store, the repository identity and the two ref states pub async fn cas_publish( store: &GitStore, ctx: &TenantContext, @@ -1001,6 +1086,7 @@ pub async fn cas_publish( owner: &str, repo: &str, parent_state: &ParentState, + workspace: &WorkspaceState, limits: PublishLimits, ) -> Result { cas_publish_inner( @@ -1010,6 +1096,7 @@ pub async fn cas_publish( owner, repo, parent_state, + workspace, PublishOptions { limits, compaction_threshold: PACK_COMPACTION_THRESHOLD, @@ -1018,6 +1105,7 @@ pub async fn cas_publish( .await } +#[allow(clippy::too_many_arguments)] // same parameters as `cas_publish` async fn cas_publish_inner( store: &GitStore, ctx: &TenantContext, @@ -1025,27 +1113,26 @@ async fn cas_publish_inner( owner: &str, repo: &str, parent_state: &ParentState, + workspace: &WorkspaceState, options: PublishOptions, ) -> Result { let limits = options.limits; let pkey = pointer_key(ctx.community(), owner, repo); + let scratch_dir = scratch_dir_of(repo_path)?; - // Hydrated repositories are direct children of the configured Git scratch - // root. Reuse that parent for publication tempfiles so they remain on the - // mounted scratch volume without adding another independent path argument. - let scratch_dir = repo_path - .parent() - .ok_or_else(|| CasError::PackCapture("repository path has no scratch parent".into()))?; - - // Snapshot post-receive-pack state from disk. `parent_state.parent.refs` + // `workspace` is the post-receive-pack state. `parent_state.parent.refs` // are the refs the workspace was hydrated from — `pack-objects --revs` // below uses them as the "negative" set to produce the delta pack. - let (refs_after, head_observed) = snapshot_workspace_state(repo_path, scratch_dir).await?; + let refs_after = workspace.refs.clone(); // Fresh bare repositories can inherit Git's environment-dependent // `master` symref even when the first push creates `main`. Publish a real // branch whenever one exists so HEAD never advertises a phantom branch. - let head = resolve_published_head(&refs_after, head_observed, &parent_state.parent.head); + let head = resolve_published_head( + &refs_after, + workspace.head.clone(), + &parent_state.parent.head, + ); let packs_before = parent_state.parent.packs.len(); let mut compaction_failure = None; @@ -1168,6 +1255,16 @@ async fn cas_publish_inner( new_pack_key, ) }; + // Stamp the publication time on both the compacted and delta-pack paths. + // Strictly after the parent's stamp, so the derived kind:30618 events sort + // in manifest-chain order whichever instance and clock emit them. + let m_after = Manifest { + published_at: Some(next_published_at( + &parent_state.parent, + nostr::Timestamp::now().as_secs(), + )), + ..m_after + }; // **Pre-CAS validation** (Sami #2 / Max / Dawn): refuse to commit an // un-clone-able manifest. `Manifest::validate` checks every refname @@ -1391,6 +1488,67 @@ mod tests { assert!(digest_from_manifest_key("not/manifests/abc").is_err()); } + #[test] + fn push_disposition_publishes_only_changed_refs_from_a_clean_exit() { + let parent: BTreeMap = + [("refs/heads/main".to_string(), "1".repeat(40))].into(); + let mut advanced = parent.clone(); + advanced.insert("refs/heads/main".into(), "2".repeat(40)); + let mut created = parent.clone(); + created.insert("refs/heads/feature".into(), "1".repeat(40)); + let deleted = BTreeMap::new(); + + for exited_ok in [true, false] { + assert_eq!( + push_disposition(exited_ok, &parent, &parent), + PushDisposition::RelayOnly, + "unchanged refs are never published (exited_ok = {exited_ok})" + ); + } + for changed in [&advanced, &created, &deleted] { + assert_eq!( + push_disposition(true, &parent, changed), + PushDisposition::Publish + ); + assert_eq!( + push_disposition(false, &parent, changed), + PushDisposition::Abort + ); + } + } + + #[test] + fn ref_snapshot_rejects_every_line_it_cannot_read() { + let oid = "a".repeat(40); + let good = format!("refs/heads/main {oid}\nrefs/tags/v1 {oid}\n"); + let refs = parse_ref_snapshot(good.as_bytes()).expect("well-formed snapshot"); + assert_eq!(refs.len(), 2); + assert_eq!(refs.get("refs/heads/main"), Some(&oid)); + assert!(parse_ref_snapshot(b"").expect("empty snapshot").is_empty()); + + // A skipped line would publish a manifest without that ref. Each of + // these used to be skipped, and non-UTF-8 output used to read as an + // empty repository. + let mut not_utf8 = good.clone().into_bytes(); + not_utf8.extend_from_slice(b"refs/heads/\xff "); + not_utf8.extend_from_slice(oid.as_bytes()); + not_utf8.push(b'\n'); + let malformed: [Vec; 5] = [ + not_utf8, + format!("{good}refs/heads/no-oid\n").into_bytes(), + format!("{good}refs/heads/short abc123\n").into_bytes(), + format!("{good}refs/heads/not-hex {}\n", "z".repeat(40)).into_bytes(), + format!("{good} {oid}\n").into_bytes(), + ]; + for input in malformed { + assert!( + matches!(parse_ref_snapshot(&input), Err(CasError::PackCapture(_))), + "accepted {:?}", + String::from_utf8_lossy(&input) + ); + } + } + #[test] fn compose_after_first_push() { let parent = ParentState::fresh().parent; @@ -1700,6 +1858,8 @@ mod tests { refs: parent_refs, packs: vec![first_pack_key, second_pack_key], parent: None, + // Stamped by an instance whose clock runs far ahead of this one. + published_at: Some(4_000_000_000), }; parent.validate().expect("parent manifest"); let parent_key = store @@ -1764,6 +1924,9 @@ mod tests { limits, compaction_threshold: 2, }; + let workspace = snapshot_workspace(hydrated.path()) + .await + .expect("snapshot pushed workspace"); let success = cas_publish_inner( &store, &ctx, @@ -1771,6 +1934,7 @@ mod tests { &owner, repo, &parent_state, + &workspace, test_options, ) .await @@ -1782,6 +1946,11 @@ mod tests { ); assert!(success.manifest.refs.contains_key("refs/tags/v1")); assert_eq!(success.manifest.parent, Some(parent_digest)); + assert_eq!( + success.manifest.published_at, + Some(4_000_000_001), + "the child's kind:30618 must sort after its parent's" + ); let conflict = cas_publish_inner( &store, @@ -1790,6 +1959,7 @@ mod tests { &owner, repo, &parent_state, + &workspace, test_options, ) .await diff --git a/crates/buzz-relay/src/api/git/hydrate.rs b/crates/buzz-relay/src/api/git/hydrate.rs index 080bbd5c1cc..2c7f712b56b 100644 --- a/crates/buzz-relay/src/api/git/hydrate.rs +++ b/crates/buzz-relay/src/api/git/hydrate.rs @@ -558,6 +558,7 @@ mod tests { refs: BTreeMap::new(), packs: Vec::new(), parent: None, + published_at: None, }; let cache = GitPackCache::new(scratch.path(), u64::MAX, 2).expect("cache"); @@ -666,6 +667,7 @@ mod tests { refs, packs: vec![pack_key.clone()], parent: None, + published_at: None, }; let manifest_bytes = manifest.canonical_bytes().expect("serialize"); let manifest_key = st @@ -814,6 +816,7 @@ mod tests { refs: BTreeMap::new(), packs: vec![], parent: None, + published_at: None, }; let manifest_bytes = manifest.canonical_bytes().expect("serialize"); let manifest_key = st diff --git a/crates/buzz-relay/src/api/git/manifest.rs b/crates/buzz-relay/src/api/git/manifest.rs index 0dfbdb35a4d..1d2687da4ac 100644 --- a/crates/buzz-relay/src/api/git/manifest.rs +++ b/crates/buzz-relay/src/api/git/manifest.rs @@ -12,8 +12,9 @@ //! //! - `refs: BTreeMap` — sorted ref names at serialization. //! - `packs: Vec` — sorted by `canonical_bytes()` before writing. -//! - Struct field order: `version`, `head`, `refs`, `packs`, `parent` -//! (matches declaration; serde emits in this order). +//! - Struct field order: `version`, `head`, `refs`, `packs`, `parent`, +//! `published_at` (matches declaration; serde emits in this order, and +//! omits `published_at` when absent). //! - `serde_json::to_vec` — no whitespace. //! //! Round-trip + byte-stability are pinned in unit tests. @@ -68,6 +69,29 @@ pub struct Manifest { /// reads literally as `parent = pointer.digest`. Writers must strip any /// `manifests/` prefix before assigning. Enforced by `validate()`. pub parent: Option, + /// Unix seconds at which a push published this manifest, strictly greater + /// than the parent's. The derived kind:30618 carries it as `created_at`, + /// so readers that pick the newest event follow the manifest chain rather + /// than the order in which relay instances happened to stamp events. + /// `None` for the shared announce-time seed and for manifests written + /// before the field existed; omitted from canonical JSON in that case so + /// those manifests keep their bytes and digests. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub published_at: Option, +} + +/// The `published_at` for a manifest superseding `parent`: `now`, advanced +/// past the parent's own `published_at` when the clock has not moved on (two +/// pushes in one second) or runs behind the instance that wrote the parent. +/// +/// An unstamped parent (the announce-time seed, or a manifest written before +/// the field existed) had its kind:30618 stamped at or before `now`, possibly +/// in this same second, so the successor takes `now + 1` to sort after it. +pub fn next_published_at(parent: &Manifest, now: u64) -> u64 { + match parent.published_at { + Some(previous) => now.max(previous.saturating_add(1)), + None => now.saturating_add(1), + } } /// Errors from manifest (de)serialization or validation. @@ -296,6 +320,7 @@ mod tests { refs, packs: vec![pack_key('c'), pack_key('d')], parent: Some("ee".repeat(32)), + published_at: None, } } @@ -371,6 +396,7 @@ mod tests { refs: BTreeMap::new(), packs: Vec::new(), parent: None, + published_at: None, }; m.validate().expect("empty manifest is the announce-seed"); // Canonical bytes must be deterministic + stable so all empty manifests @@ -567,6 +593,7 @@ mod tests { refs, packs: vec![pack_key('1')], parent: None, + published_at: None, }; let bytes = m.canonical_bytes().unwrap(); let s = std::str::from_utf8(&bytes).unwrap(); @@ -578,4 +605,44 @@ mod tests { ) ); } + + #[test] + fn published_at_serializes_last_and_round_trips() { + let mut m = sample(); + m.parent = None; + m.refs.clear(); + m.packs.clear(); + m.published_at = Some(1_700_000_000); + let bytes = m.canonical_bytes().unwrap(); + assert_eq!( + std::str::from_utf8(&bytes).unwrap(), + r#"{"version":1,"head":"refs/heads/main","refs":{},"packs":[],"parent":null,"published_at":1700000000}"# + ); + assert_eq!(Manifest::from_bytes(&bytes).unwrap(), m); + } + + #[test] + fn manifests_without_published_at_still_parse() { + let legacy = + br#"{"version":1,"head":"refs/heads/main","refs":{},"packs":[],"parent":null}"#; + let m = Manifest::from_bytes(legacy).unwrap(); + assert_eq!(m.published_at, None); + assert_eq!(m.canonical_bytes().unwrap(), legacy.to_vec()); + } + + #[test] + fn next_published_at_strictly_follows_the_parent() { + let mut parent = sample(); + parent.published_at = None; + assert_eq!(next_published_at(&parent, 100), 101); + + parent.published_at = Some(90); + assert_eq!(next_published_at(&parent, 100), 100); + // Same second as the parent. + parent.published_at = Some(100); + assert_eq!(next_published_at(&parent, 100), 101); + // The parent's instance clock ran ahead of ours. + parent.published_at = Some(105); + assert_eq!(next_published_at(&parent, 100), 106); + } } diff --git a/crates/buzz-relay/src/api/git/manifest_event.rs b/crates/buzz-relay/src/api/git/manifest_event.rs index 698f27e9d1e..96ab7931790 100644 --- a/crates/buzz-relay/src/api/git/manifest_event.rs +++ b/crates/buzz-relay/src/api/git/manifest_event.rs @@ -18,7 +18,7 @@ use std::collections::BTreeMap; -use nostr::{Event, EventBuilder, Keys, Kind, PublicKey, Tag, TagKind}; +use nostr::{Event, EventBuilder, Keys, Kind, PublicKey, Tag, TagKind, Timestamp}; /// Subset of `Manifest` needed to emit a kind:30618 event. /// @@ -39,6 +39,10 @@ pub struct RefStateInputs<'a> { /// the pusher's pubkey from the receive-pack hook. On repo-creation, this /// is the kind:30617 author (repo owner). Hex-encoded (64 chars). pub actor_pubkey_hex: &'a str, + /// The manifest's `published_at`, used as the event's `created_at` so + /// readers that pick the newest kind:30618 see the newest manifest. `None` + /// (a manifest written before the field existed) falls back to now. + pub published_at: Option, } /// Errors from building a kind:30618 ref-state event. @@ -105,8 +109,11 @@ pub fn build_ref_state_event( // p-tag: buzz extension (pusher or owner pubkey). tags.push(Tag::public_key(actor)); - let event = EventBuilder::new(Kind::Custom(30618), "") - .tags(tags) + let mut builder = EventBuilder::new(Kind::Custom(30618), "").tags(tags); + if let Some(published_at) = inputs.published_at { + builder = builder.custom_created_at(Timestamp::from(published_at)); + } + let event = builder .sign_with_keys(relay_keys) .map_err(|e| BuildError::Sign(e.to_string()))?; @@ -183,6 +190,7 @@ mod tests { head: "refs/heads/main", refs: &refs, actor_pubkey_hex: &owner, + published_at: None, }; let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); @@ -214,6 +222,7 @@ mod tests { head: "refs/heads/dev", refs: &refs, actor_pubkey_hex: &owner_hex(), + published_at: None, }; let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); assert_eq!(first_tag(&ev, "HEAD").unwrap()[1], "ref: refs/heads/dev"); @@ -234,6 +243,7 @@ mod tests { head: "refs/heads/main", refs: &refs, actor_pubkey_hex: &owner_hex(), + published_at: None, }; let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); @@ -277,6 +287,7 @@ mod tests { head: "refs/heads/main", refs: &refs, actor_pubkey_hex: &owner_hex(), + published_at: None, }; let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); @@ -300,6 +311,7 @@ mod tests { head: "refs/heads/sha1-branch", refs: &refs, actor_pubkey_hex: &owner_hex(), + published_at: None, }; let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); assert!(first_tag(&ev, "refs/heads/sha1-branch").is_some()); @@ -325,6 +337,7 @@ mod tests { head: "refs/heads/ok", refs: &refs, actor_pubkey_hex: &owner_hex(), + published_at: None, }; let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); assert!(first_tag(&ev, "refs/heads/short").is_none()); @@ -358,6 +371,7 @@ mod tests { head: "refs/heads/legit", refs: &refs, actor_pubkey_hex: &owner_hex(), + published_at: None, }; let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); assert!(first_tag(&ev, "refs/heads/legit").is_some()); @@ -373,6 +387,7 @@ mod tests { head: "refs/heads/main", refs: &refs, actor_pubkey_hex: "not-a-pubkey", + published_at: None, }; let err = build_ref_state_event(&inputs, &relay_keys()).unwrap_err(); assert!(matches!(err, BuildError::InvalidActor(_))); @@ -386,10 +401,26 @@ mod tests { head: "refs/heads/main", refs: &refs, actor_pubkey_hex: &owner_hex(), + published_at: None, }; let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); assert_eq!(first_tag(&ev, "d").unwrap()[1], "myrepo"); // Pin: caller responsibility — if they pass "myrepo.git", that's what // ends up in the d-tag and won't match the kind:30617 announcement. } + + #[test] + fn created_at_is_the_manifest_published_at() { + let refs = refs_with(&[]); + let inputs = RefStateInputs { + repo_id: "r", + head: "refs/heads/main", + refs: &refs, + actor_pubkey_hex: &owner_hex(), + published_at: Some(1_700_000_000), + }; + let ev = build_ref_state_event(&inputs, &relay_keys()).unwrap(); + assert_eq!(ev.created_at, Timestamp::from(1_700_000_000)); + ev.verify().expect("signature covers the custom created_at"); + } } diff --git a/crates/buzz-relay/src/api/git/mod.rs b/crates/buzz-relay/src/api/git/mod.rs index 1db75ce39c5..b012fdf65c5 100644 --- a/crates/buzz-relay/src/api/git/mod.rs +++ b/crates/buzz-relay/src/api/git/mod.rs @@ -62,7 +62,9 @@ async fn require_localhost(req: Request, next: Next) -> Response { pub fn git_policy_router(state: Arc) -> Router { Router::new() .route("/internal/git/policy", post(policy::hook_policy_check)) - .layer(RequestBodyLimitLayer::new(1024 * 1024)) // 1 MB - .layer(middleware::from_fn(require_localhost)) + // Scope both guards to this path; Router::layer also wraps the default + // fallback, which would reject unrelated unknown URLs after merging. + .route_layer(RequestBodyLimitLayer::new(1024 * 1024)) // 1 MB + .route_layer(middleware::from_fn(require_localhost)) .with_state(state) } diff --git a/crates/buzz-relay/src/api/git/policy.rs b/crates/buzz-relay/src/api/git/policy.rs index 1e376501ab1..3db5e351b39 100644 --- a/crates/buzz-relay/src/api/git/policy.rs +++ b/crates/buzz-relay/src/api/git/policy.rs @@ -244,6 +244,16 @@ pub async fn hook_policy_check( return (StatusCode::FORBIDDEN, "callback timestamp invalid").into_response(); } + // The localhost callback selects its tenant by an HMAC-bound UUID rather + // than Host. Keep the control-plane transport usable for canonical pushes + // without authorizing an extra community in single-community mode. + if !state.config.multi_community_relay { + match state.db.lookup_community_host(community).await { + Ok(Some(host)) if crate::single_community::serves_host(&state.config, &host) => {} + _ => return (StatusCode::FORBIDDEN, "community not served").into_response(), + } + } + // 4. Validate and resolve kind:30617 for this repo. // Query by (community_id, kind=30617, pubkey=owner, d_tag=repo_id) to // prevent spoofing and keep the localhost hook callback on the same @@ -835,9 +845,7 @@ printf '%s' "$HMAC_INPUT" | openssl dgst -sha256 -hmac "{secret}" -hex 2>/dev/nu .await .expect("connect test DB"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await diff --git a/crates/buzz-relay/src/api/git/settings.rs b/crates/buzz-relay/src/api/git/settings.rs index f11e11026b1..5fc3a8a2a66 100644 --- a/crates/buzz-relay/src/api/git/settings.rs +++ b/crates/buzz-relay/src/api/git/settings.rs @@ -25,7 +25,7 @@ use serde_json::{json, Value}; use super::{ binding::{resolve_repo_binding, RepoBinding}, hydrate::load_pointer, - manifest::{is_safe_refname, pointer_key, Manifest}, + manifest::{is_safe_refname, next_published_at, pointer_key, Manifest}, manifest_event::{build_ref_state_event, RefStateInputs}, store::{CasOutcome, ETag, GitStore, Precond}, transport::{authorize_git_read, deny_banned_git_principal, validate_repo_id}, @@ -130,6 +130,10 @@ impl DefaultBranchSnapshot { } let changed = self.manifest.head != head; if changed { + self.manifest.published_at = Some(next_published_at( + &self.manifest, + nostr::Timestamp::now().as_secs(), + )); self.manifest.head = head; self.manifest.parent = Some(self.digest.clone()); self.manifest.validate().map_err(backend)?; @@ -166,6 +170,7 @@ struct SettingsAuth { async fn authenticate( state: &Arc, + slot: &crate::access::AccessSlot, headers: &HeaderMap, path: &str, body: Option<&[u8]>, @@ -188,7 +193,9 @@ async fn authenticate( let admission = admit_nip_fi_http_on_state( state, headers, + slot, bridge::make_nip98_closure_for_admission( + slot.clone(), headers.clone(), method, url, @@ -198,18 +205,16 @@ async fn authenticate( ), ) .await?; - let pubkey = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let (event_id_bytes, signed_created_at) = admission.into_extra(); + let mut caller = bridge::ProvenCaller::new(admission, slot, &tenant); + let (pubkey, signed_created_at, token_owner) = + (caller.pubkey, caller.signed_at, caller.token_owner); - bridge::enforce_http_admission(state, &tenant, &pubkey) - .await - .map_err(IntoResponse::into_response)?; - bridge::check_nip98_replay(state, &tenant, event_id_bytes) + caller + .rate_limit_and_replay(state, &tenant) .await .map_err(IntoResponse::into_response)?; let tag = relay_members::extract_auth_tag_header(headers); - relay_members::enforce_relay_membership( + let membership = relay_members::enforce_relay_membership( state, &tenant, pubkey.as_bytes(), @@ -217,11 +222,13 @@ async fn authenticate( signed_created_at, token_owner, ) - .await - .map_err(IntoResponse::into_response)?; + .await; + caller + .check(membership, relay_members::MembershipRefusal::auth_result) + .map_err(IntoResponse::into_response)?; #[cfg(test)] crate::nip_fi_test_hooks::before_http_ban_recheck(tenant.community()).await; - deny_banned_git_principal( + let ban = deny_banned_git_principal( &state.db, tenant.community(), &pubkey, @@ -229,17 +236,24 @@ async fn authenticate( signed_created_at, token_owner, ) - .await - .map_err(|legacy| match token_owner { - // A verified agent token gets only NIP-FI's fixed denial, as smart - // Git transport does, so the response never shows which step refused. - Some(_) => crate::nip_fi_core::http_denial(if legacy.status().is_server_error() { - buzz_auth::DenialClass::AuthorizationUnavailable - } else { - buzz_auth::DenialClass::AuthorizationDenied - }), - None => legacy, - })?; + .await; + caller + .admit(ban, |refused| { + crate::access::AuthResult::Denied(match refused.status() { + StatusCode::FORBIDDEN => crate::access::AuthReason::Banned, + _ => crate::access::AuthReason::BanCheckUnavailable, + }) + }) + .map_err(|legacy| match token_owner { + // A verified agent token gets only NIP-FI's fixed denial, as smart + // Git transport does, so the response never shows which step refused. + Some(_) => crate::nip_fi_core::http_denial(if legacy.status().is_server_error() { + buzz_auth::DenialClass::AuthorizationUnavailable + } else { + buzz_auth::DenialClass::AuthorizationDenied + }), + None => legacy, + })?; // Admission ignores kind= restrictions by design (NIP-AA). Repository // management must not turn a message-only credential into write authority. // This HTTP operation has no event kind: only kind-unrestricted credentials @@ -331,12 +345,13 @@ async fn authorize_management( async fn get_default_branch( State(state): State>, + slot: crate::access::AccessSlot, Path((owner, repo)): Path<(String, String)>, headers: HeaderMap, ) -> Result, Response> { let path = format!("/git/{owner}/{repo}/default-branch"); let repo_name = validate_repo_id(&owner, &repo)?; - let auth = authenticate(&state, &headers, &path, None).await?; + let auth = authenticate(&state, &slot, &headers, &path, None).await?; authorize_git_read( &state.db, auth.tenant.community(), @@ -352,13 +367,14 @@ async fn get_default_branch( async fn set_default_branch( State(state): State>, + slot: crate::access::AccessSlot, Path((owner, repo)): Path<(String, String)>, headers: HeaderMap, body: Bytes, ) -> Result, Response> { let path = format!("/git/{owner}/{repo}/default-branch"); let repo_name = validate_repo_id(&owner, &repo)?; - let auth = authenticate(&state, &headers, &path, Some(&body)).await?; + let auth = authenticate(&state, &slot, &headers, &path, Some(&body)).await?; let announcement = authorize_git_read( &state.db, auth.tenant.community(), @@ -389,10 +405,17 @@ async fn set_default_branch( ) })?; serving_write.verify().await.map_err(backend)?; - let (snapshot, changed) = serving_write - .protect(snapshot.set(&state.git_store, request)) + // As in `finalize_push`, a pointer CAS that landed stands even if the lease + // check after it fails; the lease-guarded kind:30618 insert decides + // whether publication may continue. + let (set, lease_after_cas) = serving_write + .protect_landed(snapshot.set(&state.git_store, request)) .await - .map_err(backend)??; + .map_err(backend)?; + let (snapshot, changed) = set?; + if let Err(error) = lease_after_cas { + tracing::warn!(%error, "serving lease check failed after the default-branch CAS landed; continuing publication"); + } let publication = async { if changed { let actor = auth.caller.to_hex(); @@ -402,6 +425,7 @@ async fn set_default_branch( head: &snapshot.manifest.head, refs: &snapshot.manifest.refs, actor_pubkey_hex: &actor, + published_at: snapshot.manifest.published_at, }, &state.relay_keypair, ) @@ -423,7 +447,9 @@ async fn set_default_branch( Ok::<(), Response>(()) } .await; - serving_write.finish().await.map_err(backend)?; + if let Err(error) = serving_write.finish().await { + tracing::warn!(%error, "failed to release community serving lease after default-branch publication"); + } // Publication failure is not mistaken for a rolled-back manifest. if publication.is_err() { return Err(error(StatusCode::INTERNAL_SERVER_ERROR, "default branch committed but notification failed; read the current default branch before retrying")); diff --git a/crates/buzz-relay/src/api/git/settings_tests.rs b/crates/buzz-relay/src/api/git/settings_tests.rs index a1dd438e227..0e6bdbb5fcd 100644 --- a/crates/buzz-relay/src/api/git/settings_tests.rs +++ b/crates/buzz-relay/src/api/git/settings_tests.rs @@ -67,9 +67,7 @@ mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -243,9 +241,7 @@ mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -344,9 +340,7 @@ mod postgres_tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1190,9 +1184,7 @@ mod external_infra { if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { db.migrate().await.unwrap(); } - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1344,6 +1336,9 @@ mod external_infra { &self.owner.public_key().to_hex(), &self.repo, &super::super::super::cas_publish::ParentState::fresh(), + &super::super::super::cas_publish::snapshot_workspace(&source) + .await + .unwrap(), limits(0), ) .await @@ -1808,6 +1803,9 @@ mod external_infra { &f.owner.public_key().to_hex(), &f.repo, &parent, + &super::super::super::cas_publish::snapshot_workspace(push.path()) + .await + .unwrap(), limits(push.hydrated_bytes()), ) .await; @@ -1835,6 +1833,9 @@ mod external_infra { &f.owner.public_key().to_hex(), &f.repo, &parent, + &super::super::super::cas_publish::snapshot_workspace(push.path()) + .await + .unwrap(), limits(push.hydrated_bytes()), ) .await @@ -1885,6 +1886,9 @@ mod external_infra { &f.owner.public_key().to_hex(), &f.repo, &parent, + &super::super::super::cas_publish::snapshot_workspace(push.path()) + .await + .unwrap(), limits(push.hydrated_bytes()), ) .await @@ -1911,6 +1915,9 @@ mod external_infra { &f.owner.public_key().to_hex(), &f.repo, &parent, + &super::super::super::cas_publish::snapshot_workspace(push.path()) + .await + .unwrap(), limits(push.hydrated_bytes()), ) .await diff --git a/crates/buzz-relay/src/api/git/store.rs b/crates/buzz-relay/src/api/git/store.rs index bdfca8dcf2d..20b6c026d65 100644 --- a/crates/buzz-relay/src/api/git/store.rs +++ b/crates/buzz-relay/src/api/git/store.rs @@ -99,6 +99,24 @@ pub enum StoreError { Probe(ProbeFailure), } +/// Whether a probe racer's outcome is unknown rather than evidence about A3: +/// it never got a classified response (`Reqwest`/`Http`/`Io` — socket or send +/// failure), or the backend answered 5xx, which S3 documents as a retryable +/// server fault that classifies neither a win nor a precondition loss. The +/// race phases drop these from the observer set; a backend that fails every +/// racer this way still fails closed on the two-observer floor. +fn racer_outcome_unknown(err: &StoreError) -> bool { + matches!( + err, + StoreError::Backend( + S3Error::Reqwest(_) + | S3Error::Http(_) + | S3Error::Io(_) + | S3Error::HttpFailWithBody(500..=599, _) + ) + ) +} + /// Configuration for `GitStore::run_conformance_probe`. /// /// Defaults: 32-way concurrency, 3 rounds. The probe is a deployment gate — @@ -131,9 +149,9 @@ pub struct ProbeReport { /// Total number of *transport-unknown* per-racer outcomes across all /// race rounds (sum of both `if_match_race` and `if_none_match_race` /// phases). A "transport-unknown" is a pre-classification failure — - /// `S3Error::{Reqwest, Http, Io}` — that means the racer never got a - /// classified response from the backend, so its outcome is neither - /// evidence for nor against A3 linearizability. Such racers are + /// `S3Error::{Reqwest, Http, Io}` — or a 5xx response, meaning the racer + /// never got a classified response from the backend, so its outcome is + /// neither evidence for nor against A3 linearizability. Such racers are /// dropped from the observer set (see the race phases for the /// invariant: `classified >= 2` and `winners == 1` *among classified /// observers*). @@ -564,7 +582,10 @@ impl GitStore { /// (read-after-write). /// 2. **`if_match_race`** — `race_width` parallel `put_pointer` calls /// predicated on the same ETag. Exactly one must `Won`; the rest must - /// `LostRace`. Tests A3. + /// `LostRace`, apart from racers whose outcome is unknown (dropped, see + /// `racer_outcome_unknown`). After each round the pointer must read back + /// as the winner's body and ETag, so a dropped racer's write that + /// landed anyway cannot pass. Tests A3. /// 3. **`if_none_match_race`** — `race_width` parallel create-only writes /// against the same digest-shaped key (the same `put_immutable` path /// `put_pack`/`put_manifest` use). Tests A1 + A3 on the create-only @@ -638,49 +659,51 @@ impl GitStore { }; for round in 0..cfg.race_rounds { let arc_self: Arc<&Self> = Arc::new(self); + let bodies: Vec> = (0..cfg.race_width) + .map(|i| format!("round={round},racer={i},nonce={nonce}").into_bytes()) + .collect(); let mut tasks = Vec::with_capacity(cfg.race_width); - for i in 0..cfg.race_width { + for body in &bodies { let me = Arc::clone(&arc_self); let pkey = pointer_key.clone(); let et = etag.clone(); - let body = format!("round={round},racer={i},nonce={nonce}").into_bytes(); - tasks.push(async move { me.put_pointer(&pkey, &body, Precond::IfMatch(et)).await }); + tasks.push(async move { me.put_pointer(&pkey, body, Precond::IfMatch(et)).await }); } let outcomes = futures_util::future::join_all(tasks).await; // Drop-and-floor classification. A `Reqwest`/`Http`/`Io` error // means the racer never got a classified response from the - // backend (couldn't open a socket, send flaked, etc.); its - // outcome is *unknown*, not negative. A3 is a claim about + // backend (couldn't open a socket, send flaked, etc.), and a 5xx + // is the backend declining to classify it; its outcome is + // *unknown*, not negative (`racer_outcome_unknown`). A3 is a claim about // **observers**: dropping unknowns from the observer set // sharpens the assertion ("exactly one winner among observers") // and avoids smuggling a network-stack test into the // conformance probe. Parse/decode errors (`Utf8`, - // `ReqwestHeaderToStr`, `SerdeXml`, ...) and `HttpFailWithBody` - // stay in the catch-all — those mean the backend *did* answer - // but not in the contract shape, which is a real conformance - // signal. + // `ReqwestHeaderToStr`, `SerdeXml`, ...) and non-5xx + // `HttpFailWithBody` stay in the catch-all — those + // mean the backend *did* answer but not in the contract shape, + // which is a real conformance signal. let mut classified = 0usize; let mut winners = 0usize; - let mut new_etag: Option = None; + let mut winner: Option<(ETag, &[u8])> = None; for (i, outcome) in outcomes.into_iter().enumerate() { match outcome { Ok(CasOutcome::Won(e)) => { classified += 1; winners += 1; - new_etag = Some(e); + winner = Some((e, &bodies[i])); } Ok(CasOutcome::LostRace) => { classified += 1; } - Err(StoreError::Backend( - S3Error::Reqwest(_) | S3Error::Http(_) | S3Error::Io(_), - )) => { + Err(e) if racer_outcome_unknown(&e) => { transport_drops += 1; tracing::warn!( phase = "if_match_race", round, racer = i, - "transport drop (pre-classification: socket/send failure)" + error = %e, + "transport drop (outcome unknown: socket/send failure or 5xx)" ); } Err(e) => { @@ -709,18 +732,62 @@ impl GitStore { } .into()); } - if winners != 1 { - return Err(ProbeFailure { + let (won_etag, won_body) = match winner { + Some(w) if winners == 1 => w, + _ => { + return Err(ProbeFailure { + phase: "if_match_race", + round, + key: pointer_key, + reason: format!( + "expected exactly 1 winner among {classified} classified observers, got {winners}" + ), + } + .into()) + } + }; + // Counting outcomes alone can't see a dropped racer whose write + // landed anyway (a backend that commits a stale `If-Match` PUT + // and then answers 5xx). Read the pointer back and require the + // winner's exact body and ETag before the next round predicates + // on that ETag. Without this, the last round has no next round + // to catch it. + let stored = self + .get_pointer(&pointer_key) + .await + .map_err(|e| ProbeFailure { phase: "if_match_race", round, - key: pointer_key, - reason: format!( - "expected exactly 1 winner among {classified} classified observers, got {winners}" - ), + key: pointer_key.clone(), + reason: format!("post-race read failed: {e}"), + })?; + match stored { + Some((stored_etag, stored_body)) + if stored_etag == won_etag && stored_body[..] == won_body[..] => {} + Some((stored_etag, _)) => { + return Err(ProbeFailure { + phase: "if_match_race", + round, + key: pointer_key, + reason: format!( + "post-race read is not the winner's write: \ + winner etag {}, stored etag {}", + won_etag.0, stored_etag.0 + ), + } + .into()) + } + None => { + return Err(ProbeFailure { + phase: "if_match_race", + round, + key: pointer_key, + reason: "pointer vanished after the race".into(), + } + .into()) } - .into()); } - etag = new_etag.expect("winner exists"); + etag = won_etag; } // -- Phase 3: if_none_match_race ------------------------------------------ @@ -741,8 +808,8 @@ impl GitStore { } let results = futures_util::future::join_all(tasks).await; // Drop-and-floor: same classification rule as Phase 2. Drop - // `Reqwest`/`Http`/`Io` (pre-classification — socket/send - // failure); count 2xx + 412 as the classified observers. Any + // unknown outcomes (socket/send failure or 5xx); count 2xx + 412 + // as the classified observers. Any // other status or any non-transport `StoreError` is a real // conformance signal and fails closed. let mut classified = 0usize; @@ -767,15 +834,14 @@ impl GitStore { } .into()) } - Err(StoreError::Backend( - S3Error::Reqwest(_) | S3Error::Http(_) | S3Error::Io(_), - )) => { + Err(e) if racer_outcome_unknown(&e) => { transport_drops += 1; tracing::warn!( phase = "if_none_match_race", round, racer = i, - "transport drop (pre-classification: socket/send failure)" + error = %e, + "transport drop (outcome unknown: socket/send failure or 5xx)" ); } Err(e) => { @@ -938,6 +1004,23 @@ mod tests { assert_eq!(GitStore::classify_cas(r).unwrap(), CasOutcome::LostRace); } + /// Regression: an S3 `500 InternalError` on one probe racer killed relay + /// startup. A 5xx is an unknown outcome (dropped from the observer set); + /// every answer in the contract's shape — 412 or another 4xx — still + /// counts as evidence. + #[test] + fn probe_drops_5xx_racers_but_keeps_4xx_as_evidence() { + let http = |code: u16| StoreError::Backend(S3Error::HttpFailWithBody(code, String::new())); + for code in [500, 503, 599] { + assert!(racer_outcome_unknown(&http(code)), "{code} is unknown"); + } + for code in [400, 403, 412, 499] { + assert!(!racer_outcome_unknown(&http(code)), "{code} is evidence"); + } + let io = StoreError::Backend(S3Error::Io(std::io::Error::other("reset"))); + assert!(racer_outcome_unknown(&io)); + } + #[test] fn classify_cas_other_4xx_bubbles() { let r = Err(S3Error::HttpFailWithBody(403, "AccessDenied".into())); @@ -1016,6 +1099,306 @@ mod tests { } } +#[cfg(test)] +mod fault_probe { + //! `run_conformance_probe` against an in-process S3 fake that injects + //! racer faults at the HTTP boundary, so the responses go through + //! rust-s3's real `fail-on-err` mapping and retry before the race phases + //! classify them. + + use std::collections::HashMap; + use std::sync::Mutex; + use std::time::{Duration, Instant}; + + use axum::extract::State; + use axum::http::{HeaderMap, Method, StatusCode, Uri}; + use axum::response::{IntoResponse, Response}; + + use super::*; + + const BUCKET: &str = "buzz-git"; + + /// Which `if_none_match_race` PUTs the fake faults. + #[derive(Clone, Copy)] + enum InmFault { + None, + /// Every racer PUT. + All(u16), + /// Every racer PUT once the winner has created the object, leaving + /// the winner as the only classified observer. + AllButWinner(u16), + /// The first PUT of each burst. Phase-3 racers send identical bytes, + /// so the fake can't single one out. rust-s3 retries every non-2xx + /// once after 1s, so the faulted slot recurs in the retry burst, and + /// the net effect is exactly one racer ending on this status. + FirstOfBurst(u16), + } + + #[derive(Clone)] + struct Faults { + /// `if_match_race` racer indices answered with `if_match_status`. + /// Their bodies carry `racer=`, so the fault survives the retry. + if_match_racers: Vec, + if_match_status: u16, + /// A non-linearizable backend: a faulted `if_match_race` PUT whose + /// `If-Match` is already stale is committed anyway before the fault + /// status goes out. A faulted PUT whose `If-Match` still matches is + /// answered without mutating, so rust-s3's retry 1s later is the one + /// that lands, after the round's real winner. + if_match_stale_commit: bool, + inm: InmFault, + } + + #[derive(Default)] + struct Objects { + /// key → (body, ETag) + objects: HashMap, + versions: u64, + last_inm_put: HashMap, + } + + struct Fake { + faults: Faults, + state: Mutex, + } + + fn status(code: u16) -> Response { + let code = StatusCode::from_u16(code).expect("valid status"); + (code, format!("{code}")).into_response() + } + + impl Fake { + fn fault(&self, key: &str, body: &[u8], st: &mut Objects) -> Option { + if key.starts_with("probe/pointer-") { + let body = std::str::from_utf8(body).unwrap_or_default(); + let hit = self + .faults + .if_match_racers + .iter() + .any(|i| body.contains(&format!(",racer={i},"))); + return hit.then_some(self.faults.if_match_status); + } + if key.starts_with("probe/inm-race/") { + let now = Instant::now(); + let new_burst = st + .last_inm_put + .insert(key.to_string(), now) + .is_none_or(|prev| now - prev > Duration::from_millis(500)); + return match self.faults.inm { + InmFault::None => None, + InmFault::All(code) => Some(code), + InmFault::AllButWinner(code) => st.objects.contains_key(key).then_some(code), + InmFault::FirstOfBurst(code) => new_burst.then_some(code), + }; + } + None + } + + fn commit(st: &mut Objects, key: String, body: Bytes) -> String { + st.versions += 1; + let etag = format!("\"v{}\"", st.versions); + st.objects.insert(key, (body, etag.clone())); + etag + } + + fn handle(&self, method: Method, key: String, headers: HeaderMap, body: Bytes) -> Response { + let mut st = self.state.lock().unwrap(); + match method { + Method::GET => match st.objects.get(&key) { + Some((bytes, etag)) => { + ([("etag", etag.clone())], bytes.clone()).into_response() + } + None => status(404), + }, + Method::DELETE => { + st.objects.remove(&key); + StatusCode::NO_CONTENT.into_response() + } + Method::PUT => { + let current = st.objects.get(&key).map(|(_, etag)| etag.as_str()); + let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()); + let precondition_failed = match (header("if-none-match"), header("if-match")) { + (Some("*"), _) => current.is_some(), + (_, Some(tag)) => current != Some(tag), + _ => false, + }; + if let Some(code) = self.fault(&key, &body, &mut st) { + if self.faults.if_match_stale_commit && precondition_failed { + Self::commit(&mut st, key, body); + } + return status(code); + } + if precondition_failed { + return status(412); + } + let etag = Self::commit(&mut st, key, body); + ([("etag", etag)], "").into_response() + } + _ => status(405), + } + } + } + + async fn serve( + State(fake): State>, + method: Method, + uri: Uri, + headers: HeaderMap, + body: Bytes, + ) -> Response { + let prefix = format!("/{BUCKET}/"); + let Some(key) = uri.path().strip_prefix(&prefix) else { + return status(404); + }; + fake.handle(method, key.to_string(), headers, body) + } + + async fn run(faults: Faults) -> Result { + let fake = Arc::new(Fake { + faults, + state: Mutex::default(), + }); + let app = axum::Router::new().fallback(serve).with_state(fake); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let store = GitStore::new( + &format!("http://{addr}"), + "fake", + "fake", + BUCKET, + "us-east-1", + buzz_media::config::S3AddressingStyle::Path, + ) + .expect("construct git store"); + let result = store + .run_conformance_probe(ProbeConfig { + race_width: 3, + race_rounds: 1, + }) + .await; + server.abort(); + result + } + + fn clean() -> Faults { + Faults { + if_match_racers: Vec::new(), + if_match_status: 500, + if_match_stale_commit: false, + inm: InmFault::None, + } + } + + fn assert_probe_failure(result: Result, phase: &str, reason: &str) { + match result { + Err(StoreError::Probe(f)) => { + assert_eq!(f.phase, phase, "{f}"); + assert!(f.reason.contains(reason), "{f}"); + } + other => panic!("expected {phase} probe failure, got {other:?}"), + } + } + + #[tokio::test] + async fn fake_backend_passes_clean_probe() { + let report = run(clean()).await.expect("clean probe passes"); + assert_eq!(report.transport_drops, 0); + } + + /// Regression: an S3 `500 InternalError` on one probe racer killed relay + /// startup. With a winner and a 412 still observed, each race phase drops + /// the 5xx racer and admits the backend. + #[tokio::test] + async fn one_5xx_racer_per_phase_is_dropped_and_admitted() { + for (phase, faults) in [ + ( + "if_match_race", + Faults { + if_match_racers: vec![0], + ..clean() + }, + ), + ( + "if_none_match_race", + Faults { + inm: InmFault::FirstOfBurst(500), + ..clean() + }, + ), + ] { + let report = run(faults) + .await + .unwrap_or_else(|e| panic!("{phase}: one 5xx racer must not fail: {e}")); + assert_eq!(report.transport_drops, 1, "{phase}"); + } + } + + #[tokio::test] + async fn too_few_classified_observers_fail_closed() { + let one_observer = Faults { + if_match_racers: vec![0, 1], + ..clean() + }; + assert_probe_failure( + run(one_observer).await, + "if_match_race", + "race not observed", + ); + let winner_only = Faults { + inm: InmFault::AllButWinner(500), + ..clean() + }; + assert_probe_failure( + run(winner_only).await, + "if_none_match_race", + "race not observed", + ); + let all_5xx = Faults { + inm: InmFault::All(503), + ..clean() + }; + assert_probe_failure( + run(all_5xx).await, + "if_none_match_race", + "race not observed", + ); + } + + /// A racer answered 5xx is dropped as unknown, but its stale write + /// landed. In the final `if_match_race` round no later `If-Match` round + /// trips over it, so only the post-race readback stops the backend + /// from being admitted with a failed payload as the pointer. + #[tokio::test] + async fn dropped_racer_whose_stale_write_lands_fails_closed() { + let stale_commit = Faults { + if_match_racers: vec![0], + if_match_stale_commit: true, + ..clean() + }; + assert_probe_failure( + run(stale_commit).await, + "if_match_race", + "not the winner's write", + ); + } + + #[tokio::test] + async fn unexpected_4xx_racer_fails_closed() { + let if_match = Faults { + if_match_racers: vec![0], + if_match_status: 403, + ..clean() + }; + assert_probe_failure(run(if_match).await, "if_match_race", "racer 0"); + let inm = Faults { + inm: InmFault::FirstOfBurst(403), + ..clean() + }; + assert_probe_failure(run(inm).await, "if_none_match_race", "backend error"); + } +} + #[cfg(test)] mod probe { //! Empirical probe of rust-s3 + `fail-on-err` + MinIO surfacing of 412. diff --git a/crates/buzz-relay/src/api/git/transport.rs b/crates/buzz-relay/src/api/git/transport.rs index 1c0c08a600b..24e89610663 100644 --- a/crates/buzz-relay/src/api/git/transport.rs +++ b/crates/buzz-relay/src/api/git/transport.rs @@ -11,6 +11,7 @@ // Response is the natural error type for axum handlers. #![allow(clippy::result_large_err)] +use crate::access::{auth_error_code, AccessSlot, AuthMethod, AuthResult}; use std::future::Future; use std::path::Path; use std::sync::Arc; @@ -32,7 +33,10 @@ use tower_http::limit::RequestBodyLimitLayer; use tracing::{error, info, warn}; use super::binding::{resolve_repo_binding, RepoBinding}; -use super::cas_publish::{cas_publish, CasError, ParentState, PublishLimits}; +use super::cas_publish::{ + cas_publish, push_disposition, snapshot_workspace, CasError, ParentState, PublishLimits, + PushDisposition, WorkspaceState, +}; use super::hook::install_hook; use super::hydrate::{ hydrate_for_read, hydrate_for_write, load_manifest_for_read, HydrateError, HydratedRepo, @@ -88,6 +92,38 @@ impl axum::extract::FromRequestParts> for GitAuth { parts: &mut axum::http::request::Parts, state: &Arc, ) -> Result { + let global = state.config.nip_fi.mode; + if !global.evaluates() { + return Self::from_parts_with_policy(parts, state, global).await; + } + match crate::nip_fi_policy::resolve(state, &parts.headers).await { + Ok(policy) => { + crate::nip_fi_policy::with_policy(policy, async { + let mode = crate::nip_fi_policy::mode(state, &parts.headers).await; + Self::from_parts_with_policy(parts, state, mode).await + }) + .await + } + Err(response) => { + // Preserve the early gate's legacy host-miss ordering. A failed + // lookup is never turned into a usable optional policy scope. + let mode = if response.status() == StatusCode::NOT_FOUND { + global + } else { + buzz_auth::NipFiMode::unavailable() + }; + Self::from_parts_with_policy(parts, state, mode).await + } + } + } +} + +impl GitAuth { + async fn from_parts_with_policy( + parts: &mut axum::http::request::Parts, + state: &Arc, + mode: buzz_auth::NipFiMode, + ) -> Result { let method = parts.method.as_str(); // Off mode: parse and validate the Authorization header BEFORE tenant @@ -95,7 +131,8 @@ impl axum::extract::FromRequestParts> for GitAuth { // missing credentials → 401 + WWW-Authenticate challenge; // malformed credentials (bad base64, bad UTF-8) → 401 without challenge; // regardless of whether the Host resolves to a known community. No - // database work for syntactically bad requests in Off mode. + // tenant-binding work for syntactically bad requests. In evaluating modes, + // policy resolution first prevents a required row taking the legacy path. // // Enforce: the header syntax is validated // inside the NIP-FI admission closure below, where proof failures are @@ -104,9 +141,10 @@ impl axum::extract::FromRequestParts> for GitAuth { // admission (immediately after this block) because the signed `u` tag // must be verified against the tenant-bound host, not a process-global // domain. - let mode = state.config.nip_fi.mode; + let slot = AccessSlot::of(parts); if !mode.restricts() { if let Err(rejection) = parse_git_auth_header(&parts.headers, method) { + git_header_rejected(&slot, &parts.headers); // Off returns `rejection` as is; shadow also records the // enforce verdict for the failed proof. crate::nip_fi_http::observe_failed_proof(state, &parts.headers).await; @@ -155,53 +193,19 @@ impl axum::extract::FromRequestParts> for GitAuth { // Token is time-bounded (±60s) and URL-locked — acceptable trade-off. let headers_clone = parts.headers.clone(); let method_str = method.to_owned(); + let proof_slot = slot.clone(); let admission = crate::nip_fi_http::admit_nip_fi_http_on_state( state, &parts.headers, - move || -> Result, Response> { - // In Off mode `parse_git_auth_header` already ran above and - // succeeded, so re-parsing here is purely for the return value. - // In Enforce mode it runs for the first time inside this closure - // (on the auth-rejection path the NIP-FI layer maps the error). - let (event_json, method_for_verify) = - parse_git_auth_header_full(&headers_clone, &method_str)?; - - // SECURITY: method intentionally not verified for git routes. The tautological - // check (event.method == event.method) is deliberate — see comment block above. - // Git's credential protocol signs once with GET and reuses for POST. The URL tag - // provides the real security boundary (±60s timestamp + URL lock + HTTPS). - let pubkey = buzz_auth::nip98::verify_nip98_event( - &event_json, - &expected_url, - &method_for_verify, - None, - ) - .map_err(|e| { - warn!(error = %e, "git NIP-98 auth failed"); - (StatusCode::UNAUTHORIZED, "NIP-98 auth failed").into_response() - })?; - - // NOTE: NIP-98 event-ID dedup intentionally NOT implemented here. - // Git's credential protocol reuses one signed token across multiple requests - // in a session (info_refs GET -> upload-pack/receive-pack POST). Rejecting - // replayed event IDs would break normal clone/push operations. - // The +-60s timestamp window + URL scoping + HTTPS transport provide sufficient - // replay protection for v1. Per-request signing requires protocol changes. - - let event: nostr::Event = serde_json::from_str(&event_json).map_err(|_| { - (StatusCode::UNAUTHORIZED, "invalid auth event").into_response() - })?; - let signed_auth_created_at = event.created_at.as_secs(); - - Ok(crate::nip_fi_http::Nip98Proof::new( - pubkey, - (event, signed_auth_created_at), - )) - }, + &slot, + move || verify_git_proof(&headers_clone, &method_str, &expected_url, &proof_slot), ) .await?; let pubkey = *admission.proven_pubkey(); + // Git reuses one signed token per session, so there is no replay + // step: the membership and ban gates below make the final decision. + slot.in_community(tenant.community()); let token_owner = admission.token_owner(); let (event, signed_auth_created_at) = admission.into_extra(); @@ -244,6 +248,9 @@ impl axum::extract::FromRequestParts> for GitAuth { { Ok(crate::api::relay_members::MembershipDecision::Denied) => { warn!(pubkey = %pubkey.to_hex(), "git: relay membership denied"); + slot.finish(AuthResult::Denied( + crate::access::AuthReason::NotRelayMember, + )); return Err(denied( (StatusCode::FORBIDDEN, "restricted: not a relay member").into_response(), )); @@ -251,6 +258,9 @@ impl axum::extract::FromRequestParts> for GitAuth { Ok(_) => {} Err(e) => { warn!(pubkey = %pubkey.to_hex(), error = %e, "git: relay membership lookup failed"); + slot.finish(AuthResult::Denied( + crate::access::AuthReason::MembershipUnavailable, + )); return Err(unavailable( ( StatusCode::SERVICE_UNAVAILABLE, @@ -272,8 +282,12 @@ impl axum::extract::FromRequestParts> for GitAuth { .await .map_err(|denial| { if denial.status() == StatusCode::SERVICE_UNAVAILABLE { + slot.finish(AuthResult::Denied( + crate::access::AuthReason::BanCheckUnavailable, + )); unavailable(denial) } else { + slot.finish(AuthResult::Denied(crate::access::AuthReason::Banned)); denied(denial) } })?; @@ -285,22 +299,35 @@ impl axum::extract::FromRequestParts> for GitAuth { match link_agent_owner(state, &tenant, &pubkey, &owner).await { OwnerLink::Linked => {} OwnerLink::Conflict => { + crate::nip_fi_http::owner_refused( + buzz_auth::DenialClass::AuthorizationDenied, + "not_stored_owner", + ); + slot.finish(AuthResult::Denied(crate::access::AuthReason::OwnerMismatch)); return Err(crate::nip_fi_core::http_denial( buzz_auth::DenialClass::AuthorizationDenied, - )) + )); } OwnerLink::Unavailable => { + crate::nip_fi_http::owner_refused( + buzz_auth::DenialClass::AuthorizationUnavailable, + "owner_link_unavailable", + ); + slot.finish(AuthResult::Denied( + crate::access::AuthReason::NipOaOwnerUnlinked, + )); return Err(unavailable( ( StatusCode::SERVICE_UNAVAILABLE, crate::handlers::auth::OWNER_LINK_ERROR, ) .into_response(), - )) + )); } } } + slot.finish(AuthResult::Success); Ok(GitAuth { pubkey, tenant }) } } @@ -324,7 +351,24 @@ pub(super) async fn deny_banned_git_principal( signed_auth_created_at: Option, token_owner: Option, ) -> Result<(), Response> { - let agent = git_restriction_state(db, community, pubkey).await?; + // A verified agent token's ban state is its owner step: an unreadable + // ban state or a banned token owner is that step's refusal, as shadow + // records it. + let owner_refused = |class, reason| { + if token_owner.is_some() { + crate::nip_fi_http::owner_refused(class, reason); + } + }; + let unavailable = |denial| { + owner_refused( + buzz_auth::DenialClass::AuthorizationUnavailable, + "owner_ban_unavailable", + ); + denial + }; + let agent = git_restriction_state(db, community, pubkey) + .await + .map_err(unavailable)?; // Skip the owner read when the agent is already banned: the denial is // identical either way. Mirrors the WebSocket cascade's short-circuit. @@ -340,11 +384,20 @@ pub(super) async fn deny_banned_git_principal( }) }; let owner_state = match owner { - Some(owner) => Some(git_restriction_state(db, community, &owner).await?), + Some(owner) => Some( + git_restriction_state(db, community, &owner) + .await + .map_err(unavailable)?, + ), None => None, }; enforce_git_ban_cascade(&agent, owner_state.as_ref()).map_err(|status| { + // The agent's own ban is not its owner's; a ban inherited from its + // stored owner, or its token owner's, is. + if !agent.own_banned { + owner_refused(buzz_auth::DenialClass::AuthorizationDenied, "owner_banned"); + } warn!( pubkey = %pubkey.to_hex(), owner = ?owner.map(|owner| owner.to_hex()), @@ -396,6 +449,74 @@ fn enforce_git_ban_cascade( } } +/// Record a rejected git proof. +fn git_failed(slot: &AccessSlot, reason: &'static str) { + slot.method(AuthMethod::Nip98); + slot.finish(AuthResult::Failed(reason)); +} + +/// Verify a git request's NIP-98 proof (the admission closure). Each failure +/// records a fixed code, never the error text. +#[allow(clippy::result_large_err)] +fn verify_git_proof( + headers: &axum::http::HeaderMap, + method: &str, + expected_url: &str, + slot: &AccessSlot, +) -> Result, Response> { + // In Off mode `parse_git_auth_header` already ran above and + // succeeded, so re-parsing here is purely for the return value. + // In Enforce mode it runs for the first time inside this closure + // (on the auth-rejection path the NIP-FI layer maps the error). + let (event_json, method_for_verify) = parse_git_auth_header_full(headers, method) + .inspect_err(|_| git_header_rejected(slot, headers))?; + + // SECURITY: method intentionally not verified for git routes. The tautological + // check (event.method == event.method) is deliberate — see comment block above. + // Git's credential protocol signs once with GET and reuses for POST. The URL tag + // provides the real security boundary (±60s timestamp + URL lock + HTTPS). + let pubkey = + buzz_auth::nip98::verify_nip98_event(&event_json, expected_url, &method_for_verify, None) + .map_err(|e| { + // Fixed code only: a URL-mismatch error echoes the + // client's whole signed `u` tag. + git_failed(slot, auth_error_code(&e)); + (StatusCode::UNAUTHORIZED, "NIP-98 auth failed").into_response() + })?; + + // NOTE: NIP-98 event-ID dedup intentionally NOT implemented here. + // Git's credential protocol reuses one signed token across multiple requests + // in a session (info_refs GET -> upload-pack/receive-pack POST). Rejecting + // replayed event IDs would break normal clone/push operations. + // The +-60s timestamp window + URL scoping + HTTPS transport provide sufficient + // replay protection for v1. Per-request signing requires protocol changes. + + let event: nostr::Event = serde_json::from_str(&event_json).map_err(|_| { + git_failed(slot, "nip98_invalid"); + (StatusCode::UNAUTHORIZED, "invalid auth event").into_response() + })?; + let signed_auth_created_at = event.created_at.as_secs(); + + Ok(crate::nip_fi_http::Nip98Proof::new( + pubkey, + (event, signed_auth_created_at), + )) +} + +/// The access-log code for a git `Authorization` header that failed to parse. +/// Log a request whose `Authorization` header was refused. A missing header +/// is git's credential-less first request, answered with the 401 challenge +/// it asks for, so it is `challenged`; a header that is present but bad is a +/// failed proof. +fn git_header_rejected(slot: &AccessSlot, headers: &axum::http::HeaderMap) { + if headers.contains_key(header::AUTHORIZATION) { + git_failed(slot, "nip98_invalid"); + } else { + slot.method(AuthMethod::Nip98); + slot.finish(AuthResult::Challenged); + } +} + /// Parse and syntax-validate the `Authorization: Nostr ` header for /// Git HTTP requests. Returns `Ok(())` on success (the caller only needs to /// know whether the syntax is valid); on failure returns a `Response` that @@ -1250,9 +1371,10 @@ pub async fn upload_pack( /// 4. Run `receive-pack --stateless-rpc` against the tempdir. The hook /// enforces fast-forward + branch protection in-process. /// 5. `finalize_push(PushContext { pack, parent_state, repo, ... })` is -/// the only path that builds a push `Response`. It calls -/// `cas_publish` (§Push steps 2–7) and emits kind:30618 on `Won`, -/// *only then* builds the 2xx. +/// the only path that builds a push `Response`. It compares the +/// workspace refs with the hydrated ones (§Push step 3); if they +/// changed it calls `cas_publish` (§Push steps 4–7) and emits +/// kind:30618 on `Won`, and *only then* builds the 2xx. pub async fn receive_pack( State(state): State>, auth: GitAuth, @@ -1266,19 +1388,18 @@ pub async fn receive_pack( let _permit = acquire_git_permit(&state, "receive_pack")?; // **No per-repo advisory lock — by design.** Writer serialization is - // the pointer CAS at `cas_publish` step 7 (`Inv_NoFork` proves this - // sufficient). The previous code held a per-repo `tokio::Mutex`, but - // that only spanned one process; once we run >1 relay instance - // (which is the point of "no local stateful disk"), it spans nothing - // and CAS is the only serialization that holds. The named tradeoff: - // two concurrent same-repo pushes each hydrate + run receive-pack, - // and the loser's CPU/IO is thrown away on `Conflict`. **Accepted - // for v1** — same-ref contention is rare, and a cross-instance lock - // would be a distributed-lock service we explicitly don't want. - // If contention shows up in metrics, the fix is a short local - // best-effort lock as a *latency optimization*, never a correctness - // dependency. (Eva's call, on record in #proj-git-on-s3 with the - // ParentState seam review.) + // the pointer CAS at `cas_publish` step 7 (the `Refines` check in + // `docs/spec/GitOnObjectStore.tla` shows this is sufficient). The + // previous code held a per-repo `tokio::Mutex`, but that only spanned + // one process; once we run >1 relay instance (which is the point of + // "no local stateful disk"), it spans nothing and CAS is the only + // serialization that holds. The named tradeoff: two concurrent + // same-repo pushes each hydrate + run receive-pack, and the loser's + // CPU/IO is thrown away on `Conflict`. **Accepted for v1** — same-ref + // contention is rare, and a cross-instance lock would be a + // distributed-lock service we explicitly don't want. If contention + // shows up in metrics, the fix is a short local best-effort lock as a + // *latency optimization*, never a correctness dependency. // Hydrate parent state + workspace in one round-trip. ParentState // travels with the workspace into finalize_push so the CAS predicates @@ -1380,18 +1501,15 @@ fn receive_pack_git_config(hooks_dir: String) -> Vec<(&'static str, String)> { /// [`finalize_push`] has decided to build a `Response` from these bytes. pub(crate) struct PackOutput { pub stdout: Vec, - /// Whether the push is safe to publish: the `git receive-pack` subprocess - /// exited 0 **and** its report-status reported no rejected (`ng`) ref. + /// Whether the git subprocess exited with status 0. /// - /// A pre-receive hook decline (authorization denied) does NOT surface as a - /// non-zero exit — `git receive-pack --stateless-rpc` exits 0 and reports - /// the rejection only in-band as report-status. So `ok` must fold in the - /// report-status scan (`receive_pack_report_rejected`), not the exit code - /// alone. `finalize_push` treats `false` as "push did not happen": skip the - /// CAS publish and the derived kind:30618 so a rejected push leaves **no - /// published state**. The buffered stdout still carries git's in-band - /// report-status so the client prints the rejection. - pub ok: bool, + /// For `receive-pack` this says nothing about whether the push was + /// accepted: git exits 0 when a pre-receive hook declines the push, when + /// some ref updates are refused, and when the request carries no commands + /// at all. [`finalize_push`] therefore decides from the refs the workspace + /// holds afterwards (`push_disposition`), and uses this flag only to + /// refuse to publish the result of a run that failed part-way. + pub exited_ok: bool, } /// Spawn a `git --stateless-rpc ` subprocess against the given @@ -1514,37 +1632,21 @@ async fn run_git_at( } if !status.success() { + // Hook output lands in stderr, so it stays out of WARN. let stderr = read_log_prefix(stderr_tmp.path(), 64 * 1024).await; - warn!(stderr = %stderr, service = %service, "git subprocess exited with error"); + warn!(service = %service, ?status, "git subprocess exited with error"); + tracing::debug!(stderr = %stderr, service = %service, "git subprocess stderr"); // Still return output — git protocol errors are communicated in-band. - // A non-zero exit feeds `PackOutput.ok` below, but it is NOT the signal - // for a pre-receive hook decline: `git receive-pack --stateless-rpc` - // exits 0 on a hook decline, reporting the rejection only in-band as - // report-status (see `receive_pack_report_rejected`). The exit code - // still guards genuine subprocess failures (spawn/IO/abort). } - // Primary fence for a denied push: scan the report-status for an `ng` - // (rejected) ref update. `git receive-pack` exits 0 on a pre-receive hook - // decline, so the exit code alone is insufficient — the rejection lives in - // the in-band report-status. Fold both signals into `ok` so `finalize_push` - // skips CAS publish + kind:30618 on any rejected ref. let stdout = tokio::fs::read(stdout_tmp.path()).await.map_err(|e| { error!(error = %e, service = %service, "git stdout read failed"); (StatusCode::INTERNAL_SERVER_ERROR, "git error").into_response() })?; - let report_rejected = service == "receive-pack" && receive_pack_report_rejected(&stdout); - if report_rejected { - warn!( - service = %service, - "git receive-pack report-status contains a rejected (ng) ref update" - ); - } - Ok(PackOutput { stdout, - ok: status.success() && !report_rejected, + exited_ok: status.success(), }) } @@ -1562,97 +1664,6 @@ async fn read_log_prefix(path: &Path, max_bytes: u64) -> String { String::from_utf8_lossy(&bytes).to_string() } -/// Returns true when a `git receive-pack` report-status stream contains an -/// `ng ` line — i.e. git rejected at least one ref update. -/// -/// Empirically, `git receive-pack --stateless-rpc` exits **0** even when a -/// pre-receive hook rejects a push: the rejection is communicated only in-band -/// to the client as report-status (`unpack ok` followed by `ng refs/... -/// pre-receive hook declined`). The relay must therefore treat an `ng` status -/// as "push did not happen" for the publish fence, not rely on the exit code. -/// -/// ## Wire format -/// -/// The report-status is a pkt-line stream. When side-band-64k is negotiated -/// (which the stock client does), the status pkt-lines are **nested**: each -/// outer pkt-line's payload begins with a channel byte (`1` = data, `2`/`3` = -/// progress/error text), and the band-1 payload carries its *own* inner -/// pkt-line stream: -/// -/// ```text -/// \x01unpack ok\nng refs/heads/main ...\n0000 -/// ``` -/// -/// A naive "strip the band byte then split on \n" misses this: the rejection -/// line surfaces as `0031ng refs/...` (inner length prefix glued on), which -/// does not start with `ng `. So we de-frame one level deeper — for a band-1 -/// payload we parse the inner pkt-lines before matching. Without side-band the -/// status pkt-lines appear directly at the outer level, which we also match. -fn receive_pack_report_rejected(stdout: &[u8]) -> bool { - for payload in PktLineIter::new(stdout) { - match payload.first() { - // Side-band channel 1 (data): carries a nested pkt-line stream. - Some(1) => { - if PktLineIter::new(&payload[1..]).any(|line| line.starts_with(b"ng ")) { - return true; - } - } - // Side-band channel 2/3 (progress/error text): never status lines. - Some(2 | 3) => {} - // No side-band: the status pkt-line payload is the line itself. - _ => { - if payload.starts_with(b"ng ") { - return true; - } - } - } - } - false -} - -/// Iterator over the payloads of a pkt-line stream. -/// -/// Yields the bytes between the 4-hex length prefix and the end of each -/// pkt-line. Skips flush (`0000`) / delim (`0001`) / response-end (`0002`) -/// control pkts. Stops on the first malformed length or truncated frame -/// (defensive: a corrupt stream simply produces no further matches rather -/// than panicking). -struct PktLineIter<'a> { - buf: &'a [u8], - i: usize, -} - -impl<'a> PktLineIter<'a> { - fn new(buf: &'a [u8]) -> Self { - Self { buf, i: 0 } - } -} - -impl<'a> Iterator for PktLineIter<'a> { - type Item = &'a [u8]; - - fn next(&mut self) -> Option<&'a [u8]> { - loop { - if self.i + 4 > self.buf.len() { - return None; - } - let len_hex = std::str::from_utf8(&self.buf[self.i..self.i + 4]).ok()?; - let len = usize::from_str_radix(len_hex, 16).ok()?; - // 0000 (flush), 0001 (delim), 0002 (response-end): no payload. - if len < 4 { - self.i += 4; - continue; - } - if self.i + len > self.buf.len() { - return None; - } - let payload = &self.buf[self.i + 4..self.i + len]; - self.i += len; - return Some(payload); - } - } -} - /// Keeps the git subprocess and its hydrated workspace alive for exactly as /// long as the response body is being streamed. /// @@ -1952,6 +1963,10 @@ struct FinalizePushHooks { post_cas_gate: Option>, #[cfg(test)] fail_ref_state_insert: bool, + /// Fire the lease-loss signal as the pointer CAS completes, as a failed + /// heartbeat renewal would, while the durable lease stays valid. + #[cfg(test)] + lose_lease_signal_after_cas: bool, } #[cfg(test)] @@ -1974,6 +1989,19 @@ async fn finalize_push(state: &Arc, ctx: PushContext) -> Response { finalize_push_inner(state, ctx, &FinalizePushHooks::default()).await } +/// Read what a finished `receive-pack` run left in the workspace and decide +/// what the relay owes the client: git's answer alone, a publication, or a +/// failure. The returned snapshot is the one a publication must use. +async fn observe_push( + pack: &PackOutput, + parent_state: &ParentState, + repo_path: &Path, +) -> Result<(PushDisposition, WorkspaceState), CasError> { + let workspace = snapshot_workspace(repo_path).await?; + let disposition = push_disposition(pack.exited_ok, &parent_state.parent.refs, &workspace.refs); + Ok((disposition, workspace)) +} + async fn finalize_push_inner( state: &Arc, ctx: PushContext, @@ -1982,34 +2010,72 @@ async fn finalize_push_inner( #[cfg(not(test))] let _ = hooks; - // The push fence, part 0 — **a rejected push publishes nothing.** + // The push fence, part 0 — **publish exactly what the push changed.** // - // `ctx.pack.ok` is false when git aborted the ref updates: either the - // subprocess exited non-zero (genuine failure) OR — the important case — - // a pre-receive hook declined the push. A hook decline does NOT yield a - // non-zero exit; `git receive-pack --stateless-rpc` exits 0 and reports - // the rejection only in-band as report-status (`ng `), which - // `run_git_at` folds into `ok` via `receive_pack_report_rejected`. In - // either case the workspace refs were NOT advanced, so there is no - // committed state to publish: skip the CAS pointer write AND the derived - // kind:30618. Otherwise a denied push would emit a relay-signed, fanned-out - // 30618 falsely attributing the ref state to the *denied* pusher - // (`actor = ctx.pusher`), breaking the invariant "rejected push → no - // published state". + // The workspace refs are the only evidence of what receive-pack did, so + // the decision is taken from them (`push_disposition`), not from git's + // exit status or its report to the client: // - // git's in-band report-status (already buffered in `ctx.pack.stdout`) - // still streams back so the client prints `! [remote rejected]` / the - // hook's decline message; only the publish side effects are suppressed. - if !ctx.pack.ok { - warn!( - owner = %ctx.owner, - repo = %ctx.repo_id, - "receive-pack exited non-zero (e.g. pre-receive hook decline); \ - skipping CAS publish and kind:30618 — no state published" - ); - let response = build_git_response("receive-pack", ctx.pack); - drop(ctx.repo_handle); - return response; + // - Refs unchanged: nothing was accepted. This covers a hook decline, a + // request with no commands, and a push whose every command was refused. + // Publishing here would move the pointer and emit a relay-signed + // kind:30618 naming a pusher the policy never approved. + // - Refs changed, git exited 0: at least one command was applied, and git + // reports `ok` for it even if it reports `ng` for others. Those refs must + // be published before the client sees that report. + // - Refs changed, git exited non-zero: the run failed part-way and its + // report may be incomplete. Nothing is published and the request fails. + let (disposition, workspace) = + match observe_push(&ctx.pack, &ctx.parent_state, ctx.repo_handle.path()).await { + Ok(observed) => observed, + Err(CasError::ResourceLimit(e)) => { + warn!( + owner = %ctx.owner, + repo = %ctx.repo_id, + error = %e, + "push rejected: repo exceeds relay resource limits" + ); + return ( + StatusCode::PAYLOAD_TOO_LARGE, + "repository exceeds relay resource limits", + ) + .into_response(); + } + Err(error) => { + error!( + owner = %ctx.owner, + repo = %ctx.repo_id, + %error, + "could not read workspace refs after receive-pack; nothing published" + ); + return (StatusCode::INTERNAL_SERVER_ERROR, "git backend error").into_response(); + } + }; + match disposition { + PushDisposition::Publish => {} + PushDisposition::RelayOnly => { + info!( + owner = %ctx.owner, + repo = %ctx.repo_id, + exited_ok = ctx.pack.exited_ok, + "receive-pack changed no ref; nothing published" + ); + let response = build_git_response("receive-pack", ctx.pack); + drop(ctx.repo_handle); + return response; + } + PushDisposition::Abort => { + error!( + owner = %ctx.owner, + repo = %ctx.repo_id, + "receive-pack exited non-zero after changing refs; nothing published" + ); + return ( + StatusCode::INTERNAL_SERVER_ERROR, + "git receive-pack failed; nothing was published", + ) + .into_response(); + } } // An already-running receive-pack may cross the durable fence after @@ -2053,76 +2119,31 @@ async fn finalize_push_inner( &ctx.owner, &ctx.repo, &ctx.parent_state, + &workspace, PublishLimits { parent_hydrated_bytes: ctx.repo_handle.hydrated_bytes(), max_pack_bytes: state.config.git_max_pack_bytes, max_repo_bytes: state.config.git_max_repo_bytes, }, ); - let success = match serving_write.protect(publish).await { - Ok(result) => match result { - Ok(s) => s, - Err(CasError::Conflict { - winner_manifest_key, - .. - }) => { - warn!( - owner = %ctx.owner, - repo = %ctx.repo, - winner = %winner_manifest_key, - "push lost CAS race; tempdir dropped, returning 409" - ); - return ( - StatusCode::CONFLICT, - "push superseded by a concurrent writer; pull and retry", - ) - .into_response(); - } - Err(CasError::ManifestInvalid(e)) => { - // 4xx-class: the workspace produced refs/HEAD/oids the - // manifest validator rejects (unsafe refname, malformed oid, - // empty head, malformed parent). Pre-CAS — no pointer was - // written. - warn!( - owner = %ctx.owner, - repo = %ctx.repo, - error = %e, - "push rejected: manifest validation failed" - ); - return ( - StatusCode::BAD_REQUEST, - "push produced invalid manifest state", - ) - .into_response(); - } - Err(CasError::ResourceLimit(e)) => { - warn!( - owner = %ctx.owner, - repo = %ctx.repo, - error = %e, - "push rejected: repo exceeds relay resource limits" - ); - return ( - StatusCode::PAYLOAD_TOO_LARGE, - "repository exceeds relay resource limits", - ) - .into_response(); - } - Err(e) => { - // 5xx-class: ManifestReadFailed (parent corruption), - // Backend, PackCapture. The tempdir drops on scope exit; no - // pointer was written (or, on rare ManifestReadFailed during - // winner-fetch, the winner is already installed and the - // loser's data is unrelated). - error!( - owner = %ctx.owner, - repo = %ctx.repo, - error = %e, - "push failed pre-response" - ); - return (StatusCode::INTERNAL_SERVER_ERROR, "git backend error").into_response(); - } - }, + #[cfg(test)] + let lost_after_cas = hooks + .lose_lease_signal_after_cas + .then(|| serving_write.lost()); + #[cfg(test)] + let publish = async move { + let result = publish.await; + if let Some(lost) = lost_after_cas { + lost.cancel(); + } + result + }; + // `protect_landed`, not `protect`: once `cas_publish` returns, its outcome + // stands even if the lease check that follows fails. A landed pointer CAS + // cannot be undone, so reporting it as a failure would tell the client + // the push did not land when it did, and would skip its kind:30618. + let (result, lease_after_cas) = match serving_write.protect_landed(publish).await { + Ok(landed) => landed, Err(error) => { warn!(owner = %ctx.owner, repo = %ctx.repo, %error, "push lost community serving lease during CAS publish"); return ( @@ -2132,6 +2153,82 @@ async fn finalize_push_inner( .into_response(); } }; + let success = match result { + Ok(s) => s, + Err(CasError::Conflict { + winner_manifest_key, + .. + }) => { + warn!( + owner = %ctx.owner, + repo = %ctx.repo, + winner = %winner_manifest_key, + "push lost CAS race; tempdir dropped, returning 409" + ); + return ( + StatusCode::CONFLICT, + "push superseded by a concurrent writer; pull and retry", + ) + .into_response(); + } + Err(CasError::ManifestInvalid(e)) => { + // 4xx-class: the workspace produced refs/HEAD/oids the + // manifest validator rejects (unsafe refname, malformed oid, + // empty head, malformed parent). Pre-CAS — no pointer was + // written. + warn!( + owner = %ctx.owner, + repo = %ctx.repo, + error = %e, + "push rejected: manifest validation failed" + ); + return ( + StatusCode::BAD_REQUEST, + "push produced invalid manifest state", + ) + .into_response(); + } + Err(CasError::ResourceLimit(e)) => { + warn!( + owner = %ctx.owner, + repo = %ctx.repo, + error = %e, + "push rejected: repo exceeds relay resource limits" + ); + return ( + StatusCode::PAYLOAD_TOO_LARGE, + "repository exceeds relay resource limits", + ) + .into_response(); + } + Err(e) => { + // 5xx-class: ManifestReadFailed (parent corruption), + // Backend, PackCapture. The tempdir drops on scope exit; no + // pointer was written (or, on rare ManifestReadFailed during + // winner-fetch, the winner is already installed and the + // loser's data is unrelated). + error!( + owner = %ctx.owner, + repo = %ctx.repo, + error = %e, + "push failed pre-response" + ); + return (StatusCode::INTERNAL_SERVER_ERROR, "git backend error").into_response(); + } + }; + // The pointer is committed. A lapsed lease no longer decides the response: + // the kind:30618 insert below is admitted against the durable lease, so it + // fails if deletion has fenced the community, and succeeds if only the + // local heartbeat signal fired. + if let Err(error) = lease_after_cas { + warn!( + owner = %ctx.owner, + repo = %ctx.repo, + manifest = %success.manifest_key, + %error, + "serving lease check failed after the pointer CAS landed; continuing publication" + ); + } #[cfg(test)] if let Some(gate) = &hooks.post_cas_gate { @@ -2140,34 +2237,16 @@ async fn finalize_push_inner( } // Derived after CAS: kind:30618 ref-state event over the *committed* - // manifest's refs/head. Spec §Implementation Correspondence: - // "kind:30618 is derived after CAS, never the commit." We emit only - // when the committed manifest differs from the parent — a true no-op - // push pays no 30618 cost. - // - // **Strict no-op detection.** We emit unless the canonical manifest - // is byte-identical to the parent (Dawn's `canonical_bytes` is - // deterministic, so equal published state ⇒ equal digest by - // construction). The cases this differs from "refs+head equality": - // pack-only changes (rare; internal recompaction, or a push that - // produces a new pack covering existing tips with different deltas) - // would emit a 30618 with identical `(refs, head)`. The relay DB's - // `Ok((_, false))` arm below dedups it for free — one extra DB - // round-trip per pack-only push, which clients don't normally - // generate. Tightening to refs+head equality is a future - // micro-optimization only if that dedup cost becomes visible. - let parent_digest_str: Option<&str> = ctx.parent_state.parent_digest.as_deref(); - let after_digest = success.manifest_key.strip_prefix("manifests/"); - let manifest_changed = match (parent_digest_str, after_digest) { - (Some(before), Some(after)) => before != after, - _ => true, // first push (parent None) or impossible-shape after key → publish - }; - let publication_result: Result<(), String> = if manifest_changed { + // manifest's refs/head. The event is derived from the commit and is never + // the commit itself. Every publication reaches this point with changed + // refs (`PushDisposition::Publish`), so there is always an event to emit. + let publication_result: Result<(), String> = { let inputs = RefStateInputs { repo_id: &ctx.repo_id, head: &success.manifest.head, refs: &success.manifest.refs, actor_pubkey_hex: &hex::encode(ctx.pusher.to_bytes()), + published_at: success.manifest.published_at, }; match build_ref_state_event(&inputs, &state.relay_keypair) { Ok(event) => { @@ -2221,20 +2300,15 @@ async fn finalize_push_inner( } Err(error) => Err(format!("kind:30618 build failed: {error}")), } - } else { - Ok(()) }; // The admitted serving write spans the complete publication attempt. Fence // acquisition cannot overtake the pointer CAS, durable 30618 insert, or // local fan-out attempt; only now may the lease be released. + // A failed release does not change the outcome either: the pointer CAS + // and the lease-guarded kind:30618 insert have both already happened. if let Err(error) = serving_write.finish().await { warn!(owner = %ctx.owner, repo = %ctx.repo, %error, "failed to release community serving lease after push publication"); - return ( - StatusCode::SERVICE_UNAVAILABLE, - "community write lease lost during publication", - ) - .into_response(); } if let Err(error) = publication_result { error!( @@ -2416,16 +2490,378 @@ mod track_c_tests { "receive-pack failed: {}", String::from_utf8_lossy(&output.stderr) ); - assert!( - !receive_pack_report_rejected(&output.stdout), - "receive-pack rejected the deletion: {}", - String::from_utf8_lossy(&output.stdout) - ); - assert!(!remote.join("refs/heads/main").exists()); assert!(remote.join("refs/heads/master").exists()); } + /// A pack with no objects, which a client sends when the refs it pushes + /// name objects the remote already has. + #[cfg(unix)] + const EMPTY_PACK: &[u8] = &[ + b'P', b'A', b'C', b'K', 0, 0, 0, 2, 0, 0, 0, 0, 0x02, 0x9d, 0x08, 0x82, 0x3b, 0xd8, 0xa8, + 0xea, 0xb5, 0x10, 0xad, 0x6a, 0xc7, 0x5c, 0x82, 0x3c, 0xfd, 0x3e, 0xd3, 0x1e, + ]; + + /// A `receive-pack` request body: one pkt-line per `(old, new, ref)` + /// command, the capability list on the first, a flush, and an empty pack + /// when there is a command. + #[cfg(unix)] + fn push_request(commands: &[(&str, &str, &str)], capabilities: &str) -> Vec { + let mut request = Vec::new(); + for (index, (old, new, name)) in commands.iter().enumerate() { + let line = if index == 0 { + format!("{old} {new} {name}\0{capabilities}\n") + } else { + format!("{old} {new} {name}\n") + }; + request.extend_from_slice(format!("{:04x}", line.len() + 4).as_bytes()); + request.extend_from_slice(line.as_bytes()); + } + request.extend_from_slice(b"0000"); + if !commands.is_empty() { + request.extend_from_slice(EMPTY_PACK); + } + request + } + + /// A hydrated workspace stand-in: a bare repository whose `main` is the + /// second of two commits, with a pre-receive hook that accepts or declines + /// every push. Returns the scratch root, the repository path, and the two + /// commit ids, oldest first. Unix only: the hook is a shell script made + /// executable through its file mode. + #[cfg(unix)] + fn push_fixture(hook_accepts: bool) -> (TempDir, std::path::PathBuf, String, String) { + use std::os::unix::fs::PermissionsExt; + + let root = TempDir::new().expect("tempdir"); + let remote = root.path().join("remote.git"); + let source = root.path().join("source"); + let remote_arg = remote.to_str().expect("utf-8 remote path"); + let source_arg = source.to_str().expect("utf-8 source path"); + let setup: [(&Path, &[&str]); 9] = [ + (root.path(), &["init", "--bare", "--quiet", remote_arg]), + ( + root.path(), + &["init", "--quiet", "--initial-branch=main", source_arg], + ), + (&source, &["config", "user.name", "Buzz Test"]), + (&source, &["config", "user.email", "buzz-test@example.com"]), + ( + &source, + &["commit", "--quiet", "--allow-empty", "-m", "first"], + ), + ( + &source, + &["commit", "--quiet", "--allow-empty", "-m", "second"], + ), + (&source, &["push", "--quiet", remote_arg, "main"]), + (&source, &["rev-parse", "HEAD~1"]), + (&source, &["rev-parse", "HEAD"]), + ]; + let mut oids = Vec::new(); + for (cwd, args) in setup { + let output = run_test_git(cwd, args, &[]); + assert!( + output.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + if args[0] == "rev-parse" { + oids.push(String::from_utf8(output.stdout).expect("utf-8 oid")); + } + } + let hook = remote.join("hooks").join("pre-receive"); + std::fs::create_dir_all(remote.join("hooks")).expect("hooks directory"); + let exit_code = if hook_accepts { 0 } else { 1 }; + std::fs::write( + &hook, + format!("#!/bin/sh\ncat >/dev/null\nexit {exit_code}\n"), + ) + .expect("write hook"); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)) + .expect("make hook executable"); + ( + root, + remote, + oids[0].trim().to_string(), + oids[1].trim().to_string(), + ) + } + + /// The publish decision is taken from what `git receive-pack` did to the + /// workspace, for each way a push can end. Every case runs real git through + /// the production `run_git_at` and decides with the production + /// `observe_push`. + /// + /// The first two cases are the ones the earlier rule (publish when git + /// exits 0 and reports no `ng`) got wrong in the permissive direction: git + /// exits 0 and reports nothing, yet no push was accepted. A rule that + /// publishes when the report has an `ok` line or no `ng` line gets them + /// wrong in the same way. The last two cases are the ones the earlier rule + /// got wrong in the other direction: git reports `ok` for a ref it + /// updated, and the rule dropped that update because another ref was + /// refused, for a stale old value or for a name that conflicts with + /// another ref in the same push. The case before them shows that an `ok` line does not by itself + /// mean a ref changed. + #[cfg(unix)] + #[tokio::test] + async fn push_is_published_exactly_when_receive_pack_changed_refs() { + /// One ref-update command: `(old, new, ref)`. + type RefCommand = (String, String, &'static str); + struct Case { + name: &'static str, + hook_accepts: bool, + capabilities: &'static str, + /// Builds the commands from the two fixture commits. + commands: fn(&str, &str) -> Vec, + expect: PushDisposition, + /// Status lines git must have reported to the client. + reported: &'static [&'static str], + } + let create_feature = |first: &str, _second: &str| { + vec![("0".repeat(40), first.to_string(), "refs/heads/feature")] + }; + let cases = [ + Case { + name: "request with no commands, hook would decline", + hook_accepts: false, + capabilities: "", + commands: |_, _| Vec::new(), + expect: PushDisposition::RelayOnly, + reported: &[], + }, + Case { + name: "declined push from a client that asked for no status report", + hook_accepts: false, + capabilities: "", + commands: create_feature, + expect: PushDisposition::RelayOnly, + reported: &[], + }, + Case { + name: "declined push with a status report", + hook_accepts: false, + capabilities: "report-status", + commands: create_feature, + expect: PushDisposition::RelayOnly, + reported: &["ng refs/heads/feature"], + }, + Case { + name: "accepted push", + hook_accepts: true, + capabilities: "report-status", + commands: create_feature, + expect: PushDisposition::Publish, + reported: &["ok refs/heads/feature"], + }, + Case { + name: "accepted command that asks for the value the ref already has", + hook_accepts: true, + capabilities: "report-status", + // git reports `ok` and changes nothing, so there is nothing + // to publish and the report is true of the published state. + commands: |_, second| { + vec![(second.to_string(), second.to_string(), "refs/heads/main")] + }, + expect: PushDisposition::RelayOnly, + reported: &["ok refs/heads/main"], + }, + Case { + name: "accepted push, one ref updated and one refused", + hook_accepts: true, + capabilities: "report-status", + // `main` is at the second commit, so an update that names the + // first commit as its old value is refused. + commands: |first, second| { + vec![ + ("0".repeat(40), first.to_string(), "refs/heads/feature"), + (first.to_string(), second.to_string(), "refs/heads/main"), + ] + }, + expect: PushDisposition::Publish, + reported: &["ok refs/heads/feature", "ng refs/heads/main"], + }, + Case { + name: "accepted push, two refs whose names conflict", + hook_accepts: true, + capabilities: "report-status", + // A ref name cannot be both a file and a directory, so git + // creates one of `feature` and `feature/x` and refuses the + // other. Which one it creates depends on the git version, so + // the expected lines match either outcome and the check below + // ties each ref's presence to its own `ok` line. + commands: |first, second| { + vec![ + ("0".repeat(40), first.to_string(), "refs/heads/feature"), + ("0".repeat(40), second.to_string(), "refs/heads/feature/x"), + ] + }, + expect: PushDisposition::Publish, + reported: &["ok refs/heads/feature", "ng refs/heads/feature"], + }, + ]; + + for case in cases { + let (root, remote, first, second) = push_fixture(case.hook_accepts); + let before = snapshot_workspace(&remote).await.expect("snapshot before"); + assert_eq!(before.refs.get("refs/heads/main"), Some(&second)); + let mut parent_state = ParentState::fresh(); + parent_state.parent.refs = before.refs.clone(); + + let commands = (case.commands)(&first, &second); + let borrowed: Vec<(&str, &str, &str)> = commands + .iter() + .map(|(old, new, name)| (old.as_str(), new.as_str(), *name)) + .collect(); + let request = push_request(&borrowed, case.capabilities); + let git_config = receive_pack_git_config(remote.join("hooks").display().to_string()); + let pack = match run_git_at( + &remote, + "receive-pack", + Body::from(request), + &git_config, + root.path(), + RECEIVE_PACK_MAX_OUTPUT_BYTES, + ) + .await + { + Ok(pack) => pack, + Err(response) => panic!("{}: run_git_at failed: {}", case.name, response.status()), + }; + // git exits 0 in every case, so the exit status cannot be what + // separates an accepted push from a declined or empty one. + assert!(pack.exited_ok, "{}: receive-pack exit status", case.name); + let stdout = String::from_utf8_lossy(&pack.stdout).to_string(); + for line in case.reported { + assert!( + stdout.contains(line), + "{}: expected {line:?} in {stdout:?}", + case.name + ); + } + if case.reported.is_empty() { + assert!( + !stdout.contains("ng ") && !stdout.contains("ok "), + "{}: expected no status report, got {stdout:?}", + case.name + ); + } + + let (disposition, after) = observe_push(&pack, &parent_state, &remote) + .await + .expect("observe push"); + assert_eq!(disposition, case.expect, "{}", case.name); + // The snapshot handed to the publication holds exactly the refs + // git reported as created. + for created in ["refs/heads/feature", "refs/heads/feature/x"] { + assert_eq!( + after.refs.contains_key(created), + stdout.contains(&format!("ok {created}\n")), + "{}: {created} in snapshot", + case.name + ); + } + assert_eq!( + after.refs.get("refs/heads/main"), + Some(&second), + "{}", + case.name + ); + } + } + + /// A push whose ref snapshot crosses the manifest ref cap is a permanent + /// repository limit: it must answer 413, as the publish path did before + /// the snapshot moved ahead of the publish decision, not a 500 a client + /// would retry. + #[cfg(unix)] + #[tokio::test] + async fn snapshot_resource_limit_answers_413() { + let state = crate::state::tests::test_state().await; + let scratch = TempDir::new().expect("scratch"); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("mock object store listener"); + let addr = listener.local_addr().expect("mock address"); + let app = Router::new().fallback(|| async { StatusCode::NOT_FOUND }); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let store = super::super::store::GitStore::new( + &format!("http://{addr}"), + "fixture", + "fixture", + "fixture", + "us-east-1", + buzz_media::config::S3AddressingStyle::Path, + ) + .expect("mock Git store"); + let tenant = TenantContext::resolved( + CommunityId::from_uuid(uuid::Uuid::from_u128(1)), + "git.example", + ); + let (hydrated, parent_state) = hydrate_for_write( + &store, + &tenant, + &"a".repeat(64), + "snapshot-limit", + HydrationOptions { + pack_cache: &state.git_pack_cache, + scratch_dir: scratch.path(), + max_pack_bytes: 1024 * 1024, + max_repo_bytes: 2 * 1024 * 1024, + }, + ) + .await + .expect("hydrate empty fixture"); + server.abort(); + let _ = server.await; + + let (_fixture_root, source, _, tip) = push_fixture(true); + assert_git_success( + run_test_git( + &source, + &["push", "--quiet", hydrated.path().to_str().unwrap(), "main"], + &[], + ), + "seed fixture commit", + ); + let mut packed_refs = String::from("# pack-refs with: peeled fully-peeled sorted\n"); + for index in 0..=super::super::manifest::MAX_MANIFEST_REFS { + packed_refs.push_str(&format!("{tip} refs/heads/ref-{index:05}\n")); + } + std::fs::write(hydrated.path().join("packed-refs"), packed_refs).expect("fixture refs"); + assert!(matches!( + snapshot_workspace(hydrated.path()).await, + Err(CasError::ResourceLimit(_)) + )); + let response = finalize_push( + &state, + PushContext { + pack: PackOutput { + stdout: Vec::new(), + exited_ok: true, + }, + parent_state, + owner: "a".repeat(64), + repo: "snapshot-limit".into(), + repo_id: "snapshot-limit".into(), + pusher: Keys::generate().public_key(), + tenant, + repo_handle: hydrated, + }, + ) + .await; + let status = response.status(); + let body = axum::body::to_bytes(response.into_body(), 4096) + .await + .unwrap(); + assert_eq!( + status, + StatusCode::PAYLOAD_TOO_LARGE, + "snapshot resource limits must not become backend errors; body: {}", + String::from_utf8_lossy(&body) + ); + } + async fn run_finalize_git(repo: &Path, args: &[&str]) -> std::process::Output { let mut command = Command::new("git"); command.current_dir(repo).args(args); @@ -2452,9 +2888,7 @@ mod track_c_tests { .expect("connect test DB"); let db = buzz_db::Db::from_pool(pool.clone()); db.migrate().await.expect("migrate test DB"); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -2497,7 +2931,12 @@ mod track_c_tests { let store = state.db.deletion_store(); let request = store - .submit(host, "git-finalize-test", Some("post-CAS lease regression")) + .submit( + Some(host), + "git-finalize-test", + Some("post-CAS lease regression"), + None, + ) .await .expect("submit deletion"); let inventory = FrozenInventory { @@ -2534,7 +2973,10 @@ mod track_c_tests { (request, claim) } - async fn pushed_context( + /// A push context whose workspace is exactly as hydrated: what + /// `finalize_push` receives when `receive-pack` exited 0 without applying + /// a command (a declined push, or a request with no commands). + async fn unchanged_context( state: &AppState, community: CommunityId, host: &str, @@ -2558,6 +3000,32 @@ mod track_c_tests { ) .await .expect("hydrate empty test repo"); + PushContext { + pack: PackOutput { + stdout: b"git-answer".to_vec(), + exited_ok: true, + }, + parent_state, + owner, + repo: repo.clone(), + repo_id: repo, + pusher, + tenant, + repo_handle: hydrated, + } + } + + /// A push context whose workspace gained a commit on `main`. + async fn pushed_context( + state: &AppState, + community: CommunityId, + host: &str, + owner: String, + repo: String, + pusher: nostr::PublicKey, + scratch: &Path, + ) -> PushContext { + let mut ctx = unchanged_context(state, community, host, owner, repo, pusher, scratch).await; let source = scratch.join("source"); tokio::fs::create_dir(&source) .await @@ -2570,22 +3038,15 @@ mod track_c_tests { .expect("write source file"); run_finalize_git(&source, &["add", "file.txt"]).await; run_finalize_git(&source, &["commit", "--quiet", "-m", "committed"]).await; - let remote = hydrated.path().to_str().expect("hydrated path utf8"); - run_finalize_git(&source, &["push", "--quiet", remote, "main"]).await; - - PushContext { - pack: PackOutput { - stdout: b"push-ok".to_vec(), - ok: true, - }, - parent_state, - owner, - repo: repo.clone(), - repo_id: repo, - pusher, - tenant, - repo_handle: hydrated, - } + let remote = ctx + .repo_handle + .path() + .to_str() + .expect("hydrated path utf8") + .to_string(); + run_finalize_git(&source, &["push", "--quiet", &remote, "main"]).await; + ctx.pack.stdout = b"push-ok".to_vec(); + ctx } async fn repo_announcement_holds_serving_lease_until_pointer_is_seeded() { @@ -2711,6 +3172,7 @@ mod track_c_tests { let hooks = FinalizePushHooks { post_cas_gate: Some(Arc::clone(&gate)), fail_ref_state_insert: false, + lose_lease_signal_after_cas: false, }; let finalize_state = Arc::clone(&state); let finalize = @@ -2801,6 +3263,7 @@ mod track_c_tests { let hooks = FinalizePushHooks { post_cas_gate: None, fail_ref_state_insert: true, + lose_lease_signal_after_cas: false, }; let response = finalize_push_inner(&state, ctx, &hooks).await; @@ -2815,6 +3278,131 @@ mod track_c_tests { pool.close().await; } + async fn finalize_push_lease_signal_after_landed_cas_still_publishes() { + let (state, pool) = finalize_test_state().await; + let host = format!( + "git-finalize-lease-signal-{}.example", + uuid::Uuid::new_v4().simple() + ); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("create test community") + .id; + let scratch = TempDir::new().expect("scratch"); + let owner = format!("owner-{}", uuid::Uuid::new_v4().simple()); + let repo = format!("repo-{}", uuid::Uuid::new_v4().simple()); + let ctx = pushed_context( + &state, + community, + &host, + owner.clone(), + repo.clone(), + Keys::generate().public_key(), + scratch.path(), + ) + .await; + let hooks = FinalizePushHooks { + post_cas_gate: None, + fail_ref_state_insert: false, + lose_lease_signal_after_cas: true, + }; + + let response = finalize_push_inner(&state, ctx, &hooks).await; + assert_eq!( + response.status(), + StatusCode::OK, + "a landed CAS must not be reported as a failed push" + ); + let pointer = crate::api::git::manifest::pointer_key(community, &owner, &repo); + assert!( + state + .git_store + .get_pointer(&pointer) + .await + .expect("read pointer") + .is_some(), + "the CAS landed" + ); + let mut query = buzz_db::event::EventQuery::for_community(community); + query.kinds = Some(vec![30_618]); + query.d_tag = Some(repo); + let events = state.db.query_events(&query).await.expect("query 30618"); + assert_eq!( + events.len(), + 1, + "the landed CAS still derives its kind:30618" + ); + assert!(state + .db + .deletion_store() + .serving_writes_drained(community) + .await + .expect("serving lease released")); + drop(state); + pool.close().await; + } + + /// git exits 0 for a push the hook declined and for a request with no + /// commands. Neither changes a ref, so the relay must answer with git's + /// output and publish nothing: no pointer write, and no kind:30618 naming + /// the caller as the pusher of a state they were not allowed to push. + async fn finalize_push_publishes_nothing_when_receive_pack_changed_no_ref() { + let (state, pool) = finalize_test_state().await; + let host = format!( + "git-finalize-unchanged-{}.example", + uuid::Uuid::new_v4().simple() + ); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("create test community") + .id; + let scratch = TempDir::new().expect("scratch"); + let owner = format!("owner-{}", uuid::Uuid::new_v4().simple()); + let repo = format!("repo-{}", uuid::Uuid::new_v4().simple()); + let ctx = unchanged_context( + &state, + community, + &host, + owner.clone(), + repo.clone(), + Keys::generate().public_key(), + scratch.path(), + ) + .await; + + let response = finalize_push_inner(&state, ctx, &FinalizePushHooks::default()).await; + assert_eq!(response.status(), StatusCode::OK); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .expect("response body"); + assert_eq!(&body[..], b"git-answer", "git's own answer is relayed"); + + let pointer = crate::api::git::manifest::pointer_key(community, &owner, &repo); + assert!( + state + .git_store + .get_pointer(&pointer) + .await + .expect("read pointer") + .is_none(), + "a push that changed no ref must not write the pointer" + ); + let mut query = buzz_db::event::EventQuery::for_community(community); + query.kinds = Some(vec![30_618]); + query.d_tag = Some(repo); + let events = state.db.query_events(&query).await.expect("query 30618"); + assert!( + events.is_empty(), + "a push that changed no ref must not be attributed to the caller" + ); + drop(state); + pool.close().await; + } + mod external_infra_minio_tests { #[tokio::test] #[ignore = "requires Postgres and MinIO"] @@ -2833,6 +3421,18 @@ mod track_c_tests { async fn finalize_push_db_failure_after_cas_is_not_success_and_releases_lease() { super::finalize_push_db_failure_after_cas_is_not_success_and_releases_lease().await; } + + #[tokio::test] + #[ignore = "requires Postgres and MinIO"] + async fn finalize_push_lease_signal_after_landed_cas_still_publishes() { + super::finalize_push_lease_signal_after_landed_cas_still_publishes().await; + } + + #[tokio::test] + #[ignore = "requires Postgres and MinIO"] + async fn finalize_push_publishes_nothing_when_receive_pack_changed_no_ref() { + super::finalize_push_publishes_nothing_when_receive_pack_changed_no_ref().await; + } } /// A gzip-encoded request body is transparently inflated before it @@ -2955,6 +3555,7 @@ mod track_c_tests { refs, packs: vec!["packs/deadbeef".to_string()], parent: None, + published_at: None, } } @@ -2974,12 +3575,6 @@ mod track_c_tests { serde_json::to_string(&event).expect("serialize") } - fn pkt(payload: &[u8]) -> Vec { - let mut out = Vec::new(); - super::pkt_line(&mut out, payload); - out - } - #[test] fn streaming_body_holds_git_permit_until_drop() { let semaphore = Arc::new(tokio::sync::Semaphore::new(1)); @@ -3033,95 +3628,6 @@ mod track_c_tests { assert_eq!(stream.streamed_bytes, 5); } - /// Wrap inner status pkt-lines in one side-band-64k band-1 (data) outer - /// pkt-line — the real shape git emits when side-band is negotiated: - /// `\x01`. - fn sideband_data(inner_pkts: &[&[u8]]) -> Vec { - let mut inner = vec![0x01u8]; // band 1 = data channel - for p in inner_pkts { - inner.extend(pkt(p)); - } - pkt(&inner) - } - - #[test] - fn receive_pack_report_rejected_detects_plain_ng_line() { - // No side-band: status pkt-lines at the outer level. - let mut out = Vec::new(); - out.extend(pkt(b"unpack ok\n")); - out.extend(pkt(b"ng refs/heads/main pre-receive hook declined\n")); - out.extend_from_slice(b"0000"); - - assert!(receive_pack_report_rejected(&out)); - } - - #[test] - fn receive_pack_report_rejected_detects_sideband_ng_line() { - // Real side-band-64k shape: status pkt-lines NESTED inside a band-1 - // outer pkt-line. A naive "strip band byte, split on \n" parser misses - // this — the rejection surfaces as `0031ng refs/...`. - let mut out = sideband_data(&[ - b"unpack ok\n", - b"ng refs/heads/main pre-receive hook declined\n", - ]); - out.extend_from_slice(b"0000"); - - assert!(receive_pack_report_rejected(&out)); - } - - #[test] - fn receive_pack_report_rejected_ignores_ok_status() { - // Real side-band-64k success shape — nested `ok` pkt-lines, no `ng`. - let mut out = sideband_data(&[b"unpack ok\n", b"ok refs/heads/main\n"]); - out.extend_from_slice(b"0000"); - - assert!(!receive_pack_report_rejected(&out)); - } - - #[test] - fn receive_pack_report_rejected_matches_real_git_deny_shape() { - // Mirrors report-status captured from `git receive-pack` (2.50.1) on a - // pre-receive hook decline: - // policy: denied\n (progress/error text) - // 000eunpack ok\n0031ng refs/heads/main pre-receive hook declined\n - // 0000 - // The band-1 payload carries its OWN inner pkt stream — the exact case - // a flat parser returns `false` on. - let mut out = Vec::new(); - out.extend(pkt(b"\x02policy: denied\n")); // band 2 = progress/error - out.extend(sideband_data(&[ - b"unpack ok\n", - b"ng refs/heads/main pre-receive hook declined\n", - ])); - out.extend_from_slice(b"0000"); - - assert!( - receive_pack_report_rejected(&out), - "must detect the nested band-1 ng line on a real deny" - ); - } - - #[test] - fn receive_pack_report_rejected_ignores_progress_channel_noise() { - // A band-2 (progress) line must never be mistaken for a status line, - // even if it contained bytes resembling a status — only band-1 counts. - let mut out = Vec::new(); - out.extend(pkt(b"\x02ng-looking progress noise\n")); // band 2 noise - out.extend(sideband_data(&[b"unpack ok\n", b"ok refs/heads/main\n"])); - out.extend_from_slice(b"0000"); - - assert!(!receive_pack_report_rejected(&out)); - } - - #[test] - fn receive_pack_report_rejected_handles_truncated_and_malformed() { - // Defensive: malformed length / truncated frame yields no match, never - // a panic. - assert!(!receive_pack_report_rejected(b"")); - assert!(!receive_pack_report_rejected(b"zzzz")); - assert!(!receive_pack_report_rejected(b"0048")); // length, no payload - } - #[test] fn git_expected_url_uses_tenant_host_not_config_host() { let tenant_a = tenant("host-a.example", 1); @@ -3374,6 +3880,7 @@ mod sec005_postgres_tests { fn durable_ban_denies_git_even_with_otherwise_valid_auth() { let restriction = buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }; @@ -3384,6 +3891,7 @@ mod sec005_postgres_tests { fn timeout_without_ban_does_not_revoke_git_access() { let restriction = buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: Some(chrono::Utc::now()), }; @@ -3393,6 +3901,7 @@ mod sec005_postgres_tests { fn restriction(banned: bool) -> buzz_db::moderation::RestrictionState { buzz_db::moderation::RestrictionState { banned, + own_banned: banned, muted_until: None, } } @@ -4150,9 +4659,7 @@ mod off_mode_precedence_tests { let pool = sqlx::PgPool::connect(&config.database_url).await.ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -4253,6 +4760,10 @@ mod off_mode_precedence_tests { .body(axum::body::Body::empty()) .expect("build request"); let resp = git_router(Arc::clone(&state)) + .layer(axum::middleware::from_fn_with_state( + Arc::clone(&state), + crate::access::http_access_log, + )) .oneshot(req) .await .expect("router oneshot"); @@ -4284,6 +4795,172 @@ mod off_mode_precedence_tests { } } + /// Through the production router: git's credential-less first request + /// in Enforce mode is one INFO `challenged` line, a malformed proof + /// beside a valid assertion is one WARN `failed` line carrying the + /// remapped 403, and the same proof in Off mode carries its legacy 401. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn git_access_lines_carry_level_outcome_and_status_sent() { + struct AdmitAnyAssertion; + impl buzz_auth::VerifyAssertion for AdmitAnyAssertion { + fn verify_assertion( + &self, + _token: &str, + _community: &buzz_auth::CommunityBinding, + ) -> Result + { + Ok(buzz_auth::VerifiedAssertion::new_for_test( + nostr::Keys::generate().public_key(), + )) + } + } + /// Mode, request headers, then the expected status, outcome and level. + type Case = ( + buzz_auth::NipFiMode, + &'static [(&'static str, &'static str)], + u16, + &'static str, + &'static str, + ); + let cases: [Case; 3] = [ + ( + buzz_auth::NipFiMode::Enforce, + &[], + 401, + "challenged", + "INFO", + ), + ( + buzz_auth::NipFiMode::Enforce, + &[ + ("authorization", "Nostr !!!bad!!!"), + (buzz_auth::CLIENT_ATTACHED_HEADER, "Bearer any.valid.token"), + ], + 403, + "failed", + "WARN", + ), + ( + buzz_auth::NipFiMode::Off, + &[("authorization", "Nostr !!!bad!!!")], + 401, + "failed", + "WARN", + ), + ]; + for (mode, headers, status, outcome, level) in cases { + let mut state = off_mode_state().await.expect("local Postgres"); + let host = format!("git-access-{}.test", uuid::Uuid::new_v4().simple()); + state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community"); + { + let s = Arc::get_mut(&mut state).expect("fixture state is uniquely owned"); + Arc::make_mut(&mut s.config).nip_fi.mode = mode; + Arc::make_mut(&mut s.config).nip_fi.communities = + crate::nip_fi_core::test_support::any_host( + "https://git-access.relay.invalid", + ); + s.nip_fi_verifier = Some(Arc::new(AdmitAnyAssertion)); + } + let mut req = axum::http::Request::builder() + .method("GET") + .uri(GIT_PATH) + .header("host", &host); + for (name, value) in headers { + req = req.header(*name, *value); + } + let req = req.body(axum::body::Body::empty()).expect("build request"); + let (guard, out) = crate::access::tests::capture_scoped(); + let resp = crate::router::build_router(state) + .oneshot(req) + .await + .expect("router oneshot"); + drop(guard); + assert_eq!(resp.status().as_u16(), status, "{mode:?} {headers:?}"); + let lines: Vec<_> = out + .lines() + .into_iter() + .filter(|l| l["event"] == "http") + .collect(); + assert_eq!(lines.len(), 1, "{mode:?} {headers:?}: {lines:?}"); + let line = &lines[0]; + assert_eq!(line["outcome"], outcome, "{line}"); + assert_eq!(line["level"], level, "{line}"); + assert_eq!(line["status"], status, "{line}"); + } + } + + /// A Git request dropped while its relay-membership lookup is in + /// flight still writes one `aborted` line. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn git_request_dropped_during_membership_logs_one_aborted_line() { + use base64::Engine as _; + let state = off_mode_state().await.expect("local Postgres"); + let host = format!("git-drop-{}.test", uuid::Uuid::new_v4().simple()); + let tenant = { + state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community"); + crate::tenant::bind_community(&state.db, &host) + .await + .expect("bind community") + }; + let keys = nostr::Keys::generate(); + let scheme = if state.config.relay_url.starts_with("wss://") { + "https" + } else { + "http" + }; + let signed_url = format!("{scheme}://{host}/git/{OWNER_HEX}/myrepo"); + let event = nostr::EventBuilder::new(nostr::Kind::HttpAuth, "") + .tags([ + nostr::Tag::parse(["u", signed_url.as_str()]).expect("u tag"), + nostr::Tag::parse(["method", "GET"]).expect("method tag"), + ]) + .sign_with_keys(&keys) + .expect("sign NIP-98 event"); + let auth = format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD + .encode(serde_json::to_string(&event).expect("serialize")) + ); + // The hook parks the request right before the membership lookup. + let (arrived, _release) = + crate::nip_fi_test_hooks::git_membership_hook::arm(tenant.community()); + let (guard, out) = crate::access::tests::capture_scoped(); + tokio::select! { + _ = production_git_request(state, &host, &auth) => { + panic!("the membership wait must stall"); + } + arrived = arrived => arrived.expect("request reached the membership wait"), + } + drop(guard); + crate::access::tests::assert_one_aborted_line(&out, &keys.public_key()); + } + + /// Sends the request through the production router, whose access + /// layer owns the line written when the request is dropped. + async fn production_git_request(state: Arc, host: &str, auth: &str) { + let req = axum::http::Request::builder() + .method("GET") + .uri(GIT_PATH) + .header("host", host) + .header("authorization", auth) + .body(axum::body::Body::empty()) + .expect("build request"); + let _ = crate::router::build_router(state) + .oneshot(req) + .await + .expect("router oneshot"); + } + async fn git_request( state: Arc, host: &str, @@ -4322,7 +4999,7 @@ mod off_mode_precedence_tests { // and bad-UTF8 do NOT (those use `into_response()` without the header). #[tokio::test] #[ignore = "requires Postgres"] - async fn off_mode_unmapped_host_missing_auth_returns_401_before_db() { + async fn off_mode_unmapped_host_missing_auth_returns_401_before_tenant_binding() { let Some(state) = off_mode_state().await else { panic!("local Postgres not reachable"); }; @@ -4365,7 +5042,7 @@ mod off_mode_precedence_tests { // Falsifying mutation: delete transport.rs:101-104 → 404. #[tokio::test] #[ignore = "requires Postgres"] - async fn off_mode_unmapped_host_wrong_scheme_returns_401_before_db() { + async fn off_mode_unmapped_host_wrong_scheme_returns_401_before_tenant_binding() { let Some(state) = off_mode_state().await else { panic!("local Postgres not reachable"); }; @@ -4405,7 +5082,7 @@ mod off_mode_precedence_tests { // Falsifying mutation: delete transport.rs:101-104 → 404. #[tokio::test] #[ignore = "requires Postgres"] - async fn off_mode_unmapped_host_invalid_base64_returns_401_before_db() { + async fn off_mode_unmapped_host_invalid_base64_returns_401_before_tenant_binding() { let Some(state) = off_mode_state().await else { panic!("local Postgres not reachable"); }; @@ -4439,7 +5116,7 @@ mod off_mode_precedence_tests { // Falsifying mutation: delete transport.rs:101-104 → 404. #[tokio::test] #[ignore = "requires Postgres"] - async fn off_mode_unmapped_host_bad_utf8_returns_401_before_db() { + async fn off_mode_unmapped_host_bad_utf8_returns_401_before_tenant_binding() { let Some(state) = off_mode_state().await else { panic!("local Postgres not reachable"); }; @@ -4644,9 +5321,7 @@ mod off_mode_precedence_tests { Err(_) => panic!("local Postgres not reachable (enforce git)"), }; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -4783,9 +5458,7 @@ mod off_mode_precedence_tests { Err(_) => panic!("local Postgres not reachable (pack routes)"), }; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -5527,3 +6200,49 @@ mod off_mode_precedence_tests { } } } + +#[cfg(test)] +mod access_log_tests { + use super::*; + + // A URL-mismatch failure logs one fixed-code access line; the client's + // signed `u` tag (and anything smuggled into it) never reaches the logs. + #[test] + fn git_url_mismatch_logs_a_fixed_code_without_the_signed_url() { + const MARKER: &str = "sentinel-7f3c9a"; + let event = nostr::EventBuilder::new(nostr::Kind::HttpAuth, "") + .tag( + nostr::Tag::parse(["u", &format!("https://evil.example/x?token={MARKER}")]) + .unwrap(), + ) + .tag(nostr::Tag::parse(["method", "GET"]).unwrap()) + .sign_with_keys(&nostr::Keys::generate()) + .unwrap(); + let token = + base64::engine::general_purpose::STANDARD.encode(nostr::JsonUtil::as_json(&event)); + let mut headers = axum::http::HeaderMap::new(); + headers.insert( + header::AUTHORIZATION, + format!("Nostr {token}").parse().unwrap(), + ); + + let (refused, out) = crate::access::tests::capture(|| { + let slot = AccessSlot::default(); + let refused = verify_git_proof( + &headers, + "GET", + "https://relay.example/git/o/r.git/info/refs", + &slot, + ) + .is_err(); + slot.emit("/git/{owner}/{repo}/info/refs", 401); + refused + }); + assert!(refused); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "failed"); + assert_eq!(lines[0]["reason"], "nip98_invalid"); + assert!(!out.raw().contains(MARKER), "marker leaked: {}", out.raw()); + } +} diff --git a/crates/buzz-relay/src/api/invites.rs b/crates/buzz-relay/src/api/invites.rs index d229b83eb1e..2f15061a96a 100644 --- a/crates/buzz-relay/src/api/invites.rs +++ b/crates/buzz-relay/src/api/invites.rs @@ -24,7 +24,10 @@ use axum::{ use serde::Deserialize; use serde_json::Value; -use crate::handlers::side_effects::{fan_out_nip43_membership_list, publish_nip43_member_added}; +use crate::access::{AccessSlot, AuthReason, AuthResult}; +use crate::handlers::side_effects::{ + auto_join_default_channels, fan_out_nip43_membership_list, publish_nip43_member_added, +}; use crate::nip_fi_http::admit_nip_fi_http_on_state; use buzz_core::invite::{ hash_v2_code, validate_v2_code, DEFAULT_INVITE_TTL_SECS, MAX_INVITE_TTL_SECS, MAX_INVITE_USES, @@ -35,6 +38,8 @@ use crate::invite_token; use crate::state::AppState; use super::{api_error, bridge, internal_error}; +mod claim_auth; +use claim_auth::{authenticate, map_claim_error}; /// Fixed-window size for the per-pubkey claim rate limiter. pub(crate) const CLAIM_RATE_WINDOW: Duration = Duration::from_secs(60); @@ -61,7 +66,7 @@ pub struct MintInviteRequest { pub max_uses: Option, } -fn validate_mint_request( +pub(crate) fn validate_mint_request( request: &MintInviteRequest, ) -> Result<(u64, Option), (StatusCode, Json)> { let ttl = request.ttl_secs.unwrap_or(DEFAULT_INVITE_TTL_SECS); @@ -226,40 +231,13 @@ pub async fn accept_policy( Ok(Json(serde_json::json!({ "receipt": receipt }))) } -/// Shared prelude: bind the tenant from the Host header and verify the NIP-98 -/// signature + replay for `path`. -async fn authenticate( - state: &Arc, - headers: &HeaderMap, - path: &str, - body: &[u8], -) -> Result<(buzz_core::TenantContext, nostr::PublicKey), (StatusCode, Json)> { - let raw_host = headers - .get(axum::http::header::HOST) - .and_then(|v| v.to_str().ok()) - .unwrap_or(""); - let tenant = crate::tenant::bind_community(&state.db, raw_host) - .await - .map_err(|_| { - api_error( - StatusCode::NOT_FOUND, - "relay: no community is configured for this host", - ) - })?; - - let url = bridge::nip98_expected_url(&state.config.relay_url, &tenant, path); - let bridge::VerifiedBridgeAuth { - pubkey, - event_id_bytes, - .. - } = bridge::verify_nip98_exempt_invite_claim(headers, "POST", &url, Some(body))?; - bridge::check_nip98_replay(state, &tenant, event_id_bytes).await?; - - Ok((tenant, pubkey)) -} - -fn map_mint_error(error: buzz_db::DbError) -> (StatusCode, Json) { +pub(crate) fn map_mint_error(error: buzz_db::DbError) -> (StatusCode, Json) { match error { + buzz_db::DbError::InviteRestricted => api_error(StatusCode::FORBIDDEN, "invite_restricted"), + buzz_db::DbError::InviteIssuerNotAdmin => api_error( + StatusCode::FORBIDDEN, + "only relay owners and admins can create invites", + ), buzz_db::DbError::InvalidData(message) | buzz_db::DbError::DeletionSafety(message) => { api_error(StatusCode::BAD_REQUEST, &message) } @@ -277,17 +255,19 @@ fn map_mint_error(error: buzz_db::DbError) -> (StatusCode, Json) { /// tenant host. pub async fn mint_invite( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> axum::response::Response { // NIP-FI gate wraps the entire handler so the denial is emitted as exact // text/plain bytes. [FI-TRACE-AUTHORITY-UNIFORM] - mint_invite_checked(state, headers, body).await + mint_invite_checked(state, slot, headers, body).await } #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn mint_invite_checked( state: Arc, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> axum::response::Response { @@ -309,7 +289,9 @@ async fn mint_invite_checked( let admission = match admit_nip_fi_http_on_state( &state, &headers, + &slot, bridge::make_nip98_closure_for_admission( + slot.clone(), headers.clone(), "POST", url, @@ -323,55 +305,98 @@ async fn mint_invite_checked( Ok(a) => a, Err(resp) => return resp, }; - let pubkey = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let (event_id_bytes, signed_created_at) = admission.into_extra(); + let mut caller = bridge::ProvenCaller::new(admission, &slot, &tenant); + let pubkey = caller.pubkey; // Replay detection runs after NIP-98+assertion admission (both proofs verified). - if let Err(e) = bridge::check_nip98_replay(&state, &tenant, event_id_bytes).await { + if let Err(e) = caller.replay(&state, &tenant).await { return e.into_response(); } // Membership and community ban, same step as the other NIP-98 routes. - if let Err(e) = super::relay_members::enforce_relay_membership( + let membership = super::relay_members::enforce_relay_membership( &state, &tenant, pubkey.as_bytes(), super::relay_members::extract_auth_tag_header(&headers), - signed_created_at, - token_owner, + caller.signed_at, + caller.token_owner, ) - .await - { + .await; + if let Err(e) = caller.check( + membership, + super::relay_members::MembershipRefusal::auth_result, + ) { return e.into_response(); } - match mint_invite_inner(&state, body, tenant, pubkey).await { - Ok(json) => json.into_response(), + if let Some(owner) = super::relay_members::extract_nip_oa_owner( + pubkey.as_bytes(), + super::relay_members::extract_auth_tag_header(&headers), + caller.signed_at, + ) { + match super::relay_members::link_agent_owner(&state, &tenant, &pubkey, &owner).await { + super::relay_members::OwnerLink::Linked => {} + super::relay_members::OwnerLink::Conflict => { + slot.finish(AuthResult::Denied(AuthReason::OwnerMismatch)); + return api_error(StatusCode::FORBIDDEN, "invite_owner_mismatch").into_response(); + } + super::relay_members::OwnerLink::Unavailable => { + slot.finish(AuthResult::Denied(AuthReason::NipOaOwnerUnlinked)); + return api_error( + StatusCode::SERVICE_UNAVAILABLE, + crate::handlers::auth::OWNER_LINK_ERROR, + ) + .into_response(); + } + } + } + + // The request's access line carries the minted invite. + match mint_invite_inner(&state, &mut caller, body, tenant, pubkey).await { + Ok((json, minted)) => { + slot.detail(minted); + json.into_response() + } Err(e) => e.into_response(), } } async fn mint_invite_inner( state: &AppState, + caller: &mut bridge::ProvenCaller, body: axum::body::Bytes, tenant: buzz_core::TenantContext, pubkey: nostr::PublicKey, -) -> Result, (StatusCode, Json)> { +) -> Result<(Json, crate::access::Detail), (StatusCode, Json)> { // Authz mirrors kind:9030 (add member): owner or admin only. let sender_hex = pubkey.to_hex(); - let member = state - .db - .get_relay_member(tenant.community(), &sender_hex) - .await + let member = caller + .check( + state + .db + .get_relay_member(tenant.community(), &sender_hex) + .await, + |_| AuthResult::Denied(AuthReason::AuthorizationUnavailable), + ) .map_err(|e| internal_error(&format!("invite mint role lookup: {e}")))?; + // The role gate is the route's last admission step. let role = member.map(|m| m.role).unwrap_or_default(); - if role != "owner" && role != "admin" { - return Err(api_error( - StatusCode::FORBIDDEN, - "only relay owners and admins can create invites", - )); - } + caller + .admit( + if role == "owner" || role == "admin" { + Ok(()) + } else { + Err(()) + }, + |()| AuthResult::Denied(AuthReason::NotRelayAdmin), + ) + .map_err(|()| { + api_error( + StatusCode::FORBIDDEN, + "only relay owners and admins can create invites", + ) + })?; let request: MintInviteRequest = if body.is_empty() { MintInviteRequest::default() @@ -389,10 +414,30 @@ async fn mint_invite_inner( // Mint a v2 opaque, database-backed invite. let invite = state .db - .mint_relay_invite(tenant.community(), &sender_hex, ttl, max_uses) + .mint_relay_invite_as_admin(tenant.community(), &sender_hex, ttl, max_uses) .await .map_err(map_mint_error)?; + let minted = crate::access::Detail { + invite_id: Some(invite.invite_id), + expires_at: Some(invite.expires_at.timestamp()), + max_uses: invite.max_uses, + ..Default::default() + }; + + Ok(( + Json(minted_invite_json(state, tenant.host(), &invite)), + minted, + )) +} + +/// The mint response contract shared by every mint route: the code, its +/// expiry in Unix seconds, its use limits, and the landing-page URL on `host`. +pub(crate) fn minted_invite_json( + state: &AppState, + host: &str, + invite: &buzz_db::relay_invite::MintedInvite, +) -> Value { // Same TLS-posture logic as nip98_expected_url: wss deployments get an // https landing page URL, ws dev/test deployments get http. let scheme = if state.config.relay_url.trim_start().starts_with("wss://") { @@ -400,26 +445,13 @@ async fn mint_invite_inner( } else { "http" }; - - tracing::info!( - community = %tenant.community(), - minted_by = %sender_hex, - invite_id = %invite.invite_id, - expires_at = %invite.expires_at, - max_uses = ?invite.max_uses, - "relay invite minted" - ); - - // expires_at as unix seconds for the response contract. - let expires_at_unix = invite.expires_at.timestamp() as u64; - - Ok(Json(serde_json::json!({ + serde_json::json!({ "code": invite.code, - "expires_at": expires_at_unix, + "expires_at": invite.expires_at.timestamp() as u64, "max_uses": invite.max_uses, "uses_remaining": invite.uses_remaining, - "url": format!("{scheme}://{}/invite/{}", tenant.host(), invite.code), - }))) + "url": format!("{scheme}://{host}/invite/{}", invite.code), + }) } /// Claim an invite code — `POST /api/invites/claim`, NIP-98 signed by the @@ -430,22 +462,43 @@ async fn mint_invite_inner( /// code is never fallen back to v1 verification. pub async fn claim_invite( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { - let (tenant, pubkey) = authenticate(&state, &headers, "/api/invites/claim", &body).await?; + let (tenant, pubkey, verified_owner) = + authenticate(&state, &slot, &headers, "/api/invites/claim", &body).await?; + // The request's access line carries whether the claim joined. + let claimed = claim_invite_authed(&state, &slot, tenant, pubkey, verified_owner, &body).await; + if let Ok(Json(json)) = &claimed { + slot.detail(crate::access::Detail { + joined: Some(json["status"] == "joined"), + ..Default::default() + }); + } + claimed +} - if claim_rate_limited(&state, tenant.community(), &pubkey) { +async fn claim_invite_authed( + state: &Arc, + slot: &AccessSlot, + tenant: buzz_core::TenantContext, + pubkey: nostr::PublicKey, + verified_owner: Option, + body: &[u8], +) -> Result, (StatusCode, Json)> { + if claim_rate_limited(state, tenant.community(), &pubkey) { return Err(api_error( StatusCode::TOO_MANY_REQUESTS, "too many invite claim attempts, slow down", )); } - let request: ClaimInviteRequest = serde_json::from_slice(&body) + let request: ClaimInviteRequest = serde_json::from_slice(body) .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid claim JSON: {e}")))?; let claimer_hex = pubkey.to_hex(); + let owner_hex = verified_owner.map(|owner| owner.to_hex()); let key = invite_token::derive_invite_key(&state.relay_keypair); // --- v2 database-backed path --- @@ -470,7 +523,7 @@ pub async fn claim_invite( let token_hash = hash_v2_code(&request.code); let write = state .db - .claim_relay_invite( + .claim_relay_invite_with_owner( tenant.community(), &token_hash, &claimer_hex, @@ -479,32 +532,36 @@ pub async fn claim_invite( .join_policy .as_ref() .map(|policy| policy.version.as_str()), + owner_hex.as_deref(), &state.relay_keypair, ) .await - .map_err(|e| internal_error(&format!("v2 invite claim: {e}")))?; - fan_out_nip43_membership_list(&tenant, &state, write.snapshot).await; - - return match write.outcome { - buzz_db::relay_invite::ClaimOutcome::Joined { .. } => { - tracing::info!( - community = %tenant.community(), - member = %claimer_hex, - "relay member added via v2 invite" - ); - // NIP-43 side effects only on Joined, never on other outcomes. - if let Err(e) = publish_nip43_member_added(&tenant, &state, &claimer_hex).await { - tracing::warn!( - "failed to publish NIP-43 member-added delta after v2 claim: {e}" - ); - } - Ok(Json(serde_json::json!({ - "status": "joined", - "community_id": tenant.community().to_string(), - "host": tenant.host(), - "role": "member", - }))) - } + .map_err(|e| map_claim_error(slot, e))?; + metrics::counter!("buzz_users_created_total", "community" => tenant.host().to_owned()) + .increment(write.outcome.users_created); + if write.outcome.owner_link_created { + state.disconnect_unowned_agent_clusterwide(&tenant, pubkey.as_bytes()); + } + // Publish the member-added delta only on Joined; successful repeated + // claims may still have durable default-channel work to finish. + let joined = matches!( + write.outcome.outcome, + buzz_db::relay_invite::ClaimOutcome::Joined { .. } + ); + if matches!( + write.outcome.outcome, + buzz_db::relay_invite::ClaimOutcome::Joined { .. } + | buzz_db::relay_invite::ClaimOutcome::AlreadyMember { .. } + ) { + finish_committed_claim(&tenant, state, &claimer_hex, write.snapshot, joined).await; + } + return match write.outcome.outcome { + buzz_db::relay_invite::ClaimOutcome::Joined { .. } => Ok(Json(serde_json::json!({ + "status": "joined", + "community_id": tenant.community().to_string(), + "host": tenant.host(), + "role": "member", + }))), buzz_db::relay_invite::ClaimOutcome::AlreadyMember { .. } => { Ok(Json(serde_json::json!({ "status": "already_member", @@ -519,6 +576,17 @@ pub async fn claim_invite( buzz_db::relay_invite::ClaimOutcome::Exhausted => { Err(api_error(StatusCode::FORBIDDEN, "invite_exhausted")) } + // Deliberately indistinguishable, even for an issuer timeout whose + // link works again later: a claim never reveals the issuer's + // moderation state. + buzz_db::relay_invite::ClaimOutcome::Revoked + | buzz_db::relay_invite::ClaimOutcome::IssuerRestricted => { + Err(api_error(StatusCode::FORBIDDEN, "invite_invalid")) + } + buzz_db::relay_invite::ClaimOutcome::Restricted => { + slot.finish(AuthResult::Denied(AuthReason::Restricted)); + Err(api_error(StatusCode::FORBIDDEN, "invite_restricted")) + } buzz_db::relay_invite::ClaimOutcome::Invalid => { Err(api_error(StatusCode::FORBIDDEN, "invite_invalid")) } @@ -526,16 +594,18 @@ pub async fn claim_invite( } // --- v1 HMAC path (stateless tokens, drain window) --- - let payload = invite_token::verify_invite(&key, tenant.community(), &request.code).map_err( - |e| match e { - // Expired is post-MAC: revealing it helps the UX without helping a forger. - invite_token::InviteError::Expired => { - api_error(StatusCode::FORBIDDEN, "invite_expired") - } - // Everything else stays coarse so the endpoint is a poor oracle. - _ => api_error(StatusCode::FORBIDDEN, "invite_invalid"), - }, - )?; + let payload = invite_token::verify_invite_with_cutoff( + &key, + tenant.community(), + &request.code, + state.config.invite_v1_invalid_after, + ) + .map_err(|e| match e { + // Expired is post-MAC: revealing it helps the UX without helping a forger. + invite_token::InviteError::Expired => api_error(StatusCode::FORBIDDEN, "invite_expired"), + // Everything else stays coarse so the endpoint is a poor oracle. + _ => api_error(StatusCode::FORBIDDEN, "invite_invalid"), + })?; if let Some(policy) = &state.config.join_policy { let receipt = request @@ -548,7 +618,7 @@ pub async fn claim_invite( let write = state .db - .claim_relay_membership( + .claim_relay_membership_with_owner( tenant.community(), &claimer_hex, &payload.r, @@ -557,23 +627,18 @@ pub async fn claim_invite( .join_policy .as_ref() .map(|policy| policy.version.as_str()), + owner_hex.as_deref(), &state.relay_keypair, ) .await - .map_err(|e| internal_error(&format!("invite claim insert: {e}")))?; - let was_inserted = write.outcome; - fan_out_nip43_membership_list(&tenant, &state, write.snapshot).await; - - if was_inserted { - tracing::info!( - community = %tenant.community(), - member = %claimer_hex, - "relay member added via invite" - ); - if let Err(e) = publish_nip43_member_added(&tenant, &state, &claimer_hex).await { - tracing::warn!("failed to publish NIP-43 member-added delta after claim: {e}"); - } + .map_err(|e| map_claim_error(slot, e))?; + metrics::counter!("buzz_users_created_total", "community" => tenant.host().to_owned()) + .increment(write.outcome.users_created); + if write.outcome.owner_link_created { + state.disconnect_unowned_agent_clusterwide(&tenant, pubkey.as_bytes()); } + let was_inserted = write.outcome.inserted; + finish_committed_claim(&tenant, state, &claimer_hex, write.snapshot, was_inserted).await; Ok(Json(serde_json::json!({ "status": if was_inserted { "joined" } else { "already_member" }, @@ -583,6 +648,39 @@ pub async fn claim_invite( }))) } +/// The follow-up of a claim whose roster write committed: the NIP-43 +/// membership-list fan-out, the member-added delta for new members, and +/// any unfinished default-channel joins (including on a repeated claim). +/// +/// It runs on its own task, which the handler awaits, so the response still +/// waits for the joins. A client that disconnects first makes the server +/// drop the handler's future: that detaches the task rather than cancelling +/// it partway. The durable token also survives a relay restart. +async fn finish_committed_claim( + tenant: &buzz_core::TenantContext, + state: &Arc, + claimer_hex: &str, + snapshot: Option, + joined: bool, +) { + let follow_up = tokio::spawn({ + let (tenant, state, claimer_hex) = + (tenant.clone(), Arc::clone(state), claimer_hex.to_owned()); + async move { + fan_out_nip43_membership_list(&tenant, &state, snapshot).await; + if joined { + if let Err(e) = publish_nip43_member_added(&tenant, &state, &claimer_hex).await { + tracing::warn!("failed to publish NIP-43 member-added delta after claim: {e}"); + } + } + auto_join_default_channels(&tenant, &state, &claimer_hex, None).await; + } + }); + if let Err(e) = follow_up.await { + tracing::error!(member = %claimer_hex, error = %e, "invite claim follow-up task failed"); + } +} + /// Fixed-window rate limit on claim attempts, keyed by community and claimer /// pubkey so traffic for one tenant cannot consume another tenant's allowance. /// @@ -611,6 +709,9 @@ fn claim_key_rate_limited( #[cfg(test)] mod postgres_tests { + mod owner_admission_tests; + mod recovery_postgres_tests; + mod restriction_tests; use std::sync::Arc; use std::time::Duration; @@ -748,9 +849,7 @@ mod postgres_tests { let db = buzz_db::Db::from_pool(pool.clone()); db.ensure_configured_community(host).await.ok()?; - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -934,7 +1033,7 @@ mod postgres_tests { .await .expect("lookup") .expect("community exists"); - state + let _ = state .db .add_relay_member( community.id, @@ -1187,6 +1286,643 @@ mod postgres_tests { ); } + /// How many kind:44100 notifications name `member_hex` across the + /// community, one per channel the relay joined them to. + async fn added_notification_count( + state: &AppState, + community: buzz_core::CommunityId, + member_hex: &str, + ) -> i64 { + state + .db + .count_events(&buzz_db::EventQuery { + kinds: Some(vec![buzz_core::kind::KIND_MEMBER_ADDED_NOTIFICATION as i32]), + p_tag_hex: Some(member_hex.to_string()), + global_only: true, + ..buzz_db::EventQuery::for_community(community) + }) + .await + .expect("count 44100") + } + + /// How many `member_joined` kind:40099 notices in `channel_id` target + /// `member_hex`. + async fn member_joined_notice_count( + state: &AppState, + community: buzz_core::CommunityId, + channel_id: Uuid, + member_hex: &str, + ) -> usize { + state + .db + .query_events(&buzz_db::EventQuery { + kinds: Some(vec![40099]), + channel_id: Some(channel_id), + ..buzz_db::EventQuery::for_community(community) + }) + .await + .expect("query 40099") + .iter() + .filter_map(|stored| serde_json::from_str::(&stored.event.content).ok()) + .filter(|content| content["type"] == "member_joined" && content["target"] == member_hex) + .count() + } + + /// The channel roles the relay holds for `keys` in `channels`, in order. + async fn channel_roles( + state: &AppState, + community: buzz_core::CommunityId, + channels: &[Uuid], + keys: &Keys, + ) -> Vec> { + let mut roles = Vec::new(); + for channel_id in channels { + roles.push( + state + .db + .get_member_role(community, *channel_id, &keys.public_key().to_bytes()) + .await + .expect("member role"), + ); + } + roles + } + + /// Wait until a session blocked by `blocker_pid` waits for the channel + /// row lock `put_member` takes, failing if `task` finishes first. + async fn wait_for_put_member_behind( + pool: &sqlx::PgPool, + blocker_pid: i32, + task: &tokio::task::JoinHandle, + ) { + let deadline = std::time::Instant::now() + Duration::from_secs(10); + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity \ + WHERE wait_event_type = 'Lock' \ + AND $1 = ANY(pg_blocking_pids(pid)) \ + AND query LIKE 'SELECT archived_at FROM channels %FOR NO KEY UPDATE')", + ) + .bind(blocker_pid) + .fetch_one(pool) + .await + .expect("read lock waiters"); + if waiting { + return; + } + assert!( + !task.is_finished(), + "the join finished without waiting for the held channel row" + ); + assert!( + std::time::Instant::now() < deadline, + "the join never waited for the held channel row" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + + /// Claiming an invite joins the new member to the community's effective + /// default channels, once. Four channels flagged by the relay owner: + /// one open, one archived after flagging, one made private after + /// flagging, plus an unflagged control. A v2 claim joins the open one + /// only, with its kind:39002 roster, one kind:44100 and one + /// `member_joined` notice; a kind:9022 leave followed by a re-claim is + /// `already_member` and does not re-add. The v1 token path joins the same + /// way. The archived guard the shared join body owns is bound directly. + /// Mutation: delete `auto_join_default_channels` at either claim site → + /// RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn claim_auto_joins_default_channels_once() { + use crate::handlers::group_state_postgres_tests::{ + create_channel, edit_channel, group_state_tags, http_auth, + }; + use crate::handlers::ingest::ingest_event; + use crate::handlers::side_effects::join_channel_as_self; + + let host = format!("invites-auto-join-{}.example", Uuid::new_v4().simple()); + let owner = Keys::generate(); + let state = invite_test_state(&host) + .await + .expect("requires reachable Postgres and relay test state"); + let community = state + .db + .lookup_community_by_host(&host) + .await + .expect("lookup") + .expect("community exists") + .id; + let tenant = buzz_core::TenantContext::resolved(community, &host); + state + .db + .add_relay_member( + community, + &owner.public_key().to_hex(), + "owner", + None, + &Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("seed owner"); + + let flagged = create_channel(&state, &tenant, &owner, &[]).await; + let archived = create_channel(&state, &tenant, &owner, &[]).await; + let private = create_channel(&state, &tenant, &owner, &[]).await; + let control = create_channel(&state, &tenant, &owner, &[]).await; + for channel_id in [flagged, archived, private] { + edit_channel( + &state, + &tenant, + &owner, + channel_id, + &[&["auto_join", "true"]], + ) + .await + .expect("relay owner flags channel"); + } + edit_channel(&state, &tenant, &owner, archived, &[&["archived", "true"]]) + .await + .expect("archive after flagging"); + edit_channel( + &state, + &tenant, + &owner, + private, + &[&["visibility", "private"]], + ) + .await + .expect("make private after flagging"); + let channels = [flagged, archived, private, control]; + + let joiner = Keys::generate(); + let joiner_hex = joiner.public_key().to_hex(); + let archived_refusal = + join_channel_as_self(&tenant, &state, archived, &joiner.public_key().to_bytes()) + .await + .expect_err("self-join of an archived channel"); + assert!( + archived_refusal.to_string().contains("archived"), + "{archived_refusal}" + ); + assert_eq!( + added_notification_count(&state, community, &joiner_hex).await, + 0 + ); + + let code = mint_code( + state.clone(), + &host, + &owner, + serde_json::json!({ "max_uses": 1 }), + ) + .await; + let claim_body = serde_json::json!({ "code": code }).to_string(); + let response = post_json( + state.clone(), + &host, + "/api/invites/claim", + &joiner, + claim_body.clone(), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(read_json(response).await["status"], "joined"); + assert_eq!( + channel_roles(&state, community, &channels, &joiner).await, + [Some("member".to_string()), None, None, None], + "joined to the effective default channel only" + ); + assert!( + group_state_tags(&state, &tenant, flagged, 39002) + .await + .iter() + .any(|tag| tag[0] == "p" && tag[1] == joiner_hex), + "kind:39002 of the default channel lists the new member" + ); + assert_eq!( + added_notification_count(&state, community, &joiner_hex).await, + 1 + ); + assert_eq!( + member_joined_notice_count(&state, community, flagged, &joiner_hex).await, + 1 + ); + + // Leaving is respected: a re-claim is a no-op, not a re-add. + let leave = EventBuilder::new(Kind::Custom(9022), "") + .tags([Tag::parse(["h", &flagged.to_string()]).unwrap()]) + .sign_with_keys(&joiner) + .expect("sign 9022"); + let left = ingest_event(&state, &tenant, leave, http_auth(&joiner)) + .await + .expect("ingest 9022"); + assert!(left.accepted, "{:?}", left.message); + assert_eq!( + channel_roles(&state, community, &[flagged], &joiner).await, + [None] + ); + let response = post_json( + state.clone(), + &host, + "/api/invites/claim", + &joiner, + claim_body, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(read_json(response).await["status"], "already_member"); + assert_eq!( + channel_roles(&state, community, &channels, &joiner).await, + [None, None, None, None], + "a re-claim must not resurrect a kind:9022 leave" + ); + assert_eq!( + added_notification_count(&state, community, &joiner_hex).await, + 1 + ); + assert_eq!( + member_joined_notice_count(&state, community, flagged, &joiner_hex).await, + 1 + ); + + // The v1 HMAC token path joins the same way. + let v1_joiner = Keys::generate(); + let v1_joiner_hex = v1_joiner.public_key().to_hex(); + let v1_code = forge_v1_invite_code(&state, community, unix_now() + 3600); + let response = post_json( + state.clone(), + &host, + "/api/invites/claim", + &v1_joiner, + serde_json::json!({ "code": v1_code }).to_string(), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(read_json(response).await["status"], "joined"); + assert_eq!( + channel_roles(&state, community, &channels, &v1_joiner).await, + [Some("member".to_string()), None, None, None] + ); + assert_eq!( + added_notification_count(&state, community, &v1_joiner_hex).await, + 1 + ); + } + + /// A default channel archived after the auto-join listed it is skipped: + /// no membership row, no kind:39002 roster entry, no kind:44100 and no + /// `member_joined` notice. The test holds an uncommitted archive of the + /// listed channel, so the auto-join reads the committed channel state and + /// then waits for the membership write's channel row lock. The archive + /// commits and the join resumes on an archived channel. Mutation: drop the channel row lock or the archived refusal + /// from `put_members` → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn auto_join_skips_a_default_channel_archived_while_it_joins() { + use crate::handlers::group_state_postgres_tests::{ + create_channel, edit_channel, group_state_tags, + }; + use crate::handlers::side_effects::auto_join_default_channels; + + let host = format!( + "invites-auto-join-archive-{}.example", + Uuid::new_v4().simple() + ); + let owner = Keys::generate(); + let state = invite_test_state(&host) + .await + .expect("requires reachable Postgres and relay test state"); + let community = state + .db + .lookup_community_by_host(&host) + .await + .expect("lookup") + .expect("community exists") + .id; + let tenant = buzz_core::TenantContext::resolved(community, &host); + let joiner = Keys::generate(); + let joiner_hex = joiner.public_key().to_hex(); + let _ = state + .db + .add_relay_member( + community, + &owner.public_key().to_hex(), + "owner", + None, + &Keys::generate(), + ) + .await + .expect("seed relay owner"); + let _ = state + .db + .add_relay_member_with_default_channels( + community, + &joiner_hex, + "member", + &joiner_hex, + &Keys::generate(), + ) + .await + .expect("seed pending default-channel admission"); + let starter = create_channel(&state, &tenant, &owner, &[]).await; + edit_channel(&state, &tenant, &owner, starter, &[&["auto_join", "true"]]) + .await + .expect("relay owner flags channel"); + + let pool = state.db.pool().clone(); + let mut archive = pool.begin().await.expect("begin archive"); + let archive_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *archive) + .await + .expect("archive backend pid"); + sqlx::query("UPDATE channels SET archived_at = NOW() WHERE community_id = $1 AND id = $2") + .bind(community.as_uuid()) + .bind(starter) + .execute(&mut *archive) + .await + .expect("archive the default channel"); + + let auto_join = tokio::spawn({ + let state = Arc::clone(&state); + let tenant = tenant.clone(); + let joiner_hex = joiner_hex.clone(); + async move { auto_join_default_channels(&tenant, &state, &joiner_hex, None).await } + }); + // Wait until the join is blocked on the channel row lock in + // the membership write, behind the archive, so it has already listed + // the channel. + wait_for_put_member_behind(&pool, archive_pid, &auto_join).await; + archive.commit().await.expect("commit archive"); + tokio::time::timeout(Duration::from_secs(10), auto_join) + .await + .expect("the auto-join returns after the archive commits") + .expect("auto-join task must not panic"); + + assert_eq!( + channel_roles(&state, community, &[starter], &joiner).await, + [None], + "an archived default channel must not admit the new member" + ); + assert!( + !group_state_tags(&state, &tenant, starter, 39002) + .await + .iter() + .any(|tag| tag[0] == "p" && tag[1] == joiner_hex), + "kind:39002 must not list the new member" + ); + assert_eq!( + added_notification_count(&state, community, &joiner_hex).await, + 0 + ); + assert_eq!( + member_joined_notice_count(&state, community, starter, &joiner_hex).await, + 0 + ); + } + + /// A client that disconnects mid-claim does not cut the auto-join short. + /// The server drops the handler's future on a disconnect; the test does + /// the same by aborting the request while the auto-join waits in + /// `put_member` behind a held lock on the first default channel's row. + /// Once the lock is released, the claimer still joins both default + /// channels, for a v2 and a v1 claim. Mutation: run the follow-up inline + /// in the handler again → RED (the claimer joins no channel). + #[tokio::test] + #[ignore = "requires Postgres"] + async fn claim_follow_up_survives_a_client_disconnect() { + use crate::handlers::group_state_postgres_tests::{create_channel, edit_channel}; + + let host = format!( + "invites-auto-join-disconnect-{}.example", + Uuid::new_v4().simple() + ); + let owner = Keys::generate(); + let state = invite_test_state(&host) + .await + .expect("requires reachable Postgres and relay test state"); + let community = state + .db + .lookup_community_by_host(&host) + .await + .expect("lookup") + .expect("community exists") + .id; + let tenant = buzz_core::TenantContext::resolved(community, &host); + state + .db + .add_relay_member( + community, + &owner.public_key().to_hex(), + "owner", + None, + &Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("seed owner"); + let first = create_channel(&state, &tenant, &owner, &[]).await; + let second = create_channel(&state, &tenant, &owner, &[]).await; + for channel_id in [first, second] { + edit_channel( + &state, + &tenant, + &owner, + channel_id, + &[&["auto_join", "true"]], + ) + .await + .expect("relay owner flags channel"); + } + + let v2_code = mint_code( + state.clone(), + &host, + &owner, + serde_json::json!({ "max_uses": 1 }), + ) + .await; + let v1_code = forge_v1_invite_code(&state, community, unix_now() + 3600); + let pool = state.db.pool().clone(); + for code in [v2_code, v1_code] { + let joiner = Keys::generate(); + let joiner_hex = joiner.public_key().to_hex(); + let mut hold = pool.begin().await.expect("begin hold"); + let hold_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *hold) + .await + .expect("hold backend pid"); + sqlx::query("SELECT 1 FROM channels WHERE community_id = $1 AND id = $2 FOR UPDATE") + .bind(community.as_uuid()) + .bind(first) + .execute(&mut *hold) + .await + .expect("hold the first default channel's row"); + + let claim = tokio::spawn({ + let (state, host, joiner) = (state.clone(), host.clone(), joiner.clone()); + let body = serde_json::json!({ "code": code }).to_string(); + async move { post_json(state, &host, "/api/invites/claim", &joiner, body).await } + }); + wait_for_put_member_behind(&pool, hold_pid, &claim).await; + claim.abort(); + assert!( + claim + .await + .expect_err("the claim was still waiting") + .is_cancelled(), + "the claim request was dropped" + ); + hold.rollback().await.expect("release the held row"); + + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while added_notification_count(&state, community, &joiner_hex).await < 2 { + assert!( + std::time::Instant::now() < deadline, + "the auto-join stopped with the dropped claim: {:?}", + channel_roles(&state, community, &[first, second], &joiner).await + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!( + channel_roles(&state, community, &[first, second], &joiner).await, + [Some("member".to_string()), Some("member".to_string())] + ); + } + } + + /// A mint and a claim each write one access line carrying what they + /// did, and the invite code reaches no log. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn mint_and_claim_write_one_line_each_without_the_code() { + let host = format!("invites-{}.example", Uuid::new_v4().simple()); + let (owner, joiner) = (Keys::generate(), Keys::generate()); + let state = invite_test_state(&host).await.expect("local Postgres"); + let community = state + .db + .lookup_community_by_host(&host) + .await + .expect("lookup") + .expect("community exists"); + let _ = state + .db + .add_relay_member( + community.id, + &owner.public_key().to_hex(), + "owner", + None, + &nostr::Keys::generate(), + ) + .await + .expect("seed owner"); + + let (_guard, out) = crate::access::tests::capture_scoped(); + let code = mint_code( + state.clone(), + &host, + &owner, + serde_json::json!({ "max_uses": 3 }), + ) + .await; + let mint = out.lines(); + assert_eq!(mint.len(), 1, "{mint:?}"); + assert_eq!(mint[0]["route"], "/api/invites", "{}", mint[0]); + assert_eq!(mint[0]["status"], 200, "{}", mint[0]); + assert_eq!(mint[0]["max_uses"], 3, "{}", mint[0]); + assert!(mint[0]["invite_id"].is_string(), "{}", mint[0]); + assert!(mint[0]["expires_at"].is_i64(), "{}", mint[0]); + + let response = post_json( + state, + &host, + "/api/invites/claim", + &joiner, + serde_json::json!({ "code": code }).to_string(), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let lines = out.lines(); + assert_eq!(lines.len(), 2, "one line per request: {lines:?}"); + assert_eq!(lines[1]["route"], "/api/invites/claim", "{}", lines[1]); + assert_eq!(lines[1]["joined"], true, "{}", lines[1]); + assert_eq!( + lines[1]["pubkey"], + joiner.public_key().to_hex(), + "{}", + lines[1] + ); + assert!( + !out.raw().contains(&code), + "invite code logged: {}", + out.raw() + ); + } + + /// A member who is not an owner or admin is refused a mint, and a banned + /// claimer is refused a claim: each logs `denied` with its reason, never + /// the membership admission's `success`. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn invite_refusals_after_membership_log_denied() { + let host = format!("invites-{}.example", Uuid::new_v4().simple()); + let (owner, member, banned) = (Keys::generate(), Keys::generate(), Keys::generate()); + let state = invite_test_state(&host).await.expect("local Postgres"); + let community = state + .db + .lookup_community_by_host(&host) + .await + .expect("lookup") + .expect("community exists") + .id; + for (key, role) in [(&owner, "owner"), (&member, "member")] { + let _ = state + .db + .add_relay_member( + community, + &key.public_key().to_hex(), + role, + None, + &Keys::generate(), + ) + .await + .expect("seed member"); + } + let code = mint_code(state.clone(), &host, &owner, serde_json::json!({})).await; + state + .db + .ban_community_member( + community, + banned.public_key().as_bytes(), + owner.public_key().as_bytes(), + None, + None, + ) + .await + .expect("seed ban"); + + let (_guard, out) = crate::access::tests::capture_scoped(); + let mint = post_json(state.clone(), &host, "/api/invites", &member, "{}".into()).await; + assert_eq!(mint.status(), StatusCode::FORBIDDEN); + let claim = post_json( + state, + &host, + "/api/invites/claim", + &banned, + serde_json::json!({ "code": code }).to_string(), + ) + .await; + assert_eq!(claim.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(claim).await["error"], "invite_restricted"); + let lines = out.lines(); + assert_eq!(lines.len(), 2, "one line per request: {lines:?}"); + for (line, reason) in lines.iter().zip(["not_relay_admin", "restricted"]) { + assert_eq!(line["outcome"], "denied", "{line}"); + assert_eq!(line["reason"], reason, "{line}"); + } + } + #[tokio::test] #[ignore = "requires Postgres"] async fn owner_mints_and_new_pubkey_claims() { @@ -1600,24 +2336,27 @@ mod postgres_tests { assert_eq!(response.status(), StatusCode::FORBIDDEN); } - /// Forge an already-expired invite payload signed with the relay's derived - /// invite key. `mint_invite` clamps ttl to 60s minimum, so the only way to - /// produce an expired code is to build the payload by hand at the token - /// layer. - fn forge_expired_invite_code( + fn unix_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("time") + .as_secs() + } + + /// Forge a v1 HMAC invite payload expiring at `expires_at`, signed with + /// the relay's derived invite key. `mint_invite` only mints v2 codes now + /// and clamps ttl to 60s minimum, so v1 and expired codes are built by + /// hand at the token layer. + fn forge_v1_invite_code( state: &AppState, community: buzz_core::CommunityId, - seconds_ago: u64, + expires_at: u64, ) -> String { let key = derive_invite_key(&state.relay_keypair); - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("time") - .as_secs(); let payload = InvitePayload { c: community.as_uuid().to_string(), r: "member".to_string(), - e: now.saturating_sub(seconds_ago), + e: expires_at, n: "test-nonce".to_string(), }; let payload_bytes = serde_json::to_vec(&payload).expect("payload serializes"); @@ -1649,7 +2388,7 @@ mod postgres_tests { .await .expect("lookup") .expect("community exists"); - let code = forge_expired_invite_code(&state, community.id, 10); + let code = forge_v1_invite_code(&state, community.id, unix_now() - 10); let body = serde_json::json!({ "code": code }).to_string(); let response = post_json(state.clone(), &host, "/api/invites/claim", &joiner, body).await; @@ -1946,11 +2685,7 @@ mod postgres_tests { const NIP_FI_TEST_ISSUER: &str = "https://issuer.example"; const NIP_FI_TEST_AUDIENCE: &str = "https://relay.example"; const NIP_FI_TEST_KID: &str = "test-key-1"; - const NIP_FI_TEST_EC_PKCS8_PEM: &str = "-----BEGIN PRIVATE KEY-----\n\ - MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\n\ - WZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\n\ - zhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n\ - -----END PRIVATE KEY-----\n"; + const NIP_FI_TEST_EC_PKCS8_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\nWZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\nzhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n-----END PRIVATE KEY-----\n"; // sadscan:disable np.pem.1 kingfisher.privkey.2 -- public ES256 test fixture /// Clone `base` into an Enforce-mode state. With `with_verifier`, a real /// ES256 verifier over the static test key is injected so a signed diff --git a/crates/buzz-relay/src/api/invites/claim_auth.rs b/crates/buzz-relay/src/api/invites/claim_auth.rs new file mode 100644 index 00000000000..a3089c26187 --- /dev/null +++ b/crates/buzz-relay/src/api/invites/claim_auth.rs @@ -0,0 +1,76 @@ +use super::{api_error, bridge, internal_error, AppState}; +use axum::{ + http::{HeaderMap, StatusCode}, + response::Json, +}; +use serde_json::Value; +use std::sync::Arc; + +/// Verify tenant-scoped NIP-98 and optional NIP-OA provenance without user writes. +pub(super) async fn authenticate( + state: &Arc, + slot: &crate::access::AccessSlot, + headers: &HeaderMap, + path: &'static str, + body: &[u8], +) -> Result< + ( + buzz_core::TenantContext, + nostr::PublicKey, + Option, + ), + (StatusCode, Json), +> { + let raw_host = headers + .get(axum::http::header::HOST) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + let tenant = crate::tenant::bind_community(&**state, raw_host) + .await + .map_err(|_| { + api_error( + StatusCode::NOT_FOUND, + "relay: no community is configured for this host", + ) + })?; + let url = bridge::nip98_expected_url(&state.config.relay_url, &tenant, path); + let bridge::VerifiedBridgeAuth { + pubkey, + event_id_bytes, + signed_created_at, + } = bridge::verify_nip98_exempt_invite_claim(slot, headers, "POST", &url, Some(body))?; + // Claiming an invite is how a non-member joins: replay is the last + // admission step, so it decides the request. + slot.attempt(crate::access::AuthMethod::Nip98, Some(pubkey), true); + slot.in_community(tenant.community()); + slot.gate( + bridge::check_nip98_replay(state, &tenant, event_id_bytes).await, + bridge::ReplayRejection::auth_result, + )?; + slot.finish(crate::access::AuthResult::Success); + let owner = super::super::relay_members::extract_nip_oa_owner( + pubkey.as_bytes(), + super::super::relay_members::extract_auth_tag_header(headers), + signed_created_at, + ); + Ok((tenant, pubkey, owner)) +} + +/// The claim write's refusal, recording an active ban or timeout on `slot`. +pub(super) fn map_claim_error( + slot: &crate::access::AccessSlot, + error: buzz_db::DbError, +) -> (StatusCode, Json) { + match error { + buzz_db::DbError::InviteRestricted => { + slot.finish(crate::access::AuthResult::Denied( + crate::access::AuthReason::Restricted, + )); + api_error(StatusCode::FORBIDDEN, "invite_restricted") + } + buzz_db::DbError::InviteOwnerMismatch => { + api_error(StatusCode::FORBIDDEN, "invite_owner_mismatch") + } + e => internal_error(&format!("invite claim: {e}")), + } +} diff --git a/crates/buzz-relay/src/api/invites/postgres_tests/owner_admission_tests.rs b/crates/buzz-relay/src/api/invites/postgres_tests/owner_admission_tests.rs new file mode 100644 index 00000000000..8046353d7f9 --- /dev/null +++ b/crates/buzz-relay/src/api/invites/postgres_tests/owner_admission_tests.rs @@ -0,0 +1,250 @@ +mod postgres_tests { + use super::super::restriction_tests::postgres_tests::{fixture, post_with_owner_tag}; + use super::super::*; + + async fn users(state: &AppState, community: buzz_core::CommunityId) -> i64 { + sqlx::query_scalar("SELECT count(*) FROM users WHERE community_id=$1") + .bind(community.as_uuid()) + .fetch_one(state.db.pool()) + .await + .unwrap() + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn mint_rejects_a_different_verified_owner_without_retrying_or_rebinding() { + let (state, host, community, agent) = fixture().await; + let recorded_owner = Keys::generate(); + for key in [&agent, &recorded_owner] { + state + .db + .ensure_user_for_authorization(community, key.public_key().as_bytes()) + .await + .unwrap(); + } + assert!(state + .db + .set_agent_owner_for_authorization( + community, + agent.public_key().as_bytes(), + recorded_owner.public_key().as_bytes(), + ) + .await + .unwrap()); + let other_owner = Keys::generate(); + let tag = + buzz_sdk::nip_oa::compute_auth_tag(&other_owner, &agent.public_key(), "").unwrap(); + let (guard, out) = crate::access::tests::capture_scoped(); + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites", + &agent, + "{}".into(), + &tag, + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(response).await["error"], "invite_owner_mismatch"); + drop(guard); + // The mismatch, not the membership admission before it, decides the line. + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "denied", "{}", lines[0]); + assert_eq!(lines[0]["reason"], "owner_mismatch", "{}", lines[0]); + assert!(state + .db + .is_agent_owner( + community, + agent.public_key().as_bytes(), + recorded_owner.public_key().as_bytes(), + ) + .await + .unwrap()); + let count: i64 = + sqlx::query_scalar("SELECT count(*) FROM relay_invites WHERE community_id=$1") + .bind(community.as_uuid()) + .fetch_one(state.db.pool()) + .await + .unwrap(); + assert_eq!( + count, 0, + "mismatched credentials must not mint an invitation" + ); + + // Healthy storage and the recorded owner still admit a signed mint. + let tag = + buzz_sdk::nip_oa::compute_auth_tag(&recorded_owner, &agent.public_key(), "").unwrap(); + assert_eq!( + post_with_owner_tag(state, &host, "/api/invites", &agent, "{}".into(), &tag) + .await + .status(), + StatusCode::OK + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn invalid_signed_claims_do_not_materialize_fresh_owner_identities() { + let (state, host, community, _issuer) = fixture().await; + let before = users(&state, community).await; + let unknown_v2 = buzz_core::invite::encode_v2_code(&[42; 32]); + for code in ["garbage", "v2.bad", &unknown_v2] { + let owner = Keys::generate(); + let agent = Keys::generate(); + let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "").unwrap(); + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &agent, + serde_json::json!({"code":code}).to_string(), + &tag, + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(users(&state, community).await, before); + assert!(!state + .db + .is_relay_member(community, &agent.public_key().to_hex()) + .await + .unwrap()); + } + let owner = Keys::generate(); + let agent = Keys::generate(); + let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "").unwrap(); + for attempt in 0..=CLAIM_RATE_LIMIT { + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &agent, + serde_json::json!({"code":"garbage"}).to_string(), + &tag, + ) + .await; + assert_eq!( + response.status(), + if attempt == CLAIM_RATE_LIMIT { + StatusCode::TOO_MANY_REQUESTS + } else { + StatusCode::FORBIDDEN + } + ); + assert_eq!(users(&state, community).await, before); + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn verified_owner_is_committed_only_with_successful_v1_and_v2_claims() { + let (state, host, community, issuer) = fixture().await; + let v2 = mint_code( + state.clone(), + &host, + &issuer, + serde_json::json!({"max_uses":1}), + ) + .await; + let key = derive_invite_key(&state.relay_keypair); + let (v1, _) = crate::invite_token::mint_invite(&key, community, 3600); + for code in [v1, v2] { + let owner = Keys::generate(); + let agent = Keys::generate(); + let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "").unwrap(); + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &agent, + serde_json::json!({"code":code}).to_string(), + &tag, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(read_json(response).await["status"], "joined"); + assert!(state + .db + .is_agent_owner( + community, + agent.public_key().as_bytes(), + owner.public_key().as_bytes() + ) + .await + .unwrap()); + let before = users(&state, community).await; + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &agent, + serde_json::json!({"code":code}).to_string(), + &tag, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(read_json(response).await["status"], "already_member"); + assert_eq!(users(&state, community).await, before); + let impostor_owner = Keys::generate(); + let mismatched = + buzz_sdk::nip_oa::compute_auth_tag(&impostor_owner, &agent.public_key(), "") + .unwrap(); + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &agent, + serde_json::json!({"code":code}).to_string(), + &mismatched, + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(response).await["error"], "invite_owner_mismatch"); + assert_eq!(users(&state, community).await, before); + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn banned_verified_owner_creates_no_users_in_either_claim_format() { + let (state, host, community, issuer) = fixture().await; + let v2 = mint_code( + state.clone(), + &host, + &issuer, + serde_json::json!({"max_uses":1}), + ) + .await; + let key = derive_invite_key(&state.relay_keypair); + let (v1, _) = crate::invite_token::mint_invite(&key, community, 3600); + let owner = Keys::generate(); + state + .db + .ban_community_member( + community, + owner.public_key().as_bytes(), + issuer.public_key().as_bytes(), + None, + None, + ) + .await + .unwrap(); + let before = users(&state, community).await; + for code in [v1, v2] { + let agent = Keys::generate(); + let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "").unwrap(); + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &agent, + serde_json::json!({"code":code}).to_string(), + &tag, + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(response).await["error"], "invite_restricted"); + assert_eq!(users(&state, community).await, before); + } + } +} diff --git a/crates/buzz-relay/src/api/invites/postgres_tests/recovery_postgres_tests.rs b/crates/buzz-relay/src/api/invites/postgres_tests/recovery_postgres_tests.rs new file mode 100644 index 00000000000..8481240ea71 --- /dev/null +++ b/crates/buzz-relay/src/api/invites/postgres_tests/recovery_postgres_tests.rs @@ -0,0 +1,480 @@ +mod postgres_tests { + use super::super::*; + use crate::handlers::group_state_postgres_tests::{create_channel, edit_channel, http_auth}; + use crate::handlers::ingest::ingest_event; + use crate::handlers::side_effects::auto_join_default_channels; + + // Cancel the real listing query only after PostgreSQL reports that it is + // blocked by our table lock. No timer or production-only failure hook. + async fn cancel_blocked_query(pool: &sqlx::PgPool, pattern: &str) { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let cancelled: Vec = sqlx::query_scalar( + "SELECT pg_cancel_backend(pid) FROM pg_stat_activity \ + WHERE datname = current_database() AND wait_event_type = 'Lock' \ + AND query LIKE $1", + ) + .bind(pattern) + .fetch_all(pool) + .await + .expect("cancel blocked default-channel listing"); + if !cancelled.is_empty() { + assert!(cancelled.into_iter().all(|cancelled| cancelled)); + return; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("the admission must reach the actual default-channel listing"); + } + + async fn recovery_fixture( + label: &str, + channel_count: usize, + ) -> ( + Arc, + buzz_core::TenantContext, + Keys, + Keys, + Vec, + ) { + let host = format!("join-{label}-{}.example", Uuid::new_v4().simple()); + let state = invite_test_state(&host).await.expect("isolated Postgres"); + let community = state + .db + .lookup_community_by_host(&host) + .await + .unwrap() + .unwrap() + .id; + let tenant = buzz_core::TenantContext::resolved(community, &host); + let (owner, member) = (Keys::generate(), Keys::generate()); + let _ = state + .db + .add_relay_member( + community, + &owner.public_key().to_hex(), + "owner", + None, + &state.relay_keypair, + ) + .await + .unwrap(); + let mut channels = Vec::new(); + for _ in 0..channel_count { + let channel = create_channel(&state, &tenant, &owner, &[]).await; + edit_channel(&state, &tenant, &owner, channel, &[&["auto_join", "true"]]) + .await + .unwrap(); + channels.push(channel); + } + assert_eq!( + state + .db + .list_auto_join_channels(community) + .await + .unwrap() + .iter() + .map(|channel| channel.id) + .collect::>(), + channels, + "the failing channel must precede the healthy one", + ); + let _ = state + .db + .add_relay_member_with_default_channels( + community, + &member.public_key().to_hex(), + "member", + &member.public_key().to_hex(), + &state.relay_keypair, + ) + .await + .unwrap(); + (state, tenant, owner, member, channels) + } + + // Target only the connection blocked by this test's transaction, even + // when another recovery test is running against the same database. + async fn cancel_query_blocked_by(pool: &sqlx::PgPool, blocker: i32) { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let cancelled: Vec = sqlx::query_scalar( + "SELECT pg_cancel_backend(pid) FROM pg_stat_activity \ + WHERE datname = current_database() AND wait_event_type = 'Lock' \ + AND $1 = ANY(pg_blocking_pids(pid))", + ) + .bind(blocker) + .fetch_all(pool) + .await + .unwrap(); + if !cancelled.is_empty() { + assert_eq!(cancelled, [true], "exactly our recovery query was blocked"); + return; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("recovery must reach the held PostgreSQL lock"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_local_failures_continue_later_defaults_and_retain_retry_work() { + let (state, tenant, _, member, channels) = recovery_fixture("membership", 2).await; + let community = tenant.community(); + let member_hex = member.public_key().to_hex(); + let pending = state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap() + .unwrap(); + let mut blocker = state.db.pool().begin().await.unwrap(); + let blocker_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *blocker) + .await + .unwrap(); + sqlx::query("SELECT id FROM channels WHERE community_id = $1 AND id = $2 FOR UPDATE") + .bind(community.as_uuid()) + .bind(channels[0]) + .fetch_one(&mut *blocker) + .await + .unwrap(); + let retry = tokio::spawn({ + let (state, tenant, member_hex) = (state.clone(), tenant.clone(), member_hex.clone()); + async move { auto_join_default_channels(&tenant, &state, &member_hex, None).await } + }); + cancel_query_blocked_by(state.db.pool(), blocker_pid).await; + // Only the first channel fails. Later memberships can write. + blocker.rollback().await.unwrap(); + tokio::time::timeout(Duration::from_secs(10), retry) + .await + .unwrap() + .unwrap(); + assert_eq!( + channel_roles(&state, community, &channels, &member).await, + [None, Some("member".into())], + "a local failure must not strand the later channel", + ); + assert_eq!( + state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap() + .unwrap() + .token, + pending.token + ); + auto_join_default_channels(&tenant, &state, &member_hex, None).await; + assert_eq!( + channel_roles(&state, community, &channels, &member).await, + [Some("member".into()), Some("member".into())] + ); + assert!(state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap() + .is_none()); + assert_eq!( + added_notification_count(&state, community, &member_hex).await, + 2 + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn temporary_listing_failure_is_recovered_for_each_admission_path() { + let host = format!("join-recovery-{}.example", Uuid::new_v4().simple()); + let state = invite_test_state(&host).await.expect("test state"); + let community = state + .db + .lookup_community_by_host(&host) + .await + .unwrap() + .unwrap() + .id; + let tenant = buzz_core::TenantContext::resolved(community, &host); + let owner = Keys::generate(); + let _ = state + .db + .add_relay_member( + community, + &owner.public_key().to_hex(), + "owner", + None, + &state.relay_keypair, + ) + .await + .unwrap(); + let channel = create_channel(&state, &tenant, &owner, &[]).await; + edit_channel(&state, &tenant, &owner, channel, &[&["auto_join", "true"]]) + .await + .unwrap(); + + for path in ["v1", "v2", "admin"] { + let member = Keys::generate(); + let member_hex = member.public_key().to_hex(); + let body = match path { + "v1" => serde_json::json!({"code": forge_v1_invite_code(&state, community, unix_now() + 3600)}).to_string(), + "v2" => serde_json::json!({"code": mint_code(state.clone(), &host, &owner, + serde_json::json!({"max_uses": 1})).await}).to_string(), + _ => String::new(), + }; + let add = EventBuilder::new(Kind::Custom(9030), "") + .tags([Tag::public_key(member.public_key())]) + .sign_with_keys(&owner) + .unwrap(); + let admit = || { + let (state, host, member, body, tenant, add, owner) = ( + state.clone(), + host.clone(), + member.clone(), + body.clone(), + tenant.clone(), + add.clone(), + owner.clone(), + ); + async move { + if path == "admin" { + let mut auth = http_auth(&owner); + if let crate::handlers::ingest::IngestAuth::Http { scopes, .. } = &mut auth + { + scopes.push(buzz_auth::Scope::AdminUsers); + } + let result = ingest_event(&state, &tenant, add, auth).await.unwrap(); + assert!(result.accepted, "{:?}", result.message); + } else { + let response = + post_json(state, &host, "/api/invites/claim", &member, body).await; + assert_eq!(response.status(), StatusCode::OK); + } + } + }; + let mut blocker = state.db.pool().begin().await.unwrap(); + sqlx::query("LOCK TABLE channels IN ACCESS EXCLUSIVE MODE") + .execute(&mut *blocker) + .await + .unwrap(); + let request = tokio::spawn(admit()); + cancel_blocked_query( + state.db.pool(), + "%FROM channels%WHERE community_id = $1 AND auto_join%", + ) + .await; + tokio::time::timeout(Duration::from_secs(10), request) + .await + .unwrap() + .unwrap(); + blocker.rollback().await.unwrap(); + assert!(state + .db + .is_relay_member(community, &member_hex) + .await + .unwrap()); + let pending = state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap(); + assert!( + pending.is_some(), + "{path}: committed admission lost its retry record" + ); + assert_eq!( + channel_roles(&state, community, &[channel], &member).await, + [None] + ); + + // A retry is already_member (and a single-use v2 invite is exhausted + // for new claimants), so recovery cannot depend on a fresh insertion. + admit().await; + assert_eq!( + channel_roles(&state, community, &[channel], &member).await, + [Some("member".to_string())], + "{path}: retry must finish the join" + ); + assert!(state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap() + .is_none()); + assert_eq!( + added_notification_count(&state, community, &member_hex).await, + 1 + ); + let leave = EventBuilder::new(Kind::Custom(9022), "") + .tags([Tag::parse(["h", &channel.to_string()]).unwrap()]) + .sign_with_keys(&member) + .unwrap(); + assert!( + ingest_event(&state, &tenant, leave, http_auth(&member)) + .await + .unwrap() + .accepted + ); + admit().await; + assert_eq!( + channel_roles(&state, community, &[channel], &member).await, + [None] + ); + } + } + + /// Recovery preserves a leave made during partial completion, rejects stale + /// generations after removal/re-addition, and still enforces the original actor. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn pending_join_preserves_leaves_and_fences_old_admissions() { + let host = format!("join-fence-{}.example", Uuid::new_v4().simple()); + let state = invite_test_state(&host).await.unwrap(); + let community = state + .db + .lookup_community_by_host(&host) + .await + .unwrap() + .unwrap() + .id; + let tenant = buzz_core::TenantContext::resolved(community, &host); + let (owner, member) = (Keys::generate(), Keys::generate()); + let member_hex = member.public_key().to_hex(); + for (keys, role) in [(&owner, "owner"), (&member, "member")] { + let _ = state + .db + .add_relay_member_with_default_channels( + community, + &keys.public_key().to_hex(), + role, + &owner.public_key().to_hex(), + &state.relay_keypair, + ) + .await + .unwrap(); + } + let a = create_channel(&state, &tenant, &owner, &[]).await; + let b = create_channel(&state, &tenant, &owner, &[]).await; + for channel in [a, b] { + edit_channel(&state, &tenant, &owner, channel, &[&["auto_join", "true"]]) + .await + .unwrap(); + } + let old = state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap() + .unwrap() + .token; + assert!(state + .db + .put_pending_default_member(community, a, &member.public_key().to_bytes(), old) + .await + .unwrap() + .is_some()); + state + .db + .remove_member( + community, + a, + &member.public_key().to_bytes(), + &member.public_key().to_bytes(), + ) + .await + .unwrap(); + auto_join_default_channels(&tenant, &state, &member_hex, None).await; + assert_eq!( + channel_roles(&state, community, &[a, b], &member).await, + [None, Some("member".to_string())] + ); + + let _ = state + .db + .remove_relay_member(community, &member_hex, &state.relay_keypair) + .await + .unwrap(); + let _ = state + .db + .add_relay_member_with_default_channels( + community, + &member_hex, + "member", + &owner.public_key().to_hex(), + &state.relay_keypair, + ) + .await + .unwrap(); + let new = state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap() + .unwrap() + .token; + assert_ne!(old, new); + let c = create_channel(&state, &tenant, &owner, &[]).await; + edit_channel(&state, &tenant, &owner, c, &[&["auto_join", "true"]]) + .await + .unwrap(); + assert!(state + .db + .put_pending_default_member(community, c, &member.public_key().to_bytes(), old) + .await + .unwrap() + .is_none()); + state + .db + .finish_default_channel_join(community, &member_hex, old) + .await + .unwrap(); + assert_eq!( + state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap() + .unwrap() + .token, + new + ); + assert!( + state + .db + .put_pending_default_member(community, a, &member.public_key().to_bytes(), new,) + .await + .unwrap() + .is_some(), + "a fresh roster admission restores a leave from the previous admission" + ); + // If the failed admin-add is retried by the member, it must still ask the + // original admin's permission rather than treating the retry as self-join. + state + .db + .ensure_user(community, &member.public_key().to_bytes()) + .await + .unwrap(); + sqlx::query( + "UPDATE users SET channel_add_policy = 'nobody' WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community.as_uuid()) + .bind(member.public_key().to_bytes().as_slice()) + .execute(state.db.pool()) + .await + .unwrap(); + auto_join_default_channels(&tenant, &state, &member_hex, None).await; + assert_eq!( + channel_roles(&state, community, &[c], &member).await, + [None] + ); + assert!(state + .db + .pending_default_channel_join(community, &member_hex) + .await + .unwrap() + .is_none()); + } +} diff --git a/crates/buzz-relay/src/api/invites/postgres_tests/restriction_tests.rs b/crates/buzz-relay/src/api/invites/postgres_tests/restriction_tests.rs new file mode 100644 index 00000000000..ae8b577bc91 --- /dev/null +++ b/crates/buzz-relay/src/api/invites/postgres_tests/restriction_tests.rs @@ -0,0 +1,409 @@ +pub(super) mod postgres_tests { + use super::super::*; + + pub(in crate::api::invites::postgres_tests) async fn fixture( + ) -> (Arc, String, buzz_core::CommunityId, Keys) { + let host = format!("restricted-invite-{}.example", Uuid::new_v4().simple()); + let state = invite_test_state(&host) + .await + .expect("isolated PostgreSQL state"); + let community = state + .db + .ensure_configured_community(&host) + .await + .unwrap() + .id; + let owner = Keys::generate(); + state + .db + .add_relay_member( + community, + &owner.public_key().to_hex(), + "owner", + None, + &state.relay_keypair, + ) + .await + .map(|write| write.outcome) + .unwrap(); + (state, host, community, owner) + } + + pub(in crate::api::invites::postgres_tests) async fn post_with_owner_tag( + state: Arc, + host: &str, + path: &str, + agent: &Keys, + body: String, + auth_tag: &str, + ) -> axum::response::Response { + let auth = nip98_auth_header(agent, &format!("https://{host}{path}"), body.as_bytes()); + build_router(state) + .oneshot( + Request::builder() + .method("POST") + .uri(path) + .header(header::HOST, host) + .header(header::AUTHORIZATION, auth) + .header("x-auth-tag", auth_tag) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap() + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn signed_nonmember_claims_reject_restrictions_without_consuming_invite() { + let (state, host, community, issuer) = fixture().await; + let code = mint_code( + state.clone(), + &host, + &issuer, + serde_json::json!({"max_uses":1}), + ) + .await; + let claimant = Keys::generate(); + state + .db + .ban_community_member( + community, + claimant.public_key().as_bytes(), + issuer.public_key().as_bytes(), + None, + None, + ) + .await + .unwrap(); + let timed_out = Keys::generate(); + state + .db + .timeout_community_member( + community, + timed_out.public_key().as_bytes(), + issuer.public_key().as_bytes(), + chrono::Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + .unwrap(); + let key = derive_invite_key(&state.relay_keypair); + let (legacy, _) = crate::invite_token::mint_invite(&key, community, 3600); + // A ban and a timeout each log one `denied`/`restricted` line on v2 + // and v1 alike, never the replay admission's `success`. + for restricted in [&claimant, &timed_out] { + for bearer in [&code, &legacy] { + let (guard, out) = crate::access::tests::capture_scoped(); + let response = post_json( + state.clone(), + &host, + "/api/invites/claim", + restricted, + serde_json::json!({"code":bearer}).to_string(), + ) + .await; + drop(guard); + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(response).await["error"], "invite_restricted"); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "denied", "{}", lines[0]); + assert_eq!(lines[0]["reason"], "restricted", "{}", lines[0]); + } + } + assert!(!state + .db + .is_relay_member(community, &claimant.public_key().to_hex()) + .await + .unwrap()); + let unrestricted = Keys::generate(); + assert_eq!( + post_json( + state, + &host, + "/api/invites/claim", + &unrestricted, + serde_json::json!({"code":code}).to_string() + ) + .await + .status(), + StatusCode::OK + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn verified_owner_blocks_first_agent_claim_but_forged_owner_does_not_bind() { + let (state, host, community, issuer) = fixture().await; + let code = mint_code(state.clone(), &host, &issuer, serde_json::json!({})).await; + let owner = Keys::generate(); + state + .db + .ban_community_member( + community, + owner.public_key().as_bytes(), + issuer.public_key().as_bytes(), + None, + None, + ) + .await + .unwrap(); + let agent = Keys::generate(); + let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "").unwrap(); + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &agent, + serde_json::json!({"code":code}).to_string(), + &tag, + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(response).await["error"], "invite_restricted"); + assert!(!state + .db + .is_relay_member(community, &agent.public_key().to_hex()) + .await + .unwrap()); + for key in [&agent, &owner] { + assert!(state + .db + .get_user(community, key.public_key().as_bytes()) + .await + .unwrap() + .is_none()); + } + state + .db + .unban_community_member( + community, + owner.public_key().as_bytes(), + issuer.public_key().as_bytes(), + ) + .await + .unwrap(); + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &agent, + serde_json::json!({"code":code}).to_string(), + &tag, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert!(state + .db + .is_agent_owner( + community, + agent.public_key().as_bytes(), + owner.public_key().as_bytes() + ) + .await + .unwrap()); + let other_agent = Keys::generate(); + // A credential signed for another key cannot bind this claimant's owner. + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites/claim", + &other_agent, + serde_json::json!({"code":code}).to_string(), + &tag, + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert!(!state + .db + .is_agent_owner( + community, + other_agent.public_key().as_bytes(), + owner.public_key().as_bytes() + ) + .await + .unwrap()); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn committed_issuer_ban_survives_unban_through_http() { + let (state, host, community, issuer) = fixture().await; + let code = mint_code(state.clone(), &host, &issuer, serde_json::json!({})).await; + state + .db + .ban_community_member( + community, + issuer.public_key().as_bytes(), + issuer.public_key().as_bytes(), + None, + None, + ) + .await + .unwrap(); + state + .db + .unban_community_member( + community, + issuer.public_key().as_bytes(), + issuer.public_key().as_bytes(), + ) + .await + .unwrap(); + let response = post_json( + state.clone(), + &host, + "/api/invites/claim", + &Keys::generate(), + serde_json::json!({"code":code}).to_string(), + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(response).await["error"], "invite_invalid"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn cutoff_rejects_only_v1_and_restriction_or_owner_lookup_failure_never_admits() { + let Some(identity) = [ + "NEXTEST_RUN_ID", + "NEXTEST_BINARY_ID", + "NEXTEST_TEST_NAME", + "NEXTEST_ATTEMPT_ID", + ] + .iter() + .map(|name| std::env::var(name).ok()) + .collect::>>() else { + eprintln!("skipping destructive fixture outside postgres-isolation wrapper"); + return; + }; + let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap_or_default(); + assert!( + wrapper_owns_database(&url, &identity.join(":")), + "refusing destructive DDL on a shared database" + ); + let (state, host, community, issuer) = fixture().await; + let code = mint_code(state.clone(), &host, &issuer, serde_json::json!({})).await; + let key = derive_invite_key(&state.relay_keypair); + let (legacy, _) = crate::invite_token::mint_invite(&key, community, 3600); + let Ok(mut state) = Arc::try_unwrap(state) else { + panic!("exclusive fixture state"); + }; + Arc::make_mut(&mut state.config).invite_v1_invalid_after = Some(0); + let state = Arc::new(state); + let response = post_json( + state.clone(), + &host, + "/api/invites/claim", + &Keys::generate(), + serde_json::json!({"code":legacy}).to_string(), + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(response).await["error"], "invite_expired"); + assert_eq!( + post_json( + state.clone(), + &host, + "/api/invites/claim", + &Keys::generate(), + serde_json::json!({"code":code}).to_string() + ) + .await + .status(), + StatusCode::OK + ); + // This test owns its per-process database; never alters a shared fixture. + sqlx::query("ALTER TABLE community_bans RENAME TO unavailable_restrictions") + .execute(state.db.pool()) + .await + .unwrap(); + let claimant = Keys::generate(); + let response = post_json( + state.clone(), + &host, + "/api/invites/claim", + &claimant, + serde_json::json!({"code":code}).to_string(), + ) + .await; + let status = response.status(); + let membership = state + .db + .is_relay_member(community, &claimant.public_key().to_hex()) + .await; + sqlx::query("ALTER TABLE unavailable_restrictions RENAME TO community_bans") + .execute(state.db.pool()) + .await + .unwrap(); + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); + assert!(!membership.unwrap()); + + // Fail specifically inside owner materialization, after membership and + // ban reads succeed. This fixture is wrapper-owned, as checked above. + let owner = Keys::generate(); + let tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &issuer.public_key(), "").unwrap(); + let before: i64 = sqlx::query_scalar("SELECT count(*) FROM relay_invites") + .fetch_one(state.db.pool()) + .await + .unwrap(); + // Keep restriction and membership reads healthy, but reject the new + // owner's insert in the production materialization helper. + sqlx::query( + "ALTER TABLE users ADD CONSTRAINT test_owner_write_failure CHECK (false) NOT VALID", + ) + .execute(state.db.pool()) + .await + .unwrap(); + let response = post_with_owner_tag( + state.clone(), + &host, + "/api/invites", + &issuer, + "{}".into(), + &tag, + ) + .await; + sqlx::query("ALTER TABLE users DROP CONSTRAINT test_owner_write_failure") + .execute(state.db.pool()) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + read_json(response).await["error"], + crate::handlers::auth::OWNER_LINK_ERROR + ); + let after: i64 = sqlx::query_scalar("SELECT count(*) FROM relay_invites") + .fetch_one(state.db.pool()) + .await + .unwrap(); + assert_eq!( + after, before, + "a storage failure must not mint an invitation" + ); + } + + fn wrapper_owns_database(url: &str, identity: &str) -> bool { + let hash = hex::encode(Sha256::digest(identity.as_bytes())); + url.rsplit('/').next() == Some(format!("buzz_nt_{}", &hash[..24]).as_str()) + } + + #[test] + fn destructive_fixture_rejects_shared_database_urls() { + let identity = "run:binary:test:attempt"; + let hash = hex::encode(Sha256::digest(identity.as_bytes())); + assert!(wrapper_owns_database( + &format!("postgres://localhost/buzz_nt_{}", &hash[..24]), + identity + )); + for url in [ + "postgres://localhost/buzz", + "postgres://localhost/buzz_nt_other", + "", + ] { + assert!(!wrapper_owns_database(url, identity)); + } + } +} diff --git a/crates/buzz-relay/src/api/media.rs b/crates/buzz-relay/src/api/media.rs index 2592574b9b4..9e3515beff4 100644 --- a/crates/buzz-relay/src/api/media.rs +++ b/crates/buzz-relay/src/api/media.rs @@ -22,10 +22,12 @@ use buzz_audit::{AuditAction, NewAuditEntry}; use buzz_auth::DenialClass; use buzz_core::tenant::TenantContext; use buzz_media::auth::BlossomStrictness; +use buzz_media::thumbnail::{Thumb, JPEG}; use buzz_media::{ BlobDescriptor, BlossomDenialKind, MediaError, UploadAttribution, UploadNetworkInfo, }; +use crate::access::{AccessSlot, AuthMethod, AuthResult}; use crate::state::AppState; /// Lightweight pre-auth upload context: tenant + route mode only. @@ -88,7 +90,7 @@ enum UploadRouteMode { /// /// Non-Blossom errors (`blossom_denial_kind()` returns `None`) always fall /// through to `MediaError::into_response()` regardless of mode. -pub(crate) struct MediaDenial(MediaError, BlossomStrictness); +pub(crate) struct MediaDenial(pub(super) MediaError, pub(super) BlossomStrictness); impl IntoResponse for MediaDenial { fn into_response(self) -> Response { @@ -110,7 +112,8 @@ impl IntoResponse for MediaDenial { ); let mut builder = axum::http::Response::builder() .status(class.http_status()) - .header(header::CONTENT_TYPE, class.content_type()); + .header(header::CONTENT_TYPE, class.content_type()) + .header(header::CACHE_CONTROL, "private, no-store"); if let Some(challenge) = class.www_authenticate() { builder = builder.header("WWW-Authenticate", challenge); } @@ -119,7 +122,12 @@ impl IntoResponse for MediaDenial { .expect("NIP-FI denial response is always valid"); } } - error.into_response() + let mut response = error.into_response(); + response.headers_mut().insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, no-store"), + ); + response } } @@ -317,6 +325,7 @@ fn serving_lease_lost(error: anyhow::Error) -> MediaError { #[allow(clippy::result_large_err)] // Response is the natural error type for axum closures pub(crate) async fn upload_blob( State(state): State>, + slot: AccessSlot, ctx: UploadContext, headers: HeaderMap, body: axum::body::Body, @@ -333,6 +342,7 @@ pub(crate) async fn upload_blob( // as the read path. [FI-TRACE-AUTHORITY-UNIFORM] let strictness = blossom_strictness_from_state(&state); let tenant_host = ctx.tenant.host().to_owned(); + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "blossom"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "blossom", || { let event = extract_blossom_auth(&headers).map_err(drop)?; let strict = BlossomStrictness::Strict; @@ -341,12 +351,31 @@ pub(crate) async fn upload_blob( }) .await; let headers_clone = headers.clone(); - let admission = match admit_nip_fi_http_on_state(&state, &headers, move || { - let auth_event = extract_blossom_auth(&headers_clone).map_err(|e| e.into_response())?; + let proof_slot = slot.clone(); + let admission = match admit_nip_fi_http_on_state(&state, &headers, &slot, move || { + let reject = |e: MediaError, claimed: Option| { + proof_slot.attempt(AuthMethod::Blossom, claimed, false); + proof_slot.finish(AuthResult::Failed(blossom_proof_code(&e))); + e.into_response() + }; // Pre-body check: freshness, cardinality, and server tag. The x-tag // hash binding is checked after body completion. - buzz_media::auth::verify_blossom_auth_event(&auth_event, Some(&tenant_host), strictness) - .map_err(|e| e.into_response())?; + let auth_event = proof + .record( + extract_blossom_auth(&headers_clone) + .map_err(|e| (e, None)) + .and_then(|auth_event| { + let claimed = auth_event.pubkey; + buzz_media::auth::verify_blossom_auth_event( + &auth_event, + Some(&tenant_host), + strictness, + ) + .map(|()| auth_event) + .map_err(|e| (e, Some(claimed))) + }), + ) + .map_err(|(e, claimed)| reject(e, claimed))?; let pubkey = auth_event.pubkey; Ok(Nip98Proof::new(pubkey, auth_event)) }) @@ -355,6 +384,10 @@ pub(crate) async fn upload_blob( Ok(a) => a, Err(resp) => return resp, }; + // A refusal at any admission step below, or success once the + // concurrency permit is held. + admission.record(&slot, AuthMethod::Blossom); + slot.in_community(ctx.tenant.community()); let token_owner = admission.token_owner(); let auth_event = admission.into_extra(); @@ -364,27 +397,26 @@ pub(crate) async fn upload_blob( let claimed_hash = match headers.get("x-sha-256").and_then(|v| v.to_str().ok()) { Some(h) => h.to_owned(), None => { - return media_denial(MediaError::MissingTag("x-sha-256"), strictness).into_response() + slot.finish(AuthResult::Failed("missing_hash")); + return media_denial(MediaError::MissingTag("x-sha-256"), strictness).into_response(); } }; - if claimed_hash.len() != 64 - || !claimed_hash + let hash_bound = claimed_hash.len() == 64 + && claimed_hash .chars() .all(|c| matches!(c, '0'..='9' | 'a'..='f')) - { - return media_denial(MediaError::HashMismatch, strictness).into_response(); - } - let has_matching_x = auth_event - .tags - .iter() - .any(|tag| tag.kind().to_string() == "x" && (tag.content() == Some(&claimed_hash))); - if !has_matching_x { + && auth_event + .tags + .iter() + .any(|tag| tag.kind().to_string() == "x" && (tag.content() == Some(&claimed_hash))); + if !hash_bound { + slot.finish(AuthResult::Failed("hash_mismatch")); return media_denial(MediaError::HashMismatch, strictness).into_response(); } // Post-admission: relay membership gate (NIP-43). let auth_tag = crate::api::relay_members::extract_auth_tag_header(&headers); - if let Err(e) = crate::api::relay_members::enforce_relay_membership( + let membership = crate::api::relay_members::enforce_relay_membership( &state, &ctx.tenant, auth_event.pubkey.as_bytes(), @@ -392,17 +424,19 @@ pub(crate) async fn upload_blob( Some(auth_event.created_at.as_secs()), token_owner, ) - .await - .map(|_| ()) - .map_err(|e| membership_denial(e, strictness)) - { - return e.into_response(); + .await; + if let Err(e) = slot.gate( + membership, + crate::api::relay_members::MembershipRefusal::auth_result, + ) { + return membership_denial(e, strictness).into_response(); } // Post-admission: rate limit and concurrency permit. if upload_rate_limited(&state, ctx.tenant.community(), &auth_event.pubkey) { metrics::counter!("buzz_media_upload_rejections_total", "reason" => "rate_limit") .increment(1); + slot.finish(AuthResult::Denied(crate::access::AuthReason::QuotaExceeded)); return MediaError::UploadRateLimitExceeded.into_response(); } let upload_permit = match acquire_upload_permit( @@ -415,8 +449,14 @@ pub(crate) async fn upload_blob( .increment(1); }) { Ok(p) => p, - Err(e) => return e.into_response(), + Err(e) => { + slot.finish(AuthResult::Denied( + crate::access::AuthReason::ConcurrencyLimit, + )); + return e.into_response(); + } }; + slot.finish(AuthResult::Success); let auth = AuthenticatedUpload { auth_event, @@ -575,6 +615,69 @@ async fn upload_blob_result( // get the same NIP-FI shape as pre-body ones. .map_err(|e| media_denial(e, strictness))?; + if state.config.media_read_mode != super::media_access::MediaReadMode::Off { + let mut recording_reason = "lookup_error"; + let recording: Result<(), MediaDenial> = async { + // A reupload of a legacy attachment must remember that it has been + // published before recording new preview authority. Otherwise purging + // the legacy source later could resurrect uploader preview access. + let base = media_base_url_for_tenant(&state.config.relay_url, auth.tenant.host()); + let ext = descriptor + .url + .rsplit('.') + .next() + .ok_or_else(|| media_denial(MediaError::Internal, strictness))?; + let existing = state + .db + .media_access( + auth.tenant.community(), + &descriptor.sha256, + ext, + &base, + auth.auth_event.pubkey.as_bytes(), + false, + crate::handlers::req::event_visible_to_reader, + ) + .await + .map_err(|error| { + if matches!(error, buzz_db::DbError::MediaAuthorizationCapacity) { + recording_reason = "capacity"; + } + media_denial(MediaError::AuthorizationUnavailable, strictness) + })?; + if matches!( + existing, + buzz_db::media::MediaAccess::Allowed | buzz_db::media::MediaAccess::Restricted + ) { + state + .db + .record_media_publications( + auth.tenant.community(), + vec![descriptor.sha256.clone()], + ) + .await + .map_err(|_| media_denial(MediaError::AuthorizationUnavailable, strictness))?; + } + state + .db + .record_media_upload( + auth.tenant.community(), + &descriptor.sha256, + auth.auth_event.pubkey.as_bytes(), + ) + .await + .map_err(|_| media_denial(MediaError::AuthorizationUnavailable, strictness))?; + Ok(()) + } + .await; + if let Err(error) = recording { + metrics::counter!("buzz_media_upload_access_total", "mode" => state.config.media_read_mode.label(), "reason" => recording_reason).increment(1); + if state.config.media_read_mode == super::media_access::MediaReadMode::Enforce { + return Err(error); + } + } + } + rewrite_descriptor_urls_for_tenant( &mut descriptor, &state.config.relay_url, @@ -645,8 +748,13 @@ fn rewrite_descriptor_urls_for_tenant( .filter(|ext| is_safe_ext(ext)) .unwrap_or("bin"); descriptor.url = format!("{base}/{}.{ext}", descriptor.sha256); - if descriptor.thumb.is_some() { - descriptor.thumb = Some(format!("{base}/{}.thumb.jpg", descriptor.sha256)); + if let Some(thumb) = &descriptor.thumb { + let variant = thumb + .rsplit('/') + .next() + .and_then(Thumb::parse) + .map_or(JPEG, |(_, t)| t); + descriptor.thumb = Some(format!("{base}/{}", variant.key(&descriptor.sha256))); } } @@ -696,9 +804,10 @@ async fn enforce_blossom_read_membership( token_owner: Option, headers: &HeaderMap, strictness: BlossomStrictness, + slot: &AccessSlot, ) -> Result<(), MediaDenial> { let auth_tag = crate::api::relay_members::extract_auth_tag_header(headers); - crate::api::relay_members::enforce_relay_membership( + let membership = crate::api::relay_members::enforce_relay_membership( state, tenant, auth_event.pubkey.as_bytes(), @@ -706,13 +815,18 @@ async fn enforce_blossom_read_membership( Some(auth_event.created_at.as_secs()), token_owner, ) - .await - .map(|_| ()) - .map_err(|e| membership_denial(e, strictness)) + .await; + slot.gate( + membership, + crate::api::relay_members::MembershipRefusal::auth_result, + ) + .map_err(|e| membership_denial(e, strictness))?; + slot.finish(AuthResult::Success); + Ok(()) } fn blob_cache_control() -> &'static str { - "private, max-age=31536000, immutable" + "private, no-store" } /// Whether a path-segment extension is a safe token. @@ -732,7 +846,7 @@ pub(crate) fn is_safe_ext(ext: &str) -> bool { /// Accepted forms (max 3 segments): /// - `{sha256}` — bare 64-char lowercase hex /// - `{sha256}.{ext}` — hash + extension -/// - `{sha256}.thumb.jpg` — hash + thumb variant (always JPEG) +/// - `{sha256}.thumb.{webp,jpg}` — hash + thumb variant (see [`buzz_media::thumbnail::THUMBS`]) /// /// `{ext}` must be a safe token (see [`is_safe_ext`]); the sidecar comparison /// downstream enforces the actual canonical extension. @@ -761,8 +875,7 @@ fn validate_media_path(sha256_ext: &str) -> Result<(), MediaError> { } } 3 => { - // {hash}.thumb.jpg — thumbnails are always JPEG - if segments[1] != "thumb" || segments[2] != "jpg" { + if Thumb::parse(sha256_ext).is_none() { return Err(MediaError::NotFound); } } @@ -784,7 +897,7 @@ const MAX_RANGE_CHUNK: u64 = 16 * 1024 * 1024; /// `sha256_ext` is either: /// - `.` — direct key (e.g. `abc123.jpg`) /// - `` — bare hash; extension resolved from sidecar -/// - `.thumb.jpg` — thumbnail variant +/// - `.thumb.` — thumbnail variant /// /// Range request behaviour (RFC 9110 §14.2): /// - No `Range` header → 200 with full body @@ -797,6 +910,7 @@ const MAX_RANGE_CHUNK: u64 = 16 * 1024 * 1024; #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers pub(crate) async fn get_blob( State(state): State>, + slot: AccessSlot, Path(sha256_ext): Path, req_headers: HeaderMap, ) -> Result { @@ -817,6 +931,7 @@ pub(crate) async fn get_blob( // In Enforce mode: extraction failure → NIP-FI denial bytes (MissingEvidence/ // EvidenceRejected). In Off mode: MediaError propagates unchanged [FI-INV-15]. use crate::nip_fi_http::admit_nip_fi_http_on_state; + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &req_headers, "blossom"); crate::nip_fi_shadow::observe_strict_proof(&state, &req_headers, "blossom", || { extract_blossom_read_proof( &req_headers, @@ -827,15 +942,28 @@ pub(crate) async fn get_blob( .map(drop) }) .await; - let admission = match admit_nip_fi_http_on_state(&state, &req_headers, move || { - extract_blossom_read_proof(&headers_clone, &sha256, &tenant_host, strictness) - .map_err(|e| e.into_response()) + let proof_slot = slot.clone(); + let admission = match admit_nip_fi_http_on_state(&state, &req_headers, &slot, move || { + proof + .record(extract_blossom_read_proof( + &headers_clone, + &sha256, + &tenant_host, + strictness, + )) + .map_err(|e| { + proof_slot.method(AuthMethod::Blossom); + proof_slot.finish(AuthResult::Failed(blossom_proof_code(&e))); + e.into_response() + }) }) .await { Ok(a) => a, Err(resp) => return Ok(resp), }; + admission.record(&slot, AuthMethod::Blossom); + slot.in_community(tenant.community()); let token_owner = admission.token_owner(); let auth_event = admission.into_extra(); // Post-admission: membership gate. @@ -846,6 +974,15 @@ pub(crate) async fn get_blob( token_owner, &req_headers, strictness, + &slot, + ) + .await?; + super::media_access::enforce_read( + &state, + &tenant, + &sha256_ext, + auth_event.pubkey.as_bytes(), + strictness, ) .await?; serve_blob_for_tenant(&state, &tenant, &sha256_ext, &req_headers) @@ -868,14 +1005,13 @@ pub(crate) async fn serve_blob_for_tenant( let cache_control = blob_cache_control(); // Sidecar gate FIRST — reject before any blob I/O. Storage is not authoritative. - let content_type = if sha256_ext.ends_with(".thumb.jpg") { - let parent_hash = sha256_ext.strip_suffix(".thumb.jpg").unwrap_or(sha256_ext); + let content_type = if let Some((parent_hash, thumb)) = Thumb::parse(sha256_ext) { let _ = state .media_storage .read_sidecar_mime(tenant, parent_hash) .await .ok_or(MediaError::NotFound)?; - "image/jpeg".to_string() + thumb.mime.to_string() } else { // For explicit paths (hash.ext), verify the requested extension matches // the sidecar's canonical extension — sidecar is authoritative. @@ -923,9 +1059,7 @@ pub(crate) async fn serve_blob_for_tenant( match single_range { None => { // Full response — 200 OK. Stream from S3 — never loads full blob into RAM. - let total = state - .media_storage - .head_with_metadata(&key) + let total = head_or_regenerate_thumb(state, tenant, sha256_ext, &key) .await? .ok_or(MediaError::NotFound)? .size; @@ -945,9 +1079,7 @@ pub(crate) async fn serve_blob_for_tenant( } Some(range_str) => { // S3-native single-range response, capped to bound request memory. - let total = state - .media_storage - .head_with_metadata(&key) + let total = head_or_regenerate_thumb(state, tenant, sha256_ext, &key) .await? .ok_or(MediaError::NotFound)? .size; @@ -958,6 +1090,7 @@ pub(crate) async fn serve_blob_for_tenant( if start >= total { return axum::response::Response::builder() .status(StatusCode::RANGE_NOT_SATISFIABLE) + .header(header::CACHE_CONTROL, cache_control) .header(header::CONTENT_RANGE, format!("bytes */{total}")) .body(axum::body::Body::empty()) .map_err(|_| MediaError::Internal); @@ -985,6 +1118,7 @@ pub(crate) async fn serve_blob_for_tenant( } None => Ok(axum::response::Response::builder() .status(StatusCode::RANGE_NOT_SATISFIABLE) + .header(header::CACHE_CONTROL, cache_control) .header(header::CONTENT_RANGE, format!("bytes */{total}")) .body(axum::body::Body::empty()) .map_err(|_| MediaError::Internal)?), @@ -1111,6 +1245,7 @@ fn parse_byte_range(range: &str, total: u64) -> Option<(u64, u64)> { #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers pub(crate) async fn head_blob( State(state): State>, + slot: AccessSlot, headers: HeaderMap, Path(sha256_ext): Path, ) -> Result { @@ -1128,20 +1263,34 @@ pub(crate) async fn head_blob( let tenant_host = tenant.host().to_owned(); let headers_clone = headers.clone(); use crate::nip_fi_http::admit_nip_fi_http_on_state; + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "blossom"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "blossom", || { extract_blossom_read_proof(&headers, &sha256, &tenant_host, BlossomStrictness::Strict) .map(drop) }) .await; - let admission = match admit_nip_fi_http_on_state(&state, &headers, move || { - extract_blossom_read_proof(&headers_clone, &sha256, &tenant_host, strictness) - .map_err(|e| e.into_response()) + let proof_slot = slot.clone(); + let admission = match admit_nip_fi_http_on_state(&state, &headers, &slot, move || { + proof + .record(extract_blossom_read_proof( + &headers_clone, + &sha256, + &tenant_host, + strictness, + )) + .map_err(|e| { + proof_slot.method(AuthMethod::Blossom); + proof_slot.finish(AuthResult::Failed(blossom_proof_code(&e))); + e.into_response() + }) }) .await { Ok(a) => a, Err(resp) => return Ok(resp), }; + admission.record(&slot, AuthMethod::Blossom); + slot.in_community(tenant.community()); let token_owner = admission.token_owner(); let auth_event = admission.into_extra(); enforce_blossom_read_membership( @@ -1151,19 +1300,27 @@ pub(crate) async fn head_blob( token_owner, &headers, strictness, + &slot, + ) + .await?; + super::media_access::enforce_read( + &state, + &tenant, + &sha256_ext, + auth_event.pubkey.as_bytes(), + strictness, ) .await?; let cache_control = blob_cache_control(); // Sidecar gate FIRST — reject before any blob I/O. - let content_type = if sha256_ext.ends_with(".thumb.jpg") { - let parent_hash = sha256_ext.strip_suffix(".thumb.jpg").unwrap_or(&sha256_ext); + let content_type = if let Some((parent_hash, thumb)) = Thumb::parse(&sha256_ext) { let _ = state .media_storage .read_sidecar_mime(&tenant, parent_hash) .await .ok_or(MediaError::NotFound)?; - "image/jpeg".to_string() + thumb.mime.to_string() } else { let sidecar_mime = state .media_storage @@ -1185,7 +1342,7 @@ pub(crate) async fn head_blob( }; let key = resolve_s3_key(&state.media_storage, &tenant, &sha256_ext).await?; - match state.media_storage.head_with_metadata(&key).await? { + match head_or_regenerate_thumb(&state, &tenant, &sha256_ext, &key).await? { Some(meta) => { let size_str = meta.size.to_string(); Ok(( @@ -1203,6 +1360,73 @@ pub(crate) async fn head_blob( } } +/// Concurrent on-demand thumbnail regenerations per relay process. Each holds +/// a full-size decode in memory, so excess requests get a plain 404 instead of +/// waiting. +static THUMB_REGEN: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(2); + +/// `head_with_metadata`, first regenerating a missing thumbnail variant from +/// its image original (uploaded before the variant existed, or a failed write). +/// +/// Callers have already passed the tenant and sidecar gates for `sha256_ext`. +/// Regeneration failure is logged and reads as absent, never an error. +async fn head_or_regenerate_thumb( + state: &AppState, + tenant: &TenantContext, + sha256_ext: &str, + key: &str, +) -> Result, MediaError> { + let head = state.media_storage.head_with_metadata(key).await?; + let Some((sha256, _)) = Thumb::parse(sha256_ext).filter(|_| head.is_none()) else { + return Ok(head); + }; + match regenerate_thumbs(state, tenant, sha256).await { + Ok(true) => state.media_storage.head_with_metadata(key).await, + Ok(false) => Ok(None), + Err(e) => { + tracing::warn!(sha256, error = %e, "thumbnail regeneration failed"); + Ok(None) + } + } +} + +/// Rebuild every thumbnail of the tenant's image `sha256`. `Ok(false)` means +/// there was nothing to do: not an image, no original, too large, or busy. +async fn regenerate_thumbs( + state: &AppState, + tenant: &TenantContext, + sha256: &str, +) -> Result { + let storage = &state.media_storage; + let meta = storage.get_sidecar(tenant, sha256).await?; + if !meta.mime_type.starts_with("image/") || !is_safe_ext(&meta.ext) { + return Ok(false); + } + let key = format!("{sha256}.{}", meta.ext); + let max = state.config.media.max_image_bytes; + if !storage + .head_with_metadata(&key) + .await? + .is_some_and(|h| h.size <= max) + { + return Ok(false); + } + let Ok(_permit) = THUMB_REGEN.try_acquire() else { + return Ok(false); + }; + let body = bytes::Bytes::from(storage.get(&key).await?); + buzz_media::upload::store_image_thumbnails( + storage, + &state.config.media, + sha256, + body, + &meta.mime_type, + &meta.ext, + ) + .await?; + Ok(true) +} + /// Resolve the S3 key from a URL path segment. /// /// - `sha256.ext` → used as-is (already validated by `validate_media_path`) @@ -1230,6 +1454,20 @@ async fn resolve_s3_key( } } +/// A fixed access-log code for a rejected Blossom proof. +fn blossom_proof_code(e: &MediaError) -> &'static str { + match e { + MediaError::MissingAuth => "missing_auth", + MediaError::InvalidAuthScheme + | MediaError::InvalidBase64 + | MediaError::InvalidAuthEvent => "malformed_auth", + MediaError::InvalidSignature => "invalid_signature", + MediaError::TokenExpired | MediaError::TimestampOutOfWindow => "event_expired", + MediaError::ServerMismatch => "server_mismatch", + _ => "blossom_invalid", + } +} + /// Extract and verify a kind:24242 Blossom auth event from the `Authorization` header. /// /// Accepts both base64url (BUD-11 spec) and standard base64 (nostr-tools compat). @@ -1276,14 +1514,12 @@ fn blossom_strictness_from_state(state: &AppState) -> BlossomStrictness { #[cfg(test)] mod tests { use super::*; - use std::sync::Arc; use axum::{ - body::{to_bytes, Body}, - http::{header, Request, StatusCode}, + body::to_bytes, + http::{header, StatusCode}, }; - use nostr::{EventBuilder, JsonUtil, Keys, Kind, Tag, Timestamp}; - use tower::ServiceExt; + use nostr::{JsonUtil, Timestamp}; use uuid::Uuid; const VALID_HASH: &str = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"; @@ -1702,216 +1938,6 @@ mod tests { assert!(should_stream_as_video(bytes)); } - async fn test_state() -> Arc { - let mut config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE] - config.require_relay_membership = false; - config.redis_url = "redis://127.0.0.1:1".to_string(); - config.media_uploads_per_minute = 1; - config.media_max_concurrent_uploads = 2; - config.media_max_concurrent_uploads_per_pubkey = 1; - - let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); - let db = buzz_db::Db::from_pool(pool.clone()); - db.ensure_configured_community("relay.example") - .await - .expect("seed relay.example community for host-bound media tests"); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); - let pubsub = Arc::new( - buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) - .await - .expect("pubsub manager"), - ); - let audit = buzz_audit::AuditService::new(pool.clone()); - let auth = buzz_auth::AuthService::new(config.auth.clone()); - let search = buzz_search::SearchService::new(pool.clone()); - let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new( - db.clone(), - buzz_workflow::WorkflowConfig::default(), - )); - let media_storage = buzz_media::MediaStorage::new(&config.media).expect("media storage"); - let (state, _audit_shutdown) = AppState::new( - config, - db, - redis_pool, - audit, - pubsub, - auth, - search, - workflow_engine, - nostr::Keys::generate(), - media_storage, - ); - Arc::new(state) - } - - async fn media_get_auth_router() -> axum::Router { - let state = test_state().await; - axum::Router::new() - .route( - "/media/{sha256_ext}", - axum::routing::get(get_blob).head(head_blob), - ) - .with_state(state) - } - - fn media_get_auth_header(keys: &Keys, tags: Vec) -> String { - let event = EventBuilder::new(Kind::from(24242), "Get media") - .tags(tags) - .sign_with_keys(keys) - .expect("sign get auth"); - format!( - "Nostr {}", - base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(event.as_json().as_bytes()) - ) - } - - fn media_get_tags_for(host: &str, sha256: Option<&str>) -> Vec { - let now = Timestamp::now().as_secs(); - let expiration = (now + 55).to_string(); - let mut tags = vec![ - Tag::parse(["t", "get"]).expect("t tag"), - Tag::parse(["expiration", &expiration]).expect("expiration tag"), - Tag::parse(["server", host]).expect("server tag"), - ]; - if let Some(sha256) = sha256 { - tags.push(Tag::parse(["x", sha256]).expect("x tag")); - } - tags - } - - fn media_request(method: &str, auth: Option) -> Request { - let mut builder = Request::builder() - .method(method) - .uri(format!("/media/{VALID_HASH}.jpg")) - .header(header::HOST, "relay.example"); - if let Some(auth) = auth { - builder = builder.header(header::AUTHORIZATION, auth); - } - builder.body(Body::empty()).expect("request") - } - - #[tokio::test] - async fn media_reads_reject_unauthenticated_get_and_head_before_sidecar_gate() { - for method in ["GET", "HEAD"] { - let response = media_get_auth_router() - .await - .oneshot(media_request(method, None)) - .await - .expect("response"); - - assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{method}"); - } - } - - #[tokio::test] - async fn media_read_with_valid_server_scoped_token_reaches_sidecar_gate() { - let keys = Keys::generate(); - let auth = media_get_auth_header(&keys, media_get_tags_for("relay.example", None)); - let response = media_get_auth_router() - .await - .oneshot(media_request("GET", Some(auth))) - .await - .expect("response"); - - assert_eq!(response.status(), StatusCode::NOT_FOUND); - } - - #[tokio::test] - async fn media_read_rejects_upload_verb_wrong_server_and_wrong_x() { - let keys = Keys::generate(); - let now = Timestamp::now().as_secs(); - let expiration = (now + 55).to_string(); - let cases = [ - vec![ - Tag::parse(["t", "upload"]).expect("t tag"), - Tag::parse(["expiration", &expiration]).expect("expiration tag"), - Tag::parse(["server", "relay.example"]).expect("server tag"), - ], - vec![ - Tag::parse(["t", "get"]).expect("t tag"), - Tag::parse(["expiration", &expiration]).expect("expiration tag"), - Tag::parse(["server", "evil.example"]).expect("server tag"), - ], - vec![ - Tag::parse(["t", "get"]).expect("t tag"), - Tag::parse(["expiration", &expiration]).expect("expiration tag"), - Tag::parse(["x", &"f".repeat(64)]).expect("x tag"), - ], - ]; - - for tags in cases { - let auth = media_get_auth_header(&keys, tags); - let response = media_get_auth_router() - .await - .oneshot(media_request("GET", Some(auth))) - .await - .expect("response"); - - assert_ne!(response.status(), StatusCode::NOT_FOUND); - assert!( - response.status() == StatusCode::UNAUTHORIZED - || response.status() == StatusCode::FORBIDDEN, - "unexpected status {}", - response.status() - ); - } - } - - #[tokio::test] - async fn media_read_accepts_range_header_only_after_auth() { - let keys = Keys::generate(); - let auth = media_get_auth_header(&keys, media_get_tags_for("relay.example", None)); - let mut request = media_request("GET", Some(auth)); - request - .headers_mut() - .insert(header::RANGE, "bytes=0-0".parse().expect("range header")); - - let response = media_get_auth_router() - .await - .oneshot(request) - .await - .expect("response"); - - assert_eq!(response.status(), StatusCode::NOT_FOUND); - } - - #[tokio::test] - async fn upload_rate_limiter_is_scoped_by_community() { - let state = test_state().await; - let pubkey = nostr::Keys::generate().public_key(); - let community_a = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xAAAA)); - let community_b = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xBBBB)); - - assert!(!upload_rate_limited(&state, community_a, &pubkey)); - assert!(upload_rate_limited(&state, community_a, &pubkey)); - assert!( - !upload_rate_limited(&state, community_b, &pubkey), - "A's exhausted upload budget must not rate-limit the same key in B" - ); - } - - #[tokio::test] - async fn upload_concurrency_limit_is_scoped_by_community() { - let state = test_state().await; - let pubkey = nostr::Keys::generate().public_key(); - let community_a = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xAAAA)); - let community_b = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xBBBB)); - - let permit_a = - acquire_upload_permit(&state, community_a, &pubkey).expect("first A upload allowed"); - assert!(matches!( - acquire_upload_permit(&state, community_a, &pubkey), - Err(MediaError::UploadConcurrencyLimitReached) - )); - let permit_b = acquire_upload_permit(&state, community_b, &pubkey) - .expect("A's in-flight upload must not block B"); - - drop(permit_b); - drop(permit_a); - } - #[test] fn test_validate_media_path_bare_hash() { assert!(validate_media_path(VALID_HASH).is_ok()); @@ -1925,11 +1951,11 @@ mod tests { } #[test] - fn test_validate_media_path_thumb_jpg_only() { + fn test_validate_media_path_thumb_variants_only() { assert!(validate_media_path(&format!("{VALID_HASH}.thumb.jpg")).is_ok()); - // Other thumb extensions rejected — thumbnails are always JPEG + assert!(validate_media_path(&format!("{VALID_HASH}.thumb.webp")).is_ok()); + // Other thumb extensions rejected: only stored variants are served assert!(validate_media_path(&format!("{VALID_HASH}.thumb.png")).is_err()); - assert!(validate_media_path(&format!("{VALID_HASH}.thumb.webp")).is_err()); } #[test] @@ -2032,7 +2058,7 @@ mod tests { uploaded: 1700000000, dim: Some("1x1".to_string()), blurhash: None, - thumb: Some(format!("https://primary.example/media/{hash}.thumb.jpg")), + thumb: Some(format!("https://primary.example/media/{hash}.thumb.webp")), duration: None, }; @@ -2048,7 +2074,8 @@ mod tests { ); assert_eq!( descriptor.thumb, - Some(format!("https://tenant-b.example/media/{hash}.thumb.jpg")) + Some(format!("https://tenant-b.example/media/{hash}.thumb.webp")), + "the rewrite keeps the descriptor's thumbnail variant" ); } @@ -2114,7 +2141,7 @@ mod tests { // ── NIP-FI media regression tests ──────────────────────────────────────── // // These postgres-backed tests prove the NIP-FI admission gate is wired into - // the media upload and read routes at the router level. They all require a + // the media upload and read routes at the router level. They require a // live Postgres + Redis and are tagged #[ignore = "requires Postgres"]. // // Verified contract rows (NIP-FI.md rejection table): @@ -2166,11 +2193,7 @@ mod tests { const TEST_ISSUER: &str = "https://issuer.example"; const TEST_AUDIENCE: &str = "https://relay.example"; const TEST_KID: &str = "test-key-1"; - const TEST_EC_PKCS8_PEM: &str = "-----BEGIN PRIVATE KEY-----\n\ - MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\n\ - WZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\n\ - zhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n\ - -----END PRIVATE KEY-----\n"; + const TEST_EC_PKCS8_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\nWZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\nzhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n-----END PRIVATE KEY-----\n"; // sadscan:disable np.pem.1 kingfisher.privkey.2 -- public ES256 test fixture /// Build an AppState with NIP-FI Enforce and a real injected P-256 verifier. async fn media_enforce_test_state() -> Option> { @@ -2195,9 +2218,7 @@ mod tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -2282,9 +2303,7 @@ mod tests { .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -2662,6 +2681,170 @@ mod tests { } } + /// Run an upload with access lines captured; return the response and + /// the `event=http` lines. + fn upload_auth_lines( + rt: &tokio::runtime::Runtime, + state: &Arc, + host: &str, + authorization: &str, + assertion: Option<&str>, + ) -> (StatusCode, Vec) { + let ((status, _, _), out) = crate::access::tests::capture(|| { + upload_request(rt, state, "/upload", host, &[authorization], assertion) + }); + let lines = out + .lines() + .into_iter() + .filter(|l| l["event"] == "http") + .collect(); + (status, lines) + } + + fn assert_one_upload_line( + lines: &[serde_json::Value], + method: &str, + outcome: &str, + reason: Option<&str>, + ) { + assert_eq!(lines.len(), 1, "exactly one access line: {lines:?}"); + let line = &lines[0]; + assert_eq!(line["method"], method, "{line}"); + assert_eq!(line["outcome"], outcome, "{line}"); + assert_eq!(line["route"], "/upload", "{line}"); + match reason { + Some(reason) => assert_eq!(line["reason"], reason, "{line}"), + None => assert!(line.get("reason").is_none(), "{line}"), + } + } + + /// A banned caller's valid signed upload is refused at the membership + /// step: one `denied` line and no `success`. + #[test] + #[ignore = "requires Postgres"] + fn banned_upload_logs_one_denied_line() { + let (rt, state, host) = media_fixture(media_off_test_state()); + let tenant = rt + .block_on(crate::tenant::bind_community(&state.db, &host)) + .expect("bind community"); + let keys = Keys::generate(); + rt.block_on( + sqlx::query( + "INSERT INTO community_bans (community_id, pubkey, banned, actor_pubkey) \ + VALUES ($1, $2, true, $2)", + ) + .bind(tenant.community().as_uuid()) + .bind(keys.public_key().to_bytes().as_slice()) + .execute(state.db.pool()), + ) + .expect("ban"); + let proof = blossom_upload_auth_value(&keys, &host, &sha256_hex(AUDIO_BODY)); + let (status, lines) = upload_auth_lines(&rt, &state, &host, &proof, None); + assert_eq!(status, StatusCode::FORBIDDEN); + assert_one_upload_line(&lines, "blossom", "denied", Some("banned")); + } + + /// A malformed proof alongside a valid enterprise assertion: the proof + /// closure writes one `failed` line and the enterprise helper adds none. + /// Off mode, where the helper is bypassed, also writes exactly one. + #[test] + #[ignore = "requires Postgres"] + fn bad_upload_proof_logs_one_failed_line() { + let (rt, state, host) = media_fixture(media_enforce_test_state()); + let assertion = signed_assertion(&Keys::generate().public_key().to_hex()); + let (status, lines) = upload_auth_lines( + &rt, + &state, + &host, + "Nostr !!!not-base64!!!", + Some(&assertion), + ); + assert_eq!(status, StatusCode::FORBIDDEN); + assert_one_upload_line(&lines, "blossom", "failed", Some("malformed_auth")); + assert_eq!(lines[0]["status"], 403, "the remapped status: {}", lines[0]); + + let (rt, state, host) = media_fixture(media_off_test_state()); + let (status, lines) = + upload_auth_lines(&rt, &state, &host, "Nostr !!!not-base64!!!", None); + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert_one_upload_line(&lines, "blossom", "failed", Some("malformed_auth")); + assert_eq!(lines[0]["status"], 401, "the legacy status: {}", lines[0]); + } + + /// A malformed read proof alongside a valid enterprise assertion: GET + /// and HEAD each write one WARN `failed` line carrying the 403 sent. + #[test] + #[ignore = "requires Postgres"] + fn bad_read_proof_logs_the_status_sent() { + let (rt, state, host) = media_fixture(media_enforce_test_state()); + let path = format!("/media/{}.jpg", "d".repeat(64)); + for method in ["GET", "HEAD"] { + let mut headers = axum::http::HeaderMap::new(); + headers.insert( + axum::http::header::AUTHORIZATION, + "Nostr !!!bad!!!".parse().expect("valid header bytes"), + ); + headers.insert( + buzz_auth::CLIENT_ATTACHED_HEADER, + format!( + "Bearer {}", + signed_assertion(&Keys::generate().public_key().to_hex()) + ) + .parse() + .expect("valid header"), + ); + let ((status, _, _), out) = crate::access::tests::capture(|| { + rt.block_on(media_oneshot( + Arc::clone(&state), + method, + &path, + &host, + headers, + b"", + )) + }); + assert_eq!(status, StatusCode::FORBIDDEN, "{method}"); + let lines: Vec<_> = out + .lines() + .into_iter() + .filter(|l| l["event"] == "http") + .collect(); + assert_eq!(lines.len(), 1, "{method}: {lines:?}"); + let line = &lines[0]; + assert_eq!(line["outcome"], "failed", "{method}: {line}"); + assert_eq!(line["level"], "WARN", "{method}: {line}"); + assert_eq!(line["status"], 403, "{method}: {line}"); + assert_eq!(line["route"], "/media/{sha256_ext}", "{method}: {line}"); + // The hash never reaches any field of the line. + assert!( + !out.raw().contains(&"d".repeat(64)), + "{method}: {}", + out.raw() + ); + } + } + + /// An admitted upload logs one `success` once the concurrency permit + /// is held, in both modes; the later content rejection adds nothing. + #[test] + #[ignore = "requires Postgres"] + fn admitted_upload_logs_one_success_line() { + let (rt, state, host) = media_fixture(media_off_test_state()); + let keys = Keys::generate(); + let proof = blossom_upload_auth_value(&keys, &host, &sha256_hex(AUDIO_BODY)); + let (status, lines) = upload_auth_lines(&rt, &state, &host, &proof, None); + assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE); + assert_one_upload_line(&lines, "blossom", "success", None); + + let (rt, state, host) = media_fixture(media_enforce_test_state()); + let keys = Keys::generate(); + let assertion = signed_assertion(&keys.public_key().to_hex()); + let proof = blossom_upload_auth_value(&keys, &host, &sha256_hex(AUDIO_BODY)); + let (status, lines) = upload_auth_lines(&rt, &state, &host, &proof, Some(&assertion)); + assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE); + assert_one_upload_line(&lines, "nip_fi", "success", None); + } + /// Off mode skips the cardinality gate and `HeaderMap::get` takes the /// first Authorization value. A single valid proof and a /// valid-first/malformed-second pair both reach the exact 415; applying @@ -3308,6 +3491,7 @@ mod tests { .expect("valid header"), ); + let (guard, out) = crate::access::tests::capture_scoped(); let (status, resp_headers, body) = rt.block_on(media_oneshot( Arc::clone(&state), "GET", @@ -3316,6 +3500,17 @@ mod tests { headers, b"", )); + drop(guard); + // The rejected read proof writes exactly one access line. + let auth: Vec<_> = out + .lines() + .into_iter() + .filter(|l| l["event"] == "http") + .collect(); + assert_eq!(auth.len(), 1, "{auth:?}"); + assert_eq!(auth[0]["method"], "blossom"); + assert_eq!(auth[0]["outcome"], "failed"); + assert_eq!(auth[0]["route"], "/media/{sha256_ext}"); assert_eq!( status, @@ -4415,5 +4610,444 @@ mod tests { ); } } + + // ── Host-bound media reads and per-community upload limits ───────────── + // + // `test_state` seeds the relay.example community, so these need Postgres + // too. Its Redis URL is unreachable on purpose: none of them use Redis. + + async fn test_state() -> Arc { + let mut config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE] + config.database_url = crate::test_support::database_url(); + config.require_relay_membership = false; + config.redis_url = "redis://127.0.0.1:1".to_string(); + config.media_uploads_per_minute = 1; + config.media_max_concurrent_uploads = 2; + config.media_max_concurrent_uploads_per_pubkey = 1; + + let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); + let db = buzz_db::Db::from_pool(pool.clone()); + db.ensure_configured_community("relay.example") + .await + .expect("seed relay.example community for host-bound media tests"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); + let pubsub = Arc::new( + buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) + .await + .expect("pubsub manager"), + ); + let audit = buzz_audit::AuditService::new(pool.clone()); + let auth = buzz_auth::AuthService::new(config.auth.clone()); + let search = buzz_search::SearchService::new(pool.clone()); + let workflow_engine = Arc::new(buzz_workflow::WorkflowEngine::new( + db.clone(), + buzz_workflow::WorkflowConfig::default(), + )); + let media_storage = + buzz_media::MediaStorage::new(&config.media).expect("media storage"); + let (state, _audit_shutdown) = AppState::new( + config, + db, + redis_pool, + audit, + pubsub, + auth, + search, + workflow_engine, + nostr::Keys::generate(), + media_storage, + ); + Arc::new(state) + } + + async fn media_get_auth_router() -> axum::Router { + let state = test_state().await; + axum::Router::new() + .route( + "/media/{sha256_ext}", + axum::routing::get(get_blob).head(head_blob), + ) + .with_state(state) + } + + fn media_get_auth_header(keys: &Keys, tags: Vec) -> String { + let event = EventBuilder::new(Kind::from(24242), "Get media") + .tags(tags) + .sign_with_keys(keys) + .expect("sign get auth"); + format!( + "Nostr {}", + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(event.as_json().as_bytes()) + ) + } + + fn media_get_tags_for(host: &str, sha256: Option<&str>) -> Vec { + let now = Timestamp::now().as_secs(); + let expiration = (now + 55).to_string(); + let mut tags = vec![ + Tag::parse(["t", "get"]).expect("t tag"), + Tag::parse(["expiration", &expiration]).expect("expiration tag"), + Tag::parse(["server", host]).expect("server tag"), + ]; + if let Some(sha256) = sha256 { + tags.push(Tag::parse(["x", sha256]).expect("x tag")); + } + tags + } + + fn media_request(method: &str, auth: Option) -> Request { + let mut builder = Request::builder() + .method(method) + .uri(format!("/media/{VALID_HASH}.jpg")) + .header(header::HOST, "relay.example"); + if let Some(auth) = auth { + builder = builder.header(header::AUTHORIZATION, auth); + } + builder.body(Body::empty()).expect("request") + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn media_reads_reject_unauthenticated_get_and_head_before_sidecar_gate() { + for method in ["GET", "HEAD"] { + let response = media_get_auth_router() + .await + .oneshot(media_request(method, None)) + .await + .expect("response"); + + assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{method}"); + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn media_read_with_valid_server_scoped_token_reaches_sidecar_gate() { + let keys = Keys::generate(); + let auth = media_get_auth_header(&keys, media_get_tags_for("relay.example", None)); + let response = media_get_auth_router() + .await + .oneshot(media_request("GET", Some(auth))) + .await + .expect("response"); + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn media_read_rejects_upload_verb_wrong_server_and_wrong_x() { + let keys = Keys::generate(); + let now = Timestamp::now().as_secs(); + let expiration = (now + 55).to_string(); + let cases = [ + vec![ + Tag::parse(["t", "upload"]).expect("t tag"), + Tag::parse(["expiration", &expiration]).expect("expiration tag"), + Tag::parse(["server", "relay.example"]).expect("server tag"), + ], + vec![ + Tag::parse(["t", "get"]).expect("t tag"), + Tag::parse(["expiration", &expiration]).expect("expiration tag"), + Tag::parse(["server", "evil.example"]).expect("server tag"), + ], + vec![ + Tag::parse(["t", "get"]).expect("t tag"), + Tag::parse(["expiration", &expiration]).expect("expiration tag"), + Tag::parse(["x", &"f".repeat(64)]).expect("x tag"), + ], + ]; + + for tags in cases { + let auth = media_get_auth_header(&keys, tags); + let response = media_get_auth_router() + .await + .oneshot(media_request("GET", Some(auth))) + .await + .expect("response"); + + assert_ne!(response.status(), StatusCode::NOT_FOUND); + assert!( + response.status() == StatusCode::UNAUTHORIZED + || response.status() == StatusCode::FORBIDDEN, + "unexpected status {}", + response.status() + ); + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn media_read_accepts_range_header_only_after_auth() { + let keys = Keys::generate(); + let auth = media_get_auth_header(&keys, media_get_tags_for("relay.example", None)); + let mut request = media_request("GET", Some(auth)); + request + .headers_mut() + .insert(header::RANGE, "bytes=0-0".parse().expect("range header")); + + let response = media_get_auth_router() + .await + .oneshot(request) + .await + .expect("response"); + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn upload_rate_limiter_is_scoped_by_community() { + let state = test_state().await; + let pubkey = nostr::Keys::generate().public_key(); + let community_a = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xAAAA)); + let community_b = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xBBBB)); + + assert!(!upload_rate_limited(&state, community_a, &pubkey)); + assert!(upload_rate_limited(&state, community_a, &pubkey)); + assert!( + !upload_rate_limited(&state, community_b, &pubkey), + "A's exhausted upload budget must not rate-limit the same key in B" + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn upload_concurrency_limit_is_scoped_by_community() { + let state = test_state().await; + let pubkey = nostr::Keys::generate().public_key(); + let community_a = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xAAAA)); + let community_b = buzz_core::CommunityId::from_uuid(Uuid::from_u128(0xBBBB)); + + let permit_a = acquire_upload_permit(&state, community_a, &pubkey) + .expect("first A upload allowed"); + assert!(matches!( + acquire_upload_permit(&state, community_a, &pubkey), + Err(MediaError::UploadConcurrencyLimitReached) + )); + let permit_b = acquire_upload_permit(&state, community_b, &pubkey) + .expect("A's in-flight upload must not block B"); + + drop(permit_b); + drop(permit_a); + } + + /// Thumbnail regeneration needs real object storage, so these also + /// need MinIO. They share one image and the process-wide regeneration + /// permits, so they run one at a time. + mod external_infra_minio_tests { + use super::*; + + static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// A valid 4x4 PNG with no ancillary chunks. + const PNG: &[u8] = &[ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, + 0x44, 0x52, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x08, 0x02, 0x00, 0x00, + 0x00, 0x26, 0x93, 0x09, 0x29, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x78, + 0x9c, 0x63, 0x38, 0x21, 0x27, 0x07, 0x47, 0x0c, 0xc4, 0x71, 0x00, 0xb1, 0x63, 0x10, + 0x41, 0x3b, 0x4b, 0x63, 0x82, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, + 0x42, 0x60, 0x82, + ]; + + /// A valid all-black grayscale PNG of the given size. + fn blank_png(width: u32, height: u32) -> Vec { + use std::io::Write; + let chunk = |png: &mut Vec, kind: &[u8], data: &[u8]| { + let mut crc = flate2::Crc::new(); + crc.update(kind); + crc.update(data); + png.extend((data.len() as u32).to_be_bytes()); + png.extend(kind); + png.extend(data); + png.extend(crc.sum().to_be_bytes()); + }; + let mut ihdr = [width.to_be_bytes(), height.to_be_bytes()].concat(); + ihdr.extend([8, 0, 0, 0, 0]); + let mut pixels = + flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); + pixels + .write_all(&vec![0; (width as usize + 1) * height as usize]) + .expect("compress"); + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + chunk(&mut png, b"IHDR", &ihdr); + chunk(&mut png, b"IDAT", &pixels.finish().expect("compress")); + chunk(&mut png, b"IEND", &[]); + png + } + + struct Fixture { + rt: tokio::runtime::Runtime, + state: Arc, + host: String, + sha: String, + } + + impl Fixture { + /// Upload [`PNG`] through the real route, apply `configure`, and delete its thumbnails. + fn new(configure: impl FnOnce(&mut crate::config::Config)) -> Self { + let (rt, mut state, host) = media_fixture(media_off_test_state()); + let sha = sha256_hex(PNG); + let proof = blossom_upload_auth_value(&Keys::generate(), &host, &sha); + let (status, _, body) = upload_request_with( + &rt, + &state, + "/media/upload", + &host, + (Some(&sha), PNG), + &[&proof], + None, + ); + assert_eq!(status, StatusCode::OK, "upload: {body:?}"); + mutate_state(&mut state, configure); + let fixture = Self { + rt, + state, + host, + sha, + }; + fixture.delete_thumbs(); + fixture + } + + /// Switch to `bytes`, stored under their own hash with a sidecar + /// but without the upload route's validation or thumbnails. + fn with_blob(self, bytes: &[u8], ext: &str, mime: &str) -> Self { + let sha = sha256_hex(bytes); + self.rt.block_on(async { + let tenant = crate::tenant::bind_community(&self.state.db, &self.host) + .await + .expect("bind community"); + let storage = &self.state.media_storage; + storage + .put(&format!("{sha}.{ext}"), bytes, mime) + .await + .expect("put blob"); + let meta = buzz_media::BlobMeta { + ext: ext.into(), + mime_type: mime.into(), + size: bytes.len() as u64, + ..Default::default() + }; + storage + .put_sidecar(&tenant, &sha, &meta) + .await + .expect("put sidecar"); + }); + Self { sha, ..self } + } + + fn thumb_key(&self, ext: &str) -> String { + format!("{}.thumb.{ext}", self.sha) + } + + fn delete_thumbs(&self) { + for ext in ["webp", "jpg"] { + self.rt + .block_on(self.state.media_storage.delete(&self.thumb_key(ext))) + .expect("delete thumbnail"); + } + } + + fn stored(&self, key: &str) -> bool { + self.rt + .block_on(self.state.media_storage.head(key)) + .expect("head") + } + + fn read( + &self, + method: &str, + ext: &str, + ) -> (StatusCode, axum::http::HeaderMap, bytes::Bytes) { + let mut headers = axum::http::HeaderMap::new(); + headers.insert( + axum::http::header::AUTHORIZATION, + blossom_get_auth_value(&Keys::generate(), &self.host, &self.sha) + .parse() + .expect("valid header"), + ); + self.rt.block_on(media_oneshot( + Arc::clone(&self.state), + method, + &format!("/media/{}", self.thumb_key(ext)), + &self.host, + headers, + b"", + )) + } + } + + /// A thumbnail variant missing from storage while its image original + /// exists is rebuilt and served, by GET and by HEAD, for each variant. + #[test] + #[ignore = "requires Postgres and MinIO"] + fn missing_thumbnail_is_regenerated_from_image_original() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let f = Fixture::new(|_| {}); + for (method, ext, mime) in [ + ("GET", "webp", "image/webp"), + ("GET", "jpg", "image/jpeg"), + ("HEAD", "webp", "image/webp"), + ("HEAD", "jpg", "image/jpeg"), + ] { + f.delete_thumbs(); + let (status, headers, body) = f.read(method, ext); + assert_eq!(status, StatusCode::OK, "{method} {ext}: {body:?}"); + assert_eq!(headers["content-type"], mime, "{method} {ext}"); + if method == "GET" { + assert!(!body.is_empty(), "{ext} body"); + } + for ext in ["webp", "jpg"] { + assert!(f.stored(&f.thumb_key(ext)), "{method} {ext}: {ext} stored"); + } + } + } + + /// Regeneration stays a 404 and writes nothing when the sidecar says the + /// blob is not an image, the original is gone, the original exceeds + /// `max_image_bytes` or 25 megapixels, or every regeneration permit + /// is taken. + #[test] + #[ignore = "requires Postgres and MinIO"] + fn missing_thumbnail_is_not_regenerated_when_unsafe() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let assert_absent = |f: &Fixture, case: &str| { + for ext in ["webp", "jpg"] { + let (status, _, body) = f.read("GET", ext); + assert_eq!(status, StatusCode::NOT_FOUND, "{case} {ext}: {body:?}"); + assert!(!f.stored(&f.thumb_key(ext)), "{case}: {ext} written"); + } + }; + + // Not an image: a text blob under its own hash. + let text = format!("not an image {}", uuid::Uuid::new_v4()).into_bytes(); + let f = Fixture::new(|_| {}).with_blob(&text, "txt", "text/plain"); + assert_absent(&f, "non-image"); + + // Original missing: sidecar still says image. + let f = Fixture::new(|_| {}); + f.rt.block_on(f.state.media_storage.delete(&format!("{}.png", f.sha))) + .expect("delete original"); + assert_absent(&f, "missing original"); + + // Original over the size cap. + let f = Fixture::new(|c| c.media.max_image_bytes = PNG.len() as u64 - 1); + assert_absent(&f, "oversize"); + + // Original over the 25 MP pixel cap, within the byte cap. + let f = + Fixture::new(|_| {}).with_blob(&blank_png(5_001, 5_000), "png", "image/png"); + assert_absent(&f, "over 25 MP"); + + // No free permit, then a free one. + let f = Fixture::new(|_| {}); + let held: Vec<_> = std::iter::from_fn(|| THUMB_REGEN.try_acquire().ok()).collect(); + assert!(!held.is_empty(), "fixture must hold a regeneration permit"); + assert_absent(&f, "busy"); + drop(held); + assert_eq!(f.read("GET", "webp").0, StatusCode::OK, "after release"); + } + } } } diff --git a/crates/buzz-relay/src/api/media_access.rs b/crates/buzz-relay/src/api/media_access.rs new file mode 100644 index 00000000000..d6a6b21df44 --- /dev/null +++ b/crates/buzz-relay/src/api/media_access.rs @@ -0,0 +1,126 @@ +//! Channel media policy, separate from Blossom proof/community admission. +use super::media::MediaDenial; +use crate::state::AppState; +use buzz_core::TenantContext; +use buzz_media::{auth::BlossomStrictness, MediaError}; + +/// Startup-selected rollout policy. Off preserves the current community gate. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum MediaReadMode { + /// Skip reference authorization (does not provide channel revocation). + #[default] + Off, + /// Evaluate and count the policy without refusing reads/publications. + Shadow, + /// Enforce fresh channel and event authorization. + Enforce, +} +impl std::str::FromStr for MediaReadMode { + type Err = String; + fn from_str(value: &str) -> Result { + match value { + "off" => Ok(Self::Off), + "shadow" => Ok(Self::Shadow), + "enforce" => Ok(Self::Enforce), + _ => Err("BUZZ_MEDIA_READ_MODE must be off, shadow, or enforce".into()), + } + } +} +impl MediaReadMode { + pub(crate) fn label(self) -> &'static str { + match self { + Self::Off => "off", + Self::Shadow => "shadow", + Self::Enforce => "enforce", + } + } +} + +/// Authorize the parent hash before any blob/thumbnail/range information. +/// The tenant sidecar is a cheap first gate before the new DB lookup. +pub(super) async fn enforce_read( + state: &AppState, + tenant: &TenantContext, + path: &str, + pubkey: &[u8], + strictness: BlossomStrictness, +) -> Result<(), MediaDenial> { + let mode = state.config.media_read_mode; + if mode == MediaReadMode::Off { + return Ok(()); + } + let hash = path + .split('.') + .next() + .ok_or(MediaDenial(MediaError::NotFound, strictness))?; + let meta = match state.media_storage.get_sidecar(tenant, hash).await { + Ok(meta) => meta, + Err(error) => { + let missing = matches!(&error, MediaError::NotFound); + metrics::counter!("buzz_media_read_access_total","mode"=>mode.label(),"reason"=>if missing {"no_ref"} else {"lookup_error"}).increment(1); + if mode == MediaReadMode::Shadow { + return Ok(()); + } + return Err(MediaDenial( + if missing { + MediaError::NotFound + } else { + MediaError::ServiceUnavailable + }, + strictness, + )); + } + }; + let base = super::media::media_base_url_for_tenant(&state.config.relay_url, tenant.host()); + let result = state + .db + .media_access( + tenant.community(), + hash, + &meta.ext, + &base, + pubkey, + false, + crate::handlers::req::event_visible_to_reader, + ) + .await; + let (reason, error) = match result { + Ok(buzz_db::media::MediaAccess::Allowed | buzz_db::media::MediaAccess::UploaderPreview) => { + ("allow", None) + } + Ok(buzz_db::media::MediaAccess::NoReference) => ("no_ref", Some(MediaError::NotFound)), + Ok(buzz_db::media::MediaAccess::Restricted) => ("not_member", Some(MediaError::NotFound)), + Err(error) => { + tracing::warn!(error_kind = %error.kind(), "media authorization lookup failed"); + ( + if matches!(error, buzz_db::DbError::MediaAuthorizationCapacity) { + "capacity" + } else { + "lookup_error" + }, + Some(MediaError::AuthorizationUnavailable), + ) + } + }; + metrics::counter!("buzz_media_read_access_total", "mode" => mode.label(), "reason" => reason) + .increment(1); + if mode == MediaReadMode::Enforce { + if let Some(error) = error { + return Err(MediaDenial(error, strictness)); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rollout_mode_is_explicit() { + for mode in ["off", "shadow", "enforce"] { + assert!(mode.parse::().is_ok()); + } + assert!("typo".parse::().is_err()); + assert_eq!(MediaReadMode::default(), MediaReadMode::Off); + } +} diff --git a/crates/buzz-relay/src/api/media_access_postgres_tests.rs b/crates/buzz-relay/src/api/media_access_postgres_tests.rs new file mode 100644 index 00000000000..ec6d9140c7e --- /dev/null +++ b/crates/buzz-relay/src/api/media_access_postgres_tests.rs @@ -0,0 +1,970 @@ +//! Real media handlers and PostgreSQL, with an in-process S3 HTTP fixture. +use super::media::{get_blob, head_blob, upload_blob}; +use crate::state::AppState; +use axum::{ + body::{to_bytes, Body, Bytes}, + http::{Method, Request}, + routing::any, + Router, +}; +use axum::{ + extract::{Path, State}, + http::{header, StatusCode}, + response::{IntoResponse, Response}, +}; +use base64::Engine; +use buzz_db::channel::{ChannelType, ChannelVisibility, MemberRole}; +use nostr::{EventBuilder, JsonUtil, Keys, Kind, Tag, Timestamp}; +use sha2::{Digest, Sha256}; +use std::{ + collections::HashMap, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }, +}; +use tokio::sync::Mutex; +use tower::ServiceExt; +use uuid::Uuid; + +#[derive(Clone, Default)] +struct Bucket { + objects: Arc>>, + reads: Arc, +} +async fn object( + State(bucket): State, + Path(key): Path, + request: Request, +) -> Response { + if request.method() == Method::PUT { + let data = to_bytes(request.into_body(), 2_000_000).await.unwrap(); + bucket.objects.lock().await.insert(key, data); + return StatusCode::OK.into_response(); + } + bucket.reads.fetch_add(1, Ordering::SeqCst); + let Some(mut data) = bucket.objects.lock().await.get(&key).cloned() else { + return StatusCode::NOT_FOUND.into_response(); + }; + let mut status = StatusCode::OK; + if let Some(range) = request.headers().get(header::RANGE) { + let (start, end) = range + .to_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap() + .split_once('-') + .unwrap(); + let start: usize = start.parse().unwrap(); + let end: usize = end.parse().unwrap_or(data.len() - 1).min(data.len() - 1); + data = data.slice(start..=end); + status = StatusCode::PARTIAL_CONTENT; + } + Response::builder() + .status(status) + .header(header::CONTENT_LENGTH, data.len()) + .body(if request.method() == Method::HEAD { + Body::empty() + } else { + Body::from(data) + }) + .unwrap() +} +fn proof(keys: &Keys, host: &str, hash: &str, verb: &str) -> String { + let event = EventBuilder::new(Kind::Custom(24242), "media fixture") + .tags([ + Tag::parse(["t", verb]).unwrap(), + Tag::parse(["x", hash]).unwrap(), + Tag::parse(["server", host]).unwrap(), + Tag::parse(["expiration", &(Timestamp::now().as_secs() + 55).to_string()]).unwrap(), + ]) + .sign_with_keys(keys) + .unwrap(); + format!( + "Nostr {}", + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(event.as_json()) + ) +} +fn get( + keys: &Keys, + host: &str, + hash: &str, + path: &str, + method: &str, + range: Option<&str>, +) -> Request { + let mut req = Request::builder() + .method(method) + .uri(format!("/media/{path}")) + .header(header::HOST, host) + .header(header::AUTHORIZATION, proof(keys, host, hash, "get")); + if let Some(range) = range { + req = req.header(header::RANGE, range); + } + req.body(Body::empty()).unwrap() +} +async fn fixture(endpoint: &str, mode: super::media_access::MediaReadMode) -> Arc { + let mut config = crate::config::Config::for_test(); + config.database_url = crate::test_support::database_url(); + config.require_relay_membership = false; + config.media_read_mode = mode; + config.media.s3_endpoint = endpoint.to_owned(); + config.media.s3_access_key = "fixture".into(); + config.media.s3_secret_key = "fixture".into(); + config.media_uploads_per_minute = 100; + config.redis_url = + std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://localhost:6379".into()); + let pool = sqlx::PgPool::connect(&config.database_url).await.unwrap(); + let db = buzz_db::Db::from_pool(pool.clone()); + let redis = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); + let pubsub = Arc::new( + buzz_pubsub::PubSubManager::new(&config.redis_url, redis.clone()) + .await + .unwrap(), + ); + let audit = buzz_audit::AuditService::new(pool.clone()); + let auth = buzz_auth::AuthService::new(config.auth.clone()); + let search = buzz_search::SearchService::new(pool); + let workflow = Arc::new(buzz_workflow::WorkflowEngine::new( + db.clone(), + buzz_workflow::WorkflowConfig::default(), + )); + let media = buzz_media::MediaStorage::new(&config.media).unwrap(); + let (state, _) = AppState::new( + config, + db, + redis, + audit, + pubsub, + auth, + search, + workflow, + Keys::generate(), + media, + ); + Arc::new(state) +} +fn router(state: Arc) -> Router { + Router::new() + .route("/upload", axum::routing::put(upload_blob)) + .route( + "/media/{sha256_ext}", + axum::routing::get(get_blob).head(head_blob), + ) + .with_state(state) +} +async fn post( + state: &Arc, + tenant: &buzz_core::TenantContext, + keys: &Keys, + event: nostr::Event, +) -> Result { + crate::handlers::ingest::ingest_event( + state, + tenant, + event, + crate::handlers::ingest::IngestAuth::Nip42 { + pubkey: keys.public_key(), + scopes: buzz_auth::Scope::all_known(), + channel_ids: None, + conn_id: Uuid::new_v4(), + }, + ) + .await +} + +mod cli_edit_postgres_tests; +mod emoji_reference_postgres_tests; +mod reference_budget_postgres_tests; +mod reference_formats_postgres_tests; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn private_media_revocation_http_journey() { + let bucket = Bucket::default(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let service = Router::new() + .route("/{*key}", any(object)) + .with_state(bucket.clone()); + let server = tokio::spawn(async move { + axum::serve(listener, service).await.unwrap(); + }); + let state = fixture(&endpoint, super::media_access::MediaReadMode::Enforce).await; + let host = format!("private-media-{}.example", Uuid::new_v4()); + state.db.ensure_configured_community(&host).await.unwrap(); + let tenant = crate::tenant::bind_community(&state.db, &host) + .await + .unwrap(); + let owner = Keys::generate(); + let member = Keys::generate(); + let survivor = Keys::generate(); + for keys in [&owner, &member, &survivor] { + state + .db + .ensure_user(tenant.community(), keys.public_key().as_bytes()) + .await + .unwrap(); + } + let channel = state + .db + .create_channel( + tenant.community(), + "private-media", + ChannelType::Stream, + ChannelVisibility::Private, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id; + for keys in [&member, &survivor] { + state + .db + .add_member( + tenant.community(), + channel, + keys.public_key().as_bytes(), + MemberRole::Member, + Some(owner.public_key().as_bytes()), + ) + .await + .unwrap(); + } + let bytes = b"channel-secret attachment bytes"; + let hash = hex::encode(Sha256::digest(bytes)); + let upload = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, &host) + .header(header::AUTHORIZATION, proof(&owner, &host, &hash, "upload")) + .header("X-SHA-256", &hash) + .body(Body::from(bytes.as_slice())) + .unwrap(); + let response = router(state.clone()).oneshot(upload).await.unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), 100_000).await.unwrap(); + assert_eq!( + status, + StatusCode::OK, + "upload: {}", + String::from_utf8_lossy(&body) + ); + let descriptor: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let url = descriptor["url"].as_str().unwrap(); + let ext = url.rsplit('.').next().unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(get(&owner, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::OK, + "uploader preview" + ); + assert_eq!( + router(state.clone()) + .oneshot(get(&member, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND, + "unposted is uploader-only" + ); + let message = EventBuilder::new(Kind::Custom(9), "private file") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse([ + "imeta", + &format!("url {url}"), + &format!("x {hash}"), + "m application/octet-stream", + &format!("size {}", bytes.len()), + ]) + .unwrap(), + ]) + .sign_with_keys(&owner) + .unwrap(); + let result = post(&state, &tenant, &owner, message.clone()).await; + assert!(result.is_ok(), "post failed: {:?}", result.err()); + let response = router(state.clone()) + .oneshot(get(&member, &host, &hash, &hash, "GET", None)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers()[header::CACHE_CONTROL], + "private, no-store" + ); + for range in ["bytes=99999999-", "bytes=invalid"] { + let response = router(state.clone()) + .oneshot(get(&survivor, &host, &hash, &hash, "GET", Some(range))) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE); + assert_eq!( + response.headers()[header::CACHE_CONTROL], + "private, no-store" + ); + } + // Model an attachment posted before recording existed. A real reupload + // must retain its legacy publication boundary even after source purging. + sqlx::query("DELETE FROM media_publications WHERE community_id=$1 AND sha256=$2") + .bind(tenant.community().as_uuid()) + .bind(&hash) + .execute(state.db.pool()) + .await + .unwrap(); + sqlx::query("DELETE FROM media_uploaders WHERE community_id=$1 AND sha256=$2") + .bind(tenant.community().as_uuid()) + .bind(&hash) + .execute(state.db.pool()) + .await + .unwrap(); + let reupload = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, &host) + .header(header::AUTHORIZATION, proof(&owner, &host, &hash, "upload")) + .header("X-SHA-256", &hash) + .body(Body::from(bytes.as_slice())) + .unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(reupload) + .await + .unwrap() + .status(), + StatusCode::OK + ); + sqlx::query("DELETE FROM events WHERE community_id=$1 AND id=$2") + .bind(tenant.community().as_uuid()) + .bind(message.id.as_bytes().as_slice()) + .execute(state.db.pool()) + .await + .unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(get(&owner, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND, + "legacy reupload cannot resurrect preview after purging" + ); + state + .db + .insert_event(tenant.community(), &message, Some(channel)) + .await + .unwrap(); + // A normal channel view can request attachments and avatars in parallel. + let requests = (0..32) + .map(|_| router(state.clone()).oneshot(get(&member, &host, &hash, &hash, "GET", None))); + for response in futures_util::future::join_all(requests).await { + assert_eq!( + response.unwrap().status(), + StatusCode::OK, + "32 concurrent authorized reads" + ); + } + // Real thumbnail keys ensure alias positives cannot pass vacuously. + for variant in ["jpg", "webp"] { + bucket.objects.lock().await.insert( + format!("{}/{hash}.thumb.{variant}", state.config.media.s3_bucket), + Bytes::from_static(b"thumb bytes"), + ); + } + for path in [ + hash.clone(), + format!("{hash}.{ext}"), + format!("{hash}.thumb.jpg"), + format!("{hash}.thumb.webp"), + ] { + for (method, range, expected) in [ + ("GET", None, StatusCode::OK), + ("HEAD", None, StatusCode::OK), + ("GET", Some("bytes=0-3"), StatusCode::PARTIAL_CONTENT), + ] { + assert_eq!( + router(state.clone()) + .oneshot(get(&member, &host, &hash, &path, method, range)) + .await + .unwrap() + .status(), + expected, + "authorized {method} {path}" + ); + } + } + state + .db + .remove_member( + tenant.community(), + channel, + member.public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap(); + for path in [ + hash.clone(), + format!("{hash}.{ext}"), + format!("{hash}.thumb.jpg"), + format!("{hash}.thumb.webp"), + ] { + for (method, range) in [ + ("GET", None), + ("HEAD", None), + ("GET", Some("bytes=0-3")), + ("GET", Some("bytes=99999999-")), + ] { + let before = bucket.reads.load(Ordering::SeqCst); + let response = router(state.clone()) + .oneshot(get(&member, &host, &hash, &path, method, range)) + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::NOT_FOUND, + "{method} {path} {range:?}" + ); + assert!(!response.headers().contains_key(header::CONTENT_RANGE)); + assert_eq!( + bucket.reads.load(Ordering::SeqCst), + before + 1, + "denial reads only the tenant sidecar" + ); + } + } + for keys in [&owner, &survivor] { + assert_eq!( + router(state.clone()) + .oneshot(get(keys, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::OK + ); + } + let wrong = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, &host) + .header( + header::AUTHORIZATION, + proof(&member, &host, &hash, "upload"), + ) + .header("X-SHA-256", &hash) + .body(Body::from("wrong bytes")) + .unwrap(); + assert_eq!( + router(state.clone()).oneshot(wrong).await.unwrap().status(), + StatusCode::UNAUTHORIZED, + "deduplicated upload still verifies bytes before recording possession" + ); + for mode in [ + super::media_access::MediaReadMode::Off, + super::media_access::MediaReadMode::Shadow, + ] { + let rollout = fixture(&endpoint, mode).await; + assert_eq!( + router(rollout) + .oneshot(get(&member, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::OK, + "rollout mode {mode:?}" + ); + } + let open = state + .db + .create_channel( + tenant.community(), + "open-media", + ChannelType::Stream, + ChannelVisibility::Open, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id; + for event in [ + EventBuilder::new(Kind::Custom(9033), "") + .tags([Tag::parse(["icon", url]).unwrap()]) + .sign_with_keys(&member) + .unwrap(), + EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":url}).to_string(), + ) + .sign_with_keys(&member) + .unwrap(), + EventBuilder::new(Kind::Custom(9), "copy") + .tags([ + Tag::parse(["h", &open.to_string()]).unwrap(), + Tag::parse([ + "imeta", + &format!("url {url}"), + &format!("x {hash}"), + "m application/octet-stream", + &format!("size {}", bytes.len()), + ]) + .unwrap(), + ]) + .sign_with_keys(&member) + .unwrap(), + ] { + let error = post(&state, &tenant, &member, event) + .await + .err() + .expect("copied URL denied"); + assert!( + matches!(error, crate::handlers::ingest::IngestError::Rejected(ref reason) if reason == "restricted: attachment is not accessible") + ); + } + // First-party owners upload avatars before the registered agent signs kind:0. + let agent = Keys::generate(); + state + .db + .ensure_user(tenant.community(), agent.public_key().as_bytes()) + .await + .unwrap(); + state + .db + .set_agent_owner( + tenant.community(), + agent.public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap(); + state + .db + .add_member( + tenant.community(), + channel, + agent.public_key().as_bytes(), + MemberRole::Member, + Some(owner.public_key().as_bytes()), + ) + .await + .unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(get(&agent, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::OK, + "owned agent has access before removal" + ); + state + .db + .remove_member( + tenant.community(), + channel, + agent.public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(get(&agent, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND, + "owned agent loses access after removal" + ); + let stolen_profile = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":url}).to_string(), + ) + .sign_with_keys(&agent) + .unwrap(); + assert!( + post(&state, &tenant, &agent, stolen_profile).await.is_err(), + "removed owned agent cannot turn owner-uploaded private media into its avatar" + ); + let avatar_bytes = b"new agent avatar"; + let avatar = hex::encode(Sha256::digest(avatar_bytes)); + state + .db + .record_media_upload(tenant.community(), &avatar, owner.public_key().as_bytes()) + .await + .unwrap(); + let sidecar = bucket + .objects + .lock() + .await + .get(&format!( + "{}/_meta/{}/{hash}.json", + state.config.media.s3_bucket, + tenant.community() + )) + .cloned() + .unwrap(); + bucket.objects.lock().await.insert( + format!( + "{}/_meta/{}/{avatar}.json", + state.config.media.s3_bucket, + tenant.community() + ), + sidecar, + ); + let picture = format!("http://{host}/media/{avatar}.{ext}"); + let forged = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":picture}).to_string(), + ) + .tags([Tag::parse([ + "imeta", + &format!("url {url}"), + &format!("x {hash}"), + "m application/octet-stream", + &format!("size {}", bytes.len()), + ]) + .unwrap()]) + .sign_with_keys(&agent) + .unwrap(); + assert!( + post(&state, &tenant, &agent, forged).await.is_err(), + "owner avatar delegation must not authorize unrelated attachments" + ); + let profile = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":picture}).to_string(), + ) + .sign_with_keys(&agent) + .unwrap(); + assert!( + post(&state, &tenant, &agent, profile.clone()) + .await + .is_err(), + "agent must not borrow owner upload proof" + ); + // The creation path transfers actual bytes with an agent-signed upload. + let upload = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, &host) + .header( + header::AUTHORIZATION, + proof(&agent, &host, &avatar, "upload"), + ) + .header("X-SHA-256", &avatar) + .header(header::CONTENT_TYPE, "application/octet-stream") + .body(Body::from(avatar_bytes.as_slice())) + .unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(upload) + .await + .unwrap() + .status(), + StatusCode::OK + ); + let created_profile = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":picture}).to_string(), + ) + .sign_with_keys(&agent) + .unwrap(); + post(&state, &tenant, &agent, created_profile) + .await + .expect("agent's own upload permits creation under enforce"); + let copy = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":url}).to_string(), + ) + .sign_with_keys(&member) + .unwrap(); + let request = Request::builder() + .method("POST") + .uri("/events") + .header(header::HOST, &host) + .header("x-pubkey", member.public_key().to_hex()) + .body(Body::from(copy.as_json())) + .unwrap(); + let response = crate::router::build_router(state.clone()) + .oneshot(request) + .await + .unwrap(); + let body = to_bytes(response.into_body(), 100_000).await.unwrap(); + assert!( + String::from_utf8_lossy(&body).contains("attachment is not accessible"), + "REST denial: {}", + String::from_utf8_lossy(&body) + ); + use buzz_workflow::action_sink::ActionSink; + let sink = crate::workflow_sink::RelayActionSink::new(&state); + let text = serde_json::json!({"picture":url}).to_string(); + let result = sink + .send_message( + tenant.community(), + &open.to_string(), + &text, + &text, + true, + &member.public_key().to_hex(), + None, + ) + .await; + assert!( + matches!(result, Err(buzz_workflow::action_sink::ActionSinkError::InvalidInput(ref reason)) if reason.contains("attachment is not accessible")), + "workflow copy must be denied" + ); + // A legitimate readable second share preserves access after one removal. + let shared = EventBuilder::new(Kind::Custom(9), "share") + .tags([ + Tag::parse(["h", &open.to_string()]).unwrap(), + Tag::parse(["imeta", &format!("url {url}"), "m application/octet-stream"]).unwrap(), + ]) + .sign_with_keys(&owner) + .unwrap(); + state + .db + .insert_event(tenant.community(), &shared, Some(open)) + .await + .unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(get(&member, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::OK, + "legacy URL-only share" + ); + reference_budget_postgres_tests::run(&state, &tenant, &host, &owner, &member, channel).await; + emoji_reference_postgres_tests::run(&state, &tenant, &host, &owner, &survivor).await; + reference_formats_postgres_tests::run( + &state, &tenant, &host, &owner, &member, &survivor, channel, + ) + .await; + // Every event kind has bounded publication work; shadow still accepts. + let mut emoji_tags = vec![Tag::parse(["d", "large"]).unwrap()]; + for n in 1000..1513 { + let emoji_hash = format!("{n:064x}"); + state + .db + .record_media_upload( + tenant.community(), + &emoji_hash, + owner.public_key().as_bytes(), + ) + .await + .unwrap(); + let sidecar = bucket + .objects + .lock() + .await + .get(&format!( + "{}/_meta/{}/{hash}.json", + state.config.media.s3_bucket, + tenant.community() + )) + .cloned() + .unwrap(); + bucket.objects.lock().await.insert( + format!( + "{}/_meta/{}/{emoji_hash}.json", + state.config.media.s3_bucket, + tenant.community() + ), + sidecar, + ); + emoji_tags.push( + Tag::parse([ + "emoji", + &format!("emoji{n}"), + &format!("http://{host}/media/{emoji_hash}.{ext}"), + ]) + .unwrap(), + ); + } + let shadow = fixture(&endpoint, super::media_access::MediaReadMode::Shadow).await; + // Shadow counts sidecar lookup errors and lets the serving path decide + // whether storage can supply bytes. Enforce still refuses these checks. + let broken_hash = "8".repeat(64); + let broken_key = format!( + "{}/_meta/{}/{broken_hash}.json", + state.config.media.s3_bucket, + tenant.community() + ); + for malformed in [false, true] { + if malformed { + bucket + .objects + .lock() + .await + .insert(broken_key.clone(), Bytes::from_static(b"not JSON")); + } + assert!( + super::media_access::enforce_read( + &shadow, + &tenant, + &broken_hash, + owner.public_key().as_bytes(), + buzz_media::auth::BlossomStrictness::Permissive, + ) + .await + .is_ok(), + "shadow must not refuse a sidecar lookup error" + ); + assert!(super::media_access::enforce_read( + &state, + &tenant, + &broken_hash, + owner.public_key().as_bytes(), + buzz_media::auth::BlossomStrictness::Permissive + ) + .await + .is_err()); + } + for kind in [10030, 30030] { + let large_set = EventBuilder::new(Kind::Custom(kind), "") + .tags(emoji_tags.clone()) + .sign_with_keys(&owner) + .unwrap(); + let reads = bucket.reads.load(Ordering::SeqCst); + let error = + crate::handlers::media_access::validate_media_references(&tenant, &state, &large_set) + .await + .unwrap_err(); + assert!( + matches!(error,crate::handlers::ingest::IngestError::Rejected(message) if message.contains("too many attachment")) + ); + assert_eq!( + bucket.reads.load(Ordering::SeqCst), + reads, + "over-limit emoji must stop before sidecar fan-out" + ); + crate::handlers::media_access::validate_media_references(&tenant, &shadow, &large_set) + .await + .unwrap(); + } + let bounded_set = EventBuilder::new(Kind::Custom(30030), "") + .tags(emoji_tags.into_iter().take(513)) + .sign_with_keys(&owner) + .unwrap(); + crate::handlers::media_access::validate_media_references(&tenant, &state, &bounded_set) + .await + .expect("512 emoji assets remain publishable"); + let many_tags: Vec = (0..513) + .map(|n| Tag::parse(["imeta", &format!("url http://{host}/media/{n:064x}.bin")]).unwrap()) + .collect(); + let oversized = EventBuilder::new(Kind::Custom(9), "") + .tags(many_tags) + .sign_with_keys(&owner) + .unwrap(); + let error = + crate::handlers::media_access::validate_media_references(&tenant, &state, &oversized) + .await + .unwrap_err(); + assert!( + matches!(error, crate::handlers::ingest::IngestError::Rejected(message) if message.contains("too many attachment")) + ); + crate::handlers::media_access::validate_media_references(&tenant, &shadow, &oversized) + .await + .expect("shadow counts and accepts publication cap"); + + let stale_profile = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":format!("http://{host}/media/{}.bin", "f".repeat(64))}) + .to_string(), + ) + .sign_with_keys(&owner) + .unwrap(); + crate::handlers::media_access::validate_media_references(&tenant, &shadow, &stale_profile) + .await + .expect("shadow accepts a missing sidecar"); + assert!( + crate::handlers::media_access::validate_media_references(&tenant, &state, &stale_profile) + .await + .is_err(), + "enforce rejects missing sidecars" + ); + // Inject a lookup error after a real existing sidecar: authorization fails closed. + sqlx::query("ALTER TABLE media_uploaders RENAME TO unavailable_media_uploaders") + .execute(state.db.pool()) + .await + .unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(get(&owner, &host, &hash, &hash, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::SERVICE_UNAVAILABLE + ); + crate::handlers::media_access::validate_media_references(&tenant, &shadow, &bounded_set) + .await + .expect("shadow accepts database lookup failures"); + let upload = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, &host) + .header(header::AUTHORIZATION, proof(&owner, &host, &hash, "upload")) + .header("X-SHA-256", &hash) + .header(header::CONTENT_TYPE, "application/octet-stream") + .body(Body::from(bytes.as_slice())) + .unwrap(); + assert_eq!( + router(shadow.clone()) + .oneshot(upload) + .await + .unwrap() + .status(), + StatusCode::OK, + "shadow upload accepts proof lookup failure" + ); + sqlx::query("ALTER TABLE unavailable_media_uploaders RENAME TO media_uploaders") + .execute(state.db.pool()) + .await + .unwrap(); + sqlx::query("ALTER TABLE media_publications RENAME TO unavailable_media_publications") + .execute(state.db.pool()) + .await + .unwrap(); + crate::handlers::media_access::validate_media_references(&tenant, &shadow, &bounded_set) + .await + .expect("shadow accepts publication recording failure"); + assert!( + crate::handlers::media_access::validate_media_references(&tenant, &state, &bounded_set) + .await + .is_err(), + "enforce rejects recording failure" + ); + let upload = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, &host) + .header(header::AUTHORIZATION, proof(&owner, &host, &hash, "upload")) + .header("X-SHA-256", &hash) + .header(header::CONTENT_TYPE, "application/octet-stream") + .body(Body::from(bytes.as_slice())) + .unwrap(); + assert_eq!( + router(shadow).oneshot(upload).await.unwrap().status(), + StatusCode::OK, + "shadow upload accepts marker recording failure" + ); + let absent = "f".repeat(64); + assert_eq!( + router(state.clone()) + .oneshot(get(&owner, &host, &absent, &absent, "GET", None)) + .await + .unwrap() + .status(), + StatusCode::NOT_FOUND, + "missing sidecar precedes broken DB" + ); + server.abort(); +} diff --git a/crates/buzz-relay/src/api/media_access_postgres_tests/cli_edit_postgres_tests.rs b/crates/buzz-relay/src/api/media_access_postgres_tests/cli_edit_postgres_tests.rs new file mode 100644 index 00000000000..e961ada4c8d --- /dev/null +++ b/crates/buzz-relay/src/api/media_access_postgres_tests/cli_edit_postgres_tests.rs @@ -0,0 +1,734 @@ +//! Exercise the real CLI, HTTP bridge, ingest, and media reads in enforce mode. +use super::*; + +// Keep the large ingest future off the enclosing test thread's stack. +async fn publish( + state: &Arc, + tenant: &buzz_core::TenantContext, + keys: &Keys, + event: nostr::Event, +) -> Result { + Box::pin(post(state, tenant, keys, event)).await +} + +async fn lookup( + state: &Arc, + host: &str, + keys: &Keys, + channel: Uuid, + target: nostr::EventId, +) -> (StatusCode, serde_json::Value) { + let body = serde_json::to_vec(&serde_json::json!([{"kinds":[9,40002,40008,45001,45003],"ids":[target.to_hex()],"#h":[channel.to_string()],"effective_edit":1,"consistency":"strong"}])).unwrap(); + let proof = EventBuilder::new(Kind::Custom(27235), "") + .tags([ + Tag::parse(["u", &format!("http://{host}/query")]).unwrap(), + Tag::parse(["method", "POST"]).unwrap(), + Tag::parse(["payload", &hex::encode(Sha256::digest(&body))]).unwrap(), + Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), + ]) + .sign_with_keys(keys) + .unwrap(); + let request = Request::builder() + .method("POST") + .uri("/query") + .header(header::HOST, host) + .header(header::CONTENT_TYPE, "application/json") + .header( + header::AUTHORIZATION, + format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD.encode(proof.as_json()) + ), + ) + .body(Body::from(body)) + .unwrap(); + let response = crate::router::build_router(state.clone()) + .oneshot(request) + .await + .unwrap(); + let status = response.status(); + ( + status, + serde_json::from_slice(&to_bytes(response.into_body(), 1_000_000).await.unwrap()).unwrap(), + ) +} + +async fn cli_edit(url: &str, keys: &Keys, id: nostr::EventId, clear: bool, content: &str) { + let mut args = vec![ + "buzz".to_owned(), + "--relay".into(), + url.into(), + "--private-key".into(), + keys.secret_key().to_secret_hex(), + "messages".into(), + "edit".into(), + "--event".into(), + id.to_hex(), + "--content".into(), + content.into(), + ]; + if clear { + args.push("--clear-attachments".into()); + } + assert_eq!( + Box::pin(buzz_cli::run_from_args(args)).await, + 0, + "CLI edit failed" + ); +} +async fn readable( + state: &Arc, + host: &str, + hashes: &[String], + keys: &[&Keys], + expected: &[StatusCode], +) { + for (hash, status) in hashes.iter().zip(expected) { + for key in keys { + for method in ["GET", "HEAD"] { + let response = router(state.clone()) + .oneshot(get(key, host, hash, hash, method, None)) + .await + .unwrap(); + assert_eq!(response.status(), *status, "{method} {hash}"); + assert_eq!( + response.headers()[header::CACHE_CONTROL], + "private, no-store" + ); + } + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cli_successive_edits_preserve_and_revoke_attachments() { + let bucket = Bucket::default(); + let s3_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", s3_listener.local_addr().unwrap()); + let service = Router::new() + .route("/{*key}", any(object)) + .with_state(bucket); + let s3_server = tokio::spawn(async move { + axum::serve(s3_listener, service).await.unwrap(); + }); + let state = fixture( + &endpoint, + super::super::media_access::MediaReadMode::Enforce, + ) + .await; + let http_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let host_string = http_listener.local_addr().unwrap().to_string(); + let host = host_string.as_str(); + state.db.ensure_configured_community(host).await.unwrap(); + let tenant = crate::tenant::bind_community(&state.db, host) + .await + .unwrap(); + let owner = Keys::generate(); + let member = Keys::generate(); + let outsider = Keys::generate(); + for key in [&owner, &member, &outsider] { + state + .db + .ensure_user(tenant.community(), key.public_key().as_bytes()) + .await + .unwrap(); + } + let channel = state + .db + .create_channel( + tenant.community(), + "cli-edit", + ChannelType::Stream, + ChannelVisibility::Private, + None, + owner.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id; + state + .db + .add_member( + tenant.community(), + channel, + member.public_key().as_bytes(), + MemberRole::Member, + Some(owner.public_key().as_bytes()), + ) + .await + .unwrap(); + let mut media = Vec::new(); + let mut hashes = Vec::new(); + for bytes in [ + b"cli retained file".as_slice(), + b"cli removed file".as_slice(), + ] { + let hash = hex::encode(Sha256::digest(bytes)); + let upload = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, host) + .header(header::AUTHORIZATION, proof(&owner, host, &hash, "upload")) + .header("X-SHA-256", &hash) + .body(Body::from(bytes)) + .unwrap(); + let response = router(state.clone()).oneshot(upload).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let descriptor: serde_json::Value = + serde_json::from_slice(&to_bytes(response.into_body(), 100_000).await.unwrap()) + .unwrap(); + media.push(vec![ + "imeta".into(), + format!("url {}", descriptor["url"].as_str().unwrap()), + format!("x {hash}"), + "m application/octet-stream".into(), + format!("size {}", bytes.len()), + "alt original label".into(), + ]); + hashes.push(hash); + } + let original = EventBuilder::new(Kind::Custom(9), "two files") + .tags( + std::iter::once(Tag::parse(["h", &channel.to_string()]).unwrap()) + .chain(media.iter().map(|t| Tag::parse(t.clone()).unwrap())), + ) + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() - 20)) + .sign_with_keys(&owner) + .unwrap(); + publish(&state, &tenant, &owner, original.clone()) + .await + .unwrap(); + let url = format!("http://{host}"); + let http_app = crate::router::build_router(state.clone()); + let http_server = tokio::spawn(async move { + axum::serve(http_listener, http_app).await.unwrap(); + }); + for index in 0..2 { + cli_edit( + &url, + &owner, + original.id, + false, + &format!("typo fix {index}"), + ) + .await; + readable( + &state, + host, + &hashes, + &[&owner, &member], + &[StatusCode::OK; 2], + ) + .await; + readable( + &state, + host, + &hashes, + &[&outsider], + &[StatusCode::NOT_FOUND; 2], + ) + .await; + } + // Model a desktop/SDK edit removing just the second file. Keep its URL in + // the body to prove text cannot grant access or revive removed imeta. + let body = format!("retained one, removed URL {}", media[1][1]); + let partial = buzz_sdk::build_edit_with_media(channel, original.id, &body, &media[..1]) + .unwrap() + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() + 5)) + .sign_with_keys(&owner) + .unwrap(); + publish(&state, &tenant, &owner, partial.clone()) + .await + .unwrap(); + for _ in 0..2 { + cli_edit(&url, &owner, original.id, false, &body).await; + readable( + &state, + host, + &hashes, + &[&owner, &member], + &[StatusCode::OK, StatusCode::NOT_FOUND], + ) + .await; + } + // A newer edit that restores both files is then deleted. Resolve the + // latest live edit, not this deleted replacement or the original. + let deleted = + buzz_sdk::build_edit_with_media(channel, original.id, "deleted replacement", &media) + .unwrap() + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() + 20)) + .sign_with_keys(&owner) + .unwrap(); + // Seed a historical deleted replacement without publishing a new live + // restoration. The uploader still has authority to republish these bytes. + state + .db + .insert_event(tenant.community(), &deleted, Some(channel)) + .await + .unwrap(); + state + .db + .soft_delete_event_and_update_thread(tenant.community(), deleted.id.as_bytes(), None, None) + .await + .unwrap(); + cli_edit(&url, &owner, original.id, false, &body).await; + readable( + &state, + host, + &hashes, + &[&owner, &member], + &[StatusCode::OK, StatusCode::NOT_FOUND], + ) + .await; + cli_edit(&url, &owner, original.id, true, &body).await; + cli_edit(&url, &owner, original.id, false, &body).await; + readable( + &state, + host, + &hashes, + &[&owner, &member], + &[StatusCode::NOT_FOUND; 2], + ) + .await; + + // Mixed-case removal must stay removed from this message even when a + // second live reference would authorize republication of the same bytes. + let second = EventBuilder::new(Kind::Custom(9), "another reference") + .tags( + std::iter::once(Tag::parse(["h", &channel.to_string()]).unwrap()) + .chain(media[..1].iter().map(|t| Tag::parse(t.clone()).unwrap())), + ) + .sign_with_keys(&owner) + .unwrap(); + publish(&state, &tenant, &owner, second.clone()) + .await + .unwrap(); + let restored = buzz_sdk::build_edit_with_media(channel, original.id, "both", &media) + .unwrap() + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() + 30)) + .sign_with_keys(&owner) + .unwrap(); + publish(&state, &tenant, &owner, restored).await.unwrap(); + let mixed = original + .id + .to_hex() + .chars() + .enumerate() + .map(|(i, c)| { + if i % 2 == 0 { + c.to_ascii_uppercase() + } else { + c + } + }) + .collect::(); + let removal = EventBuilder::new(Kind::Custom(40003), "only second") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["e", &mixed]).unwrap(), + Tag::parse(media[1].clone()).unwrap(), + ]) + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() + 31)) + .sign_with_keys(&owner) + .unwrap(); + publish(&state, &tenant, &owner, removal).await.unwrap(); + cli_edit(&url, &owner, original.id, false, "after mixed-case removal").await; + let current = state + .db + .message_edit_state( + tenant.community(), + channel, + original.id.as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap() + .unwrap() + .edit + .unwrap(); + let carried: Vec<_> = current + .tags + .iter() + .filter(|t| t.as_slice()[0] == "imeta") + .map(|t| t.as_slice().to_vec()) + .collect(); + assert_eq!( + carried, + vec![media[1].clone()], + "must not resurrect the first file" + ); + readable( + &state, + host, + &hashes, + &[&owner, &member], + &[StatusCode::OK; 2], + ) + .await; + state + .db + .soft_delete_event_and_update_thread(tenant.community(), second.id.as_bytes(), None, None) + .await + .unwrap(); + readable( + &state, + host, + &hashes, + &[&owner, &member], + &[StatusCode::NOT_FOUND, StatusCode::OK], + ) + .await; + + // An agent owner outside this private channel has no attachment read or + // publication authority. A direct retaining edit must also be rejected. + state + .db + .set_agent_owner( + tenant.community(), + owner.public_key().as_bytes(), + outsider.public_key().as_bytes(), + ) + .await + .unwrap(); + let owner_edit = + buzz_sdk::build_edit_with_media(channel, original.id, "owner edit", &media[1..]) + .unwrap() + .sign_with_keys(&outsider) + .unwrap(); + let Err(error) = publish(&state, &tenant, &outsider, owner_edit).await else { + panic!("owner edit was accepted"); + }; + assert!( + matches!(error, crate::handlers::ingest::IngestError::Rejected(ref reason) + if reason == "restricted: attachment is not accessible"), + "{error:?}" + ); + assert_ne!( + Box::pin(buzz_cli::run_from_args(vec![ + "buzz".to_string(), + "--relay".into(), + url.clone(), + "--private-key".into(), + outsider.secret_key().to_secret_hex(), + "messages".into(), + "edit".into(), + "--event".into(), + original.id.to_hex(), + "--content".into(), + "owner edit".into() + ])) + .await, + 0 + ); + + // Knowing a private hash never lets another member attach it to their own + // message/edit. This exercises the common publication check on kind 40003. + let open = state + .db + .create_channel( + tenant.community(), + "attacker", + ChannelType::Stream, + ChannelVisibility::Open, + None, + outsider.public_key().as_bytes(), + None, + ) + .await + .unwrap() + .id; + let harmless = EventBuilder::new(Kind::Custom(9), "no files") + .tags([Tag::parse(["h", &open.to_string()]).unwrap()]) + .sign_with_keys(&outsider) + .unwrap(); + publish(&state, &tenant, &outsider, harmless.clone()) + .await + .unwrap(); + let copied = buzz_sdk::build_edit_with_media(open, harmless.id, "stolen", &media) + .unwrap() + .sign_with_keys(&outsider) + .unwrap(); + assert!(publish(&state, &tenant, &outsider, copied).await.is_err()); + readable( + &state, + host, + &hashes, + &[&outsider], + &[StatusCode::NOT_FOUND; 2], + ) + .await; + let additional_targets = Box::pin(governed_kinds_journey( + &state, &tenant, host, &url, channel, open, &owner, &member, &outsider, + )) + .await; + for kind in [40003, 7, 45002] { + let unsupported = EventBuilder::new(Kind::Custom(kind), "unsupported lookup target") + .tags([Tag::parse(["h", &open.to_string()]).unwrap()]) + .sign_with_keys(&outsider) + .unwrap(); + state + .db + .insert_event(tenant.community(), &unsupported, Some(open)) + .await + .unwrap(); + assert_eq!( + lookup(&state, host, &member, open, unsupported.id).await.0, + StatusCode::NOT_FOUND + ); + } + let forbidden = lookup(&state, host, &outsider, channel, original.id).await; + let missing = lookup( + &state, + host, + &outsider, + channel, + nostr::EventId::from_byte_array([0x42; 32]), + ) + .await; + assert_eq!( + forbidden, missing, + "inaccessible and missing states must be indistinguishable" + ); + assert_eq!(forbidden.0, StatusCode::NOT_FOUND); + state + .db + .remove_member( + tenant.community(), + channel, + member.public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .unwrap(); + assert_eq!( + lookup(&state, host, &member, channel, original.id).await, + missing, + "fresh snapshot must reject a removed member" + ); + for target in additional_targets { + assert_eq!( + lookup(&state, host, &member, channel, target).await, + missing, + "removed member must not read added target kind" + ); + } + assert_eq!( + lookup(&state, host, &member, open, harmless.id).await.0, + StatusCode::OK, + "open-channel reader needs no membership" + ); + http_server.abort(); + s3_server.abort(); +} + +// Keep this larger journey's future separately allocated on the default stack. +#[allow(clippy::too_many_arguments)] +async fn governed_kinds_journey( + state: &Arc, + tenant: &buzz_core::TenantContext, + host: &str, + url: &str, + channel: Uuid, + open: Uuid, + owner: &Keys, + member: &Keys, + outsider: &Keys, +) -> Vec { + let mut targets = Vec::new(); + for kind in [9, 40002, 40008, 45001, 45003] { + // Each original has isolated A/B bytes. Only the signer uploaded them; + // the member reader has no upload grant or alternate live reference. + let mut tags = Vec::new(); + let mut hashes = Vec::new(); + for label in ["A", "B"] { + let bytes = format!("kind {kind} {label} {}", Uuid::new_v4()).into_bytes(); + let hash = hex::encode(Sha256::digest(&bytes)); + let response = router(state.clone()) + .oneshot( + Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, host) + .header(header::AUTHORIZATION, proof(owner, host, &hash, "upload")) + .header("X-SHA-256", &hash) + .body(Body::from(bytes.clone())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let descriptor: serde_json::Value = + serde_json::from_slice(&to_bytes(response.into_body(), 100_000).await.unwrap()) + .unwrap(); + tags.push(vec![ + "imeta".into(), + format!("url {}", descriptor["url"].as_str().unwrap()), + format!("x {hash}"), + "m application/octet-stream".into(), + format!("size {}", bytes.len()), + ]); + hashes.push(hash); + } + // Creation schemas differ by surface; seed signed originals, then use + // the real HTTP lookup, CLI, ingest and media handlers for every edit. + let source = EventBuilder::new(Kind::Custom(kind), "original A") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(tags[0].clone()).unwrap(), + ]) + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() - 20)) + .sign_with_keys(owner) + .unwrap(); + state + .db + .insert_event(tenant.community(), &source, Some(channel)) + .await + .unwrap(); + targets.push(source.id); + let denied = lookup(state, host, outsider, channel, source.id).await; + let absent = lookup( + state, + host, + outsider, + channel, + nostr::EventId::from_byte_array([0x43; 32]), + ) + .await; + assert_eq!(denied, absent, "kind {kind} leaks private state"); + assert_eq!(denied.0, StatusCode::NOT_FOUND); + let retaining = + buzz_sdk::build_edit_with_media(channel, source.id, "unauthorized owner", &tags[..1]) + .unwrap() + .sign_with_keys(outsider) + .unwrap(); + let Err(error) = publish(state, tenant, outsider, retaining).await else { + panic!("owner gained media access for kind {kind}") + }; + assert!( + matches!(error,crate::handlers::ingest::IngestError::Rejected(ref reason) if reason=="restricted: attachment is not accessible"), + "{error:?}" + ); + readable( + state, + host, + &hashes, + &[member], + &[StatusCode::OK, StatusCode::NOT_FOUND], + ) + .await; + let replacement = + buzz_sdk::build_edit_with_media(channel, source.id, "replace A with B", &tags[1..]) + .unwrap() + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() - 1)) + .sign_with_keys(owner) + .unwrap(); + publish(state, tenant, owner, replacement).await.unwrap(); + for (clear, content, expected) in [ + (false, "retain B", &tags[1..]), + (true, "clear", &tags[0..0]), + (false, "still empty", &tags[0..0]), + ] { + cli_edit(url, owner, source.id, clear, content).await; + let (status, snapshot) = lookup(state, host, member, channel, source.id).await; + assert_eq!(status, StatusCode::OK); + let edit: nostr::Event = serde_json::from_value(snapshot["edit"].clone()).unwrap(); + assert_eq!(edit.content, content); + let carried: Vec<_> = edit + .tags + .iter() + .filter(|t| t.as_slice()[0] == "imeta") + .map(|t| t.as_slice().to_vec()) + .collect(); + assert_eq!(carried, expected, "kind {kind} metadata"); + readable( + state, + host, + &hashes, + &[member], + &[ + StatusCode::NOT_FOUND, + if expected.is_empty() { + StatusCode::NOT_FOUND + } else { + StatusCode::OK + }, + ], + ) + .await; + } + if kind == 45001 { + // A is no longer referenced by the attachment journey. Give only + // this forum original a snapshot reference, with no reader grant. + let image_url = tags[0][1].strip_prefix("url ").unwrap(); + let preview = EventBuilder::new(Kind::Custom(kind), "forum preview") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse([ + "link-preview", + "snapshot", + "1", + "https://example.org/page", + "title", + "site", + "description", + image_url, + &hashes[0], + "", + "", + ]) + .unwrap(), + ]) + .custom_created_at(Timestamp::from(Timestamp::now().as_secs() - 20)) + .sign_with_keys(owner) + .unwrap(); + state + .db + .insert_event(tenant.community(), &preview, Some(channel)) + .await + .unwrap(); + readable(state, host, &hashes[..1], &[member], &[StatusCode::OK]).await; + cli_edit(url, owner, preview.id, false, "keep forum preview").await; + readable(state, host, &hashes[..1], &[member], &[StatusCode::OK]).await; + let suppressed = + buzz_sdk::build_edit_with_media(channel, preview.id, "hide preview", &[]) + .unwrap() + .tags([Tag::parse(["link-preview", "none"]).unwrap()]) + .sign_with_keys(owner) + .unwrap(); + publish(state, tenant, owner, suppressed).await.unwrap(); + readable( + state, + host, + &hashes[..1], + &[member], + &[StatusCode::NOT_FOUND], + ) + .await; + cli_edit(url, owner, preview.id, false, "preview stays hidden").await; + readable( + state, + host, + &hashes[..1], + &[member], + &[StatusCode::NOT_FOUND], + ) + .await; + } + let public = EventBuilder::new(Kind::Custom(kind), "public original") + .tags([Tag::parse(["h", &open.to_string()]).unwrap()]) + .sign_with_keys(outsider) + .unwrap(); + state + .db + .insert_event(tenant.community(), &public, Some(open)) + .await + .unwrap(); + assert_eq!( + lookup(state, host, member, open, public.id).await.0, + StatusCode::OK + ); + } + targets +} diff --git a/crates/buzz-relay/src/api/media_access_postgres_tests/emoji_reference_postgres_tests.rs b/crates/buzz-relay/src/api/media_access_postgres_tests/emoji_reference_postgres_tests.rs new file mode 100644 index 00000000000..17d2f78db6a --- /dev/null +++ b/crates/buzz-relay/src/api/media_access_postgres_tests/emoji_reference_postgres_tests.rs @@ -0,0 +1,77 @@ +use super::*; + +// Extend the enforce-mode HTTP journey, including replacement of a shortcode. +pub(super) async fn run( + state: &Arc, + tenant: &buzz_core::TenantContext, + host: &str, + owner: &Keys, + member: &Keys, +) { + let mut hashes = std::collections::HashSet::new(); + for kind in [30180, 30030, 10030] { + let mut previous: Option = None; + for revision in 0..2 { + // Unique payloads cannot borrow another journey step's reference. + let bytes = + format!("emoji-media-authorization-{kind}-revision-{revision}").into_bytes(); + let hash = hex::encode(Sha256::digest(&bytes)); + assert!( + hashes.insert(hash.clone()), + "emoji fixtures must have distinct hashes" + ); + let request = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, host) + .header(header::AUTHORIZATION, proof(owner, host, &hash, "upload")) + .header("X-SHA-256", &hash) + .body(Body::from(bytes)) + .unwrap(); + let response = router(state.clone()).oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK, "upload kind {kind}"); + let body = to_bytes(response.into_body(), 100_000).await.unwrap(); + let descriptor: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let url = descriptor["url"].as_str().unwrap(); + // The asset is fresh: only the uploader can preview it. + for (keys, expected) in [(owner, StatusCode::OK), (member, StatusCode::NOT_FOUND)] { + check(state, host, keys, &hash, expected).await; + } + let builder = if kind == 30180 { + buzz_sdk::build_emoji_entry("media_test", url).unwrap() + } else { + EventBuilder::new(Kind::Custom(kind), "").tags([ + Tag::parse(["d", "media_test"]).unwrap(), + Tag::parse(["emoji", "media_test", url]).unwrap(), + ]) + }; + let event = builder + .custom_created_at(Timestamp::from( + Timestamp::now().as_secs() + revision as u64, + )) + .sign_with_keys(owner) + .unwrap(); + post(state, tenant, owner, event).await.unwrap(); + for keys in [owner, member] { + check(state, host, keys, &hash, StatusCode::OK).await; + if let Some(old_hash) = &previous { + // Replacing an entry/set retires the old reference and cannot + // revive uploader preview after publication consumed it. + check(state, host, keys, old_hash, StatusCode::NOT_FOUND).await; + } + } + previous = Some(hash); + } + } + assert_eq!(hashes.len(), 6); +} + +async fn check(state: &Arc, host: &str, keys: &Keys, hash: &str, status: StatusCode) { + for method in ["GET", "HEAD"] { + let response = router(state.clone()) + .oneshot(get(keys, host, hash, hash, method, None)) + .await + .unwrap(); + assert_eq!(response.status(), status, "emoji {method} {hash}"); + } +} diff --git a/crates/buzz-relay/src/api/media_access_postgres_tests/reference_budget_postgres_tests.rs b/crates/buzz-relay/src/api/media_access_postgres_tests/reference_budget_postgres_tests.rs new file mode 100644 index 00000000000..82da98b503d --- /dev/null +++ b/crates/buzz-relay/src/api/media_access_postgres_tests/reference_budget_postgres_tests.rs @@ -0,0 +1,97 @@ +use super::*; + +pub(super) async fn run( + state: &Arc, + tenant: &buzz_core::TenantContext, + host: &str, + owner: &Keys, + member: &Keys, + channel: Uuid, +) { + let bytes = b"reference-budget-avatar-review21"; + let hash = hex::encode(Sha256::digest(bytes)); + let request = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, host) + .header(header::AUTHORIZATION, proof(owner, host, &hash, "upload")) + .header("X-SHA-256", &hash) + .body(Body::from(bytes.as_slice())) + .unwrap(); + let response = router(state.clone()).oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let descriptor: serde_json::Value = + serde_json::from_slice(&to_bytes(response.into_body(), 100_000).await.unwrap()).unwrap(); + let url = descriptor["url"].as_str().unwrap(); + let profile = EventBuilder::new( + Kind::Metadata, + serde_json::json!({"picture":url}).to_string(), + ) + .sign_with_keys(owner) + .unwrap(); + post(state, tenant, owner, profile.clone()).await.unwrap(); + + // New artifacts must reject x-only imeta rather than accepting more decoys. + let artifact = EventBuilder::new(Kind::Custom(45010), "budget fixture") + .tags([ + Tag::parse(["ar", "1"]).unwrap(), + Tag::parse(["d", &Uuid::new_v4().to_string()]).unwrap(), + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["type", "buzz.task"]).unwrap(), + Tag::parse(["op", "create"]).unwrap(), + Tag::parse(["title", "Budget fixture"]).unwrap(), + Tag::parse(["imeta", &format!("x {hash}")]).unwrap(), + ]) + .sign_with_keys(owner) + .unwrap(); + let Err(crate::handlers::ingest::IngestError::Rejected(message)) = + post(state, tenant, owner, artifact).await + else { + panic!("expected invalid artifact imeta rejection"); + }; + assert!(message.contains("url"), "{message}"); + + // Simulate historical artifact rows, including containment decoys where the + // URL is on a separate tag. Neither is a same-tag media reference. + sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig,channel_id) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),$2,'2025-01-01'::timestamptz,45010,$3,'decoy',decode(repeat('00',64),'hex'),$4 FROM generate_series(21000,22025) n") + .bind(tenant.community().as_uuid()).bind(owner.public_key().as_bytes().as_slice()) + .bind(serde_json::json!([["imeta",format!("x {hash}")],["other",format!("url {url}")]])) + .bind(channel).execute(state.db.pool()).await.unwrap(); + // Raw-content matches in malformed or large non-image fields must not + // consume the byte budget before the real profile is examined. + let padded = serde_json::json!({"about":format!("{hash}{}","a".repeat(256*1024)),"picture":null,"image":url}).to_string(); + let profiles: Vec<_> = (0..71) + .map(|_| { + let event = EventBuilder::new(Kind::Metadata, &padded) + .custom_created_at(Timestamp::from(1_735_689_600)) + .sign_with_keys(&Keys::generate()) + .unwrap(); + serde_json::to_value(event).unwrap() + }) + .collect(); + sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig) SELECT $1,decode(p->>'id','hex'),decode(p->>'pubkey','hex'),to_timestamp((p->>'created_at')::bigint),0,p->'tags',p->>'content',decode(p->>'sig','hex') FROM jsonb_array_elements($2) p") + .bind(tenant.community().as_uuid()).bind(serde_json::Value::Array(profiles)) + .execute(state.db.pool()).await.unwrap(); + sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig) VALUES($1,decode(repeat('ab',32),'hex'),$2,now(),0,'[]',$3,decode(repeat('00',64),'hex'))") + .bind(tenant.community().as_uuid()).bind(member.public_key().as_bytes().as_slice()) + .bind(format!("not JSON {hash}")).execute(state.db.pool()).await.unwrap(); + for keys in [owner, member] { + for method in ["GET", "HEAD"] { + let response = router(state.clone()) + .oneshot(get(keys, host, &hash, &hash, method, None)) + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::OK, + "avatar remains readable beside >1024 x-only artifacts" + ); + } + } + sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(tenant.community().as_uuid()) + .bind(profile.id.as_bytes().as_slice()) + .execute(state.db.pool()) + .await + .unwrap(); +} diff --git a/crates/buzz-relay/src/api/media_access_postgres_tests/reference_formats_postgres_tests.rs b/crates/buzz-relay/src/api/media_access_postgres_tests/reference_formats_postgres_tests.rs new file mode 100644 index 00000000000..1985509bd68 --- /dev/null +++ b/crates/buzz-relay/src/api/media_access_postgres_tests/reference_formats_postgres_tests.rs @@ -0,0 +1,254 @@ +use super::*; + +// Exercise the client wire formats through real upload, ingest and download paths. +pub(super) async fn run( + state: &Arc, + tenant: &buzz_core::TenantContext, + host: &str, + owner: &Keys, + member: &Keys, + survivor: &Keys, + channel: Uuid, +) { + let images: [&[u8]; 2] = [ + include_bytes!("../../../../buzz-media/tests/fixtures/ios/uikit-sanitized.png"), + include_bytes!( + "../../../../buzz-media/tests/fixtures/android/sanitized/bitmap-srgb-sanitized.png" + ), + ]; + for (index, format) in ["snapshot", "animated", "image"].into_iter().enumerate() { + let mut assets = Vec::new(); + for bytes in images { + let hash = hex::encode(Sha256::digest(bytes)); + let request = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, host) + .header(header::AUTHORIZATION, proof(owner, host, &hash, "upload")) + .header("X-SHA-256", &hash) + .body(Body::from(bytes)) + .unwrap(); + let response = router(state.clone()).oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = to_bytes(response.into_body(), 100_000).await.unwrap(); + let descriptor: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assets.push((hash, descriptor["url"].as_str().unwrap().to_owned())); + } + let [(image_hash, image), (favicon_hash, favicon)] = assets.as_slice() else { + unreachable!() + }; + let (kind,content,tags) = match format { + "snapshot" => (Kind::Custom(9),"https://example.com/page".to_owned(),vec![ + Tag::parse(["h",&channel.to_string()]).unwrap(), + Tag::parse(["link-preview","snapshot","1","https://example.com/page","title","site","description",image,image_hash,favicon,favicon_hash]).unwrap(), + ]), + "animated" => (Kind::Metadata,serde_json::json!({"picture":format!("{image}#buzz-anim={}",url::form_urlencoded::byte_serialize(favicon.as_bytes()).collect::())}).to_string(),vec![]), + _ => (Kind::Metadata,serde_json::json!({"image":image,"banner":favicon}).to_string(),vec![]), + }; + // Owning an account or knowing a descriptor never substitutes for bytes. + let copied = EventBuilder::new(kind, &content) + .tags(tags.clone()) + .sign_with_keys(member) + .unwrap(); + assert!( + crate::handlers::media_access::validate_media_references(tenant, state, &copied) + .await + .is_err(), + "copied {format}" + ); + if format == "animated" { + let request = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, host) + .header( + header::AUTHORIZATION, + proof(member, host, image_hash, "upload"), + ) + .header("X-SHA-256", image_hash) + .body(Body::from(images[0])) + .unwrap(); + assert_eq!( + router(state.clone()) + .oneshot(request) + .await + .unwrap() + .status(), + StatusCode::OK + ); + assert!( + crate::handlers::media_access::validate_media_references(tenant, state, &copied) + .await + .is_err(), + "owning only the poster cannot publish the private animation" + ); + } + let event = EventBuilder::new(kind, content) + .tags(tags) + .custom_created_at(Timestamp::from( + Timestamp::now().as_secs() + 30 + index as u64, + )) + .sign_with_keys(owner) + .unwrap(); + post(state, tenant, owner, event.clone()).await.unwrap(); + for (hash, _) in &assets { + for keys in [owner, survivor] { + let response = router(state.clone()) + .oneshot(get(keys, host, hash, hash, "GET", None)) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK, "posted {format}"); + } + let response = router(state.clone()) + .oneshot(get(member, host, hash, hash, "GET", None)) + .await + .unwrap(); + assert_eq!( + response.status(), + if format == "snapshot" { + StatusCode::NOT_FOUND + } else { + StatusCode::OK + } + ); + } + if format == "snapshot" { + for (revision, suppress) in [(1, false), (2, true), (3, false)] { + let mut tags = vec![ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["e", &event.id.to_hex()]).unwrap(), + ]; + if suppress { + tags.push(Tag::parse(["link-preview", "none"]).unwrap()); + } + let edit = + EventBuilder::new(Kind::Custom(40003), "edited https://example.com/page") + .tags(tags) + .custom_created_at(Timestamp::from(event.created_at.as_secs() + revision)) + .sign_with_keys(owner) + .unwrap(); + post(state, tenant, owner, edit).await.unwrap(); + for (hash, _) in &assets { + for keys in [owner, survivor, member] { + for method in ["GET", "HEAD"] { + let response = router(state.clone()) + .oneshot(get(keys, host, hash, hash, method, None)) + .await + .unwrap(); + assert_eq!( + response.status(), + if revision >= 2 || keys.public_key() == member.public_key() { + StatusCode::NOT_FOUND + } else { + StatusCode::OK + }, + "latest edit preview suppression={suppress}" + ); + } + } + } + } + } + sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") + .bind(tenant.community().as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .execute(state.db.pool()) + .await + .unwrap(); + for (hash, _) in &assets { + let response = router(state.clone()) + .oneshot(get(owner, host, hash, hash, "GET", None)) + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::NOT_FOUND, + "deleting {format} must not revive uploader preview" + ); + } + } + // Persona definitions are readable only by their owner until shared. Each + // gets fresh bytes so another profile cannot hide a missing reference. + for shared in [false, true] { + let bytes = format!("persona-media-review21-shared-{shared}"); + let hash = hex::encode(Sha256::digest(bytes.as_bytes())); + let request = Request::builder() + .method("PUT") + .uri("/upload") + .header(header::HOST, host) + .header(header::AUTHORIZATION, proof(owner, host, &hash, "upload")) + .header("X-SHA-256", &hash) + .body(Body::from(bytes)) + .unwrap(); + let response = router(state.clone()).oneshot(request).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let descriptor: serde_json::Value = + serde_json::from_slice(&to_bytes(response.into_body(), 100_000).await.unwrap()) + .unwrap(); + let mut tags = vec![Tag::parse([ + "d", + if shared { + "shared-media" + } else { + "private-media" + }, + ]) + .unwrap()]; + if shared { + tags.push(Tag::parse(["shared", "true"]).unwrap()); + } + let persona = EventBuilder::new( + Kind::Custom(30175), + serde_json::json!({"name":"Media persona","avatar_url":descriptor["url"]}).to_string(), + ) + .tags(tags) + .sign_with_keys(owner) + .unwrap(); + post(state, tenant, owner, persona).await.unwrap(); + for keys in [owner, member] { + let report = EventBuilder::new(Kind::Custom(1984), "media report") + .allow_self_tagging() + .tags([ + Tag::parse(["p", &owner.public_key().to_hex()]).unwrap(), + Tag::parse(["x", &hash, "spam"]).unwrap(), + ]) + .sign_with_keys(keys) + .unwrap(); + let result = post(state, tenant, keys, report).await; + if shared || keys.public_key() == owner.public_key() { + if let Err(error) = result { + panic!("readable persona blob report shared={shared}: {error:?}"); + } + } else { + assert!( + matches!(result,Err(crate::handlers::ingest::IngestError::Rejected(message)) if message.contains("report target blob not found")) + ); + let absent = EventBuilder::new(Kind::Custom(1984), "missing report") + .tags([ + Tag::parse(["p", &owner.public_key().to_hex()]).unwrap(), + Tag::parse(["x", &"9".repeat(64), "spam"]).unwrap(), + ]) + .sign_with_keys(keys) + .unwrap(); + assert!( + matches!(post(state,tenant,keys,absent).await,Err(crate::handlers::ingest::IngestError::Rejected(message)) if message.contains("report target blob not found")) + ); + } + for method in ["GET", "HEAD"] { + let response = router(state.clone()) + .oneshot(get(keys, host, &hash, &hash, method, None)) + .await + .unwrap(); + assert_eq!( + response.status(), + if shared || keys.public_key() == owner.public_key() { + StatusCode::OK + } else { + StatusCode::NOT_FOUND + }, + "persona shared={shared}" + ); + } + } + } +} diff --git a/crates/buzz-relay/src/api/mesh_demo.rs b/crates/buzz-relay/src/api/mesh_demo.rs index 8649b97671a..e2b282b9b71 100644 --- a/crates/buzz-relay/src/api/mesh_demo.rs +++ b/crates/buzz-relay/src/api/mesh_demo.rs @@ -159,18 +159,16 @@ mod tests { use super::*; use crate::tunnel::directory::SessionDirectory; - fn pool() -> deadpool_redis::Pool { + fn pool() -> buzz_pubsub::RedisConnection { let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); - deadpool_redis::Config::from_url(url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("create redis pool") + buzz_pubsub::redis_connection(&url).expect("create redis pool") } async fn redis_directory_if_available() -> Option { let pool = pool(); - let mut conn = pool.get().await.ok()?; + let mut conn = pool.clone(); redis::cmd("PING") - .query_async::(&mut *conn) + .query_async::(&mut conn) .await .ok()?; Some(SessionDirectory::with_lease_ttl( @@ -336,8 +334,9 @@ mod tests { }, ) .await; - assert_eq!(resp.status(), StatusCode::OK); + let status = resp.status(); let body = body_json(resp).await; + assert_eq!(status, StatusCode::OK, "forwarded response: {body}"); assert_eq!(body["outcome"], "forwarded"); assert_eq!(body["echoed_payload"], "mesh echo evidence"); owner_task.abort(); diff --git a/crates/buzz-relay/src/api/mod.rs b/crates/buzz-relay/src/api/mod.rs index 50946748bb0..b0641a09ce9 100644 --- a/crates/buzz-relay/src/api/mod.rs +++ b/crates/buzz-relay/src/api/mod.rs @@ -8,6 +8,8 @@ pub mod gifs; pub mod git; pub mod invites; pub mod media; +/// Channel-aware media authorization. +pub mod media_access; pub mod mesh_demo; pub mod nip05; pub mod nip_fi; @@ -35,17 +37,45 @@ pub(crate) fn internal_error(msg: &str) -> (StatusCode, Json) /// would re-run the same expensive query. pub(crate) const QUERY_TIMED_OUT: &str = "query timed out"; +/// Stable client-visible body for a read the relay could not get a database +/// connection for (pool timeout, closed pool, socket failure), including a +/// history read shed because the reader is busy. Transient: retry later. +pub(crate) const DATABASE_UNAVAILABLE: &str = "database unavailable"; + /// Map a DB read failure: a statement-deadline cancel becomes a distinct -/// 503 `query timed out`; anything else stays a generic 500. +/// 503 `query timed out`, an unreachable or saturated database a 503 +/// `database unavailable`; anything else stays a generic 500. pub(crate) fn db_read_error( context: &str, e: &buzz_db::DbError, ) -> (StatusCode, Json) { - if e.is_statement_cancelled() { - tracing::warn!("{context}: {e}"); + if e.is_connection_unavailable() { + tracing::warn!(error_kind = %e.kind(), "{context}"); + return api_error(StatusCode::SERVICE_UNAVAILABLE, DATABASE_UNAVAILABLE); + } + read_error(context, e.is_statement_cancelled(), e.kind()) +} + +/// [`db_read_error`] for a search: a search cancelled by the search pool's +/// statement timeout gets the same 503 `query timed out`. +pub(crate) fn search_read_error( + context: &str, + e: &buzz_search::SearchError, +) -> (StatusCode, Json) { + read_error(context, e.is_statement_cancelled(), e.kind()) +} + +/// Only the error kind is logged: DB error text can repeat a bound value. +fn read_error( + context: &str, + statement_cancelled: bool, + kind: String, +) -> (StatusCode, Json) { + if statement_cancelled { + tracing::warn!(error_kind = %kind, "{context}"); return api_error(StatusCode::SERVICE_UNAVAILABLE, QUERY_TIMED_OUT); } - internal_error(&format!("{context}: {e}")) + internal_error(&format!("{context}: {kind}")) } #[allow(dead_code)] @@ -88,6 +118,7 @@ pub mod relay_members { use buzz_core::{tenant::CommunityId, TenantContext}; use tracing::{debug, info}; + use crate::access::AuthReason; use crate::state::AppState; /// Transport-neutral outcome of a relay-membership check. @@ -103,39 +134,48 @@ pub mod relay_members { Denied, } - /// An HTTP relay-membership refusal. + /// An HTTP relay-membership refusal, with its access-log reason. #[derive(Debug)] - pub enum MembershipRefusal { + pub(crate) enum MembershipRefusal { /// The relay's own JSON refusal. - Api((StatusCode, Json)), + Api(AuthReason, (StatusCode, Json)), /// NIP-FI's fixed denial. A request carrying a verified agent token /// gets only this, so the response never shows which step refused it /// or whether the agent already has a stored owner. - NipFi(DenialClass), + NipFi(AuthReason, DenialClass), } + /// A refusal decided inside [`admit_member`], before the agent-token + /// rule picks its response shape, with shadow's `owner` reason when the + /// agent token's owner decided it. + type Refused = ( + AuthReason, + (StatusCode, Json), + Option<&'static str>, + ); + impl MembershipRefusal { + /// The access-log result for this refusal. + pub(crate) fn auth_result(&self) -> crate::access::AuthResult { + let (Self::Api(reason, _) | Self::NipFi(reason, _)) = self; + crate::access::AuthResult::Denied(*reason) + } + /// The response status. pub fn status(&self) -> StatusCode { match self { - Self::Api((status, _)) => *status, - Self::NipFi(class) => StatusCode::from_u16(class.http_status()) + Self::Api(_, (status, _)) => *status, + Self::NipFi(_, class) => StatusCode::from_u16(class.http_status()) .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), } } } - impl From<(StatusCode, Json)> for MembershipRefusal { - fn from(refusal: (StatusCode, Json)) -> Self { - Self::Api(refusal) - } - } - impl IntoResponse for MembershipRefusal { fn into_response(self) -> Response { match self { - Self::Api(refusal) => refusal.into_response(), - Self::NipFi(class) => crate::nip_fi_core::http_denial(class), + Self::Api(_, refusal) => refusal.into_response(), + Self::NipFi(_, class) => crate::nip_fi_core::http_denial(class), } } } @@ -300,31 +340,7 @@ pub mod relay_members { /// /// Returns `Ok(None)` when the caller is a direct member (closed relay) or when /// no NIP-OA tag is present/applicable (open relay without auth tag). - pub async fn enforce_relay_membership( - state: &AppState, - tenant: &TenantContext, - pubkey_bytes: &[u8], - auth_tag_header: Option<&str>, - signed_auth_created_at: Option, - token_owner: Option, - ) -> Result, MembershipRefusal> { - enforce_membership( - state, - tenant, - pubkey_bytes, - auth_tag_header, - signed_auth_created_at, - token_owner, - false, - ) - .await - } - - /// [`enforce_relay_membership`] for HTTP typing pulses: the ban check - /// reads through the 30-second ephemeral-path restriction cache, the same - /// staleness bound the pulse's own write-restriction check already has. - /// Every other HTTP request reads ban state fresh. - pub async fn enforce_relay_membership_ephemeral( + pub(crate) async fn enforce_relay_membership( state: &AppState, tenant: &TenantContext, pubkey_bytes: &[u8], @@ -339,7 +355,6 @@ pub mod relay_members { auth_tag_header, signed_auth_created_at, token_owner, - true, ) .await } @@ -352,27 +367,35 @@ pub mod relay_members { auth_tag_header: Option<&str>, signed_auth_created_at: Option, token_owner: Option, - cached_ban: bool, ) -> Result, MembershipRefusal> { - admit_member( + let result = admit_member( state, tenant, pubkey_bytes, auth_tag_header, signed_auth_created_at, token_owner, - cached_ban, ) - .await - .map_err(|refusal| match token_owner { - None => MembershipRefusal::Api(refusal), - Some(_) if refusal.0.is_server_error() => { - MembershipRefusal::NipFi(DenialClass::AuthorizationUnavailable) - } - Some(_) => MembershipRefusal::NipFi(DenialClass::AuthorizationDenied), + .await; + // An agent token's owner-decided refusal is its request's NIP-FI + // verdict, as shadow's verdict includes it. + if let (Some(_), Err((_, refusal, Some(owner_reason)))) = (token_owner, &result) { + crate::nip_fi_http::owner_refused(refusal_class(refusal.0), owner_reason); + } + result.map_err(|(reason, refusal, _)| match token_owner { + None => MembershipRefusal::Api(reason, refusal), + Some(_) => MembershipRefusal::NipFi(reason, refusal_class(refusal.0)), }) } + fn refusal_class(status: StatusCode) -> DenialClass { + if status.is_server_error() { + DenialClass::AuthorizationUnavailable + } else { + DenialClass::AuthorizationDenied + } + } + async fn admit_member( state: &AppState, tenant: &TenantContext, @@ -380,8 +403,7 @@ pub mod relay_members { auth_tag_header: Option<&str>, signed_auth_created_at: Option, token_owner: Option, - cached_ban: bool, - ) -> Result, (StatusCode, Json)> { + ) -> Result, Refused> { let community = tenant.community(); let owner = match check_relay_membership( state, @@ -397,16 +419,24 @@ pub mod relay_members { Ok(MembershipDecision::ViaOwner(owner)) => Some(owner), Ok(MembershipDecision::Denied) => { return Err(( - StatusCode::FORBIDDEN, - Json(serde_json::json!({ - "error": "relay_membership_required", - "message": "You must be a relay member to access this relay" - })), + AuthReason::NotRelayMember, + ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({ + "error": "relay_membership_required", + "message": "You must be a relay member to access this relay" + })), + ), + None, )) } Err(e) => { tracing::error!("relay membership check errored: {e}"); - return Err(super::internal_error(&e)); + return Err(( + AuthReason::MembershipUnavailable, + super::internal_error(&e), + None, + )); } }; deny_banned( @@ -416,22 +446,33 @@ pub mod relay_members { auth_tag_header, signed_auth_created_at, token_owner, - cached_ban, ) .await?; if let Some(token_owner) = token_owner { let Ok(agent) = nostr::PublicKey::from_slice(pubkey_bytes) else { - return Err(super::internal_error("invalid pubkey for owner link")); + return Err(( + AuthReason::MembershipUnavailable, + super::internal_error("invalid pubkey for owner link"), + None, + )); }; match link_agent_owner(state, tenant, &agent, &token_owner).await { OwnerLink::Linked => {} OwnerLink::Conflict => { - return Err(super::api_error(StatusCode::FORBIDDEN, OWNER_MISMATCH)) + return Err(( + AuthReason::OwnerMismatch, + super::api_error(StatusCode::FORBIDDEN, OWNER_MISMATCH), + Some("not_stored_owner"), + )) } OwnerLink::Unavailable => { - return Err(super::api_error( - StatusCode::SERVICE_UNAVAILABLE, - crate::handlers::auth::OWNER_LINK_ERROR, + return Err(( + AuthReason::NipOaOwnerUnlinked, + super::api_error( + StatusCode::SERVICE_UNAVAILABLE, + crate::handlers::auth::OWNER_LINK_ERROR, + ), + Some("owner_link_unavailable"), )) } } @@ -441,7 +482,9 @@ pub mod relay_members { /// Refuse a community-banned principal (own ban or its agent owner's) on /// HTTP. Bans only: a timeout blocks writes, and HTTP writes reach the - /// ingest gate, while reads stay allowed. Fails closed with 503. + /// ingest gate, while reads stay allowed. Each request's grant ends with + /// the request, so this reads through the restriction cache (see + /// [`AppState::restriction_state_cached`]). Fails closed with 503. async fn deny_banned( state: &AppState, community: CommunityId, @@ -449,32 +492,42 @@ pub mod relay_members { auth_tag_header: Option<&str>, signed_auth_created_at: Option, token_owner: Option, - cached: bool, - ) -> Result<(), (StatusCode, Json)> { + ) -> Result<(), Refused> { let Ok(pubkey) = nostr::PublicKey::from_slice(pubkey_bytes) else { - return Err(super::internal_error("invalid pubkey for ban check")); + return Err(( + AuthReason::MembershipUnavailable, + super::internal_error("invalid pubkey for ban check"), + None, + )); }; - match crate::handlers::auth::community_ban_outcome( + let verdict = crate::handlers::auth::community_ban_verdict( state, community, pubkey, auth_tag_header, signed_auth_created_at, token_owner, - cached, + true, ) - .await - { - crate::handlers::auth::BanOutcome::Clear => Ok(()), - crate::handlers::auth::BanOutcome::Banned => Err(super::api_error( - StatusCode::FORBIDDEN, - "blocked: you are banned from this community", - )), - crate::handlers::auth::BanOutcome::DbError => Err(super::api_error( - StatusCode::SERVICE_UNAVAILABLE, - "error: internal error checking restriction state", - )), - } + .await; + let (reason, refusal) = match verdict.outcome { + crate::handlers::auth::BanOutcome::Clear => return Ok(()), + crate::handlers::auth::BanOutcome::Banned => ( + AuthReason::Banned, + super::api_error( + StatusCode::FORBIDDEN, + "blocked: you are banned from this community", + ), + ), + crate::handlers::auth::BanOutcome::DbError => ( + AuthReason::BanCheckUnavailable, + super::api_error( + StatusCode::SERVICE_UNAVAILABLE, + "error: internal error checking restriction state", + ), + ), + }; + Err((reason, refusal, verdict.owner_reason())) } /// Extract NIP-OA owner from an auth tag without membership enforcement. @@ -510,6 +563,9 @@ pub mod relay_members { /// Both principals are ensured first because `agent_owner_pubkey` has a /// community-scoped foreign key. The mapping is first-write-wins; an /// existing mapping is accepted only when it names the same owner. + /// Returns `true` only when the link is recorded; an owner conflict and a + /// storage failure both return `false`. Callers that must tell denial + /// from unavailability use `link_agent_owner` directly. /// /// A mapping already confirmed in `observer_owner_cache` returns early: /// `agent_owner_pubkey` is set once and never cleared, so the writes @@ -766,6 +822,29 @@ mod db_read_error_tests { assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(body.0["error"], "internal server error"); } + + #[test] + fn unavailable_database_maps_to_retryable_503() { + for error in [ + sqlx::Error::PoolTimedOut, + sqlx::Error::PoolClosed, + sqlx::Error::Io(std::io::Error::from(std::io::ErrorKind::ConnectionReset)), + ] { + let (status, body) = db_read_error("ctx", &buzz_db::DbError::Sqlx(error)); + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(body.0["error"], DATABASE_UNAVAILABLE); + } + } + + #[test] + fn non_cancel_search_error_stays_generic_500() { + let (status, body) = search_read_error( + "ctx", + &buzz_search::SearchError::Db(sqlx::Error::PoolTimedOut), + ); + assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!(body.0["error"], "internal server error"); + } } #[cfg(test)] @@ -866,3 +945,7 @@ mod parse_query_tests { } mod artifact; +pub(crate) mod artifact_sync; + +#[cfg(test)] +mod media_access_postgres_tests; diff --git a/crates/buzz-relay/src/api/nip05.rs b/crates/buzz-relay/src/api/nip05.rs index 2424f3b0e52..74ec3ad48d9 100644 --- a/crates/buzz-relay/src/api/nip05.rs +++ b/crates/buzz-relay/src/api/nip05.rs @@ -36,7 +36,7 @@ pub async fn nostr_nip05( .unwrap_or(""); let json = match ( params.name, - crate::tenant::bind_community(&state.db, raw_host).await, + crate::tenant::bind_community(&*state, raw_host).await, ) { (Some(n), Ok(tenant)) => { let name = n.to_lowercase(); diff --git a/crates/buzz-relay/src/api/nip_fi.rs b/crates/buzz-relay/src/api/nip_fi.rs index 6c577b42b67..fadcdbdbac4 100644 --- a/crates/buzz-relay/src/api/nip_fi.rs +++ b/crates/buzz-relay/src/api/nip_fi.rs @@ -276,7 +276,7 @@ pub fn count_disconnect_event( /// Command replay guard for this pod. Shadow claims under its own key /// prefix, so a shadow accept never uses up the enforce claim. pub fn command_replay_guard( - pool: deadpool_redis::Pool, + pool: buzz_pubsub::RedisConnection, mode: NipFiMode, ) -> Arc { if mode.observes_only() { @@ -760,7 +760,7 @@ mod route_integration_tests { // ES256 key pair — same material as command.rs tests, known-good. const TEST_PRIVATE_KEY_PEM: &str = - "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\nWZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\nzhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n-----END PRIVATE KEY-----\n"; + "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcnxDM4EiirH9dHUE\nWZc759TX4s5PAn8kO5ovXSnGxCWhRANCAARFb6ZnsfkqOOXyEhj3KBQphGKF4vTa\nzhebbavbZ1ZoklqkF1cGg+jTO7rONAVEzXvXUWtV6CdDV+rybiVmFP2w\n-----END PRIVATE KEY-----\n"; // sadscan:disable np.pem.1 kingfisher.privkey.2 -- unchanged public ES256 test fixture const TEST_ISS: &str = "https://idp.test.example.com"; const TEST_AUD: &str = "https://relay.test.example.com"; @@ -869,9 +869,7 @@ mod route_integration_tests { let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -971,9 +969,7 @@ mod route_integration_tests { let config = crate::config::Config::for_test(); let pool = sqlx::PgPool::connect_lazy(&config.database_url).unwrap(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1232,9 +1228,7 @@ mod route_integration_tests { config.nip_fi.registry.insert(test_issuer_policy()); let pool = sqlx::PgPool::connect_lazy(&config.database_url).unwrap(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1437,9 +1431,7 @@ mod route_integration_tests { config.nip_fi.registry.insert(test_issuer_policy()); let pool = sqlx::PgPool::connect_lazy(&config.database_url).unwrap(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1632,9 +1624,7 @@ mod route_integration_tests { config.nip_fi.registry.insert(test_issuer_policy()); let pool = sqlx::PgPool::connect_lazy(&config.database_url).unwrap(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1760,9 +1750,7 @@ mod route_integration_tests { let config = crate::config::Config::for_test(); let pool = sqlx::PgPool::connect_lazy(&config.database_url).unwrap(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1939,6 +1927,7 @@ mod route_integration_tests { }, )]; config.nip_fi = NipFiRelayConfig { + profile_policies: Vec::new(), source: Default::default(), mode: NipFiMode::Enforce, registry: registry.clone(), @@ -1950,9 +1939,7 @@ mod route_integration_tests { let pool = sqlx::PgPool::connect_lazy(&config.database_url).unwrap(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -2187,9 +2174,7 @@ mod route_integration_tests { config.nip_fi.registry.insert(test_issuer_policy()); let pool = sqlx::PgPool::connect_lazy(&config.database_url).unwrap(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -2490,9 +2475,102 @@ mod route_integration_tests { state.config.nip_fi.registry.clone(), key_source, ))); + state.nip_fi_policy = Arc::new(crate::nip_fi_policy::OptionalPolicy); Arc::new(state) } + struct RequiredPolicy; + impl crate::nip_fi_policy::PolicySource for RequiredPolicy { + fn lookup<'a>( + &'a self, + _host: &'a str, + ) -> futures_util::future::BoxFuture< + 'a, + Result, ()>, + > { + Box::pin(async { + Ok(Some(buzz_db::community_auth::CommunityAuthPolicy { + community_id: uuid::Uuid::nil(), + requires_nip_fi: true, + policy_generation: 1, + })) + }) + } + } + + #[tokio::test] + #[allow(clippy::result_large_err)] // Real Axum admission closure. + async fn required_mode_matrix_validates_crypto_only_when_enabled() { + use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; + for mode in [ + buzz_auth::NipFiMode::Off, + buzz_auth::NipFiMode::Shadow, + buzz_auth::NipFiMode::Enforce, + ] { + let mut state = (*http_enforce_state().await).clone(); + Arc::make_mut(&mut state.config).nip_fi.mode = mode; + Arc::make_mut(&mut state.config) + .nip_fi + .max_connection_lifetime_secs = 3600; + state.nip_fi_policy = Arc::new(RequiredPolicy); + let key = nostr::Keys::generate().public_key(); + let now = chrono::Utc::now().timestamp(); + for bad in ["valid", "issuer", "audience", "key", "expiry", "signature"] { + let mut claims = serde_json::json!({"iss": TEST_ISS, "aud": TEST_AUD, + "sub": TEST_SUB, "iat": now, "exp": now + 600, + "nostr_pubkey": key.to_hex()}); + match bad { + "issuer" => claims["iss"] = serde_json::json!("https://untrusted.example"), + "audience" => claims["aud"] = serde_json::json!("https://other.example"), + "key" => { + claims["nostr_pubkey"] = + serde_json::json!(nostr::Keys::generate().public_key().to_hex()) + } + "expiry" => { + claims["iat"] = serde_json::json!(now - 1200); + claims["exp"] = serde_json::json!(now - 600); + } + _ => {} + } + let mut header = Header::new(Algorithm::ES256); + header.typ = Some("nip-fi+jwt".to_owned()); + header.kid = Some(TEST_KID.to_owned()); + let encoding = EncodingKey::from_ec_pem(TEST_PRIVATE_KEY_PEM.as_bytes()).unwrap(); + let mut token = encode(&header, &claims, &encoding).unwrap(); + if bad == "signature" { + let at = token.rfind('.').unwrap() + 1; + let replacement = if token.as_bytes()[at] == b'A' { + "B" + } else { + "A" + }; + token.replace_range(at..at + 1, replacement); + } + let mut headers = crate::nip_fi_core::test_support::host_headers(); + headers.insert( + CLIENT_ATTACHED_HEADER, + format!("Bearer {token}").parse().unwrap(), + ); + let result = crate::nip_fi_http::admit_nip_fi_http_on_state( + &state, + &headers, + &crate::access::AccessSlot::default(), + || Ok(crate::nip_fi_http::Nip98Proof::new(key, ())), + ) + .await; + if mode.is_off() || bad == "valid" { + assert!(result.is_ok(), "{mode:?} valid assertion"); + } else { + assert_eq!( + result.err().unwrap().status(), + StatusCode::FORBIDDEN, + "{mode:?} {bad}" + ); + } + } + } + } + /// Deny `key` under issuer A through the real disconnect route. async fn deny_via_route( state: &Arc, @@ -2533,9 +2611,12 @@ mod route_integration_tests { .parse() .expect("header value"), ); - crate::nip_fi_http::admit_nip_fi_http_on_state(state, &headers, || { - Ok(crate::nip_fi_http::Nip98Proof::new(*key, ())) - }) + crate::nip_fi_http::admit_nip_fi_http_on_state( + state, + &headers, + &crate::access::AccessSlot::default(), + || Ok(crate::nip_fi_http::Nip98Proof::new(*key, ())), + ) .await .map(|_| ()) } @@ -2651,7 +2732,9 @@ mod route_integration_tests { // Off mode: the command route still records the entry, but HTTP // admission never consults the deny map — the NIP-98 closure result is // returned unchanged, byte for byte. - let state = build_test_state(1000).await; + let mut state = (*build_test_state(1000).await).clone(); + state.nip_fi_policy = Arc::new(crate::nip_fi_policy::OptionalPolicy); + let state = Arc::new(state); assert!(matches!( state.config.nip_fi.mode, buzz_auth::NipFiMode::Off @@ -2667,12 +2750,14 @@ mod route_integration_tests { "control: the route recorded the deny entry" ); - let admitted = - crate::nip_fi_http::admit_nip_fi_http_on_state(&state, &HeaderMap::new(), || { - Ok(crate::nip_fi_http::Nip98Proof::new(key, 7u8)) - }) - .await - .expect("Off mode admits on NIP-98 success regardless of deny entries"); + let admitted = crate::nip_fi_http::admit_nip_fi_http_on_state( + &state, + &crate::nip_fi_core::test_support::host_headers(), + &crate::access::AccessSlot::default(), + || Ok(crate::nip_fi_http::Nip98Proof::new(key, 7u8)), + ) + .await + .expect("Off mode admits on NIP-98 success regardless of deny entries"); assert_eq!(admitted.proven_pubkey(), &key); assert!(admitted.assertion().is_none()); assert_eq!(*admitted.extra(), 7); @@ -2686,7 +2771,8 @@ mod route_integration_tests { }; let resp = crate::nip_fi_http::admit_nip_fi_http_on_state::<(), _>( &state, - &HeaderMap::new(), + &crate::nip_fi_core::test_support::host_headers(), + &crate::access::AccessSlot::default(), || Err(legacy()), ) .await @@ -3524,9 +3610,7 @@ mod route_integration_tests { let url = std::env::var("BUZZ_TEST_REDIS_URL") .or_else(|_| std::env::var("REDIS_URL")) .unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); - let pool = deadpool_redis::Config::from_url(url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let pool = buzz_pubsub::redis_connection(&url).expect("redis pool"); Arc::new(buzz_pubsub::RedisCommandReplayGuard::new(pool)) } @@ -3565,6 +3649,7 @@ mod route_integration_tests { }, )]; config.nip_fi = NipFiRelayConfig { + profile_policies: Vec::new(), source: Default::default(), mode: NipFiMode::Shadow, registry: registry.clone(), @@ -3575,9 +3660,7 @@ mod route_integration_tests { }; let pool = sqlx::PgPool::connect_lazy(&config.database_url).unwrap(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .unwrap(); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).unwrap(); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await diff --git a/crates/buzz-relay/src/api/operator.rs b/crates/buzz-relay/src/api/operator.rs index 0663012f0d8..2f03803236a 100644 --- a/crates/buzz-relay/src/api/operator.rs +++ b/crates/buzz-relay/src/api/operator.rs @@ -4,6 +4,12 @@ //! request signing and replay protection, but they do not run through event //! ingest, relay membership, channel scoping, storage, or fan-out. +mod community_policy; +mod invites; +pub use community_policy::{community_nip_fi_policy_status, set_community_nip_fi_policy}; +pub use invites::mint_community_invite; + +use crate::access::{AccessSlot, AuthMethod, AuthResult}; use std::sync::Arc; use axum::{ @@ -194,6 +200,7 @@ fn verify_registration_proof( /// or an inbound proxy `Host` header. async fn authorize_operator_request( state: &Arc, + slot: &AccessSlot, headers: &HeaderMap, method: &str, path: &str, @@ -214,8 +221,9 @@ async fn authorize_operator_request( pubkey, event_id_bytes, .. - } = bridge::verify_nip98_exempt_operator(headers, method, &url, body)?; - check_operator_replay(state, event_id_bytes).await?; + } = bridge::verify_nip98_exempt_operator(slot, headers, method, &url, body)?; + slot.attempt(AuthMethod::Nip98, Some(pubkey), true); + check_operator_replay(state, event_id_bytes, slot).await?; let pubkey_hex = pubkey.to_hex(); if !state @@ -224,12 +232,13 @@ async fn authorize_operator_request( .iter() .any(|pk| pk == &pubkey_hex) { + slot.finish(AuthResult::Denied(crate::access::AuthReason::NotOperator)); return Err(api_error( StatusCode::FORBIDDEN, "actor not authorized: not a relay operator", )); } - + slot.finish(AuthResult::Success); Ok(pubkey) } @@ -237,6 +246,7 @@ async fn authorize_operator_request( /// identity and a NIP-98 request signature. async fn authorize_operator_listener_request( state: &Arc, + slot: &AccessSlot, headers: &HeaderMap, method: &str, path: &str, @@ -252,30 +262,42 @@ async fn authorize_operator_listener_request( pubkey, event_id_bytes, .. - } = bridge::verify_nip98_exempt_operator(headers, method, &url, Some(body))?; - check_operator_replay(state, event_id_bytes).await?; + } = bridge::verify_nip98_exempt_operator(slot, headers, method, &url, Some(body))?; + slot.attempt(AuthMethod::Nip98, Some(pubkey), true); + check_operator_replay(state, event_id_bytes, slot).await?; if !state .config .operator_listener_delivery_urls .contains_key(&pubkey.to_hex()) { + slot.finish(AuthResult::Denied( + crate::access::AuthReason::NotOperatorListener, + )); return Err(api_error( StatusCode::FORBIDDEN, "actor not authorized: not a configured operator listener", )); } + slot.finish(AuthResult::Success); Ok(pubkey) } /// Register target pubkeys for the authenticated operator listener. pub async fn register_listener_pubkeys( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { - let listener = - authorize_operator_listener_request(&state, &headers, "POST", LISTENER_PUBKEYS_PATH, &body) - .await?; + let listener = authorize_operator_listener_request( + &state, + &slot, + &headers, + "POST", + LISTENER_PUBKEYS_PATH, + &body, + ) + .await?; let origin = state .config .relay_operator_api_origin @@ -298,11 +320,13 @@ pub async fn register_listener_pubkeys( /// Remove target pubkeys for the authenticated operator listener. pub async fn remove_listener_pubkeys( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { let listener = authorize_operator_listener_request( &state, + &slot, &headers, "DELETE", LISTENER_PUBKEYS_PATH, @@ -321,6 +345,7 @@ pub async fn remove_listener_pubkeys( async fn check_operator_replay( state: &AppState, event_id_bytes: [u8; 32], + slot: &AccessSlot, ) -> Result<(), (StatusCode, Json)> { let event_id = nostr::EventId::from_byte_array(event_id_bytes); match state @@ -333,11 +358,17 @@ async fn check_operator_replay( .await { Ok(true) => Ok(()), - Ok(false) => Err(api_error( - StatusCode::UNAUTHORIZED, - "NIP-98: replay detected", - )), + Ok(false) => { + slot.finish(AuthResult::Failed("nip98_replay")); + Err(api_error( + StatusCode::UNAUTHORIZED, + "NIP-98: replay detected", + )) + } Err(error) => { + slot.finish(AuthResult::Denied( + crate::access::AuthReason::ReplayCheckUnavailable, + )); tracing::warn!( scope = OPERATOR_REPLAY_SCOPE, error = %error, @@ -365,11 +396,13 @@ async fn check_operator_replay( /// authority for this deployment-root control-plane surface. pub async fn provision_community( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { let pubkey = authorize_operator_request( &state, + &slot, &headers, "POST", "/operator/communities", @@ -392,9 +425,26 @@ pub async fn provision_community( tracing::error!("failed to serialize provision-community response: {e}"); internal_error("operator provision response serialization failed") })?)), + Err(msg) if msg == "community_creation_disabled" => Err(coded_api_error( + StatusCode::FORBIDDEN, + "community_creation_disabled", + &msg, + )), Err(msg) if msg.starts_with("actor not authorized") => { Err(api_error(StatusCode::FORBIDDEN, &msg)) } + Err(msg) if msg.starts_with("nip_fi_binding_required:") => Err(coded_api_error( + StatusCode::BAD_REQUEST, + "nip_fi_binding_required", + &msg, + )), + Err(msg) if msg.starts_with("initial_policy_requires_create_only:") => { + Err(coded_api_error( + StatusCode::BAD_REQUEST, + "initial_policy_requires_create_only", + &msg, + )) + } Err(msg) if msg.starts_with("limit_reached:") => { Err(coded_api_error(StatusCode::CONFLICT, "limit_reached", &msg)) } @@ -435,11 +485,12 @@ pub struct DeleteCommunityRequest { /// Idempotently archive a community owned by the asserted end-user identity. pub async fn archive_community( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { const PATH: &str = "/operator/communities/archive"; - authorize_operator_request(&state, &headers, "POST", PATH, None, Some(&body)).await?; + authorize_operator_request(&state, &slot, &headers, "POST", PATH, None, Some(&body)).await?; let request: ArchiveCommunityRequest = serde_json::from_slice(&body).map_err(|e| { api_error( StatusCode::BAD_REQUEST, @@ -468,6 +519,7 @@ pub async fn archive_community( .map_err(|e| internal_error(&format!("archive community: {e}")))? .ok_or_else(|| api_error(StatusCode::NOT_FOUND, "community not found"))?; let tenant = TenantContext::resolved(record.id, &record.host); + state.invalidate_community_host(&tenant); let closed = match state .disconnect_community_clusterwide(&tenant, record.archived_at) .await @@ -500,11 +552,12 @@ pub async fn archive_community( /// Idempotently restore an archived community owned by the asserted end-user identity. pub async fn unarchive_community( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { const PATH: &str = "/operator/communities/unarchive"; - authorize_operator_request(&state, &headers, "POST", PATH, None, Some(&body)).await?; + authorize_operator_request(&state, &slot, &headers, "POST", PATH, None, Some(&body)).await?; let request: ArchiveCommunityRequest = serde_json::from_slice(&body).map_err(|e| { api_error( StatusCode::BAD_REQUEST, @@ -538,6 +591,7 @@ pub async fn unarchive_community( } }; tracing::info!(community = %record.id, host = %record.host, "community unarchived"); + state.invalidate_community_host(&TenantContext::resolved(record.id, &record.host)); Ok(Json(serde_json::json!({ "community_id": record.id.to_string(), "host": record.host, @@ -586,12 +640,14 @@ pub async fn unarchive_community( /// that upstream ceremony, not verified as cryptographic owner consent. pub async fn delete_community( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result<(StatusCode, Json), (StatusCode, Json)> { const PATH: &str = "/operator/communities/delete"; let operator = - authorize_operator_request(&state, &headers, "POST", PATH, None, Some(&body)).await?; + authorize_operator_request(&state, &slot, &headers, "POST", PATH, None, Some(&body)) + .await?; let request: DeleteCommunityRequest = serde_json::from_slice(&body).map_err(|e| { coded_api_error( StatusCode::BAD_REQUEST, @@ -698,12 +754,14 @@ pub async fn delete_community( /// The operator is trusted to select the identity; this route does not bind it to a user session. pub async fn list_joined_communities( State(state): State>, + slot: AccessSlot, headers: HeaderMap, RawQuery(raw_query): RawQuery, Query(query): Query, ) -> Result, (StatusCode, Json)> { authorize_operator_request( &state, + &slot, &headers, "GET", "/operator/communities/joined", @@ -733,12 +791,14 @@ pub async fn list_joined_communities( /// List communities where a pubkey currently holds the `owner` role. pub async fn list_owned_communities( State(state): State>, + slot: AccessSlot, headers: HeaderMap, RawQuery(raw_query): RawQuery, Query(query): Query, ) -> Result, (StatusCode, Json)> { authorize_operator_request( &state, + &slot, &headers, "GET", "/operator/communities", @@ -770,7 +830,7 @@ pub async fn list_owned_communities( })).collect::>(), "quota_used": page.quota_used, "quota_limit": page.quota_limit, - "can_create": page.can_create, + "can_create": state.config.multi_community_relay && page.can_create, }))) } @@ -788,11 +848,13 @@ pub async fn list_owned_communities( /// NIP-43 membership list is best-effort, matching the provision path. pub async fn transfer_community( State(state): State>, + slot: AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, (StatusCode, Json)> { let _pubkey = authorize_operator_request( &state, + &slot, &headers, "POST", "/operator/communities/transfer", @@ -921,12 +983,14 @@ pub async fn transfer_community( /// normalized authority used by create. pub async fn community_availability( State(state): State>, + slot: AccessSlot, headers: HeaderMap, RawQuery(raw_query): RawQuery, Query(query): Query, ) -> Result, (StatusCode, Json)> { authorize_operator_request( &state, + &slot, &headers, "GET", "/operator/communities/availability", @@ -953,6 +1017,7 @@ pub async fn community_availability( "host": query.host, "normalized_host": normalized_host, "available": existing.is_none() && !reserved, + "can_create": state.config.multi_community_relay && existing.is_none() && !reserved, "community_id": existing.map(|record| record.id.to_string()), }); if reserved { @@ -980,12 +1045,14 @@ pub struct CommunityNipFiBindingQuery { /// - 404 means no community row has this host. pub async fn community_nip_fi_binding( State(state): State>, + slot: AccessSlot, headers: HeaderMap, RawQuery(raw_query): RawQuery, Query(query): Query, ) -> Result, (StatusCode, Json)> { authorize_operator_request( &state, + &slot, &headers, "GET", "/operator/communities/nip-fi-binding", @@ -1141,8 +1208,55 @@ mod tests { } } +fn upgrade_configured_trust( + state: &AppState, + host: &str, + issuer: &str, +) -> Result<(), &'static str> { + let policy = state + .config + .nip_fi_provision_binding + .as_ref() + .ok_or("authorization_unavailable")?; + let [configured_issuer] = policy.authorized_issuers() else { + return Err("authorization_unavailable"); + }; + if !policy.is_bindable(host) || configured_issuer != issuer { + return Err("issuer_conflict"); + } + if state + .config + .nip_fi + .registry + .policy_for_issuer(issuer) + .is_none() + { + return Err("authorization_unavailable"); + } + Ok(()) +} + +/// Keep all policy responses, including auth and dependency errors, out of caches. +pub async fn no_store_policy_response( + request: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + let policy = request.uri().path() == "/operator/communities/nip-fi-policy"; + let mut response = next.run(request).await; + if policy { + response.headers_mut().insert( + axum::http::header::CACHE_CONTROL, + axum::http::HeaderValue::from_static("no-store"), + ); + } + response +} + #[cfg(test)] mod postgres_tests { + mod creation_policy_postgres_tests; + mod initial_policy_postgres_tests; + mod invite_postgres_tests; use std::{ collections::HashSet, sync::{Arc, Mutex}, @@ -1241,11 +1355,24 @@ mod postgres_tests { async fn operator_test_state_with_policy( operator_keys: &[Keys], nip_fi_provision_binding: Option, + ) -> Option> { + operator_test_state_with_policy_and_redis( + operator_keys, + nip_fi_provision_binding, + "redis://127.0.0.1:1", + ) + .await + } + + async fn operator_test_state_with_policy_and_redis( + operator_keys: &[Keys], + nip_fi_provision_binding: Option, + redis_url: &str, ) -> Option> { let mut config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE] config.nip_fi_provision_binding = nip_fi_provision_binding; config.database_url = crate::test_support::database_url(); - config.redis_url = "redis://127.0.0.1:1".to_string(); + config.redis_url = redis_url.to_owned(); config.relay_url = "wss://tenant.example".to_string(); config.relay_operator_api_origin = Some(format!("http://{INGRESS_HOST}")); config.relay_operator_pubkeys = operator_keys @@ -1259,9 +1386,7 @@ mod postgres_tests { .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1444,6 +1569,35 @@ mod postgres_tests { } } + /// An operator request dropped while its replay check is in flight + /// still writes one `aborted` line. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres"] + async fn operator_request_dropped_during_replay_logs_one_aborted_line() { + let operator = Keys::generate(); + let state = operator_test_state(std::slice::from_ref(&operator)) + .await + .expect("local Postgres"); + let mut state = (*state).clone(); + let replay = Arc::new(crate::access::tests::StallingReplayGuard::default()); + state.nip98_replay = replay.clone(); + // The query string is required, or extraction refuses before auth. + let path = format!( + "/operator/communities?owner_pubkey={}", + operator.public_key().to_hex() + ); + let (guard, out) = crate::access::tests::capture_scoped(); + tokio::select! { + _ = signed_operator_request(Arc::new(state), &operator, "GET", &path, None) => { + panic!("the replay check must stall"); + } + () = replay.arrived.notified() => {} + } + drop(guard); + let line = crate::access::tests::assert_one_aborted_line(&out, &operator.public_key()); + assert_eq!(line["route"], "/operator/communities"); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn non_allowlisted_operator_key_gets_403() { @@ -2818,17 +2972,39 @@ mod postgres_tests { (policy, reserved, format!("acme.{suffix}")) } - async fn nip_fi_lookup(state: Arc, operator: &Keys, host: &str) -> Value { - let response = signed_operator_request( - state, - operator, - "GET", - &format!("/operator/communities/nip-fi-binding?host={host}"), - None, + fn fresh_upgrade_auth(keys: &Keys, url: &str, method: &str, body: Option<&[u8]>) -> String { + let mut tags = vec![ + Tag::parse(["u", url]).unwrap(), + Tag::parse(["method", method]).unwrap(), + Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), + ]; + if let Some(body) = body { + tags.push(Tag::parse(["payload", &hex::encode(Sha256::digest(body))]).unwrap()); + } + let event = EventBuilder::new(Kind::HttpAuth, "") + .tags(tags) + .sign_with_keys(keys) + .unwrap(); + format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD.encode(serde_json::to_vec(&event).unwrap()) ) - .await; - assert_eq!(response.status(), StatusCode::OK, "{host}"); - read_json(response).await + } + + async fn fresh_upgrade_request( + state: Arc, + keys: &Keys, + method: &str, + path: &str, + body: Option, + ) -> axum::response::Response { + let auth = fresh_upgrade_auth( + keys, + &format!("http://{INGRESS_HOST}{path}"), + method, + body.as_deref().map(str::as_bytes), + ); + operator_request_with_auth(state, method, path, body, auth).await } #[tokio::test] @@ -4233,9 +4409,7 @@ mod postgres_tests { let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -4274,4 +4448,18 @@ mod postgres_tests { let body = read_json(response).await; assert_eq!(body["error"], "internal server error"); } + async fn nip_fi_lookup(state: Arc, operator: &Keys, host: &str) -> Value { + let response = signed_operator_request( + state, + operator, + "GET", + &format!("/operator/communities/nip-fi-binding?host={host}"), + None, + ) + .await; + assert_eq!(response.status(), StatusCode::OK, "{host}"); + read_json(response).await + } + + mod policy_tests; } diff --git a/crates/buzz-relay/src/api/operator/community_policy.rs b/crates/buzz-relay/src/api/operator/community_policy.rs new file mode 100644 index 00000000000..ed9d660b935 --- /dev/null +++ b/crates/buzz-relay/src/api/operator/community_policy.rs @@ -0,0 +1,209 @@ +//! General operator policy intents and truthful current/historical readback. + +use super::*; +use buzz_db::community_auth::{PolicyOutcome, PolicyRecord, PolicyRequest, UpgradeRequest}; + +const PATH: &str = "/operator/communities/nip-fi-policy"; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Request { + operation_id: Uuid, + community_id: Uuid, + expected_host: String, + actor_pubkey: String, + expected_owner_pubkey: String, + #[serde(default)] + expected_issuer: Option, + requires_nip_fi: bool, + expected_policy_generation: i64, + expected_requires_nip_fi: bool, +} + +/// Exactly one of an operation receipt or a community/host current-state read. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyQuery { + operation_id: Option, + community_id: Option, + expected_host: Option, +} + +type Error = (StatusCode, Json); + +fn invalid() -> Error { + coded_api_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "invalid policy request", + ) +} + +fn unavailable(error: buzz_db::DbError) -> Error { + tracing::warn!(%error, "community auth policy unavailable"); + coded_api_error( + StatusCode::SERVICE_UNAVAILABLE, + "authorization_unavailable", + "authorization unavailable", + ) +} + +fn mode_fields(state: &AppState, required: Option) -> Value { + let mode = state.config.nip_fi.mode; + let name = crate::nip_fi_config::mode_name(mode); + serde_json::json!({ + "mode": name, + "effective_required": required.map(|r| mode.with_requirement(r).restricts()), + }) +} + +fn response(state: &AppState, mut record: PolicyRecord) -> Json { + // Supersession is history, not a trust failure. Disable needs no issuer. + if record.acceptance.state == "pending" + && upgrade_configured_trust( + state, + &record.acceptance.expected_host, + &record.acceptance.expected_issuer, + ) + .is_err() + { + record.acceptance.state = "unavailable".into(); + } + let fields = mode_fields(state, record.current_requires_nip_fi); + Json(serde_json::json!({ + "receipt": record, + "mode": fields["mode"], + "effective_required": fields["effective_required"], + })) +} + +/// Atomically accept an owner-authorized stored requirement with CAS and replay. +pub async fn set_community_nip_fi_policy( + State(state): State>, + slot: AccessSlot, + headers: HeaderMap, + body: axum::body::Bytes, +) -> Result, Error> { + let operator = + authorize_operator_request(&state, &slot, &headers, "POST", PATH, None, Some(&body)) + .await?; + let request: Request = serde_json::from_slice(&body).map_err(|_| invalid())?; + let host = normalize_candidate_host(&request.expected_host).map_err(|_| invalid())?; + if request.operation_id.is_nil() + || request.community_id.is_nil() + || request.expected_policy_generation < 0 + || host != request.expected_host + || (request.requires_nip_fi + && request + .expected_issuer + .as_ref() + .is_none_or(|s| s.is_empty())) + || (!request.requires_nip_fi && request.expected_issuer.is_some()) + { + return Err(invalid()); + } + let tuple = UpgradeRequest { + operation_id: request.operation_id, + community_id: request.community_id, + expected_host: host, + actor_pubkey: validate_pubkey_hex(&request.actor_pubkey).ok_or_else(invalid)?, + expected_owner_pubkey: validate_pubkey_hex(&request.expected_owner_pubkey) + .ok_or_else(invalid)?, + expected_issuer: request.expected_issuer.unwrap_or_default(), + operator_pubkey: operator.to_hex(), + }; + let preflight = if !state.config.nip_fi_changes { + Err("upgrades_disabled") + } else if request.requires_nip_fi { + upgrade_configured_trust(&state, &tuple.expected_host, &tuple.expected_issuer) + } else { + Ok(()) + }; + let intent = PolicyRequest { + tuple, + requires_nip_fi: request.requires_nip_fi, + expected_policy_generation: request.expected_policy_generation, + expected_requires_nip_fi: request.expected_requires_nip_fi, + }; + match state + .db + .set_community_nip_fi_policy(&intent, preflight) + .await + .map_err(unavailable)? + { + PolicyOutcome::Accepted(record) => { + state.invalidate_community_host(&TenantContext::resolved( + buzz_core::CommunityId::from_uuid(record.acceptance.community_id), + &record.acceptance.expected_host, + )); + Ok(response(&state, *record)) + } + PolicyOutcome::Refused(code) => Err(coded_api_error( + match code { + "community_not_found" => StatusCode::NOT_FOUND, + "upgrades_disabled" | "authorization_unavailable" => { + StatusCode::SERVICE_UNAVAILABLE + } + _ => StatusCode::CONFLICT, + }, + code, + code, + )), + } +} + +/// Read exact current preconditions or the originating operator's operation history. +pub async fn community_nip_fi_policy_status( + State(state): State>, + slot: AccessSlot, + headers: HeaderMap, + RawQuery(raw): RawQuery, + Query(query): Query, +) -> Result, Error> { + let operator = + authorize_operator_request(&state, &slot, &headers, "GET", PATH, raw.as_deref(), None) + .await?; + match (query.operation_id, query.community_id, query.expected_host) { + (Some(id), None, None) if !id.is_nil() => { + let record = state + .db + .community_auth_policy_status(id, &operator.to_hex()) + .await + .map_err(unavailable)? + .ok_or_else(|| { + coded_api_error( + StatusCode::NOT_FOUND, + "operation_not_found", + "operation not found", + ) + })?; + Ok(response(&state, record)) + } + (None, Some(id), Some(host)) if !id.is_nil() => { + if normalize_candidate_host(&host).map_err(|_| invalid())? != host { + return Err(invalid()); + } + let policy = state + .db + .community_auth_policy_for_host(&host) + .await + .map_err(unavailable)? + .filter(|p| p.community_id == id) + .ok_or_else(|| { + coded_api_error( + StatusCode::NOT_FOUND, + "community_not_found", + "community not found", + ) + })?; + let fields = mode_fields(&state, Some(policy.requires_nip_fi)); + Ok(Json(serde_json::json!({ + "community_id": id, "expected_host": host, + "expected_policy_generation": policy.policy_generation, + "expected_requires_nip_fi": policy.requires_nip_fi, + "mode": fields["mode"], "effective_required": fields["effective_required"], + }))) + } + _ => Err(invalid()), + } +} diff --git a/crates/buzz-relay/src/api/operator/invites.rs b/crates/buzz-relay/src/api/operator/invites.rs new file mode 100644 index 00000000000..25d358d86de --- /dev/null +++ b/crates/buzz-relay/src/api/operator/invites.rs @@ -0,0 +1,130 @@ +//! Operator-mediated invite minting for a community owner or admin. +//! +//! A trusted operator vouches only for which identity its signed-in caller is +//! bound to. The relay decides that identity's authority from its own +//! membership data at mint time, exactly as `POST /api/invites` does. + +use super::*; +use crate::access::AuthReason; +use crate::api::invites::{ + map_mint_error, minted_invite_json, validate_mint_request, MintInviteRequest, +}; + +const PATH: &str = "/operator/communities/invites"; + +type Error = (StatusCode, Json); + +/// Adds a stable `code` beside the `/api/invites` error text, so the operator +/// can tell its own misconfiguration from the actor's refusal without +/// matching on prose. +fn with_code((status, Json(mut body)): Error, code: &'static str) -> Error { + body["code"] = code.into(); + (status, Json(body)) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Request { + community_id: Uuid, + actor_pubkey: String, + #[serde(default)] + ttl_secs: Option, + #[serde(default)] + max_uses: Option, +} + +/// Mint an invite as the operator-attested `actor_pubkey`, who must be an +/// owner or admin of the active community. The limits, defaults, storage and +/// response match `POST /api/invites`; errors add a stable `code`: +/// `not_operator`, `invalid_request`, `community_not_found`, `not_owner`, +/// `restricted` or `unavailable`. +pub async fn mint_community_invite( + State(state): State>, + slot: AccessSlot, + headers: HeaderMap, + body: axum::body::Bytes, +) -> Result, Error> { + authorize_operator_request(&state, &slot, &headers, "POST", PATH, None, Some(&body)) + .await + .map_err(|error| match error.0 { + StatusCode::FORBIDDEN => with_code(error, "not_operator"), + _ => error, + })?; + let request: Request = serde_json::from_slice(&body).map_err(|e| { + coded_api_error( + StatusCode::BAD_REQUEST, + "invalid_request", + &format!("invalid community-invite JSON: {e}"), + ) + })?; + let actor = validate_pubkey_hex(&request.actor_pubkey).ok_or_else(|| { + coded_api_error( + StatusCode::BAD_REQUEST, + "invalid_request", + "invalid actor_pubkey: expected 64-char hex pubkey", + ) + })?; + let (ttl, max_uses) = validate_mint_request(&MintInviteRequest { + ttl_secs: request.ttl_secs, + max_uses: request.max_uses, + }) + .map_err(|error| with_code(error, "invalid_request"))?; + let community = CommunityId::from_uuid(request.community_id); + // Archived, deleted and deleting communities have no host here. + let host = state + .db + .lookup_community_host(community) + .await + .map_err(|e| internal_error(&format!("community invite host lookup: {e}")))? + .ok_or_else(|| { + coded_api_error( + StatusCode::NOT_FOUND, + "community_not_found", + "community not found", + ) + })?; + if !crate::single_community::serves_host(&state.config, &host) { + return Err(coded_api_error( + StatusCode::FORBIDDEN, + "community_not_served", + "community is not served in single-community mode", + )); + } + slot.in_community(community); + // The mint checks the actor's role and restriction, and the community's + // deletion state, in one transaction. It does not re-check archiving: an + // invite minted while an archive lands cannot be claimed while archived. + let invite = state + .db + .mint_relay_invite_as_admin(community, &actor, ttl, max_uses) + .await + .map_err(|error| match error { + buzz_db::DbError::InviteIssuerNotAdmin => { + slot.finish(AuthResult::Denied(AuthReason::NotRelayAdmin)); + coded_api_error( + StatusCode::FORBIDDEN, + "not_owner", + "only relay owners and admins can create invites", + ) + } + buzz_db::DbError::InviteRestricted => { + slot.finish(AuthResult::Denied(AuthReason::Restricted)); + with_code(map_mint_error(error), "restricted") + } + error => { + let error = map_mint_error(error); + match error.0 { + StatusCode::SERVICE_UNAVAILABLE => with_code(error, "unavailable"), + StatusCode::BAD_REQUEST => with_code(error, "invalid_request"), + _ => error, + } + } + })?; + slot.detail(crate::access::Detail { + invite_id: Some(invite.invite_id), + expires_at: Some(invite.expires_at.timestamp()), + max_uses: invite.max_uses, + ..Default::default() + }); + Ok(Json(minted_invite_json(&state, &host, &invite))) +} diff --git a/crates/buzz-relay/src/api/operator/postgres_tests/creation_policy_postgres_tests.rs b/crates/buzz-relay/src/api/operator/postgres_tests/creation_policy_postgres_tests.rs new file mode 100644 index 00000000000..9753a9655ef --- /dev/null +++ b/crates/buzz-relay/src/api/operator/postgres_tests/creation_policy_postgres_tests.rs @@ -0,0 +1,600 @@ +use super::*; + +fn set_creation(state: &mut Arc, enabled: bool) { + Arc::make_mut(&mut Arc::get_mut(state).expect("exclusive test state").config) + .multi_community_relay = enabled; +} + +async fn policy_state(operator: &Keys) -> Arc { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .expect("creation policy tests require Postgres"); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + buzz_db::Db::from_pool(pool) + .migrate() + .await + .expect("test schema"); + } + let redis_url = + std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_owned()); + operator_test_state_with_policy_and_redis(std::slice::from_ref(operator), None, &redis_url) + .await + .expect("test state") +} + +async fn legacy_request( + state: Arc, + operator: &Keys, + host: &str, + owner: Option<&Keys>, +) -> axum::response::Response { + let mut body = serde_json::json!({"host": host}); + if let Some(owner) = owner { + body["initial_owner_pubkey"] = owner.public_key().to_hex().into(); + } + // Deliberately omit create_only to exercise the compatibility default. + signed_operator_request( + state, + operator, + "POST", + "/operator/communities", + Some(body.to_string()), + ) + .await +} + +async fn owned(state: Arc, operator: &Keys, owner: &Keys) -> Value { + let path = format!( + "/operator/communities?owner_pubkey={}", + owner.public_key().to_hex() + ); + let response = signed_operator_request(state, operator, "GET", &path, None).await; + assert_eq!(response.status(), StatusCode::OK); + read_json(response).await +} + +mod postgres_tests { + use super::*; + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn single_mode_serves_only_canonical_and_rejects_extra_target_enrollment() { + let operator = Keys::generate(); + let owner = Keys::generate(); + let mut state = policy_state(&operator).await; + let canonical = format!("canonical-{}.example", Uuid::new_v4().simple()); + let extra = format!("extra-{}.example", Uuid::new_v4().simple()); + for host in [&canonical, &extra] { + let _fixture = state + .db + .create_community_with_owner( + host, + &owner.public_key().to_hex(), + &state.relay_keypair, + ) + .await + .expect("fixture"); + } + let extra_id = state + .db + .lookup_community_by_host_for_management(&extra) + .await + .unwrap() + .unwrap() + .id; + let config = Arc::make_mut(&mut Arc::get_mut(&mut state).expect("exclusive").config); + config.relay_url = format!("wss://{canonical}"); + set_creation(&mut state, false); + let app = build_router(state.clone()); + for host in [&canonical, &extra] { + let response = app + .clone() + .oneshot( + Request::builder() + .uri("/") + .header("host", host.as_str()) + .header("accept", "application/nostr+json") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + if host == &canonical { + StatusCode::OK + } else { + StatusCode::NOT_FOUND + } + ); + } + for path in [ + "/query", + "/api/invites/claim", + "/upload", + "/git/owner/repo/info/refs", + "/huddle/id/audio", + "/invite/token", + ] { + let response = app + .clone() + .oneshot( + Request::builder() + .uri(path) + .header("host", extra.as_str()) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NOT_FOUND, "{path}"); + } + // UUID selection through the authenticated operator is not an ordinary + // serving escape: even a valid owner cannot mint an extra's invite. + let body = serde_json::json!({"community_id":extra_id.to_string(), "actor_pubkey":owner.public_key().to_hex()}).to_string(); + let response = signed_operator_request( + state.clone(), + &operator, + "POST", + "/operator/communities/invites", + Some(body), + ) + .await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!(read_json(response).await["code"], "community_not_served"); + // A valid invite for the extra, presented on the canonical Host, may + // never enroll the caller into the extra (host is authoritative). + let invite = state + .db + .mint_relay_invite_as_admin(extra_id, &owner.public_key().to_hex(), 3600, Some(1)) + .await + .expect("invite fixture"); + let joiner = Keys::generate(); + let body = serde_json::json!({"code":invite.code, "community_id":extra_id.to_string(), "communityHost":extra}).to_string(); + let path = "/api/invites/claim"; + let url = format!("https://{canonical}{path}"); + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri(path) + .header("host", canonical) + .header("content-type", "application/json") + .header( + "authorization", + nip98_auth_header(&joiner, &url, "POST", Some(body.as_bytes())), + ) + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + assert!(!response.status().is_success()); + assert!(state + .db + .get_relay_member(extra_id, &joiner.public_key().to_hex()) + .await + .unwrap() + .is_none()); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn disabled_creation_rejects_both_modes_retries_and_concurrency_without_rows() { + let operator = Keys::generate(); + let owner = Keys::generate(); + let mut state = policy_state(&operator).await; + let (policy, _, host) = reserved_host_policy(); + Arc::make_mut(&mut Arc::get_mut(&mut state).expect("exclusive").config) + .nip_fi_provision_binding = Some(policy); + set_creation(&mut state, false); + for _ in 0..2 { + let (create, legacy) = tokio::join!( + provision_community(state.clone(), &operator, &host, &owner), + legacy_request(state.clone(), &operator, &host, Some(&owner)), + ); + for response in [create, legacy] { + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_eq!( + read_json(response).await["code"], + "community_creation_disabled" + ); + } + } + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM communities WHERE host = $1") + .bind(&host) + .fetch_one(state.db.pool()) + .await + .expect("community count"); + assert_eq!(count, 0); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM relay_members WHERE pubkey = $1") + .bind(owner.public_key().to_hex()) + .fetch_one(state.db.pool()) + .await + .expect("owner count"); + assert_eq!(count, 0); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM community_nip_fi_issuers i JOIN communities c ON c.id = i.community_id WHERE c.host = $1") + .bind(&host).fetch_one(state.db.pool()).await.expect("issuer count"); + assert_eq!(count, 0); + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM events WHERE kind = $1 AND tags::text LIKE $2", + ) + .bind(KIND_NIP43_MEMBERSHIP_LIST as i32) + .bind(format!("%{}%", owner.public_key().to_hex())) + .fetch_one(state.db.pool()) + .await + .expect("snapshot count"); + assert_eq!(count, 0); + let outsider = Keys::generate(); + let response = legacy_request(state, &outsider, &host, None).await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + assert_ne!( + read_json(response).await["code"], + "community_creation_disabled" + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn disabled_creation_preserves_existing_convergence_and_capability_quota() { + let operator = Keys::generate(); + let owner = Keys::generate(); + let mut state = policy_state(&operator).await; + let host = format!("policy-{}.example", Uuid::new_v4().simple()); + let _fixture = state + .db + .create_community_with_owner(&host, &owner.public_key().to_hex(), &state.relay_keypair) + .await + .expect("seed existing-community fixture"); + let before = owned(policy_state(&operator).await, &operator, &owner).await; + assert_eq!(before["can_create"], true); + let id = state + .db + .lookup_community_by_host_for_management(&host) + .await + .expect("lookup") + .expect("row") + .id; + state + .db + .bind_nip_fi_issuers(id, &[NIP_FI_ISSUER.to_owned()]) + .await + .expect("binding"); + Arc::make_mut(&mut Arc::get_mut(&mut state).expect("exclusive").config).relay_url = + format!("wss://{host}"); + set_creation(&mut state, false); + for _ in 0..2 { + let response = legacy_request(state.clone(), &operator, &host, Some(&owner)).await; + assert_eq!(response.status(), StatusCode::OK); + let json = read_json(response).await; + assert_eq!(json["status"], "existed"); + assert_eq!(json["community_id"], id.to_string()); + } + let issuers: Vec = sqlx::query_scalar( + "SELECT issuer FROM community_nip_fi_issuers WHERE community_id = $1", + ) + .bind(id.as_uuid()) + .fetch_all(state.db.pool()) + .await + .expect("bindings"); + assert_eq!(issuers, vec![NIP_FI_ISSUER.to_owned()]); + let after = owned(state.clone(), &operator, &owner).await; + assert_eq!(after["can_create"], false); + assert_eq!(after["quota_used"], before["quota_used"]); + assert_eq!(after["quota_limit"], before["quota_limit"]); + assert_eq!(after["communities"], before["communities"]); + assert_eq!( + provision_community(state, &operator, &host, &owner) + .await + .status(), + StatusCode::FORBIDDEN + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn disabled_creation_preserves_archive_management_and_owner_refusal() { + let operator = Keys::generate(); + let owner = Keys::generate(); + let mut state = policy_state(&operator).await; + let host = format!("policy-{}.example", Uuid::new_v4().simple()); + let _fixture = state + .db + .create_community_with_owner(&host, &owner.public_key().to_hex(), &state.relay_keypair) + .await + .expect("seed existing-community fixture"); + set_creation(&mut state, false); + let body = serde_json::json!({"host":host, "owner_pubkey":owner.public_key().to_hex()}) + .to_string(); + let archived = signed_operator_request( + state.clone(), + &operator, + "POST", + "/operator/communities/archive", + Some(body.clone()), + ) + .await; + assert_eq!(archived.status(), StatusCode::OK); + let existing = legacy_request(state.clone(), &operator, &host, None).await; + assert_eq!(existing.status(), StatusCode::FORBIDDEN); + assert_eq!( + read_json(existing).await["code"], + "community_creation_disabled" + ); + assert_eq!( + legacy_request(state.clone(), &operator, &host, Some(&owner)) + .await + .status(), + StatusCode::FORBIDDEN + ); + let restored = signed_operator_request( + state.clone(), + &operator, + "POST", + "/operator/communities/unarchive", + Some(body), + ) + .await; + assert_eq!(restored.status(), StatusCode::OK); + assert_eq!( + legacy_request(state, &operator, &host, Some(&owner)) + .await + .status(), + StatusCode::FORBIDDEN + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn disabled_creation_keeps_canonical_bootstrap_and_unknown_hosts_unmapped() { + let operator = Keys::generate(); + let mut state = policy_state(&operator).await; + set_creation(&mut state, false); + let canonical = format!("canonical-{}.example", Uuid::new_v4().simple()); + let seeded = crate::handlers::community_provisioning::ensure_deployment_community( + &state.db, None, &canonical, + ) + .await + .expect("bootstrap") + .expect("row"); + assert!(seeded.created); + let again = crate::handlers::community_provisioning::ensure_deployment_community( + &state.db, None, &canonical, + ) + .await + .expect("restart") + .expect("row"); + assert_eq!(seeded.id, again.id); + assert!(!again.created); + let missing = format!("unknown-{}.example", Uuid::new_v4().simple()); + assert!(crate::tenant::bind_community(&state.db, &missing) + .await + .is_err()); + assert!(state + .db + .lookup_community_by_host_for_management(&missing) + .await + .expect("lookup") + .is_none()); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn disabled_legacy_preserves_deletion_and_tombstone_refusals() { + let operator = Keys::generate(); + let owner = Keys::generate(); + let mut state = policy_state(&operator).await; + let host = format!("policy-{}.example", Uuid::new_v4().simple()); + let _fixture = state + .db + .create_community_with_owner(&host, &owner.public_key().to_hex(), &state.relay_keypair) + .await + .expect("seed existing-community fixture"); + let id = state + .db + .lookup_community_by_host_for_management(&host) + .await + .expect("lookup") + .expect("row") + .id; + set_creation(&mut state, false); + archive_for_owner_deletion(&state, &host, &owner).await; + let response = signed_operator_request( + state.clone(), + &operator, + "POST", + "/operator/communities/delete", + Some(owner_delete_body(&host, &owner, Uuid::new_v4())), + ) + .await; + assert_eq!(response.status(), StatusCode::ACCEPTED); + // Queue deletion while this is an extra community: the deployment + // community is protected from archival and deletion. Then select it + // as canonical to exercise legacy convergence against pending deletion. + Arc::make_mut(&mut Arc::get_mut(&mut state).expect("exclusive").config).relay_url = + format!("wss://{host}"); + let rotation = + legacy_request(state.clone(), &operator, &host, Some(&Keys::generate())).await; + assert_eq!(rotation.status(), StatusCode::CONFLICT); + assert!(read_json(rotation).await["error"] + .as_str() + .expect("error") + .contains("deletion is pending")); + for lifecycle in ["quiescing", "fenced", "tombstone"] { + let mut tx = state.db.pool().begin().await.expect("fixture transaction"); + sqlx::query("SELECT set_config('buzz.deletion_executor_community', $1, true), set_config('buzz.deletion_fence_generation', '0', true)") + .bind(id.to_string()).execute(&mut *tx).await.expect("executor fixture"); + sqlx::query("UPDATE communities SET deletion_state = $2 WHERE id = $1") + .bind(id.as_uuid()) + .bind(lifecycle) + .execute(&mut *tx) + .await + .expect("lifecycle fixture"); + tx.commit().await.expect("commit fixture"); + assert!(matches!( + state.db.existing_configured_community(&host).await, + Err(buzz_db::DbError::AccessDenied(_)) + )); + let denied = legacy_request(state.clone(), &operator, &host, None).await; + // Preserve the old ensure persistence refusal rather than report missing. + assert_eq!(denied.status(), StatusCode::INTERNAL_SERVER_ERROR); + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn disabled_creation_preserves_admin_joined_transfer_and_binding_reads() { + let operator = Keys::generate(); + let owner = Keys::generate(); + let recipient = Keys::generate(); + let mut state = policy_state(&operator).await; + let host = format!("policy-{}.example", Uuid::new_v4().simple()); + let _fixture = state + .db + .create_community_with_owner(&host, &owner.public_key().to_hex(), &state.relay_keypair) + .await + .expect("fixture"); + let id = state + .db + .lookup_community_by_host_for_management(&host) + .await + .expect("lookup") + .expect("row") + .id; + set_creation(&mut state, false); + Arc::make_mut(&mut Arc::get_mut(&mut state).expect("exclusive").config).admin = + Some(crate::config::AdminConfig { + host: INGRESS_HOST.to_owned(), + auth: crate::config::AdminAuth::Nip98, + web_dir: None, + }); + let path = "/api/admin/v1/probe"; + let url = format!("https://{INGRESS_HOST}{path}"); + let probe = operator_request_with_auth( + state.clone(), + "GET", + path, + None, + nip98_auth_header(&operator, &url, "GET", None), + ) + .await; + assert_eq!(probe.status(), StatusCode::OK); + assert_eq!(read_json(probe).await["role"], "operator"); + // An authenticated administrator can still inspect and moderate an + // extra community through the admin authority, despite serving denial. + let path = format!( + "/api/admin/v1/members/{}?communityHost={host}", + owner.public_key().to_hex() + ); + let url = format!("https://{INGRESS_HOST}{path}"); + let read = operator_request_with_auth( + state.clone(), + "GET", + &path, + None, + nip98_auth_header(&operator, &url, "GET", None), + ) + .await; + assert_eq!(read.status(), StatusCode::OK); + let target = Keys::generate(); + let path = format!( + "/api/admin/v1/members/{}/ban?communityHost={host}", + target.public_key().to_hex() + ); + let url = format!("https://{INGRESS_HOST}{path}"); + let body = serde_json::json!({"requestId": Uuid::new_v4(), "reason":"cleanup"}).to_string(); + let ban = operator_request_with_auth( + state.clone(), + "POST", + &path, + Some(body.clone()), + nip98_auth_header(&operator, &url, "POST", Some(body.as_bytes())), + ) + .await; + assert!( + ban.status().is_success(), + "admin direct action: {}", + read_json(ban).await + ); + let path = "/api/admin/v1/probe"; + let url = format!("https://{INGRESS_HOST}{path}"); + let stranger = operator_request_with_auth( + state.clone(), + "GET", + path, + None, + nip98_auth_header(&Keys::generate(), &url, "GET", None), + ) + .await; + assert_eq!(stranger.status(), StatusCode::FORBIDDEN); + let path = format!( + "/operator/communities/joined?member_pubkey={}", + owner.public_key().to_hex() + ); + let joined = signed_operator_request(state.clone(), &operator, "GET", &path, None).await; + assert_eq!(joined.status(), StatusCode::OK); + assert!(read_json(joined).await.to_string().contains(&host)); + let path = format!("/operator/communities/nip-fi-binding?host={host}"); + assert_eq!( + signed_operator_request(state.clone(), &operator, "GET", &path, None) + .await + .status(), + StatusCode::OK + ); + let path = format!( + "/operator/communities/availability?host=free-{}.example", + Uuid::new_v4().simple() + ); + let available = signed_operator_request(state.clone(), &operator, "GET", &path, None).await; + assert_eq!(available.status(), StatusCode::OK); + assert_eq!(read_json(available).await["available"], true); + let path = format!( + "/operator/communities/nip-fi-upgrade?operation_id={}", + Uuid::new_v4() + ); + assert_eq!( + signed_operator_request(state.clone(), &operator, "GET", &path, None) + .await + .status(), + StatusCode::NOT_FOUND + ); + let transfer = serde_json::json!({"community_id": id.to_string(), "expected_owner_pubkey":owner.public_key().to_hex(), "new_owner_pubkey":recipient.public_key().to_hex()}).to_string(); + assert_eq!( + signed_operator_request( + state.clone(), + &operator, + "POST", + "/operator/communities/transfer", + Some(transfer) + ) + .await + .status(), + StatusCode::OK + ); + assert_snapshot_roles( + &state, + id, + &[ + (&owner.public_key().to_hex(), "member"), + (&recipient.public_key().to_hex(), "owner"), + ], + ) + .await; + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn enabled_policy_keeps_legacy_missing_host_creation() { + let operator = Keys::generate(); + let owner = Keys::generate(); + let state = policy_state(&operator).await; + assert!(state.config.multi_community_relay); + let host = format!("policy-{}.example", Uuid::new_v4().simple()); + let created = legacy_request(state.clone(), &operator, &host, Some(&owner)).await; + assert_eq!(created.status(), StatusCode::OK); + assert_eq!(read_json(created).await["status"], "created"); + let again = legacy_request(state.clone(), &operator, &host, Some(&owner)).await; + assert_eq!(again.status(), StatusCode::OK); + assert_eq!(read_json(again).await["status"], "existed"); + } +} diff --git a/crates/buzz-relay/src/api/operator/postgres_tests/initial_policy_postgres_tests.rs b/crates/buzz-relay/src/api/operator/postgres_tests/initial_policy_postgres_tests.rs new file mode 100644 index 00000000000..e371de9186d --- /dev/null +++ b/crates/buzz-relay/src/api/operator/postgres_tests/initial_policy_postgres_tests.rs @@ -0,0 +1,205 @@ +mod postgres_tests { + use super::super::*; + + async fn create( + state: &Arc, + operator: &Keys, + owner: &Keys, + host: &str, + create_only: bool, + policy: Option, + ) -> axum::response::Response { + let mut body = serde_json::json!({"host":host,"initial_owner_pubkey":owner.public_key().to_hex(),"create_only":create_only}); + if let Some(policy) = policy { + body["initial_requires_nip_fi"] = policy; + } + signed_operator_request( + state.clone(), + operator, + "POST", + "/operator/communities", + Some(body.to_string()), + ) + .await + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn initial_policy_and_same_owner_replay_journey() { + let operator = Keys::generate(); + let (binding, reserved, control) = reserved_host_policy(); + let mut state = + operator_test_state_with_policy(std::slice::from_ref(&operator), Some(binding)) + .await + .unwrap(); + let owners: Vec<_> = (0..4).map(|_| Keys::generate()).collect(); + let owner = &owners[3]; + assert!(!state.config.nip_fi_changes); + for (index, policy) in [ + None, + Some(Value::Null), + Some(Value::Bool(false)), + Some(Value::Bool(true)), + ] + .into_iter() + .enumerate() + { + let host = control.replacen("acme.", &format!("policy-{index}."), 1); + let required = policy == Some(Value::Bool(true)); + let owner = &owners[index]; + let response = create(&state, &operator, owner, &host, true, policy).await; + assert!(response.status().is_success()); + let body = read_json(response).await; + assert_eq!(body["status"], "created"); + assert_eq!(body["requires_nip_fi"], required); + let record = state + .db + .lookup_community_by_host(&host) + .await + .unwrap() + .unwrap(); + let stored = state + .db + .community_auth_policy(record.id) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.requires_nip_fi, required); + assert_eq!(stored.policy_generation, i64::from(required)); + let response = create( + &state, + &operator, + owner, + &host, + true, + Some(Value::Bool(!required)), + ) + .await; + assert!(response.status().is_success()); + let replay = read_json(response).await; + assert_eq!(replay["status"], "existed"); + assert_eq!(replay["requires_nip_fi"], required); + assert_eq!( + state + .db + .community_auth_policy(record.id) + .await + .unwrap() + .unwrap(), + stored + ); + } + for value in [false, true] { + let response = create( + &state, + &operator, + owner, + &control, + false, + Some(Value::Bool(value)), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + read_json(response).await["code"], + "initial_policy_requires_create_only" + ); + } + let refused = create( + &state, + &operator, + owner, + &reserved, + true, + Some(Value::Bool(true)), + ) + .await; + assert_eq!(refused.status(), StatusCode::BAD_REQUEST); + assert_eq!(read_json(refused).await["code"], "reserved_host"); + let outside = format!("outside-{}.example", Uuid::new_v4().simple()); + let refusal = create( + &state, + &operator, + owner, + &outside, + true, + Some(Value::Bool(true)), + ) + .await; + assert_eq!(refusal.status(), StatusCode::BAD_REQUEST); + assert_eq!(read_json(refusal).await["code"], "nip_fi_binding_required"); + assert!(state + .db + .lookup_community_by_host(&outside) + .await + .unwrap() + .is_none()); + let host = control.replacen("acme.", "policy-3.", 1); + let record = state + .db + .lookup_community_by_host(&host) + .await + .unwrap() + .unwrap(); + sqlx::query("UPDATE communities SET requires_nip_fi = false, policy_generation = policy_generation + 1 WHERE id = $1") + .bind(record.id.as_uuid()).execute(state.db.pool()).await.unwrap(); + let disabled = state + .db + .community_auth_policy(record.id) + .await + .unwrap() + .unwrap(); + Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config).nip_fi_provision_binding = + None; + let response = create( + &state, + &operator, + owner, + &host, + true, + Some(Value::Bool(true)), + ) + .await; + assert!(response.status().is_success()); + let replay = read_json(response).await; + assert_eq!(replay["status"], "existed"); + assert_eq!(replay["requires_nip_fi"], false); + assert_eq!( + state + .db + .community_auth_policy(record.id) + .await + .unwrap() + .unwrap(), + disabled + ); + let outside = format!("unbound-{}.example", Uuid::new_v4().simple()); + let response = create( + &state, + &operator, + owner, + &outside, + true, + Some(Value::Bool(true)), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!(read_json(response).await["code"], "nip_fi_binding_required"); + assert!(state + .db + .lookup_community_by_host(&outside) + .await + .unwrap() + .is_none()); + let unauthorized = create( + &state, + &Keys::generate(), + owner, + &outside, + true, + Some(Value::Bool(true)), + ) + .await; + assert_eq!(unauthorized.status(), StatusCode::FORBIDDEN); + } +} diff --git a/crates/buzz-relay/src/api/operator/postgres_tests/invite_postgres_tests.rs b/crates/buzz-relay/src/api/operator/postgres_tests/invite_postgres_tests.rs new file mode 100644 index 00000000000..3984255d5a7 --- /dev/null +++ b/crates/buzz-relay/src/api/operator/postgres_tests/invite_postgres_tests.rs @@ -0,0 +1,381 @@ +mod postgres_tests { + use super::super::*; + + const PATH: &str = "/operator/communities/invites"; + + async fn mint(state: &Arc, operator: &Keys, body: Value) -> axum::response::Response { + signed_operator_request( + state.clone(), + operator, + "POST", + PATH, + Some(body.to_string()), + ) + .await + } + + /// The refusal's text, after checking its status and stable code. + async fn error(response: axum::response::Response, status: StatusCode, code: &str) -> String { + assert_eq!(response.status(), status); + let json = read_json(response).await; + assert_eq!(json["code"], code, "{json}"); + json["error"].as_str().expect("error text").to_owned() + } + + /// Claim `code` on the community host the way a joining app does. + async fn claim(state: &Arc, host: &str, joiner: &Keys, code: &str) -> StatusCode { + let body = serde_json::json!({ "code": code }).to_string(); + let auth = nip98_auth_header( + joiner, + &format!("https://{host}/api/invites/claim"), + "POST", + Some(body.as_bytes()), + ); + build_router(state.clone()) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/invites/claim") + .header(header::HOST, host) + .header(header::AUTHORIZATION, auth) + .header(header::CONTENT_TYPE, "application/json") + .body(Body::from(body)) + .expect("request"), + ) + .await + .expect("response") + .status() + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn operator_mints_invites_only_for_relay_owners_and_admins() { + let operator = Keys::generate(); + let Some(state) = operator_test_state(std::slice::from_ref(&operator)).await else { + return; + }; + let [owner, admin, member, outsider, joiner] = std::array::from_fn(|_| Keys::generate()); + let host = format!("community-{}.example", Uuid::new_v4().simple()); + assert_eq!( + provision_community(state.clone(), &operator, &host, &owner) + .await + .status(), + StatusCode::OK + ); + let community = state + .db + .lookup_community_by_host(&host) + .await + .expect("lookup community") + .expect("community exists") + .id; + for (keys, role) in [(&admin, "admin"), (&member, "member")] { + state + .db + .add_relay_member( + community, + &keys.public_key().to_hex(), + role, + None, + &state.relay_keypair, + ) + .await + .map(|write| write.outcome) + .expect("seed member"); + } + let request = |actor: &Keys, limits: Value| { + let mut body = serde_json::json!({ + "community_id": community.to_string(), + "actor_pubkey": actor.public_key().to_hex(), + }); + body.as_object_mut() + .expect("object") + .extend(limits.as_object().expect("limits").clone()); + body + }; + + // An owner gets the /api/invites contract with its defaults. + let response = mint(&state, &operator, request(&owner, serde_json::json!({}))).await; + assert_eq!(response.status(), StatusCode::OK); + let json = read_json(response).await; + let code = json["code"].as_str().expect("code").to_owned(); + assert_eq!(json["url"], format!("https://{host}/invite/{code}")); + assert_eq!(json["max_uses"], Value::Null); + let expires_at = json["expires_at"].as_i64().expect("expires_at"); + let default_expiry = chrono::Utc::now().timestamp() + 72 * 60 * 60; + assert!((default_expiry - 60..=default_expiry).contains(&expires_at)); + // The code is an ordinary relay invite: the join flow claims it. + assert_eq!(claim(&state, &host, &joiner, &code).await, StatusCode::OK); + assert_eq!( + state + .db + .get_relay_member(community, &joiner.public_key().to_hex()) + .await + .expect("joiner lookup") + .expect("joiner joined") + .role, + "member" + ); + + // An admin may mint too, with bounded limits. + let response = mint( + &state, + &operator, + request( + &admin, + serde_json::json!({ "ttl_secs": 3600, "max_uses": 5 }), + ), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let json = read_json(response).await; + assert_eq!(json["max_uses"], 5); + assert_eq!(json["uses_remaining"], 5); + + // A restricted admin keeps the role but can no longer mint. + state + .db + .ban_community_member( + community, + admin.public_key().as_bytes(), + owner.public_key().as_bytes(), + None, + None, + ) + .await + .expect("ban admin"); + assert_eq!( + error( + mint(&state, &operator, request(&admin, serde_json::json!({}))).await, + StatusCode::FORBIDDEN, + "restricted" + ) + .await, + "invite_restricted" + ); + + // The relay's roster decides authority, whatever the operator asserts. + for actor in [&member, &outsider] { + assert_eq!( + error( + mint(&state, &operator, request(actor, serde_json::json!({}))).await, + StatusCode::FORBIDDEN, + "not_owner" + ) + .await, + "only relay owners and admins can create invites" + ); + } + // Same bounds as /api/invites. + for (limits, message) in [ + ( + serde_json::json!({ "ttl_secs": 30 * 24 * 60 * 60 + 1 }), + "ttl_secs must be between", + ), + ( + serde_json::json!({ "max_uses": 0 }), + "max_uses must be between", + ), + ( + serde_json::json!({ "max_uses": 10_001 }), + "max_uses must be between", + ), + ] { + let text = error( + mint(&state, &operator, request(&owner, limits)).await, + StatusCode::BAD_REQUEST, + "invalid_request", + ) + .await; + assert!(text.starts_with(message), "{text}"); + } + let mut unknown = request(&owner, serde_json::json!({})); + unknown["role"] = "owner".into(); + error( + mint(&state, &operator, unknown).await, + StatusCode::BAD_REQUEST, + "invalid_request", + ) + .await; + let mut bad_actor = request(&owner, serde_json::json!({})); + bad_actor["actor_pubkey"] = "not-a-pubkey".into(); + error( + mint(&state, &operator, bad_actor).await, + StatusCode::BAD_REQUEST, + "invalid_request", + ) + .await; + // Only configured operators may vouch for a caller; that refusal is the + // operator's own misconfiguration, so it carries its own code. + error( + mint( + &state, + &Keys::generate(), + request(&owner, serde_json::json!({})), + ) + .await, + StatusCode::FORBIDDEN, + "not_operator", + ) + .await; + // Unknown and archived communities have nothing to invite to. + let mut unknown_community = request(&owner, serde_json::json!({})); + unknown_community["community_id"] = Uuid::new_v4().to_string().into(); + assert_eq!( + error( + mint(&state, &operator, unknown_community).await, + StatusCode::NOT_FOUND, + "community_not_found" + ) + .await, + "community not found" + ); + archive_for_owner_deletion(&state, &host, &owner).await; + assert_eq!( + error( + mint(&state, &operator, request(&owner, serde_json::json!({}))).await, + StatusCode::NOT_FOUND, + "community_not_found" + ) + .await, + "community not found" + ); + } + + /// Mint on a task while `holder` keeps an uncommitted change, wait until + /// the mint is blocked on it, then commit it and return the mint response. + async fn mint_across_commit( + state: &Arc, + operator: &Keys, + body: Value, + mut holder: sqlx::Transaction<'static, sqlx::Postgres>, + ) -> axum::response::Response { + let holder_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *holder) + .await + .expect("holder pid"); + let task = tokio::spawn({ + let (state, operator) = (state.clone(), operator.clone()); + async move { mint(&state, &operator, body).await } + }); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + loop { + let blocked: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity \ + WHERE $1 = ANY(pg_blocking_pids(pid)))", + ) + .bind(holder_pid) + .fetch_one(state.db.pool()) + .await + .expect("read lock waiters"); + if blocked { + break; + } + assert!(!task.is_finished(), "the mint finished without waiting"); + assert!( + std::time::Instant::now() < deadline, + "the mint never waited for the uncommitted change" + ); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + holder.commit().await.expect("commit holder"); + task.await.expect("mint task") + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn operator_mint_rechecks_role_and_lifecycle_inside_the_mint() { + let operator = Keys::generate(); + let Some(state) = operator_test_state(std::slice::from_ref(&operator)).await else { + return; + }; + let [owner, admin] = std::array::from_fn(|_| Keys::generate()); + let host = format!("community-{}.example", Uuid::new_v4().simple()); + assert_eq!( + provision_community(state.clone(), &operator, &host, &owner) + .await + .status(), + StatusCode::OK + ); + let community = state + .db + .lookup_community_by_host(&host) + .await + .expect("lookup community") + .expect("community exists") + .id; + let admin_hex = admin.public_key().to_hex(); + state + .db + .add_relay_member(community, &admin_hex, "admin", None, &state.relay_keypair) + .await + .map(|write| write.outcome) + .expect("seed admin"); + let request = |actor: &Keys| { + serde_json::json!({ + "community_id": community.to_string(), + "actor_pubkey": actor.public_key().to_hex(), + }) + }; + let invites = || async { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM relay_invites WHERE community_id = $1", + ) + .bind(community.as_uuid()) + .fetch_one(state.db.pool()) + .await + .expect("count invites") + }; + + // A demotion that lands while the mint is in flight refuses it. + let mut holder = state.db.pool().begin().await.expect("begin demotion"); + sqlx::query( + "UPDATE relay_members SET role = 'member' WHERE community_id = $1 AND pubkey = $2", + ) + .bind(community.as_uuid()) + .bind(&admin_hex) + .execute(&mut *holder) + .await + .expect("demote admin"); + error( + mint_across_commit(&state, &operator, request(&admin), holder).await, + StatusCode::FORBIDDEN, + "not_owner", + ) + .await; + assert_eq!(invites().await, 0, "a refused mint must not persist"); + + // A deletion fence that lands after the host lookup refuses it too. + let mut holder = state.db.pool().begin().await.expect("begin fence"); + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(buzz_db::deletion::community_deletion_lock_key(community)) + .execute(&mut *holder) + .await + .expect("take deletion lock"); + // Fence as the deletion executor does, so the tombstone guard admits it. + sqlx::query( + "SELECT set_config('buzz.deletion_executor_community', $1::text, true), \ + set_config('buzz.deletion_fence_generation', (deletion_fence_generation + 1)::text, true) \ + FROM communities WHERE id = $1", + ) + .bind(community.as_uuid()) + .execute(&mut *holder) + .await + .expect("act as deletion executor"); + sqlx::query( + "UPDATE communities SET deletion_state = 'quiescing', \ + deletion_fence_generation = deletion_fence_generation + 1 WHERE id = $1", + ) + .bind(community.as_uuid()) + .execute(&mut *holder) + .await + .expect("fence community"); + error( + mint_across_commit(&state, &operator, request(&owner), holder).await, + StatusCode::SERVICE_UNAVAILABLE, + "unavailable", + ) + .await; + assert_eq!(invites().await, 0, "a fenced mint must not persist"); + } +} diff --git a/crates/buzz-relay/src/api/operator/postgres_tests/policy_tests.rs b/crates/buzz-relay/src/api/operator/postgres_tests/policy_tests.rs new file mode 100644 index 00000000000..db0bbddbede --- /dev/null +++ b/crates/buzz-relay/src/api/operator/postgres_tests/policy_tests.rs @@ -0,0 +1,429 @@ +mod postgres_tests { + use super::super::*; + // Included in operator::postgres_tests to reuse the real signed HTTP fixture. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn policy_operator_http_transition_history_guards_and_modes() { + let operator = Keys::generate(); + let owner = Keys::generate(); + let (binding, _, host) = reserved_host_policy(); + let mut state = + operator_test_state_with_policy(std::slice::from_ref(&operator), Some(binding)) + .await + .unwrap(); + Arc::get_mut(&mut state).unwrap().nip98_replay = + Arc::new(SeenOnceReplayGuard(Mutex::new(HashSet::new()))); + let issuer_policy = buzz_auth::IssuerPolicy::new( + NIP_FI_ISSUER.to_owned(), + vec!["https://commands.example".into()], + buzz_auth::TokenClass::DedicatedNipFi, + buzz_auth::FreshnessClass::OfflineJwt, + vec![jsonwebtoken::Algorithm::ES256], + 30, + 3600, + None, + buzz_auth::JwksSourceContract::new(format!("{NIP_FI_ISSUER}/jwks"), 300, 86400) + .unwrap(), + ) + .unwrap(); + let config = Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config); + config.nip_fi.registry.insert(issuer_policy); + config.nip_fi.mode = buzz_auth::NipFiMode::Shadow; + config.nip_fi_changes = false; + assert_eq!( + provision_community(state.clone(), &operator, &host, &owner) + .await + .status(), + StatusCode::OK + ); + let community = state + .db + .lookup_community_by_host(&host) + .await + .unwrap() + .unwrap(); + let path = "/operator/communities/nip-fi-policy"; + let current_path = format!("{path}?community_id={}&expected_host={host}", community.id); + let current = + fresh_upgrade_request(state.clone(), &operator, "GET", ¤t_path, None).await; + assert_eq!(current.headers()[header::CACHE_CONTROL], "no-store"); + let current = read_json(current).await; + assert_eq!(current["expected_policy_generation"], 0); + assert_eq!(current["expected_requires_nip_fi"], false); + let mut body = serde_json::json!({ + "operation_id": Uuid::new_v4(), "community_id": community.id.to_string(), + "expected_host": host, "actor_pubkey": owner.public_key().to_hex(), + "expected_owner_pubkey": owner.public_key().to_hex(), "expected_issuer": NIP_FI_ISSUER, + "requires_nip_fi": true, "expected_policy_generation": 0, "expected_requires_nip_fi": false, + }); + let disabled = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(body.to_string()), + ) + .await; + assert_eq!(disabled.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(read_json(disabled).await["code"], "upgrades_disabled"); + for (field, value) in [ + ("operation_id", serde_json::json!(Uuid::nil())), + ("community_id", serde_json::json!(Uuid::nil())), + ("expected_host", serde_json::json!(host.to_uppercase())), + ("actor_pubkey", serde_json::json!("not-a-pubkey")), + ("expected_policy_generation", serde_json::json!(-1)), + ("expected_issuer", serde_json::json!("")), + ("unknown", serde_json::json!(true)), + ] { + let mut invalid = body.clone(); + invalid[field] = value; + let response = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(invalid.to_string()), + ) + .await; + assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{field}"); + assert_eq!(read_json(response).await["code"], "invalid_request"); + } + Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config).nip_fi_changes = true; + for (field, value, code) in [ + ( + "expected_issuer", + "https://unapproved.example".to_owned(), + "issuer_conflict", + ), + ( + "expected_host", + "outside.example".to_owned(), + "issuer_conflict", + ), + ( + "actor_pubkey", + Keys::generate().public_key().to_hex(), + "owner_conflict", + ), + ( + "expected_owner_pubkey", + Keys::generate().public_key().to_hex(), + "owner_conflict", + ), + ] { + let mut refused = body.clone(); + refused[field] = value.into(); + let response = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(refused.to_string()), + ) + .await; + assert_eq!(response.status(), StatusCode::CONFLICT); + assert_eq!(read_json(response).await["code"], code); + } + let mut history = Vec::new(); + for (generation, desired) in [(1, true), (2, false), (3, true)] { + body["operation_id"] = Uuid::new_v4().to_string().into(); + body["requires_nip_fi"] = desired.into(); + body["expected_policy_generation"] = (generation - 1).into(); + body["expected_requires_nip_fi"] = (!desired).into(); + if desired { + body["expected_issuer"] = NIP_FI_ISSUER.into(); + } else { + body.as_object_mut().unwrap().remove("expected_issuer"); + } + let response = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(body.to_string()), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); + let accepted = read_json(response).await; + assert_eq!(accepted["receipt"]["policy_generation"], generation); + assert_eq!(accepted["receipt"]["requires_nip_fi"], desired); + assert_eq!(accepted["effective_required"], desired); + assert_eq!( + accepted["receipt"]["state"], + if desired { "pending" } else { "applied" } + ); + if generation == 1 { + let binding = Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config) + .nip_fi_provision_binding + .take(); + let mut fresh = body.clone(); + let refused_id = Uuid::new_v4(); + fresh["operation_id"] = refused_id.to_string().into(); + fresh["expected_policy_generation"] = 1.into(); + fresh["expected_requires_nip_fi"] = true.into(); + let refused = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(fresh.to_string()), + ) + .await; + assert_eq!(refused.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + read_json(refused).await["code"], + "authorization_unavailable" + ); + assert!(state + .db + .community_auth_policy_status(refused_id, &operator.public_key().to_hex()) + .await + .unwrap() + .is_none()); + let historical = read_json( + fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(body.to_string()), + ) + .await, + ) + .await; + assert_eq!(historical["receipt"]["state"], "unavailable"); + assert_eq!(historical["receipt"]["policy_generation"], 1); + Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config) + .nip_fi_provision_binding = binding; + let text = body.to_string(); + let auth = fresh_upgrade_auth( + &operator, + &format!("http://{INGRESS_HOST}{path}"), + "POST", + Some(text.as_bytes()), + ); + let first = operator_request_with_auth( + state.clone(), + "POST", + path, + Some(text.clone()), + auth.clone(), + ) + .await; + assert_eq!(first.status(), StatusCode::OK); + let replayed_signature = + operator_request_with_auth(state.clone(), "POST", path, Some(text), auth).await; + assert_eq!(replayed_signature.status(), StatusCode::UNAUTHORIZED); + assert_eq!( + replayed_signature.headers()[header::CACHE_CONTROL], + "no-store" + ); + } + history.push(body.clone()); + for old in &history { + let id = old["operation_id"].as_str().unwrap(); + let historical = fresh_upgrade_request( + state.clone(), + &operator, + "GET", + &format!("{path}?operation_id={id}"), + None, + ) + .await; + assert_eq!(historical.status(), StatusCode::OK); + let historical = read_json(historical).await; + assert_eq!( + historical["receipt"]["current_policy_generation"], + generation + ); + assert_eq!( + historical["receipt"]["state"], + if old == &body { + if desired { + "pending" + } else { + "applied" + } + } else { + "superseded" + } + ); + let replay = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(old.to_string()), + ) + .await; + assert_eq!(read_json(replay).await, historical); + } + let current = read_json( + fresh_upgrade_request(state.clone(), &operator, "GET", ¤t_path, None).await, + ) + .await; + assert_eq!(current["expected_policy_generation"], generation); + assert_eq!(current["expected_requires_nip_fi"], desired); + } + let mut stale = history[0].clone(); + stale["operation_id"] = Uuid::new_v4().to_string().into(); + let response = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(stale.to_string()), + ) + .await; + assert_eq!(response.status(), StatusCode::CONFLICT); + assert_eq!(read_json(response).await["code"], "policy_conflict"); + let mut conflict = history[0].clone(); + conflict["requires_nip_fi"] = false.into(); + conflict.as_object_mut().unwrap().remove("expected_issuer"); + let response = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(conflict.to_string()), + ) + .await; + assert_eq!(read_json(response).await["code"], "idempotency_conflict"); + Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config).nip_fi_changes = false; + let response = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(history[0].to_string()), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + for mode in [buzz_auth::NipFiMode::Off, buzz_auth::NipFiMode::Enforce] { + Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config) + .nip_fi + .mode = mode; + let current = read_json( + fresh_upgrade_request(state.clone(), &operator, "GET", ¤t_path, None).await, + ) + .await; + assert_eq!(current["effective_required"], mode.restricts()); + } + // Enforce remains a global floor even after a stored disable. + Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config).nip_fi_changes = true; + body["operation_id"] = Uuid::new_v4().to_string().into(); + body["requires_nip_fi"] = false.into(); + body["expected_policy_generation"] = 3.into(); + body["expected_requires_nip_fi"] = true.into(); + body.as_object_mut().unwrap().remove("expected_issuer"); + let response = read_json( + fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(body.to_string()), + ) + .await, + ) + .await; + assert_eq!(response["receipt"]["state"], "applied"); + assert_eq!(response["receipt"]["current_requires_nip_fi"], false); + assert_eq!(response["effective_required"], true); + let invalid = fresh_upgrade_request( + state.clone(), + &operator, + "GET", + &format!("{current_path}&operation_id={}", Uuid::new_v4()), + None, + ) + .await; + assert_eq!(invalid.status(), StatusCode::BAD_REQUEST); + // Old acceptance rows remain recoverable through the sole supported + // endpoint, including after their target has been deleted. Their null + // preconditions cannot match a new fenced request with the same UUID. + for target in [*community.id.as_uuid(), Uuid::new_v4()] { + let id = Uuid::new_v4(); + sqlx::query("INSERT INTO community_auth_upgrades + (operation_id,target_community_id,expected_host,actor_pubkey,expected_owner_pubkey, + expected_issuer,operator_pubkey,policy_generation) VALUES ($1,$2,$3,$4,$4,$5,$6,1)") + .bind(id).bind(target).bind(&host).bind(owner.public_key().to_hex()) + .bind(NIP_FI_ISSUER).bind(operator.public_key().to_hex()) + .execute(state.db.pool()).await.unwrap(); + let receipt = read_json( + fresh_upgrade_request( + state.clone(), + &operator, + "GET", + &format!("{path}?operation_id={id}"), + None, + ) + .await, + ) + .await; + assert!(receipt["receipt"]["expected_policy_generation"].is_null()); + assert!(receipt["receipt"]["expected_requires_nip_fi"].is_null()); + assert_eq!(receipt["receipt"]["requires_nip_fi"], true); + assert_eq!( + receipt["receipt"]["state"], + if target == *community.id.as_uuid() { + "superseded" + } else { + "unavailable" + } + ); + if target != *community.id.as_uuid() { + assert!(receipt["receipt"]["current_policy_generation"].is_null()); + assert!(receipt["receipt"]["current_requires_nip_fi"].is_null()); + } + let mut reuse = history[0].clone(); + reuse["operation_id"] = id.to_string().into(); + reuse["community_id"] = target.to_string().into(); + reuse["expected_policy_generation"] = 4.into(); + let conflict = fresh_upgrade_request( + state.clone(), + &operator, + "POST", + path, + Some(reuse.to_string()), + ) + .await; + assert_eq!(conflict.status(), StatusCode::CONFLICT); + assert_eq!(read_json(conflict).await["code"], "idempotency_conflict"); + let hidden = fresh_upgrade_request( + state.clone(), + &Keys::generate(), + "GET", + &format!("{path}?operation_id={id}"), + None, + ) + .await; + assert_eq!(hidden.status(), StatusCode::FORBIDDEN); + } + let current = read_json( + fresh_upgrade_request(state.clone(), &operator, "GET", ¤t_path, None).await, + ) + .await; + assert!(current.get("requires_nip_fi").is_none()); + assert!(current.get("policy_generation").is_none()); + assert_eq!(current["expected_policy_generation"], 4); + assert_eq!(current["expected_requires_nip_fi"], false); + // The removed route has no operator-auth handler even for signed calls. + for method in ["GET", "POST"] { + let gone = fresh_upgrade_request( + state.clone(), + &operator, + method, + "/operator/communities/nip-fi-upgrade", + (method == "POST").then(|| "{}".into()), + ) + .await; + assert_eq!(gone.status(), StatusCode::NOT_FOUND); + } + // The control-plane signature and allowlist remain mandatory. + let outsider = Keys::generate(); + let response = fresh_upgrade_request(state, &outsider, "GET", ¤t_path, None).await; + assert_eq!(response.status(), StatusCode::FORBIDDEN); + } +} diff --git a/crates/buzz-relay/src/api/profiles.rs b/crates/buzz-relay/src/api/profiles.rs index 66885cf2832..6e230a4fde7 100644 --- a/crates/buzz-relay/src/api/profiles.rs +++ b/crates/buzz-relay/src/api/profiles.rs @@ -3,8 +3,10 @@ //! NIP-50 search over kind:0 matches the full profile JSON, so text inside //! avatar data URLs, `about` and `nip05` competes with real names. This //! endpoint keeps NIP-50 prefix matching and paging but applies them only to -//! the `name` and `display_name` fields of each current profile, and returns -//! the signed kind:0 events. +//! the `name` and `display_name` fields of each current profile and, where +//! the community advertises verified profiles, to the names in each current +//! relay-signed kind:30382. Pages count people; each person returns their +//! signed kind:0 and, when they have one, their kind:30382. use std::{collections::HashMap, sync::Arc}; @@ -19,7 +21,7 @@ use serde_json::Value; use crate::state::AppState; -use super::{api_error, bridge, db_read_error, internal_error}; +use super::{api_error, bridge, db_read_error, search_read_error}; /// Route path for profile name search. pub(crate) const SEARCH_PATH: &str = "/profiles/search"; @@ -72,41 +74,53 @@ fn parse_request(body: &[u8]) -> Result)> { Ok((query.to_owned(), limit, page)) } -/// Search current profiles by `name` and `display_name` for an authenticated -/// member. Responds with one page of signed kind:0 events, best match first. +/// Search people by profile and verified names for an authenticated member. +/// Responds with one page of signed kind:0 and kind:30382 events, best match +/// first. pub async fn search( State(state): State>, + slot: crate::access::AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Response { - search_inner(state, headers, body).await.into_response() + search_inner(state, slot, headers, body) + .await + .into_response() } #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn search_inner( state: Arc, + slot: crate::access::AccessSlot, headers: HeaderMap, body: axum::body::Bytes, ) -> Result, Response> { // Admission first so the denial contract wins over request validation. // [FI-TRACE-HTTP-INGRESS] let (tenant, pubkey) = - bridge::authenticate_member_post(&state, &headers, SEARCH_PATH, &body).await?; + bridge::authenticate_member_post(&state, &slot, &headers, SEARCH_PATH, &body).await?; let (query, limit, page) = parse_request(&body).map_err(IntoResponse::into_response)?; + // Verified profiles count only where this community advertises them. + let verified_by = crate::verified_profiles::discovery(&state, &tenant) + .await + .map(|_| state.relay_keypair.public_key().to_bytes()); let hits = state .search - .search_profile_names(tenant.community(), &query, page, limit) + .search_profile_names(tenant.community(), &query, verified_by, page, limit) .await - .map_err(|e| internal_error(&format!("profile search error: {e}")).into_response())? + .map_err(|e| search_read_error("profile search error", &e).into_response())? .hits; if hits.is_empty() { return Ok(Json(Value::Array(Vec::new()))); } - let ids: Vec<&[u8]> = hits.iter().map(|hit| hit.event_id.as_slice()).collect(); + let hit_keys: Vec<_> = hits + .iter() + .map(|hit| (hit.event_id, hit.created_at)) + .collect(); let stored = state .db - .get_events_by_ids_routed("profile_search_hydrate", tenant.community(), &ids) + .get_events_by_ids_at_routed("profile_search_hydrate", tenant.community(), &hit_keys) .await .map_err(|e| db_read_error("profile search fetch error", &e).into_response())?; let mut by_id: HashMap<[u8; 32], &buzz_core::StoredEvent> = stored diff --git a/crates/buzz-relay/src/api/typing_postgres_tests.rs b/crates/buzz-relay/src/api/typing_postgres_tests.rs index 6c7c7b19824..aaadf4aeba0 100644 --- a/crates/buzz-relay/src/api/typing_postgres_tests.rs +++ b/crates/buzz-relay/src/api/typing_postgres_tests.rs @@ -163,10 +163,11 @@ async fn timed_out_member_typing_is_rejected() { #[ignore = "requires Postgres and Redis"] async fn typing_uses_cached_restriction_row() { let f = Fixture::new().await; - f.state.restriction_cache.insert( + f.state.seed_restriction( (f.community, f.member.public_key().to_bytes().to_vec()), buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }, ); @@ -196,10 +197,11 @@ async fn typing_ban_gate_uses_cached_restriction_row() { ) .await .unwrap(); - f.state.restriction_cache.insert( + f.state.seed_restriction( (f.community, member), buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: None, }, ); @@ -209,17 +211,19 @@ async fn typing_ban_gate_uses_cached_restriction_row() { assert_eq!(status, axum::http::StatusCode::OK, "{body}"); } -/// Only typing uses the cached ban gate: a persistent post reads ban state -/// fresh, so a stale cached ban does not refuse a member Postgres cleared. -/// Mutation: use the cached ban gate for every kind → RED. +/// A persistent post takes the same cached ban gate as typing: a fresh +/// cached ban refuses a member Postgres never restricted. +/// Mutation: read ban state fresh in the HTTP membership gate and in ingest +/// → RED. #[tokio::test] #[ignore = "requires Postgres and Redis"] -async fn persistent_post_ban_gate_reads_fresh() { +async fn persistent_post_ban_gate_uses_cached_restriction_row() { let f = Fixture::new().await; - f.state.restriction_cache.insert( + f.state.seed_restriction( (f.community, f.member.public_key().to_bytes().to_vec()), buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }, ); @@ -228,17 +232,16 @@ async fn persistent_post_ban_gate_reads_fresh() { .sign_with_keys(&f.member) .unwrap(); let (status, body) = f.post(&f.member, &message).await; - assert_eq!(status, axum::http::StatusCode::OK, "{body}"); - assert_eq!(body["accepted"], true, "{body}"); + assert_eq!(status, axum::http::StatusCode::FORBIDDEN, "{body}"); } /// HTTP typing reads the cached serving state, like the WebSocket path. -/// Mutation: call the uncached `is_serving_active` → RED. +/// Mutation: call the uncached `is_community_active` → RED. #[tokio::test] #[ignore = "requires Postgres and Redis"] async fn typing_uses_cached_serving_state() { let f = Fixture::new().await; - f.state.serving_active_cache.insert(f.community, false); + f.state.community_active.seed(f.community, false); let (status, body) = f .post(&f.member, &f.typing(&f.member, Some(f.channel))) .await; diff --git a/crates/buzz-relay/src/api/workflows.rs b/crates/buzz-relay/src/api/workflows.rs index 957a238a808..9b35fccd7eb 100644 --- a/crates/buzz-relay/src/api/workflows.rs +++ b/crates/buzz-relay/src/api/workflows.rs @@ -44,6 +44,7 @@ fn request_path(path: &str, raw_query: Option<&str>) -> String { #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn authorize_workflow_read( state: &Arc, + slot: &crate::access::AccessSlot, headers: &HeaderMap, path: &str, raw_query: Option<&str>, @@ -64,14 +65,16 @@ async fn authorize_workflow_read( // In NIP-FI enforce/deny-protected mode a real NIP-98 event is mandatory — // the X-Pubkey dev-mode fallback must never satisfy the pairing requirement. // [NIP-FI.md:594-607, FI-TRACE-HTTP-INGRESS] - let nip_fi_active = state.config.nip_fi.mode.restricts(); + let nip_fi_active = crate::nip_fi_policy::mode(state, headers).await.restricts(); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] let require_auth = state.config.require_auth_token || nip_fi_active; let admission = admit_nip_fi_http_on_state( state, headers, + slot, bridge::make_nip98_closure_for_admission( + slot.clone(), headers.clone(), "GET", url, @@ -81,29 +84,26 @@ async fn authorize_workflow_read( ), ) .await?; - let pubkey = *admission.proven_pubkey(); - let token_owner = admission.token_owner(); - let (event_id_bytes, signed_created_at) = admission.into_extra(); - - bridge::enforce_http_admission(state, &tenant, &pubkey) - .await - .map_err(|e| e.into_response())?; - bridge::check_nip98_replay(state, &tenant, event_id_bytes) + let mut caller = bridge::ProvenCaller::new(admission, slot, &tenant); + caller + .rate_limit_and_replay(state, &tenant) .await .map_err(|e| e.into_response())?; - let pubkey_bytes = pubkey.to_bytes().to_vec(); + let pubkey_bytes = caller.pubkey.to_bytes().to_vec(); let auth_tag = super::relay_members::extract_auth_tag_header(headers); - super::relay_members::enforce_relay_membership( + let membership = super::relay_members::enforce_relay_membership( state, &tenant, &pubkey_bytes, auth_tag, - signed_created_at, - token_owner, + caller.signed_at, + caller.token_owner, ) - .await - .map_err(|e| e.into_response())?; + .await; + caller + .admit_member(membership) + .map_err(|e| e.into_response())?; // A workflow the caller cannot read answers exactly like a missing one, so // the response never reveals which workflow IDs exist. @@ -149,11 +149,12 @@ async fn authorize_workflow_read( /// `GET /workflows/{workflow_id}/runs` — one authorized, keyset-paginated page. pub async fn workflow_runs( State(state): State>, + slot: crate::access::AccessSlot, Path(workflow_id): Path, headers: HeaderMap, RawQuery(raw_query): RawQuery, ) -> Response { - workflow_runs_inner(state, workflow_id, headers, raw_query) + workflow_runs_inner(state, slot, workflow_id, headers, raw_query) .await .into_response() } @@ -161,6 +162,7 @@ pub async fn workflow_runs( #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn workflow_runs_inner( state: Arc, + slot: crate::access::AccessSlot, workflow_id: Uuid, headers: HeaderMap, raw_query: Option, @@ -170,8 +172,15 @@ async fn workflow_runs_inner( // over request-validation errors. [FI-TRACE-HTTP-INGRESS] // Raw query is preserved here; parsing happens after admission. let path = format!("/workflows/{workflow_id}/runs"); - let tenant = - authorize_workflow_read(&state, &headers, &path, raw_query.as_deref(), workflow_id).await?; + let tenant = authorize_workflow_read( + &state, + &slot, + &headers, + &path, + raw_query.as_deref(), + workflow_id, + ) + .await?; // Parse query string after admission so malformed params (e.g. ?limit=abc) // cannot 400 before the NIP-FI gate fires. A parse failure after @@ -228,10 +237,11 @@ async fn workflow_runs_inner( /// `GET /workflows/{workflow_id}/runs/{run_id}/approvals` — approvals for a run. pub async fn run_approvals( State(state): State>, + slot: crate::access::AccessSlot, Path((workflow_id, run_id)): Path<(Uuid, Uuid)>, headers: HeaderMap, ) -> Response { - run_approvals_inner(state, workflow_id, run_id, headers) + run_approvals_inner(state, slot, workflow_id, run_id, headers) .await .into_response() } @@ -239,12 +249,13 @@ pub async fn run_approvals( #[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers async fn run_approvals_inner( state: Arc, + slot: crate::access::AccessSlot, workflow_id: Uuid, run_id: Uuid, headers: HeaderMap, ) -> Result, Response> { let path = format!("/workflows/{workflow_id}/runs/{run_id}/approvals"); - let tenant = authorize_workflow_read(&state, &headers, &path, None, workflow_id).await?; + let tenant = authorize_workflow_read(&state, &slot, &headers, &path, None, workflow_id).await?; let run = state .db diff --git a/crates/buzz-relay/src/audio/handler.rs b/crates/buzz-relay/src/audio/handler.rs index eb204b8499b..4c0dd354e92 100644 --- a/crates/buzz-relay/src/audio/handler.rs +++ b/crates/buzz-relay/src/audio/handler.rs @@ -11,6 +11,7 @@ //! └─ cleanup: remove peer, broadcast left, emit lifecycle events //! ``` +use crate::access::{auth_error_code, AuthAttempt, AuthLine, AuthMethod, AuthResult}; use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::Arc; use std::time::Duration; @@ -84,10 +85,16 @@ const COMMIT_CONFIRM_SEND_TIMEOUT: Duration = Duration::from_secs(5); /// [FI-TRACE-COMMIT-CONFIRM-TIMEOUT] const CLEAN_CLOSE_SEND_TIMEOUT: Duration = Duration::from_secs(2); +/// The request path of a channel's huddle audio socket, for access lines. +fn audio_route(channel_id: Uuid) -> String { + format!("/huddle/{channel_id}/audio") +} + /// WebSocket upgrade handler for `/huddle/:channel_id/audio`. pub async fn ws_audio_handler( State(state): State>, Path(channel_id): Path, + slot: crate::access::AccessSlot, headers: HeaderMap, req: axum::extract::Request, ) -> impl IntoResponse { @@ -95,12 +102,13 @@ pub async fn ws_audio_handler( // WebSocket handshake. Running pre-lookup means a denied request skips the tenant // lookup (a resolver miss costs one bounded binding lookup) and the gate is reachable in tests without a live community. // [FI-TRACE-TRANSPORT-CLOSED] [NIP-FI.md §Admission pairing sequence] - let (nip_fi_assertion, shadow_assertion, nip_fi_deadline) = { + let (mut nip_fi_assertion, mut shadow_assertion, mut nip_fi_deadline, mut shadow_line) = { use crate::nip_fi_upgrade::check_nip_fi_at_upgrade; - let mode = state.config.nip_fi.mode; + let mode = crate::nip_fi_policy::mode(&state, &headers).await; let verifier = state.nip_fi_verifier.as_deref(); let communities = state.nip_fi_communities(); match check_nip_fi_at_upgrade( + &slot, crate::nip_fi_session::NipFiWsRoute::Audio, &headers, communities, @@ -124,20 +132,45 @@ pub async fn ws_audio_handler( .get(axum::http::header::HOST) .and_then(|v| v.to_str().ok()) .unwrap_or(""); - let tenant = match crate::tenant::bind_community(&state.db, raw_host).await { - Ok(ctx) => ctx, - Err(_) => { - return ( - StatusCode::NOT_FOUND, - "relay: no community is configured for this host", - ) - .into_response(); - } + let (tenant, bound_mode) = match crate::nip_fi_policy::bind_for_upgrade(&state, raw_host).await + { + Ok(binding) => binding, + Err(response) => return response, }; + if bound_mode.restricts() && (nip_fi_assertion.is_none() || bound_mode.denies_unconditionally()) + { + match crate::nip_fi_upgrade::check_nip_fi_at_upgrade( + &slot, + crate::nip_fi_session::NipFiWsRoute::Audio, + &headers, + state.nip_fi_communities(), + state.nip_fi_verifier.as_deref(), + bound_mode, + ) + .await + .into_assertions() + { + Ok(assertions) => { + ( + nip_fi_assertion, + shadow_assertion, + nip_fi_deadline, + shadow_line, + ) = assertions + } + Err(response) => return (*response).into_response(), + } + } // The tenant lookup awaited since the community resolved; a snapshot // that went stale meanwhile accepts no socket. if let Err(class) = nip_fi_deadline.check() { + crate::nip_fi_upgrade::record_stale( + crate::nip_fi_session::NipFiWsRoute::Audio, + crate::nip_fi_shadow::enforce_label(&state, raw_host), + nip_fi_assertion.as_ref(), + class, + ); return crate::nip_fi_core::http_denial(class).into_response(); } let shadow_assertion = crate::nip_fi_upgrade::observe_deadline( @@ -150,10 +183,15 @@ pub async fn ws_audio_handler( Err(e) => return e.into_response(), }; + let client_ip = crate::access::client_ip(&headers, state.config.client_ip_header.as_ref()); let permit = match acquire_audio_connection_permit(&state.conn_semaphore) { Some(permit) => permit, None => { - warn!(channel_id = %channel_id, "Connection limit reached, rejecting audio WebSocket"); + warn!( + channel_id = %channel_id, + client_ip = client_ip.map(tracing::field::display), + "Connection limit reached, rejecting audio WebSocket" + ); return ( StatusCode::SERVICE_UNAVAILABLE, "relay: connection limit reached", @@ -187,7 +225,9 @@ pub async fn ws_audio_handler( permit, nip_fi_assertion, shadow, + shadow_line, connection_time, + client_ip, ) }) } @@ -236,7 +276,9 @@ pub(crate) async fn handle_audio_connection( _permit: OwnedSemaphorePermit, nip_fi_assertion: Option, nip_fi_shadow: Option>, + shadow_line: Option, connection_time: chrono::DateTime, + client_ip: Option, ) { let cancel = CancellationToken::new(); @@ -263,8 +305,18 @@ pub(crate) async fn handle_audio_connection( // the inner handler drains it via ws_send. let (pre_terminal_ctrl_tx, pre_terminal_ctrl_rx) = tokio::sync::mpsc::channel::(1); - let control = CommunityConnectionControl::new(cancel); + let control = CommunityConnectionControl::new(cancel).with_client_ip(client_ip); + if let Some(assertion) = &nip_fi_assertion { + control.attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "audio", + crate::nip_fi_shadow::enforce_label(&state, tenant.host()), + assertion.asserted_key(), + )); + } control.attach_nip_fi_shadow(nip_fi_shadow); + // Its first verified AUTH writes it; else the read loop's end does. + let shadow_line = shadow_line.map(Arc::new); + control.attach_nip_fi_line(shadow_line.as_ref()); let drain_reason = control.disconnect_reason(); let pre_expiry_task = audio_session_deadline.map(|deadline| { crate::nip_fi_session::spawn_nip_fi_expiry_task( @@ -304,7 +356,7 @@ pub(crate) async fn handle_audio_connection( Uuid::new_v4(), community_id, control, - move || async move { check_state.db.is_community_active(community_id).await }, + move || async move { check_state.is_community_active_cached(community_id).await }, move |control| async move { let socket = socket_for_run .lock() @@ -601,6 +653,11 @@ async fn run_active_audio_connection( channel_id = %channel_id, "NIP-FI session deadline already expired at audio upgrade — rejecting before auth" ); + // Claim the expiry first, so this session ends as its deadline + // even when this branch beats the expiry worker. + if let Some(session) = control.nip_fi_enforce() { + session.expire(); + } deny_audio_authorization(&mut ws_send, &control, &mut terminal_ctrl_rx).await; return; } @@ -687,13 +744,37 @@ async fn run_active_audio_connection( #[cfg(test)] crate::nip_fi_test_hooks::before_auth_verify(tenant.community()).await; // Every exit before the join commit leaves the shadow session unadmitted. - let shadow_attempt = crate::nip_fi_shadow_session::AuthAttempt(control.nip_fi_shadow()); + let shadow_attempt = crate::nip_fi_shadow_session::AuthAttempt::new(&control); + // The audio login's single access line: decided at the final admission + // check below; any earlier return without a decision logs `aborted`. + let route = audio_route(channel_id); + let mut auth_line = AuthLine::new( + AuthAttempt::http( + AuthMethod::Nip42, + &route, + Some(auth_msg.event.pubkey), + false, + ) + .in_community(tenant.community()) + .with_client_ip(control.client_ip()), + ); + // Why a login cut off before its decision ended, read when the cut-off + // is seen: the session deadline passed, or the connection was cancelled + // for any other reason (the gate reports both as `SessionExpired`). + let abort_cause = || { + if audio_session_deadline.is_some_and(|deadline| chrono::Utc::now() >= deadline) { + "session_expired" + } else { + "connection_closed" + } + }; let auth_ctx = tokio::select! { biased; _ = cancel.cancelled() => { // Expiry fired while waiting for verify_auth_event. Drain the // terminal channel so the denial frame reaches the client. + auth_line.abort_reason(abort_cause()); crate::connection::send_exit_frames_bounded( &mut ws_send, terminal_exit_frames(&mut terminal_ctrl_rx, &disconnect_reason), @@ -705,7 +786,8 @@ async fn run_active_audio_connection( match result { Ok(ctx) => ctx, Err(e) => { - warn!(channel_id = %channel_id, "audio auth failed: {e}"); + warn!(channel_id = %channel_id, reason = auth_error_code(&e), "audio auth failed"); + auth_line.finish(AuthResult::Failed(auth_error_code(&e))); shadow_attempt.refused(); // Under NIP-FI the failure is classified exactly as on the // root route; Off-mode keeps the legacy bespoke frame. @@ -736,6 +818,7 @@ async fn run_active_audio_connection( }; let pubkey = auth_ctx.pubkey; + auth_line.proven(pubkey); let pubkey_hex = pubkey.to_hex(); let pubkey_bytes = pubkey.to_bytes().to_vec(); let parent_channel_id = auth_msg.parent_channel_id; @@ -749,6 +832,7 @@ async fn run_active_audio_connection( crate::nip_fi_test_hooks::record_pairing_reached_after_cancel(tenant.community()); } + control.prove_nip_fi_line(pubkey); if let Some(shadow) = control.nip_fi_shadow() { shadow.observe_pairing(pubkey); shadow @@ -773,6 +857,7 @@ async fn run_active_audio_connection( .await == crate::nip_fi_session::PairingOutcome::Denied { + auth_line.finish(AuthResult::Denied(crate::access::AuthReason::KeyMismatch)); return; } @@ -787,6 +872,12 @@ async fn run_active_audio_connection( pubkey = %pubkey_hex, "NIP-FI session deadline already expired at pairing — rejecting audio admission" ); + if let Some(session) = control.nip_fi_enforce() { + session.expire(); + } + auth_line.finish(AuthResult::Denied( + crate::access::AuthReason::SessionExpired, + )); deny_audio_authorization(&mut ws_send, &control, &mut terminal_ctrl_rx).await; return; } @@ -813,6 +904,8 @@ async fn run_active_audio_connection( pubkey = %pubkey_hex, "NIP-FI deny-set hit at audio post-registration check — denying" ); + control.deny_nip_fi_enforce(crate::nip_fi_shadow::DENY_SET.by(Some(pubkey))); + auth_line.finish(AuthResult::Denied(crate::access::AuthReason::DenySet)); deny_audio_authorization(&mut ws_send, &control, &mut terminal_ctrl_rx).await; return; } @@ -835,7 +928,7 @@ async fn run_active_audio_connection( // below rereads bans. let early_ban = match token_owner { Some(_) => { - crate::handlers::auth::community_ban_outcome( + crate::handlers::auth::community_ban_verdict( &state, tenant.community(), pubkey, @@ -846,9 +939,15 @@ async fn run_active_audio_connection( ) .await } - None => crate::handlers::auth::BanOutcome::Clear, + None => crate::handlers::auth::BanVerdict::CLEAR, }; - if let Some(denial) = crate::handlers::auth::ban_admission_denial(early_ban) { + if let Some(denial) = crate::handlers::auth::ban_verdict_denial(early_ban) { + crate::handlers::auth::record_enforce_refusal( + &control, + Some(&denial), + nip_fi_assertion.as_ref(), + ); + auth_line.finish(AuthResult::from_outcome(denial.outcome)); shadow_attempt.refused(); warn!(channel_id = %channel_id, pubkey = %pubkey_hex, reason = denial.reason, "audio: denied at ban check"); exit_authorization_refusal( @@ -897,6 +996,12 @@ async fn run_active_audio_connection( } }; if let Some(class) = relay_refusal { + auth_line.finish(AuthResult::Denied(match class { + buzz_auth::DenialClass::AuthorizationUnavailable => { + crate::access::AuthReason::MembershipUnavailable + } + _ => crate::access::AuthReason::NotRelayMember, + })); shadow_attempt.refused(); #[cfg(test)] crate::nip_fi_test_hooks::before_audio_refusal_frames(tenant.community()).await; @@ -912,7 +1017,8 @@ async fn run_active_audio_connection( .await; return; } - check_cancel!(cancel, terminal_ctrl_rx, disconnect_reason, ws_send); + check_cancel!(cancel, terminal_ctrl_rx, disconnect_reason, ws_send, + cleanup: auth_line.abort_reason(abort_cause())); // ── Step 3: membership check / auto-add ─────────────────────────────────── let membership_admission = match check_membership_for_admission( @@ -926,6 +1032,9 @@ async fn run_active_audio_connection( { Ok(admission) => admission, Err(refusal) => { + auth_line.finish(AuthResult::Denied( + crate::access::AuthReason::ChannelMembershipDenied, + )); shadow_attempt.refused(); warn!(channel_id = %channel_id, pubkey = %pubkey_hex, "audio membership denied: {refusal}"); exit_authorization_refusal( @@ -948,7 +1057,8 @@ async fn run_active_audio_connection( parent_channel_id, .. } => *parent_channel_id, }; - check_cancel!(cancel, terminal_ctrl_rx, disconnect_reason, ws_send); + check_cancel!(cancel, terminal_ctrl_rx, disconnect_reason, ws_send, + cleanup: auth_line.abort_reason(abort_cause())); // Record a delegated agent's owner link before admission, as root AUTH // does: revoking the owner finds the agent's sockets through it, so an @@ -961,6 +1071,8 @@ async fn run_active_audio_connection( let _owner_permit = match audio_gate.acquire_effect().await { Ok(permit) => permit, Err(crate::nip_fi_gate::SessionExpired) => { + shadow_attempt.effect_refused(&audio_gate); + auth_line.abort_reason(abort_cause()); cancel.cancel(); if let Some(t) = _nip_fi_admission_expiry.take() { let _ = t.await; @@ -977,6 +1089,14 @@ async fn run_active_audio_connection( }; if let Some(denial) = crate::handlers::auth::owner_link_denial(link, token_owner.is_some()) { + crate::handlers::auth::record_enforce_refusal( + &control, + Some(&denial), + nip_fi_assertion.as_ref(), + ); + auth_line.finish(AuthResult::Denied( + crate::access::AuthReason::NipOaOwnerUnlinked, + )); shadow_attempt.refused(); warn!(channel_id = %channel_id, pubkey = %pubkey_hex, owner = %owner.to_hex(), ?link, "audio: agent owner could not be linked, denying"); @@ -1022,6 +1142,12 @@ async fn run_active_audio_connection( } }; if let Some(denial) = denial { + crate::handlers::auth::record_enforce_refusal( + &control, + Some(&denial), + nip_fi_assertion.as_ref(), + ); + auth_line.finish(AuthResult::from_outcome(denial.outcome)); shadow_attempt.refused(); let (class, message) = (denial.class, denial.reason); warn!(channel_id = %channel_id, pubkey = %pubkey_hex, reason = message, "audio: denied at final admission check"); @@ -1036,7 +1162,11 @@ async fn run_active_audio_connection( .await; return; } - check_cancel!(cancel, terminal_ctrl_rx, disconnect_reason, ws_send); + check_cancel!(cancel, terminal_ctrl_rx, disconnect_reason, ws_send, + cleanup: auth_line.abort_reason(abort_cause())); + + // Every auth and admission check passed; what follows is room joining. + auth_line.finish(AuthResult::Success); // Huddle cross-pod routing (mesh) OR single-pod guardrail. // @@ -1085,6 +1215,7 @@ async fn run_active_audio_connection( let _lease_permit = match audio_gate.acquire_effect().await { Ok(permit) => permit, Err(crate::nip_fi_gate::SessionExpired) => { + shadow_attempt.effect_refused(&audio_gate); cancel.cancel(); if let Some(t) = _nip_fi_admission_expiry.take() { let _ = t.await; @@ -1392,6 +1523,7 @@ async fn run_active_audio_connection( let _add_permit = match audio_gate.acquire_effect().await { Ok(p) => p, Err(crate::nip_fi_gate::SessionExpired) => { + shadow_attempt.effect_refused(&audio_gate); // Expiry fired before we could add the peer. No peer, no commit. // IMPORTANT 3 residual: await expiry task explicitly. cancel.cancel(); @@ -1651,6 +1783,7 @@ async fn run_active_audio_connection( // Same-pod joins pass None — room.roster_snapshot() is authoritative there. guard.remote_session.as_ref().map(|s| s.roster()), control.nip_fi_shadow().map(Arc::as_ref), + control.nip_fi_enforce().map(|session| (session, pubkey)), ) .await; if committed.is_err() { @@ -2007,6 +2140,8 @@ async fn run_active_audio_connection( } } + crate::verified_profiles::admitted(&state, &tenant, nip_fi_assertion.as_ref()); + // Commit-won. Take guard fields into the live runtime — any remaining // fields in guard at this point would be double-released on drop, but all // fields were taken by commit_participant_join above. @@ -3256,11 +3391,15 @@ async fn commit_participant_join( // Admitted the instant the join commits, before publication awaits; // retired at each refusal below, before its rollback awaits. shadow: Option<&crate::nip_fi_shadow_session::ShadowSession>, + enforce: Option<(&crate::nip_fi_shadow::EnforceSession, nostr::PublicKey)>, ) -> Result { let retire_shadow = || { if let Some(shadow) = shadow { shadow.retire_pending(); } + if let Some((session, _)) = enforce { + session.retire(); + } }; // 1. Sign the 48101 event synchronously. // @@ -3494,6 +3633,11 @@ async fn commit_participant_join( let _permit = match gate.acquire_effect().await { Ok(permit) => permit, Err(crate::nip_fi_gate::SessionExpired) => { + // A deadline the gate saw first is claimed before the caller's + // refusal retirement; cancellation alone stays quiet. + if let Some((session, _)) = enforce.filter(|_| gate.deadline_passed()) { + session.expire(); + } // Rollback explicitly — no 48101 or membership write committed. let _ = tx.rollback().await; return Err(JoinCommitError::Expired); @@ -3507,6 +3651,9 @@ async fn commit_participant_join( if let Some(shadow) = shadow { shadow.admit(); } + if let Some((session, pubkey)) = enforce { + session.admit(pubkey); + } // Fix B (commit-before-publish): call `commit_peer` which atomically // marks the peer committed, increments the roster revision, and fires @@ -4192,9 +4339,7 @@ mod tests { .connect_lazy(&config.database_url) .expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -5205,6 +5350,171 @@ mod tests { let _ = server.await; } + // ── Access line: why an audio login cut off before its decision ended ────── + + /// Where [`audio_login_abort_reason`] parks the login. + #[derive(Clone, Copy)] + enum AbortStage { + /// Before `verify_auth_event`. + Verify, + /// After the deny-set check, before the relay-membership policy read. + PolicyRead, + } + + /// Run a real audio connection whose NIP-FI session ends at `deadline` + /// (no assertion, so no deadline, when `None`), park its login at `stage`, then end the connection: by an external + /// cancel when `external_cancel`, otherwise by waiting for the deadline + /// (the production expiry task cancels). Returns the login's `aborted` + /// reason, asserting it wrote exactly one auth line. + async fn audio_login_abort_reason( + community_uuid: uuid::Uuid, + deadline: Option>, + stage: AbortStage, + external_cancel: bool, + ) -> String { + use std::sync::Arc; + use tokio_tungstenite::connect_async; + + let key = nostr::Keys::generate(); + let assertion = deadline.map(|deadline| { + buzz_auth::VerifiedAssertion::for_test(Some(key.public_key()), vec![deadline]) + }); + let state = audio_test_state().await; + let community = buzz_core::tenant::CommunityId::from_uuid(community_uuid); + let tenant = + buzz_core::tenant::TenantContext::resolved(community, "test.local".to_string()); + let conn_cancel = CancellationToken::new(); + let cancel = conn_cancel.clone(); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("addr"); + let app = Router::new().route( + "/", + get(move |ws: WebSocketUpgrade| { + let (state, tenant, assertion) = + (Arc::clone(&state), tenant.clone(), assertion.clone()); + let control = crate::state::CommunityConnectionControl::new(conn_cancel.clone()); + async move { + ws.on_upgrade(move |socket| async move { + handle_active_audio_connection( + socket, + state, + tenant, + uuid::Uuid::new_v4(), + control, + assertion, + chrono::Utc::now(), + None, + ) + .await + }) + } + }), + ); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + + let (guard, out) = crate::access::tests::capture_scoped(); + let (arrived, release) = match stage { + AbortStage::Verify => crate::nip_fi_test_hooks::audio_auth_verify_hook::arm(community), + AbortStage::PolicyRead => { + crate::nip_fi_test_hooks::audio_after_deny_check_passed_hook::arm(community) + } + }; + let (mut client, _) = connect_async(format!("ws://{addr}/")) + .await + .expect("connect"); + let challenge = match client.next().await.expect("challenge").expect("frame") { + tokio_tungstenite::tungstenite::Message::Text(t) => { + serde_json::from_str::(&t).expect("json")["challenge"] + .as_str() + .expect("challenge") + .to_owned() + } + other => panic!("expected a challenge, got {other:?}"), + }; + let auth_event = nostr::EventBuilder::new(nostr::Kind::Authentication, "") + .tag(nostr::Tag::parse(["relay", "ws://test.local"]).unwrap()) + .tag(nostr::Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(&key) + .unwrap(); + let auth = serde_json::json!({"type": "auth", "event": auth_event}).to_string(); + client + .send(tokio_tungstenite::tungstenite::Message::Text(auth.into())) + .await + .expect("send auth"); + tokio::time::timeout(std::time::Duration::from_secs(5), arrived) + .await + .expect("login reaches the hook") + .expect("hook channel"); + + if external_cancel { + cancel.cancel(); + } else { + tokio::time::timeout(std::time::Duration::from_secs(5), cancel.cancelled()) + .await + .expect("the expiry task cancels at the deadline"); + } + release.notify_one(); + let _ = tokio::time::timeout(std::time::Duration::from_secs(3), async { + while client.next().await.is_some() {} + }) + .await; + server.abort(); + let _ = server.await; + drop(guard); + + let lines: Vec<_> = out + .lines() + .into_iter() + .filter(|l| l["event"] == "auth") + .collect(); + assert_eq!(lines.len(), 1, "exactly one auth line: {lines:?}"); + assert_eq!(lines[0]["outcome"], "aborted", "{}", lines[0]); + lines[0]["reason"].as_str().expect("reason").to_owned() + } + + #[tokio::test] + async fn audio_login_cancelled_with_live_session_logs_connection_closed() { + let community = uuid::Uuid::from_u128(0x0000_0000_0A81_0000_0000_0000_0000_0001); + let live = chrono::Utc::now() + chrono::Duration::hours(1); + let reason = + audio_login_abort_reason(community, Some(live), AbortStage::Verify, true).await; + assert_eq!(reason, "connection_closed"); + } + + #[tokio::test] + async fn audio_login_past_its_deadline_logs_session_expired() { + let community = uuid::Uuid::from_u128(0x0000_0000_0A81_0000_0000_0000_0000_0002); + let soon = chrono::Utc::now() + chrono::Duration::milliseconds(500); + let reason = + audio_login_abort_reason(community, Some(soon), AbortStage::Verify, false).await; + assert_eq!(reason, "session_expired"); + } + + #[tokio::test] + async fn audio_login_expiring_during_the_policy_read_logs_session_expired() { + let community = uuid::Uuid::from_u128(0x0000_0000_0A81_0000_0000_0000_0000_0003); + let soon = chrono::Utc::now() + chrono::Duration::milliseconds(500); + let reason = + audio_login_abort_reason(community, Some(soon), AbortStage::PolicyRead, false).await; + assert_eq!(reason, "session_expired"); + } + + #[tokio::test] + async fn audio_login_cancelled_during_the_policy_read_logs_connection_closed() { + let community = uuid::Uuid::from_u128(0x0000_0000_0A81_0000_0000_0000_0000_0004); + let live = chrono::Utc::now() + chrono::Duration::hours(1); + let reason = + audio_login_abort_reason(community, Some(live), AbortStage::PolicyRead, true).await; + assert_eq!(reason, "connection_closed"); + } + + #[tokio::test] + async fn audio_login_cancelled_without_a_deadline_logs_connection_closed() { + let community = uuid::Uuid::from_u128(0x0000_0000_0A81_0000_0000_0000_0000_0005); + let reason = audio_login_abort_reason(community, None, AbortStage::Verify, true).await; + assert_eq!(reason, "connection_closed"); + } + // ── W6 (B1 audio mid-admission): cancellation before room.add_peer ───────── // // With the expiry task armed before admission (above the first persisting @@ -5617,9 +5927,7 @@ mod tests { configure(&mut config); let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -6192,6 +6500,93 @@ mod tests { let _ = server.await; } + /// The already-expired bootstrap fast path claims the deadline before + /// its terminal denial, so a pending enforced session ends as its + /// deadline even with no expiry worker to win the race. + /// Mutation: dropping that branch's `session.expire()` records + /// `audio deny_set/denied`. + #[tokio::test] + async fn already_expired_audio_bootstrap_records_the_deadline() { + use chrono::{Duration, Utc}; + use std::sync::Arc; + + let key = nostr::Keys::generate(); + let deadline = Utc::now() - Duration::milliseconds(50); + let assertion = + buzz_auth::VerifiedAssertion::for_test(Some(key.public_key()), vec![deadline]); + let state = audio_test_state().await; + let tenant = buzz_core::tenant::TenantContext::resolved( + buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()), + "test.local".to_string(), + ); + let cancel = CancellationToken::new(); + let control = crate::state::CommunityConnectionControl::new(cancel.clone()); + control.attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "audio", + crate::nip_fi_shadow::BOUND.into(), + Some(key.public_key()), + )); + // No expiry worker: the fast path alone ends the session. + let gate = crate::nip_fi_gate::SessionAdmissionGate::new(deadline, cancel); + let (terminal_tx, terminal_rx) = + tokio::sync::mpsc::channel::(1); + let pre_built = Arc::new(std::sync::Mutex::new(Some(( + gate, + terminal_tx, + terminal_rx, + )))); + + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("local addr"); + let ((), records, lines) = crate::nip_fi_shadow::tests::enforce_records_during(async { + let server = tokio::spawn(async move { + let app = Router::new().route( + "/", + get(move |ws: WebSocketUpgrade| { + let (state, tenant, control, assertion, pre_built) = ( + Arc::clone(&state), + tenant.clone(), + control.clone(), + assertion.clone(), + Arc::clone(&pre_built), + ); + async move { + ws.on_upgrade(move |socket| async move { + let (gate, tx, rx) = + pre_built.lock().expect("slot").take().expect("one socket"); + handle_active_audio_connection( + socket, + state, + tenant, + uuid::Uuid::new_v4(), + control, + Some(assertion), + Utc::now(), + Some((gate, tx, rx, None)), + ) + .await + }) + } + }), + ); + axum::serve(listener, app).await.expect("test server"); + }); + let (mut client, _) = connect_async(format!("ws://{addr}/")) + .await + .expect("connect"); + // The denial frame, then the close. + for _ in 0..2 { + tokio::time::timeout(std::time::Duration::from_secs(2), client.next()) + .await + .expect("the expired session is denied"); + } + server.abort(); + let _ = server.await; + }) + .await; + assert_eq!(records, ["audio deadline/rejected"], "{lines:?}"); + } + /// Fix 3 (F3): bootstrap-drain through the real outer wrapper (`handle_audio_connection`). /// /// The `run_registered_community_connection` wrapper in `handle_audio_connection` @@ -6270,7 +6665,9 @@ mod tests { permit, Some(assertion_i), None, + None, conn_time, + None, ) .await }) @@ -6403,12 +6800,23 @@ mod tests { key: &nostr::Keys, session: Arc, community: buzz_core::tenant::CommunityId, + ) -> Vec { + let control = crate::state::CommunityConnectionControl::new(CancellationToken::new()); + control.attach_nip_fi_shadow(Some(Arc::clone(&session))); + audio_auth_on(state, key, control, community).await + } + + /// Serves one audio connection under `control` in `community`, sends + /// `key`'s AUTH and returns the text frames until the handler ends it. + async fn audio_auth_on( + state: Arc, + key: &nostr::Keys, + control: crate::state::CommunityConnectionControl, + community: buzz_core::tenant::CommunityId, ) -> Vec { use chrono::Utc; let tenant = buzz_core::tenant::TenantContext::resolved(community, "test.local".to_string()); - let control = crate::state::CommunityConnectionControl::new(CancellationToken::new()); - control.attach_nip_fi_shadow(Some(Arc::clone(&session))); let slot = Arc::new(std::sync::Mutex::new(Some(control))); let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); let addr = listener.local_addr().expect("addr"); @@ -6537,6 +6945,50 @@ mod tests { } } + // The pairing would-deny names the key AUTH proved, not the one the + // token asserts. Mutation: attributing the asserted key, or none, fails. + #[test] + fn shadow_audio_pairing_denial_logs_the_proven_key() { + use crate::nip_fi_shadow_session::tests::{shadow_logged, shadow_state}; + let key = nostr::Keys::generate(); + let asserted = nostr::Keys::generate().public_key(); + let (records, lines) = shadow_logged(async { + let state = Arc::new(shadow_state(None).await); + let (session, _) = shadow_audio_auth(state, &key, asserted).await; + session.expire(); + }); + assert_eq!(records, ["pairing/denied"]); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!(lines[0].contains("reason=\"key_mismatch\""), "{lines:?}"); + let proven = format!("pubkey=\"{}\"", key.public_key().to_hex()); + assert!(lines[0].contains(&proven), "{lines:?}"); + } + + // An upgrade would-deny's line names the key the audio AUTH verifies, + // and is counted once, at the upgrade. Mutation: deleting audio's + // `prove_nip_fi_line` logs `absent`. + #[test] + fn shadow_upgrade_would_deny_logs_the_audio_auth_key() { + use crate::nip_fi_shadow_session::tests::{shadow_logged, shadow_state}; + let key = nostr::Keys::generate(); + let (records, lines) = shadow_logged(async { + let state = Arc::new(shadow_state(None).await); + let line = crate::nip_fi_shadow::tests::upgrade_line("audio"); + let control = crate::state::CommunityConnectionControl::new(CancellationToken::new()); + control.attach_nip_fi_line(Some(&line)); + let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::new_v4()); + audio_auth_on(state, &key, control, community).await; + }); + assert_eq!(records, ["assertion/missing"]); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!( + lines[0].contains("reason=\"missing_assertion\""), + "{lines:?}" + ); + let proven = format!("pubkey=\"{}\"", key.public_key().to_hex()); + assert!(lines[0].contains(&proven), "{lines:?}"); + } + /// Consumes Ping/Pong until the socket terminates (Close, EOF or error) /// within 5s; panics on any data frame or if termination never arrives. async fn assert_terminates_without_data(client: &mut S, tag: &str) @@ -7775,6 +8227,7 @@ mod tests { &Arc::new(crate::audio::room::Room::new(tenant.community(), channel)), None, None, + None, ) .await } @@ -8428,6 +8881,7 @@ mod tests { )), None, Some(&shadow), + None, ) .await }; @@ -8442,6 +8896,126 @@ mod tests { } } + /// Enforce's audio verdict is the join commit, as shadow's is: a + /// committed join counts its admit before publication, so a deadline + /// while publication is held ends the session `expired` once with no + /// pending denial; a join + /// refused for an ordinary reason (archived) retires the session + /// before its rollback, so an expiry held inside that rollback records + /// nothing; and a deadline the commit's effect gate sees first is + /// recorded once, as `session_deadline`, however often expiry follows. + /// Mutations: dropping enforce from `retire_shadow` records + /// `audio deadline/rejected` for `Archived`; dropping the commit + /// seam's `session.expire()` records nothing for `GateFirst`; + /// dropping the commit's admit, or moving it after publication, + /// records `audio deadline/rejected` for `Committed`. + #[test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + fn enforce_join_commit_is_the_audio_admission() { + #[derive(Clone, Copy, Debug, PartialEq)] + enum Case { + Committed, + Archived, + GateFirst, + } + for (case, expected) in [ + ( + Case::Committed, + &["audio admit/admit", "audio end/expired"][..], + ), + (Case::Archived, &[][..]), + (Case::GateFirst, &["audio deadline/rejected"][..]), + ] { + let (records, lines, _, ()) = + crate::nip_fi_shadow::tests::enforce_observed(async {}, |()| async move { + let state = audio_test_state_real_db() + .await + .expect("postgres-ci provides a database"); + let pool = state.db.pool().clone(); + let (tenant, channel_id, member) = seed_audio_fixture(&pool).await; + if case == Case::Archived { + sqlx::query("UPDATE channels SET archived_at = NOW() WHERE id = $1") + .bind(channel_id) + .execute(&pool) + .await + .expect("archive channel"); + } + let key = member.public_key(); + let session = crate::nip_fi_shadow::EnforceSession::new( + "audio", + crate::nip_fi_shadow::BOUND.into(), + Some(key), + ); + let deadline = match case { + Case::GateFirst => chrono::Utc::now() - chrono::Duration::seconds(1), + _ => chrono::Utc::now() + chrono::Duration::hours(1), + }; + let gate = crate::nip_fi_gate::SessionAdmissionGate::new( + deadline, + CancellationToken::new(), + ); + let (arrived, release) = + crate::nip_fi_test_hooks::join_refusal_rollback_hook::arm( + tenant.community(), + ); + // A committed join holds publication so the deadline + // lands before the commit returns. + let fanout = (case == Case::Committed).then(|| { + crate::nip_fi_test_hooks::audio_participant_fanout_hook::arm( + tenant.community(), + ) + }); + let held = async { + if case == Case::Archived { + arrived.await.expect("the join is refused"); + session.expire(); + release.notify_one(); + } + if let Some((published, release)) = fanout { + published.await.expect("the join is published"); + session.expire(); + release.notify_one(); + } + }; + let commit = async { + commit_participant_join( + &state, + &tenant, + channel_id, + channel_id, + &key.to_hex(), + &key.to_bytes(), + uuid::Uuid::new_v4(), + 0, + 0, + 1, + "1", + &MembershipAdmission::Existing { + parent_channel_id: channel_id, + }, + &gate, + &Arc::new(crate::audio::room::Room::new( + tenant.community(), + channel_id, + )), + None, + None, + Some((&session, key)), + ) + .await + }; + let (committed, ()) = tokio::join!(commit, held); + assert_eq!(committed.is_ok(), case == Case::Committed, "{committed:?}"); + // The caller's refusal retirement, then a later expiry. + if committed.is_err() { + session.retire(); + } + session.expire(); + }); + assert_eq!(records, expected, "{case:?}: {lines:?}"); + } + } + /// F2a: committed join into an already-archived channel is rejected on /// the `Existing` path. /// @@ -8508,6 +9082,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await; @@ -8615,6 +9190,7 @@ mod tests { &room, None, None, + None, ), ) .await @@ -8718,6 +9294,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -8925,6 +9502,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9060,6 +9638,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9198,6 +9777,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9243,6 +9823,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9351,6 +9932,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9396,6 +9978,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9631,6 +10214,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9827,6 +10411,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -10393,6 +10978,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -10758,7 +11344,8 @@ mod tests { /// teardown that follows writes to Postgres and Redis, which can stall /// with no deadline. The socket must still end within the bounded wait /// for the client's Close reply. This client never replies and the - /// teardown never finishes. + /// teardown never finishes. The shadow line its AUTH wrote stays a + /// single line throughout. /// /// Mutation: move `hand_off_socket(ws_recv, None)` to after the /// teardown → the socket stays open while the teardown is held → @@ -10772,6 +11359,7 @@ mod tests { use chrono::{Duration, Utc}; use std::sync::Arc; + let log = crate::nip_fi_shadow::tests::WouldDenyLog::capture(); let state = audio_test_state_real_db().await.expect( "PostgreSQL must be available — set BUZZ_TEST_DATABASE_URL or start local postgres", ); @@ -10783,7 +11371,11 @@ mod tests { vec![Utc::now() + Duration::hours(1)], ); let relay_url = format!("ws://{}", tenant.host()); - let conn_cancel = CancellationToken::new(); + let line = crate::nip_fi_shadow::tests::upgrade_line("audio"); + let line = Arc::new(std::sync::Mutex::new(Arc::into_inner(line))); + let semaphore = Arc::new(tokio::sync::Semaphore::new(1)); + let registry = Arc::clone(&state.community_connections); + let ended = Arc::new(tokio::sync::Notify::new()); let (fanout_rx, fanout_release) = crate::nip_fi_test_hooks::audio_participant_fanout_hook::arm(community); @@ -10793,24 +11385,38 @@ mod tests { let app = axum::Router::new().route( "/", axum::routing::get({ - let conn_cancel = conn_cancel.clone(); + let (line, semaphore, ended) = ( + Arc::clone(&line), + Arc::clone(&semaphore), + Arc::clone(&ended), + ); move |ws: axum::extract::ws::WebSocketUpgrade| { - let (state, tenant, assertion) = - (Arc::clone(&state), tenant.clone(), assertion.clone()); - let control = - crate::state::CommunityConnectionControl::new(conn_cancel.clone()); + let (state, tenant, assertion, ended) = ( + Arc::clone(&state), + tenant.clone(), + assertion.clone(), + Arc::clone(&ended), + ); + let line = line.lock().expect("line").take(); + let permit = Arc::clone(&semaphore) + .try_acquire_owned() + .expect("one connection permit"); async move { - ws.on_upgrade(move |socket| { - handle_active_audio_connection( + ws.on_upgrade(move |socket| async move { + handle_audio_connection( socket, state, tenant, channel_id, - control, + permit, Some(assertion), + None, + line, Utc::now(), None, ) + .await; + ended.notify_one(); }) } } @@ -10833,6 +11439,13 @@ mod tests { .expect("fanout channel closed"); fanout_release.notify_one(); tokio::time::sleep(std::time::Duration::from_millis(10)).await; + // The upgrade's shadow line is written at AUTH, while the socket + // is open. Mutation: deleting the outer `attach_nip_fi_line`, or + // audio's `prove_nip_fi_line`, leaves no line here. + let proven = format!("pubkey=\"{}\"", key.public_key().to_hex()); + let lines = log.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!(lines[0].contains(&proven), "{lines:?}"); // From here the client only reads raw bytes, so it never answers // the server's Close. @@ -10840,11 +11453,12 @@ mod tests { panic!("plain TCP client"); }; let started = std::time::Instant::now(); - conn_cancel.cancel(); + assert_eq!(registry.disconnect_archived_community(community), 1); tokio::time::timeout(std::time::Duration::from_secs(5), teardown_rx) .await .expect("teardown must reach the stall point") .expect("teardown hook dropped"); + assert_eq!(log.lines().len(), 1, "{:?}", log.lines()); // The hook runs just after the hand-off, so the socket must end // within the bounded wait measured from here. let handed_off = std::time::Instant::now(); @@ -10860,6 +11474,71 @@ mod tests { ); teardown_release.notify_one(); + // The outer handler owns the line; once it ends, nothing does. + tokio::time::timeout(std::time::Duration::from_secs(10), ended.notified()) + .await + .expect("the handler finishes once teardown resumes"); + server.abort(); + assert_eq!(log.lines().len(), 1, "{:?}", log.lines()); + } + + /// Through `build_router`, an audio upgrade without an assertion hands + /// its shadow line to the socket, which writes it at the verified AUTH + /// with that key while the socket stays open. Mutation: passing `None` + /// instead of `shadow_line` to `handle_audio_connection` writes the + /// line as `absent` at upgrade. + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + #[tokio::test] + async fn shadow_audio_router_writes_line_at_auth_while_open() { + use std::sync::Arc; + use tokio_tungstenite::tungstenite::{client::IntoClientRequest, Message}; + + let log = crate::nip_fi_shadow::tests::WouldDenyLog::capture(); + let base = audio_test_state_real_db() + .await + .expect("postgres-ci provides a database"); + let (tenant, channel_id, key) = seed_audio_fixture(base.db.pool()).await; + let mut state = (*base).clone(); + let config = Arc::make_mut(&mut state.config); + config.nip_fi.mode = buzz_auth::NipFiMode::Shadow; + config.nip_fi.communities = crate::nip_fi_config::NipFiCommunities::for_test( + &format!("https://{}", tenant.host()), + &["https://issuer.test"], + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind test listener"); + let addr = listener.local_addr().expect("test listener addr"); + let app = crate::router::build_router(Arc::new(state)) + .into_make_service_with_connect_info::(); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let mut req = format!("ws://{addr}/huddle/{channel_id}/audio") + .into_client_request() + .expect("request"); + req.headers_mut() + .insert("host", tenant.host().parse().unwrap()); + let (mut client, _) = tokio_tungstenite::connect_async(req) + .await + .expect("shadow admits the upgrade"); + send_audio_auth(&mut client, &key, &format!("ws://{}", tenant.host()), 1).await; + + loop { + match tokio::time::timeout(std::time::Duration::from_secs(10), client.next()) + .await + .expect("joined timeout") + { + Some(Ok(Message::Text(t))) if t.contains("\"joined\"") => break, + Some(Ok(_)) => {} + other => panic!("expected joined, got {other:?}"), + } + } + + let lines = log.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + let proven = format!("pubkey=\"{}\"", key.public_key().to_hex()); + assert!(lines[0].contains(&proven), "{lines:?}"); + drop(client); server.abort(); } @@ -11014,7 +11693,9 @@ mod tests { permit, Some(assertion), None, + None, Utc::now(), + None, ) }) } @@ -11130,6 +11811,7 @@ mod tests { &room, None, // same-pod test — no owner roster None, + None, ) .await; @@ -11256,6 +11938,7 @@ mod tests { &room2, None, // same-pod test — no owner roster None, + None, ) .await }); @@ -11490,6 +12173,7 @@ mod tests { &room, None, // same-pod test — no owner roster None, + None, ) .await; assert!( @@ -11663,6 +12347,7 @@ mod tests { &ingress_room, Some(&owner_snapshot), // cross-pod: use owner-pod roster for the broadcast None, + None, ) .await; assert!( @@ -12342,6 +13027,7 @@ mod tests { &room, None, None, + None, ) .await; assert!( @@ -12996,9 +13682,7 @@ mod tests { let community = tenant.community(); let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); - let redis = deadpool_redis::Config::from_url(&redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis = buzz_pubsub::redis_connection(&redis_url).expect("redis pool"); let directory = SessionDirectory::with_db(redis, state.db.clone()); let (arrived_rx, release) = crate::nip_fi_test_hooks::directory_cas_hook::arm(community); @@ -13029,8 +13713,8 @@ mod tests { "the CAS must have minted a lease before verification" ); let mut blocker = pool.begin().await.expect("blocker tx"); - sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community.as_uuid()) + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(buzz_db::deletion::community_deletion_lock_key(community)) .execute(&mut *blocker) .await .expect("hold the exclusive deletion lock"); @@ -13074,9 +13758,7 @@ mod tests { let relay_url = format!("ws://{}", tenant.host()); let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()); - let redis = deadpool_redis::Config::from_url(&redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis = buzz_pubsub::redis_connection(&redis_url).expect("redis pool"); let directory = crate::tunnel::directory::SessionDirectory::with_db(redis, state.db.clone()); let mut mesh = @@ -13170,8 +13852,8 @@ mod tests { .expect("lock lease row"); assert_eq!(locked.len(), 1, "exactly the acquire's lease row"); if stall_release { - sqlx::query("SELECT pg_advisory_xact_lock(community_deletion_lock_key($1))") - .bind(community.as_uuid()) + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(buzz_db::deletion::community_deletion_lock_key(community)) .execute(&mut *blocker) .await .expect("hold the exclusive deletion lock"); @@ -13248,9 +13930,7 @@ mod tests { config.database_url = db_url.clone(); config.redis_url = "redis://127.0.0.1:1".to_string(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -15396,6 +16076,53 @@ mod tests { ); } + /// A banned delegated NIP-FI agent refused at the early ban check logs + /// one `denied`/`banned` auth line, not `aborted`. + /// Mutation: drop the early `auth_line.finish` → `aborted` → RED. + #[tokio::test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn nip_fi_agent_banned_at_early_check_logs_denied() { + let state = audio_test_state_real_db().await.expect( + "PostgreSQL must be available — set BUZZ_TEST_DATABASE_URL or start local postgres", + ); + let (tenant, channel_id, _member) = seed_audio_fixture(state.db.pool()).await; + let (agent, owner) = (nostr::Keys::generate(), nostr::Keys::generate()); + add_channel_member(state.db.pool(), &tenant, channel_id, &agent).await; + state + .db + .ban_community_member( + tenant.community(), + &agent.public_key().to_bytes(), + &nostr::Keys::generate().public_key().to_bytes(), + None, + None, + ) + .await + .expect("seed ban"); + let assertion = buzz_auth::VerifiedAssertion::for_test( + Some(agent.public_key()), + vec![chrono::Utc::now() + chrono::Duration::hours(1)], + ) + .with_owner_for_test(owner.public_key()); + + let (guard, out) = crate::access::tests::capture_scoped(); + let (mut client, server) = + start_audio_auth(&state, tenant, channel_id, &agent, None, Some(assertion)).await; + audio_frames_until_close(&mut client).await; + server.abort(); + let _ = server.await; + drop(guard); + + let lines: Vec<_> = out + .lines() + .into_iter() + .filter(|l| l["event"] == "auth") + .collect(); + assert_eq!(lines.len(), 1, "exactly one auth line: {lines:?}"); + assert_eq!(lines[0]["outcome"], "denied", "{}", lines[0]); + assert_eq!(lines[0]["reason"], "banned", "{}", lines[0]); + } + /// A delegated NIP-FI agent whose session expires just before its /// owner-link permit gets the canonical denial and its close, with no /// owner write and no huddle admission. @@ -16026,7 +16753,9 @@ mod tests { permit, Some(expired_assertion()), None, + None, chrono::Utc::now(), + None, ) }) } diff --git a/crates/buzz-relay/src/audio/join.rs b/crates/buzz-relay/src/audio/join.rs index c200c20abce..7f43614943f 100644 --- a/crates/buzz-relay/src/audio/join.rs +++ b/crates/buzz-relay/src/audio/join.rs @@ -402,15 +402,16 @@ const OWNER_READY_BUDGET: Duration = Duration::from_secs(2); /// Per-await bounds of the production [`SessionDirectory`] call chain. /// /// Each constant mirrors the awaits of one directory method, in order, and -/// each await's own bound: the whole-checkout Redis deadline, the redis 1.2 -/// driver's default 500 ms response timeout for one command (every script is a -/// single `EVAL`), and the serving-write lease SQL bound. +/// each await's own bound: the shared Redis connection's connect timeout (a +/// command issued while it is down waits for one attempt), its response +/// timeout for one command (every script is a single `EVAL`), and the +/// serving-write lease SQL bound. #[cfg(test)] pub(crate) mod worst_case { use std::time::Duration; - const CHECKOUT: Duration = crate::tunnel::directory::POOL_CHECKOUT_TIMEOUT; - const REDIS_COMMAND: Duration = Duration::from_millis(500); + const CHECKOUT: Duration = buzz_pubsub::REDIS_CONNECT_TIMEOUT; + const REDIS_COMMAND: Duration = buzz_pubsub::REDIS_RESPONSE_TIMEOUT; const LEASE_SQL: Duration = buzz_db::deletion::SERVING_WRITE_LEASE_SQL_TIMEOUT; const fn max(a: Duration, b: Duration) -> Duration { diff --git a/crates/buzz-relay/src/community_active.rs b/crates/buzz-relay/src/community_active.rs new file mode 100644 index 00000000000..622200e11b5 --- /dev/null +++ b/crates/buzz-relay/src/community_active.rs @@ -0,0 +1,45 @@ +//! Per-community lifecycle answers ("is this community active?") shared by +//! socket admission and the ephemeral write fence. +//! +//! Every new socket asks this before it can authenticate, so in a reconnect +//! storm one community gets thousands of identical reads at once. An answer +//! is served for [`COMMUNITY_ACTIVE_MAX_AGE`] after the read that produced it +//! checked out its connection, and concurrent misses share one read. +//! +//! A cached "active" must not undo the archive sweep. Socket admission +//! registers the socket before it asks, so a sweep closes every socket that +//! registered before it, and a socket that registers after it must see the +//! community inactive. [`FencedCache::invalidate`] runs before the sweep: it +//! drops the entry and fences every fill whose read began before it, so a +//! later socket reads afresh instead of taking a pre-archive answer from the +//! cache or from a shared in-flight read. + +use std::time::Duration; + +use buzz_core::CommunityId; + +use crate::fenced_cache::FencedCache; + +/// How long a pod serves a cached community lifecycle answer after the +/// database read that produced it began, at its connection checkout (see +/// [`buzz_db::ReadAt`]). Archive and deletion on this pod drop the entry +/// before closing sockets; a pod that misses that notification admits sockets +/// for at most this long, and lifecycle revalidation closes them. +pub(crate) const COMMUNITY_ACTIVE_MAX_AGE: Duration = Duration::from_secs(1); + +/// Cached `is_community_active` answers, fenced against invalidation. +pub(crate) type CommunityActiveCache = FencedCache; + +/// A cache whose concurrent misses wait at most `shared_read_wait` for a +/// shared read (see [`crate::shared_reads::SharedReads::new`]). +pub(crate) fn new_cache(shared_read_wait: Duration) -> CommunityActiveCache { + FencedCache::new( + 10_000, + COMMUNITY_ACTIVE_MAX_AGE, + shared_read_wait, + ( + "buzz_community_active_cache_hits_total", + "buzz_community_active_cache_misses_total", + ), + ) +} diff --git a/crates/buzz-relay/src/concurrency_limits.rs b/crates/buzz-relay/src/concurrency_limits.rs new file mode 100644 index 00000000000..56133863c9d --- /dev/null +++ b/crates/buzz-relay/src/concurrency_limits.rs @@ -0,0 +1,288 @@ +//! Operator-tunable concurrency caps, re-read from feature flags while the +//! relay runs. +//! +//! Each cap is a [`ConcurrencyGate`] with a ceiling fixed at startup and an +//! integer flag evaluated in the process context: +//! +//! | Flag | Gate | Ceiling | +//! |------|------|---------| +//! | `buzz.relay.concurrency.history-reads` | subscription-history reads on the reader pool | the reader-pool share [`buzz_db`] reserves for history | +//! | `buzz.relay.concurrency.auth` | verified NIP-42 AUTH frames in their database checks | none | +//! +//! A positive value sets the limit, clamped to the ceiling; zero, a negative +//! value, or no value leaves the gate at its ceiling. A flag can therefore +//! only tighten a cap, never loosen one past what the relay starts with, and +//! a deleted flag or a provider that has not initialized puts every gate back +//! at its ceiling. Once LaunchDarkly has delivered values, they stay in force +//! through a later outage (the SDK serves its last-known data), so a cap +//! tightened during an incident is not lost when the provider connection +//! drops. +//! A lowered gate never cancels admitted work: it admits nothing new until +//! the count in flight falls under the new limit. +//! +//! The flags are re-read every [`REFRESH_INTERVAL`], so a change reaches every +//! pod within that interval plus the provider's own propagation delay, with no +//! restart. `buzz_concurrency_limit{gate}` reports each applied limit, with +//! `0` meaning no limit. A refresh that panics is logged and retried on the +//! next tick, so one bad evaluation cannot freeze the caps for the life of +//! the pod. See `docs/operator-concurrency-caps.md` for operating them. + +use std::time::Duration; + +use buzz_db::ConcurrencyGate; +use buzz_feature_flags::{EvaluationContext, IntegerFlag}; +use tokio_util::sync::CancellationToken; +use tracing::{error, info}; + +use crate::feature_flags::FeatureFlags; + +/// Cap on subscription-history reads holding a reader connection. +pub const HISTORY_READS_FLAG: IntegerFlag = + IntegerFlag::new("buzz.relay.concurrency.history-reads", 0); +/// Cap on verified AUTH frames running their database checks. +pub const AUTH_FLAG: IntegerFlag = IntegerFlag::new("buzz.relay.concurrency.auth", 0); + +/// How often the flags are re-read. +pub const REFRESH_INTERVAL: Duration = Duration::from_secs(5); + +/// One gate whose limit a flag controls. +#[derive(Clone, Debug)] +pub struct ManagedGate { + name: &'static str, + flag: IntegerFlag, + gate: ConcurrencyGate, +} + +impl ManagedGate { + /// `gate`, controlled by `flag` and reported as `name`. + pub fn new(name: &'static str, flag: IntegerFlag, gate: ConcurrencyGate) -> Self { + Self { name, flag, gate } + } +} + +/// The relay's managed gates: history reads and AUTH. +pub fn relay_gates(state: &crate::state::AppState) -> Vec { + vec![ + ManagedGate::new( + "history_reads", + HISTORY_READS_FLAG, + state.db.history_read_gate().clone(), + ), + ManagedGate::new("auth", AUTH_FLAG, state.auth_gate.clone()), + ] +} + +/// The limit a flag value asks for on a gate with `ceiling`. +fn requested_limit(value: i64, ceiling: usize) -> usize { + if value <= 0 { + return ceiling; + } + usize::try_from(value).map_or(ceiling, |value| value.min(ceiling)) +} + +/// Evaluate every gate's flag once and apply the result. +pub fn apply(flags: &FeatureFlags, gates: &[ManagedGate]) { + let context = EvaluationContext::for_process(); + for managed in gates { + let ceiling = managed.gate.ceiling(); + let value = flags.evaluator().evaluate_int(managed.flag, &context); + let previous = managed.gate.limit(); + let applied = managed.gate.set_limit(requested_limit(value, ceiling)); + if applied != previous { + info!( + gate = managed.name, + limit = applied, + previous, + ceiling, + "concurrency limit changed" + ); + } + let reported = if applied >= tokio::sync::Semaphore::MAX_PERMITS { + 0.0 + } else { + applied as f64 + }; + metrics::gauge!("buzz_concurrency_limit", "gate" => managed.name).set(reported); + } + flags.report(); +} + +/// Apply the flags every [`REFRESH_INTERVAL`] (the first time immediately) +/// until `cancel` fires. A panicking refresh is logged and counted +/// (`buzz_concurrency_limit_refresh_panics_total`), and the next tick tries +/// again. +pub async fn run( + flags: std::sync::Arc, + gates: Vec, + cancel: CancellationToken, +) { + let mut interval = tokio::time::interval(REFRESH_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { + biased; + _ = cancel.cancelled() => break, + _ = interval.tick() => { + let refresh = std::panic::AssertUnwindSafe(|| apply(&flags, &gates)); + if std::panic::catch_unwind(refresh).is_err() { + metrics::counter!("buzz_concurrency_limit_refresh_panics_total").increment(1); + error!("concurrency limit refresh panicked; retrying on the next tick"); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use buzz_feature_flags::{BooleanFlag, FlagEvaluator}; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + + /// A provider whose values the test changes while the relay "runs". + #[derive(Default)] + struct LiveValues(Mutex>); + + impl LiveValues { + fn set(&self, flag: IntegerFlag, value: Option) { + let mut values = self.0.lock().expect("values"); + match value { + Some(value) => values.insert(flag.key(), value), + None => values.remove(flag.key()), + }; + } + } + + impl FlagEvaluator for LiveValues { + fn evaluate_bool(&self, flag: BooleanFlag, _: &EvaluationContext) -> bool { + flag.default() + } + + fn evaluate_int(&self, flag: IntegerFlag, context: &EvaluationContext) -> i64 { + assert_eq!( + context.community(), + None, + "caps evaluate in the process context" + ); + self.0 + .lock() + .expect("values") + .get(flag.key()) + .copied() + .unwrap_or(flag.default()) + } + } + + #[test] + fn flag_values_only_tighten_and_reset_to_the_ceiling() { + let values = Arc::new(LiveValues::default()); + let flags = FeatureFlags::from_evaluator("test", values.clone()); + let history = ConcurrencyGate::new(20); + let auth = ConcurrencyGate::unbounded(); + let gates = vec![ + ManagedGate::new("history_reads", HISTORY_READS_FLAG, history.clone()), + ManagedGate::new("auth", AUTH_FLAG, auth.clone()), + ]; + + // Each row: the flag values, then the limits applied. + let rows: [(Option, Option, usize, usize); 6] = [ + (None, None, 20, auth.ceiling()), + (Some(8), Some(50), 8, 50), + (Some(500), Some(i64::MAX), 20, auth.ceiling()), + (Some(0), Some(-3), 20, auth.ceiling()), + (Some(1), Some(1), 1, 1), + (None, None, 20, auth.ceiling()), + ]; + for (history_value, auth_value, history_limit, auth_limit) in rows { + values.set(HISTORY_READS_FLAG, history_value); + values.set(AUTH_FLAG, auth_value); + apply(&flags, &gates); + assert_eq!(history.limit(), history_limit, "history {history_value:?}"); + assert_eq!(auth.limit(), auth_limit, "auth {auth_value:?}"); + } + } + + #[tokio::test(start_paused = true)] + async fn the_refresh_loop_applies_changes_without_a_restart() { + let values = Arc::new(LiveValues::default()); + let flags = Arc::new(FeatureFlags::from_evaluator("test", values.clone())); + let gate = ConcurrencyGate::new(10); + let cancel = CancellationToken::new(); + let task = tokio::spawn(run( + flags, + vec![ManagedGate::new( + "history_reads", + HISTORY_READS_FLAG, + gate.clone(), + )], + cancel.clone(), + )); + + values.set(HISTORY_READS_FLAG, Some(3)); + tokio::time::sleep(REFRESH_INTERVAL + Duration::from_millis(1)).await; + assert_eq!(gate.limit(), 3, "the next refresh applies the new value"); + + values.set(HISTORY_READS_FLAG, None); + tokio::time::sleep(REFRESH_INTERVAL).await; + assert_eq!(gate.limit(), 10, "removing the flag restores the ceiling"); + + cancel.cancel(); + task.await.expect("the loop stops on cancel"); + } + + /// An evaluator that panics on its first `remaining_panics` calls, then + /// reads a fixed value. + struct PanicsFirst { + remaining_panics: std::sync::atomic::AtomicUsize, + value: i64, + } + + impl FlagEvaluator for PanicsFirst { + fn evaluate_bool(&self, flag: BooleanFlag, _: &EvaluationContext) -> bool { + flag.default() + } + + fn evaluate_int(&self, _: IntegerFlag, _: &EvaluationContext) -> i64 { + use std::sync::atomic::Ordering; + let remaining = self.remaining_panics.load(Ordering::SeqCst); + if remaining > 0 { + self.remaining_panics.store(remaining - 1, Ordering::SeqCst); + panic!("injected evaluation panic"); + } + self.value + } + } + + #[tokio::test(start_paused = true)] + async fn a_panicking_refresh_does_not_stop_the_loop() { + let flags = Arc::new(FeatureFlags::from_evaluator( + "test", + Arc::new(PanicsFirst { + remaining_panics: 1.into(), + value: 4, + }), + )); + let gate = ConcurrencyGate::new(10); + let cancel = CancellationToken::new(); + let task = tokio::spawn(run( + flags, + vec![ManagedGate::new( + "history_reads", + HISTORY_READS_FLAG, + gate.clone(), + )], + cancel.clone(), + )); + + // The first tick panics; the gate keeps its ceiling. + tokio::time::sleep(Duration::from_millis(1)).await; + assert_eq!(gate.limit(), 10, "a panicked refresh applies nothing"); + tokio::time::sleep(REFRESH_INTERVAL).await; + assert_eq!(gate.limit(), 4, "the next tick applies the flag"); + + cancel.cancel(); + task.await + .expect("the loop survives the panic and stops on cancel"); + } +} diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index c0e30144099..286e86ba246 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -32,7 +32,7 @@ pub enum ConfigError { /// # Role resolution (nip98 mode only) /// /// In `nip98` mode the authenticated pubkey is resolved to an -/// `AdminPrincipal` at request time via [`crate::api::admin::auth::resolve_admin_principal`]: +/// `AdminPrincipal` at request time via [`crate::api::admin::auth::lookup_admin_principal`]: /// - `Operator/Config` if pubkey ∈ `RELAY_OPERATOR_PUBKEYS` /// - `Operator/OwnerFallback` if pubkey == `RELAY_OWNER_PUBKEY` **and** /// `RELAY_OPERATOR_PUBKEYS` is empty (evaluated from config, never runtime rows) @@ -127,10 +127,11 @@ pub struct Config { /// `0` (the default) disables bounded-staleness replica routing; see /// [`buzz_db::DbConfig::replica_read_max_age_ms`]. pub replica_read_max_age_ms: u64, - /// Replica freshness budget for fleet usage telemetry - /// (`BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS`). Independent of serving-read - /// routing; defaults to 30 seconds and `0` disables telemetry DB queries. - pub usage_metrics_replica_max_age_ms: u64, + /// Replica fence heartbeat interval in milliseconds + /// (`BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS`). Unset (`0`) selects the + /// default; set values must lie within the accepted range. See + /// [`buzz_db::DbConfig::replica_fence_probe_interval_ms`]. + pub replica_fence_probe_interval_ms: u64, /// Upper bound, in milliseconds, of the per-connection random delay applied /// when sending the `1012 Service Restart` close frame during graceful @@ -147,12 +148,6 @@ pub struct Config { pub drain_jitter_ms: u64, /// Redis connection URL used by the pub/sub manager. pub redis_url: String, - /// Maximum connections in the shared Redis pool. Defaults to 16. - /// - /// deadpool's own default is `CPU_COUNT * 2`, which on a 2-vCPU relay - /// pod is only 4 — small enough that rate-limit checks, presence, and - /// pub/sub publishes queue behind each other under load. - pub redis_pool_size: usize, /// Maximum connections in the Postgres writer/reader pools. Defaults to 50. /// /// The `buzz-db` default of 20 was sized for a handful of pods against @@ -180,6 +175,9 @@ pub struct Config { pub max_frame_bytes: usize, /// Number of consecutive buffer-full events tolerated before cancelling a slow client. pub slow_client_grace_limit: u8, + /// `BUZZ_CLIENT_IP_HEADER`: the request header whose IP access lines log + /// as `client_ip`. `None` logs only the TCP `peer_addr`. + pub client_ip_header: Option, /// Authentication provider configuration. pub auth: buzz_auth::AuthConfig, /// Whether REST API requests must present a valid token. Independent of @@ -187,6 +185,10 @@ pub struct Config { pub require_auth_token: bool, /// Opt-in private accessory API; disabled until explicitly deployed. pub buzz_v1_enabled: bool, + /// Opt-in NIP-CL compact membership projection; dark by default. + pub membership_snapshot_enabled: bool, + /// Opt-in NIP-CL public memberships, independent of self discovery. + pub membership_public_enabled: bool, /// Author-time unread tracking duration, independent of NIP-RS retention. pub buzz_v1_retention_seconds: u32, /// Comma-separated list of allowed CORS origins. @@ -289,9 +291,20 @@ pub struct Config { /// skipped — a typo must not silently disable an operator. pub relay_operator_pubkeys: Vec, + /// Serve multiple communities (default true). When false, only the + /// normalized `relay_url` authority serves ordinary traffic; existing extra + /// communities remain available to authenticated management and cleanup. + /// Canonical startup bootstrap is preserved. Changes require a restart. + /// Set via `BUZZ_MULTI_COMMUNITY_RELAY=true|false`. + pub multi_community_relay: bool, + /// Configured operator-listener identities and their HTTP(S) delivery URLs. pub operator_listener_delivery_urls: HashMap, + /// Endpoint receiving each new per-community storage snapshot + /// (`BUZZ_STORAGE_USAGE_URL`). Unset disables storage-usage delivery. + pub storage_usage_delivery_url: Option, + /// Allow NIP-OA owner attestation for relay membership. /// /// When `true` and `require_relay_membership` is also `true`, agents @@ -312,6 +325,8 @@ pub struct Config { /// Media storage configuration (S3/MinIO). pub media: buzz_media::MediaConfig, + /// Channel media authorization rollout: off, shadow, or enforce. + pub media_read_mode: crate::api::media_access::MediaReadMode, /// Maximum concurrent media uploads handled by one relay process. pub media_max_concurrent_uploads: usize, /// Maximum concurrent media uploads accepted from one pubkey. @@ -324,6 +339,15 @@ pub struct Config { /// Set `BUZZ_AUDIT_ENABLED=false` for deployments that do not require it. pub audit_enabled: bool, + /// Which workflow runs may direct agents. With `owner` (owner-only agent + /// mentions), a workflow message carries `buzz:workflow-mention` tags only + /// if its run was started by the workflow's owner or by a timer and every + /// step of the definition is `send_message` or `delay`. Use `owner` when + /// people other than a workflow's owner can trigger it. + /// + /// Default: `any`. Set via `BUZZ_WORKFLOW_AGENT_MENTIONS=any|owner`. + pub workflow_agent_mentions: buzz_workflow::AgentMentions, + /// Optional override for ephemeral channel TTL (in seconds). /// When set, any channel created with a TTL tag will use this value instead /// of the client-provided one. Useful for testing ephemeral expiry quickly. @@ -379,6 +403,9 @@ pub struct Config { /// documents or age attestation are configured. pub join_policy: Option, + /// Absolute UTC Unix-second cutoff for legacy v1 invites; unset drains naturally. + pub invite_v1_invalid_after: Option, + /// Deployment-admin API and SPA configuration. Absent means the surface is disabled. pub admin: Option, @@ -404,6 +431,10 @@ pub struct Config { /// Parsed whatever the NIP-FI mode, since creation happens in every mode. pub nip_fi_provision_binding: Option, + /// Permit new community FI policy enables and disables. Default off; receipt + /// recovery/status remain available (`BUZZ_NIP_FI_CHANGES`). + pub nip_fi_changes: bool, + /// Database resolver bounds (`BUZZ_NIP_FI_RESOLVER_*`, /// `BUZZ_NIP_FI_SNAPSHOT_*`). Validated in every mode, so a bad value /// fails the deploy that sets it, not the later switch to shadow. @@ -415,6 +446,41 @@ fn parse_bind_addr(raw: &str) -> Result { .map_err(|e| ConfigError::InvalidBindAddr(e.to_string())) } +fn parse_invite_v1_cutoff(raw: Option<&str>) -> Result, ConfigError> { + raw.map(|value| { + chrono::DateTime::parse_from_rfc3339(value) + .ok() + .filter(|time| time.offset().local_minus_utc() == 0 && time.timestamp_subsec_nanos() == 0) + .and_then(|time| u64::try_from(time.timestamp()).ok()) + .ok_or_else(|| ConfigError::InvalidValue( + "BUZZ_INVITE_V1_INVALID_AFTER must be a UTC RFC3339 timestamp with whole seconds".into(), + )) + }).transpose() +} + +fn invite_v1_cutoff_from_env() -> Result, ConfigError> { + match std::env::var("BUZZ_INVITE_V1_INVALID_AFTER") { + Ok(raw) => parse_invite_v1_cutoff(Some(&raw)), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(std::env::VarError::NotUnicode(_)) => Err(ConfigError::InvalidValue( + "BUZZ_INVITE_V1_INVALID_AFTER must be valid Unicode".into(), + )), + } +} + +/// An empty value turns the setting off; header names match case-insensitively. +fn parse_client_ip_header(raw: &str) -> Result, ConfigError> { + let raw = raw.trim(); + if raw.is_empty() { + return Ok(None); + } + axum::http::HeaderName::from_bytes(raw.to_ascii_lowercase().as_bytes()) + .map(Some) + .map_err(|_| { + ConfigError::InvalidValue(format!("BUZZ_CLIENT_IP_HEADER is not a header name: {raw}")) + }) +} + fn positive_u64_from_env(name: &str, default: u64) -> Result { match std::env::var(name) { Ok(raw) => raw @@ -579,6 +645,19 @@ fn parse_bool(name: &str, default: bool) -> Result { } } +fn parse_workflow_agent_mentions() -> Result { + const NAME: &str = "BUZZ_WORKFLOW_AGENT_MENTIONS"; + match std::env::var(NAME) { + Err(std::env::VarError::NotPresent) => Ok(buzz_workflow::AgentMentions::Any), + Err(error) => Err(ConfigError::InvalidValue(format!( + "{NAME} must be valid UTF-8: {error}" + ))), + Ok(value) => value + .parse() + .map_err(|error| ConfigError::InvalidValue(format!("{NAME}: {error}"))), + } +} + fn parse_optional_bool(name: &str) -> Result { parse_bool(name, false) } @@ -663,15 +742,27 @@ impl Config { })?, Err(_) => 0, }; - let usage_metrics_replica_max_age_ms = - match std::env::var("BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS") { - Ok(raw) => raw.trim().parse::().map_err(|_| { - ConfigError::InvalidValue( - "BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS must be a non-negative integer" - .to_string(), - ) - })?, - Err(_) => 30_000, + + // Fence heartbeat interval: unset or empty selects the default. An + // out-of-range value fails startup rather than being clamped, so the + // deployed cadence is always the configured one. + let replica_fence_probe_interval_ms = + match std::env::var("BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS") { + Ok(raw) if !raw.trim().is_empty() => { + let min = buzz_db::replica_fence::MIN_PROBE_INTERVAL.as_millis() as u64; + let max = buzz_db::replica_fence::MAX_PROBE_INTERVAL.as_millis() as u64; + raw.trim() + .parse::() + .ok() + .filter(|ms| (min..=max).contains(ms)) + .ok_or_else(|| { + ConfigError::InvalidValue(format!( + "BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS must be an integer \ + between {min} and {max}" + )) + })? + } + _ => 0, }; // Drain jitter: 0 = off (default). Clamp oversized values so every @@ -696,12 +787,6 @@ impl Config { let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://localhost:6379".to_string()); - let redis_pool_size = std::env::var("BUZZ_REDIS_POOL_SIZE") - .ok() - .and_then(|v| v.parse::().ok()) - .filter(|&v| v > 0) - .unwrap_or(16); - let db_pool_size = std::env::var("BUZZ_DB_POOL_SIZE") .ok() .and_then(|v| v.parse::().ok()) @@ -761,6 +846,9 @@ impl Config { .and_then(|v| v.parse().ok()) .unwrap_or(15); + let client_ip_header = + parse_client_ip_header(&std::env::var("BUZZ_CLIENT_IP_HEADER").unwrap_or_default())?; + let require_auth_token = std::env::var("BUZZ_REQUIRE_AUTH_TOKEN") .map(|v| v == "true" || v == "1") .unwrap_or(false); @@ -852,6 +940,24 @@ impl Config { .map(|raw| parse_operator_api_origin(&raw)) .transpose()?; + let multi_community_relay = match std::env::var("BUZZ_MULTI_COMMUNITY_RELAY") { + Ok(value) => value.parse::().map_err(|_| { + ConfigError::InvalidValue( + "BUZZ_MULTI_COMMUNITY_RELAY must be true or false".to_string(), + ) + })?, + Err(std::env::VarError::NotPresent) => true, + Err(std::env::VarError::NotUnicode(_)) => { + return Err(ConfigError::InvalidValue( + "BUZZ_MULTI_COMMUNITY_RELAY must be true or false".to_string(), + )) + } + }; + if !multi_community_relay && crate::tenant::relay_url_authority(&relay_url).is_empty() { + return Err(ConfigError::InvalidValue( + "RELAY_URL must have a host when BUZZ_MULTI_COMMUNITY_RELAY=false".to_owned(), + )); + } let relay_operator_pubkeys = match std::env::var("RELAY_OPERATOR_PUBKEYS") { Ok(raw) => { let mut pubkeys = Vec::new(); @@ -901,6 +1007,18 @@ impl Config { ))); } }; + let storage_usage_delivery_url = match std::env::var("BUZZ_STORAGE_USAGE_URL") { + Ok(raw) => Some( + crate::storage_usage_delivery::parse_delivery_url(&raw) + .map_err(ConfigError::InvalidValue)?, + ), + Err(std::env::VarError::NotPresent) => None, + Err(error) => { + return Err(ConfigError::InvalidValue(format!( + "BUZZ_STORAGE_USAGE_URL must be valid UTF-8: {error}" + ))); + } + }; if !operator_listener_delivery_urls.is_empty() && relay_operator_api_origin.is_none() { error!( "BUZZ_OPERATOR_LISTENERS is set but RELAY_OPERATOR_API_ORIGIN is not — operator-listener registration requests will reject every request until RELAY_OPERATOR_API_ORIGIN is set" @@ -968,6 +1086,15 @@ impl Config { )); } }; + let media_read_mode = match std::env::var("BUZZ_MEDIA_READ_MODE") { + Ok(value) => value.parse().map_err(ConfigError::InvalidValue)?, + Err(std::env::VarError::NotPresent) => crate::api::media_access::MediaReadMode::Off, + Err(_) => { + return Err(ConfigError::InvalidValue( + "BUZZ_MEDIA_READ_MODE must be valid Unicode".into(), + )) + } + }; let media = buzz_media::MediaConfig { s3_endpoint: std::env::var("BUZZ_S3_ENDPOINT") .unwrap_or_else(|_| "http://localhost:9000".to_string()), @@ -1186,6 +1313,7 @@ impl Config { let privacy_markdown = read_policy_markdown("BUZZ_PRIVACY_POLICY_MARKDOWN")?; let age_attestation_required = parse_optional_bool("BUZZ_AGE_ATTESTATION_REQUIRED")?; let audit_enabled = parse_bool("BUZZ_AUDIT_ENABLED", true)?; + let workflow_agent_mentions = parse_workflow_agent_mentions()?; let join_policy = if terms_markdown.is_none() && privacy_markdown.is_none() && !age_attestation_required @@ -1400,10 +1528,9 @@ impl Config { database_url, read_database_url, replica_read_max_age_ms, - usage_metrics_replica_max_age_ms, + replica_fence_probe_interval_ms, drain_jitter_ms, redis_url, - redis_pool_size, db_pool_size, db_read_pool_size, relay_url, @@ -1413,9 +1540,14 @@ impl Config { send_buffer_size, max_frame_bytes, slow_client_grace_limit, + client_ip_header, auth, require_auth_token, buzz_v1_enabled, + membership_snapshot_enabled: std::env::var("BUZZ_MEMBERSHIP_SNAPSHOT_ENABLED") + .is_ok_and(|v| v == "true"), + membership_public_enabled: std::env::var("BUZZ_MEMBERSHIP_PUBLIC_ENABLED") + .is_ok_and(|v| v == "true"), buzz_v1_retention_seconds, cors_origins, relay_private_key, @@ -1433,14 +1565,18 @@ impl Config { relay_owner_pubkey, relay_operator_api_origin, relay_operator_pubkeys, + multi_community_relay, operator_listener_delivery_urls, + storage_usage_delivery_url, allow_nip_oa_auth, klipy, media, + media_read_mode, media_max_concurrent_uploads, media_max_concurrent_uploads_per_pubkey, media_uploads_per_minute, audit_enabled, + workflow_agent_mentions, ephemeral_ttl_override, git_repo_path, git_pack_cache_path, @@ -1457,10 +1593,12 @@ impl Config { push_gateway_timeout, operator_listener_timeout, join_policy, + invite_v1_invalid_after: invite_v1_cutoff_from_env()?, admin, web_dir, serve_git_web_gui, nip_fi_provision_binding, + nip_fi_changes: parse_bool("BUZZ_NIP_FI_CHANGES", false)?, nip_fi_resolver_bounds, nip_fi, }) @@ -1533,6 +1671,31 @@ mod tests { (fi, cfg) } + #[test] + fn nip_fi_changes_are_explicitly_default_off() { + let (_fi, _cfg) = env_guards(); + let before = std::env::var("BUZZ_NIP_FI_CHANGES").ok(); + std::env::remove_var("BUZZ_NIP_FI_CHANGES"); + assert!(!Config::from_env().unwrap().nip_fi_changes); + for value in ["true", "TRUE", "1", "on", " On "] { + std::env::set_var("BUZZ_NIP_FI_CHANGES", value); + assert!(Config::from_env().unwrap().nip_fi_changes, "{value}"); + } + for value in ["false", "FALSE", "0", "off", "", " Off "] { + std::env::set_var("BUZZ_NIP_FI_CHANGES", value); + assert!(!Config::from_env().unwrap().nip_fi_changes, "{value}"); + } + std::env::set_var("BUZZ_NIP_FI_CHANGES", "treu"); + assert!( + matches!(Config::from_env(), Err(ConfigError::InvalidValue(message)) + if message.contains("BUZZ_NIP_FI_CHANGES must be true or false")) + ); + match before { + Some(value) => std::env::set_var("BUZZ_NIP_FI_CHANGES", value), + None => std::env::remove_var("BUZZ_NIP_FI_CHANGES"), + } + } + // The three `source=database` startup guards. Mutation: dropping any one // lets that configuration start. #[test] @@ -1663,6 +1826,29 @@ mod tests { assert!(found.is_empty(), "unrelated vars must not warn: {found:?}"); } + #[test] + fn multi_community_relay_is_strict_and_default_enabled() { + let _guards = env_guards(); + std::env::remove_var("BUZZ_MULTI_COMMUNITY_RELAY"); + assert!(Config::from_env().expect("unset").multi_community_relay); + for (value, expected) in [("false", false), ("true", true)] { + std::env::set_var("BUZZ_MULTI_COMMUNITY_RELAY", value); + let config = Config::from_env(); + std::env::remove_var("BUZZ_MULTI_COMMUNITY_RELAY"); + assert_eq!( + config.expect("valid policy").multi_community_relay, + expected + ); + } + for value in ["", "FALSE", "1", "typo"] { + std::env::set_var("BUZZ_MULTI_COMMUNITY_RELAY", value); + let result = Config::from_env(); + std::env::remove_var("BUZZ_MULTI_COMMUNITY_RELAY"); + assert!(matches!(result, Err(ConfigError::InvalidValue(ref message)) + if message.contains("BUZZ_MULTI_COMMUNITY_RELAY"))); + } + } + #[test] fn defaults_are_valid() { let _guards = env_guards(); @@ -1670,7 +1856,6 @@ mod tests { assert!(config.bind_addr.port() > 0); assert!(!config.database_url.is_empty()); assert!(!config.redis_url.is_empty()); - assert_eq!(config.redis_pool_size, 16); assert_eq!(config.db_pool_size, 50); assert!(config.max_connections > 0); assert!(config.send_buffer_size > 0); @@ -2267,31 +2452,6 @@ mod tests { )); } - #[test] - fn redis_pool_size_env_override_and_invalid_fallback() { - let _guards = env_guards(); - let previous = std::env::var_os("BUZZ_REDIS_POOL_SIZE"); - - std::env::set_var("BUZZ_REDIS_POOL_SIZE", "32"); - let overridden = Config::from_env().expect("config").redis_pool_size; - - std::env::set_var("BUZZ_REDIS_POOL_SIZE", "0"); - let zero = Config::from_env().expect("config").redis_pool_size; - - std::env::set_var("BUZZ_REDIS_POOL_SIZE", "not-a-number"); - let junk = Config::from_env().expect("config").redis_pool_size; - - if let Some(value) = previous { - std::env::set_var("BUZZ_REDIS_POOL_SIZE", value); - } else { - std::env::remove_var("BUZZ_REDIS_POOL_SIZE"); - } - - assert_eq!(overridden, 32); - assert_eq!(zero, 16, "zero must fall back to the default"); - assert_eq!(junk, 16, "unparsable value must fall back to the default"); - } - #[test] fn db_pool_size_env_override_and_invalid_fallback() { let _guards = env_guards(); @@ -2427,32 +2587,41 @@ mod tests { } #[test] - fn usage_metrics_replica_budget_defaults_on_independently_of_serving_reads() { - let _guard = ENV_MUTEX.lock().unwrap(); - let previous_usage = std::env::var_os("BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS"); - let previous_serving = std::env::var_os("BUZZ_REPLICA_READ_MAX_AGE_MS"); - - std::env::remove_var("BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS"); - std::env::remove_var("BUZZ_REPLICA_READ_MAX_AGE_MS"); - let defaults = Config::from_env().expect("config"); + fn replica_fence_probe_interval_defaults_and_rejects_out_of_range() { + let _guards = env_guards(); + let previous = std::env::var_os("BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS"); + let read = |value: Option<&str>| { + match value { + Some(value) => std::env::set_var("BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS", value), + None => std::env::remove_var("BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS"), + } + Config::from_env().map(|config| config.replica_fence_probe_interval_ms) + }; - std::env::set_var("BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS", "0"); - let disabled = Config::from_env().expect("config"); + let unset = read(None); + let empty = read(Some(" ")); + let set = read(Some("500")); + let rejected = + ["soon", "0", "299", "10001", "-400"].map(|value| (value, read(Some(value)))); - if let Some(value) = previous_usage { - std::env::set_var("BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS", value); + if let Some(value) = previous { + std::env::set_var("BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS", value); } else { - std::env::remove_var("BUZZ_USAGE_METRICS_REPLICA_MAX_AGE_MS"); - } - if let Some(value) = previous_serving { - std::env::set_var("BUZZ_REPLICA_READ_MAX_AGE_MS", value); - } else { - std::env::remove_var("BUZZ_REPLICA_READ_MAX_AGE_MS"); + std::env::remove_var("BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS"); } - assert_eq!(defaults.replica_read_max_age_ms, 0); - assert_eq!(defaults.usage_metrics_replica_max_age_ms, 30_000); - assert_eq!(disabled.usage_metrics_replica_max_age_ms, 0); + assert_eq!(unset.expect("unset"), 0, "unset selects the default"); + assert_eq!(empty.expect("empty"), 0, "empty selects the default"); + assert_eq!(set.expect("set"), 500); + for (value, result) in rejected { + match result { + Err(ConfigError::InvalidValue(message)) => assert!( + message.contains("BUZZ_REPLICA_FENCE_PROBE_INTERVAL_MS"), + "{value}: {message}" + ), + other => panic!("{value} must fail startup, got {other:?}"), + } + } } #[test] @@ -2524,6 +2693,32 @@ mod tests { } } + #[test] + fn workflow_agent_mentions_defaults_to_any_and_rejects_other_values() { + use buzz_workflow::AgentMentions; + const NAME: &str = "BUZZ_WORKFLOW_AGENT_MENTIONS"; + let _guards = env_guards(); + let previous = std::env::var_os(NAME); + std::env::remove_var(NAME); + assert_eq!(parse_workflow_agent_mentions().unwrap(), AgentMentions::Any); + std::env::set_var(NAME, "any"); + assert_eq!(parse_workflow_agent_mentions().unwrap(), AgentMentions::Any); + std::env::set_var(NAME, "owner"); + assert_eq!( + parse_workflow_agent_mentions().unwrap(), + AgentMentions::Owner + ); + for invalid in ["true", "", "OWNER"] { + std::env::set_var(NAME, invalid); + assert!(parse_workflow_agent_mentions().is_err(), "{invalid:?}"); + } + if let Some(value) = previous { + std::env::set_var(NAME, value); + } else { + std::env::remove_var(NAME); + } + } + #[test] fn audit_logging_rejects_invalid_boolean() { let _guards = env_guards(); @@ -2911,6 +3106,17 @@ mod tests { ); } + #[test] + fn client_ip_header_is_off_when_empty_and_case_insensitive() { + assert_eq!(parse_client_ip_header("").unwrap(), None); + assert_eq!(parse_client_ip_header(" ").unwrap(), None); + assert_eq!( + parse_client_ip_header(" CF-Connecting-IP ").unwrap(), + Some(axum::http::HeaderName::from_static("cf-connecting-ip")) + ); + assert!(parse_client_ip_header("not a header").is_err()); + } + #[test] fn invalid_bind_addr_returns_error() { assert!(matches!( @@ -2990,3 +3196,27 @@ mod tests { ); } } + +#[cfg(test)] +mod invite_cutoff_tests { + use super::*; + + #[test] + fn cutoff_configuration_is_optional_and_strict() { + assert_eq!(parse_invite_v1_cutoff(None).unwrap(), None); + assert_eq!( + parse_invite_v1_cutoff(Some("1970-01-01T00:01:40Z")).unwrap(), + Some(100) + ); + for raw in [ + "", + "tomorrow", + "100", + "2026-10-10T00:00:00+01:00", + "1969-12-31T23:59:59Z", + "2026-10-10T00:00:00.1Z", + ] { + assert!(parse_invite_v1_cutoff(Some(raw)).is_err(), "{raw}"); + } + } +} diff --git a/crates/buzz-relay/src/connection.rs b/crates/buzz-relay/src/connection.rs index b9826168a9f..6cd277017b8 100644 --- a/crates/buzz-relay/src/connection.rs +++ b/crates/buzz-relay/src/connection.rs @@ -1,5 +1,6 @@ //! WebSocket connection lifecycle: semaphore → challenge → recv/send/heartbeat loops → cleanup. +use std::cell::Cell; use std::collections::HashMap; use std::net::SocketAddr; use std::sync::atomic::{AtomicU8, Ordering}; @@ -11,7 +12,7 @@ use futures_util::{Sink, SinkExt, StreamExt}; use tokio::sync::{mpsc, watch, Mutex}; use tokio_util::sync::CancellationToken; use tracing::Instrument as _; -use tracing::{debug, info, trace, warn}; +use tracing::{debug, trace, warn}; use uuid::Uuid; use buzz_auth::{generate_challenge, AuthContext}; @@ -36,8 +37,8 @@ const AUTH_TIMEOUT: Duration = Duration::from_secs(5); pub(crate) const WS_TERMINAL_FLUSH_TIMEOUT: Duration = Duration::from_secs(1); /// Shared mutable subscription map for a single WebSocket connection: sub ID → -/// owner token of the request that currently holds it (see `close::next_owner`). -pub(crate) type ConnectionSubscriptions = Arc>>; +/// the newest admitted request for it (see `close::SubOwner`). +pub(crate) type ConnectionSubscriptions = Arc>>; /// Pre-built NIP-FI session components created before the `is_community_active` /// bootstrap await. Passed from the HTTP-layer wrapper into the active handler so @@ -151,6 +152,9 @@ pub struct ConnectionState { /// peer cleanup) cannot start until all pre-expiry effects finish their /// bounded commits. [FI-TRACE-LEASE-BOUND, one-gate-per-connection] pub(crate) nip_fi_gate: std::sync::Arc, + + /// Bounds the access lines this client can trigger without being served. + pub(crate) refusal_budget: Arc, } impl ConnectionState { @@ -196,17 +200,18 @@ impl ConnectionState { /// Finish a pending challenge on timeout and preserve the historical rule /// that an already-failed connection is closed when its timeout expires. - fn expire_auth(&self) -> bool { + /// Returns the `close_reason` to close with, if the connection must close. + fn expire_auth(&self) -> Option<&'static str> { let mut auth = self.lock_auth_state(); match &*auth { AuthState::Pending { started_at, .. } => { let duration = started_at.elapsed(); *auth = AuthState::Failed; crate::metrics::record_auth_outcome(AuthOutcome::Timeout, duration); - true + Some("auth_timeout") } - AuthState::Failed => true, - AuthState::Authenticated(_) => false, + AuthState::Failed => Some("auth_failed"), + AuthState::Authenticated(_) => None, } } @@ -288,20 +293,27 @@ impl ConnectionState { /// aborts and panics fall back to `disconnect` and cancel child tasks. struct AuthLifecycleGuard { conn: Arc, + close: Arc, finished: bool, } impl AuthLifecycleGuard { - fn new(conn: Arc) -> Self { + fn new(conn: Arc, close: Arc) -> Self { Self { conn, + close, finished: false, } } + /// Terminalize the login, recording its identity on the close line. fn finish(&mut self, outcome: AuthOutcome) -> Option { self.finished = true; - self.conn.finish_auth_on_close(outcome) + let authenticated = self.conn.finish_auth_on_close(outcome); + if let Some(ctx) = &authenticated { + self.close.logged_in(ctx.pubkey); + } + authenticated } } @@ -309,7 +321,7 @@ impl Drop for AuthLifecycleGuard { fn drop(&mut self) { if !self.finished { self.conn.cancel.cancel(); - self.conn.finish_auth_on_close(AuthOutcome::Disconnect); + self.finish(AuthOutcome::Disconnect); } } } @@ -355,23 +367,37 @@ pub(crate) fn compute_session_deadline( /// Acquires a connection semaphore permit, sends the NIP-42 AUTH challenge, /// then drives the send, heartbeat, and receive loops until the connection closes. +#[allow(clippy::too_many_arguments)] pub(crate) async fn handle_connection( socket: WebSocket, state: Arc, addr: SocketAddr, + client_ip: Option, tenant: TenantContext, nip_fi_assertion: Option, nip_fi_shadow: Option>, + shadow_line: Option, connection_time: chrono::DateTime, ) { // Held through bootstrap, the active handler and any refusal drain, so a // socket counts against `BUZZ_MAX_CONNECTIONS` for as long as it is open. + let conn_id = Uuid::new_v4(); + // Owned from the upgrade on, so every exit (inactive community, the + // connection limit, the active handler, or this future being dropped) + // writes the connection's one line. + let close = crate::access::CloseLine::open(conn_id, tenant.community(), addr, client_ip); let Ok(_permit) = state.conn_semaphore.clone().try_acquire_owned() else { - warn!("Connection limit reached, rejecting {addr}"); + warn!( + peer_addr = %addr, + client_ip = client_ip.map(tracing::field::display), + "Connection limit reached, rejecting" + ); + close.refused("connection_limit"); return; }; - let conn_id = Uuid::new_v4(); let cancel = CancellationToken::new(); + let close_for_run = Arc::clone(&close); + let close_for_drain = Arc::clone(&close); // Fix 3: Arm the NIP-FI gate and expiry task BEFORE the `is_community_active` // bootstrap await so the session deadline is enforced even when the DB check @@ -391,8 +417,18 @@ pub(crate) async fn handle_connection( crate::nip_fi_gate::SessionAdmissionGate::off_mode(cancel.clone()) }; let (pre_terminal_ctrl_tx, pre_terminal_ctrl_rx) = mpsc::channel::(1); - let control = CommunityConnectionControl::new(cancel); + let control = CommunityConnectionControl::new(cancel).with_client_ip(client_ip); + if let Some(assertion) = &nip_fi_assertion { + control.attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "ws", + crate::nip_fi_shadow::enforce_label(&state, tenant.host()), + assertion.asserted_key(), + )); + } control.attach_nip_fi_shadow(nip_fi_shadow); + // Its first verified AUTH writes it; else the read loop's end does. + let shadow_line = shadow_line.map(Arc::new); + control.attach_nip_fi_line(shadow_line.as_ref()); let drain_reason = control.disconnect_reason(); let pre_expiry_task = pre_session_deadline.map(|deadline| { crate::nip_fi_session::spawn_nip_fi_expiry_task( @@ -435,7 +471,7 @@ pub(crate) async fn handle_connection( conn_id, community_id, control, - move || async move { check_state.db.is_community_active(community_id).await }, + move || async move { check_state.is_community_active_cached(community_id).await }, move |control| async move { let socket = socket_for_run .lock() @@ -452,7 +488,7 @@ pub(crate) async fn handle_connection( run_state, addr, tenant, - conn_id, + close_for_run, control, nip_fi_assertion, connection_time, @@ -466,6 +502,8 @@ pub(crate) async fn handle_connection( .await }, move || async move { + // Bootstrap ended the connection before serving it. + close_for_drain.refused("not_admitted"); // Deliver a queued denial frame (if any) and the reason's Close // even when the active-connection path is never entered. let socket = socket_for_drain.lock().await.take(); @@ -493,7 +531,7 @@ async fn handle_active_connection( state: Arc, addr: SocketAddr, tenant: TenantContext, - conn_id: Uuid, + close: Arc, control: CommunityConnectionControl, nip_fi_assertion: Option, connection_time: chrono::DateTime, @@ -502,6 +540,7 @@ async fn handle_active_connection( // produced by any caller but retained for future test extensibility. pre_built: Option, ) { + let conn_id = close.conn_id(); let cancel = control.cancellation_token(); let disconnect_reason = control.disconnect_reason(); // connection_time is threaded in from the HTTP handler (captured immediately @@ -581,6 +620,7 @@ async fn handle_active_connection( }); let conn = Arc::new(ConnectionState { + refusal_budget: Arc::clone(&close.refusals), conn_id, tenant, remote_addr: addr, @@ -601,7 +641,6 @@ async fn handle_active_connection( community_control: control.clone(), }); - info!(conn_id = %conn_id, addr = %addr, "WebSocket connection established"); metrics::counter!( "buzz_ws_connections_total", "community" => conn.tenant.host().to_owned() @@ -615,6 +654,7 @@ async fn handle_active_connection( .is_err() { warn!(conn_id = %conn_id, "Failed to send AUTH challenge — client disconnected immediately"); + close.closed("client_closed"); return; } @@ -622,7 +662,7 @@ async fn handle_active_connection( // don't leak. Decremented in the cleanup path below. metrics::gauge!("buzz_ws_connections_active").increment(1.0); crate::metrics::record_auth_attempt_started(); - let mut auth_lifecycle = AuthLifecycleGuard::new(Arc::clone(&conn)); + let mut auth_lifecycle = AuthLifecycleGuard::new(Arc::clone(&conn), Arc::clone(&close)); // Register after challenge succeeds — avoids leaked entries on early disconnect. state.conn_manager.register( @@ -642,6 +682,7 @@ async fn handle_active_connection( let (ws_send, ws_recv) = socket.split(); let send_cancel = cancel.child_token(); + let ws_send = crate::access::CountingSink::new(ws_send, Arc::clone(&close.queued)); let send_task = tokio::spawn(send_loop( ws_send, rx, @@ -658,15 +699,18 @@ async fn handle_active_connection( ctrl_tx, Arc::clone(&missed_pongs), heartbeat_cancel, + Arc::clone(&close), )); let auth_timeout_conn = Arc::clone(&conn); let auth_timeout_cancel = cancel.clone(); + let auth_timeout_close = Arc::clone(&close); let auth_timeout_task = tokio::spawn(async move { tokio::select! { _ = tokio::time::sleep(AUTH_TIMEOUT) => { - if auth_timeout_conn.expire_auth() { - warn!( + if let Some(reason) = auth_timeout_conn.expire_auth() { + auth_timeout_close.closed(reason); + debug!( conn_id = %auth_timeout_conn.conn_id, timeout_secs = AUTH_TIMEOUT.as_secs(), "NIP-42 auth timeout — closing connection" @@ -720,10 +764,15 @@ async fn handle_active_connection( Arc::clone(&state), Arc::clone(&missed_pongs), cancel.clone(), + &close, ) .await; cancel.cancel(); + // Whoever cancelled first recorded its own reason; this fills in the rest. + close.closed(server_close_reason(&state, &conn).unwrap_or("server_closed")); + // The socket can no longer AUTH; cleanup below may block. + conn.community_control.finish_nip_fi_line(); let close_outcome = if state.shutting_down.load(Ordering::Acquire) { AuthOutcome::Shutdown } else { @@ -770,7 +819,6 @@ async fn handle_active_connection( }; tokio::join!(cleanup, await_client_close(ws_recv)); metrics::gauge!("buzz_ws_connections_active").decrement(1.0); - info!(conn_id = %conn_id, addr = %addr, "WebSocket connection closed"); } /// Send WebSocket messages in priority order: control frames before data frames. @@ -779,15 +827,18 @@ async fn handle_active_connection( /// giving them priority over data frames. If the underlying socket writer /// is stalled, control frames queue in the small ctrl_rx buffer; callers /// treat a full control channel as terminal (Bug 7 fix). -async fn send_loop( - ws_send: futures_util::stream::SplitSink, +async fn send_loop( + ws_send: S, data_rx: mpsc::Receiver, ctrl_rx: mpsc::Receiver, terminal_ctrl_rx: mpsc::Receiver, restart_rx: mpsc::Receiver, cancel: CancellationToken, disconnect_reason: watch::Receiver>, -) { +) where + S: Sink + Unpin, + S::Error: std::error::Error + 'static, +{ send_loop_inner( ws_send, data_rx, @@ -1136,6 +1187,29 @@ async fn send_loop_inner( } } +/// The `close_reason` of a close the server already decided on, if any: +/// shutdown, then a policy disconnect, then a cancellation (`auth_failed` if +/// it rejected AUTH). The reader defers to it, so a peer's reply to the +/// server's Close is not logged as the cause. +pub(crate) fn server_close_reason( + state: &AppState, + conn: &ConnectionState, +) -> Option<&'static str> { + if state.shutting_down.load(Ordering::Acquire) { + return Some("shutdown"); + } + if let Some(reason) = *conn.community_control.disconnect_reason().borrow() { + return Some(reason.as_str()); + } + conn.cancel.is_cancelled().then(|| { + if matches!(conn.auth_state_snapshot(), AuthState::Failed) { + "auth_failed" + } else { + "server_closed" + } + }) +} + /// 3 missed pongs → disconnect. /// /// Sends Ping through the control channel so it isn't blocked by a full @@ -1145,23 +1219,31 @@ async fn heartbeat_loop( ctrl_tx: mpsc::Sender, missed_pongs: Arc, cancel: CancellationToken, + close: Arc, ) { let mut interval = tokio::time::interval(Duration::from_secs(30)); loop { tokio::select! { _ = interval.tick() => { + // A tick racing a close already decided is not a miss. + if cancel.is_cancelled() { + break; + } // fetch_add returns the *previous* value before incrementing: // prev=0 → now 1 (first miss) // prev=1 → now 2 (second miss) // prev=2 → now 3 (third miss → disconnect) let missed = missed_pongs.fetch_add(1, Ordering::Relaxed); if missed >= 2 { - warn!("3 missed pongs — closing connection"); + debug!("3 missed pongs — closing connection"); + metrics::counter!("buzz_ws_missed_pong_disconnects_total").increment(1); + close.closed("missed_pongs"); cancel.cancel(); break; } if ctrl_tx.try_send(WsMessage::Ping(axum::body::Bytes::new())).is_err() { warn!("control channel full — cannot send Ping, closing"); + close.closed("control_channel_full"); cancel.cancel(); break; } @@ -1182,6 +1264,7 @@ async fn recv_loop( state: Arc, missed_pongs: Arc, cancel: CancellationToken, + close: &crate::access::CloseLine, ) -> ( futures_util::stream::SplitStream, Option>, @@ -1204,6 +1287,7 @@ async fn recv_loop( text.len(), max_frame_bytes )); + close.closed("frame_too_large"); break; } trace!(len = text.len(), "frame received"); @@ -1226,6 +1310,7 @@ async fn recv_loop( bytes.len(), max_frame_bytes )); + close.closed("frame_too_large"); break; } // Binary frames: attempt UTF-8 decode and treat as text. Some clients @@ -1248,15 +1333,18 @@ async fn recv_loop( // Control channel full means the socket writer is // completely stalled — treat as terminal. warn!(conn_id = %conn.conn_id, "control channel full — cannot send Pong, closing"); + close.closed("control_channel_full"); break; } } Some(Ok(WsMessage::Close(_))) | None => { debug!("WebSocket closed by client"); + close.closed(server_close_reason(&state, &conn).unwrap_or("client_closed")); break; } Some(Err(e)) => { debug!("WebSocket error: {e}"); + close.closed(server_close_reason(&state, &conn).unwrap_or("socket_error")); break; } } @@ -1321,21 +1409,25 @@ async fn handle_text_message(text: String, conn: Arc, state: Ar } }; - if !enforce_ws_admission(&msg, &conn, &state).await { + match &msg { + ClientMessage::Req { .. } => crate::metrics::record_ws_read("req"), + ClientMessage::Count { .. } => crate::metrics::record_ws_read("count"), + ClientMessage::ArtifactSync { .. } => crate::metrics::record_ws_read("sync"), + _ => {} + } + + if let Err(reason) = enforce_ws_admission(&msg, &conn, &state).await { + // An EVENT's write line is written where its OK is sent. + crate::access::ReadLog::refused(&msg, &conn, reason); return; } match msg { ClientMessage::Auth(event) => { // AUTH remains inline so only one frame can race the connection's - // pending lifecycle, but cancellation can preempt dependency waits. - let span = tracing::info_span!("ws.auth", conn_id = %conn.conn_id); - tokio::select! { - biased; - _ = conn.cancel.cancelled() => {} - _ = handlers::auth::handle_auth(event, Arc::clone(&conn), Arc::clone(&state)) - .instrument(span) => {} - } + // pending lifecycle. Boxed: the handler's future is deep enough + // to overflow the layout depth limit when nested here. + Box::pin(handle_auth_frame(event, &conn, &state)).await; } ClientMessage::Event(event) => { let conn = Arc::clone(&conn); @@ -1345,10 +1437,11 @@ async fn handle_text_message(text: String, conn: Arc, state: Ar Err(_) => { // Correlate to the event id: a bare NOTICE here strands the // client's pending publish exactly as an over-quota one did. - conn.send(request_rejection_message( + let queued = conn.send(request_rejection_message( RejectionTarget::Event(event.id), "rate-limited: too many concurrent requests", )); + crate::access::WriteLog::refused(&conn, &event, "rate-limited", queued); return; } }; @@ -1378,22 +1471,104 @@ async fn handle_text_message(text: String, conn: Arc, state: Ar let permit = match state.handler_semaphore.clone().try_acquire_owned() { Ok(p) => p, Err(_) => { - conn.send(request_rejection_message( - RejectionTarget::Subscription(&sub_id), + // Retires whatever held the ID before `CLOSED`. + handlers::close::refuse( + &sub_id, "rate-limited: too many concurrent requests", - )); + &conn, + &state, + ) + .await; + crate::access::ReadLog::refused_read( + "req", + &conn, + &sub_id, + &filters, + "too_many_concurrent_requests", + ); + return; + } + }; + // Admit before spawning: arrival order decides which request owns + // the ID, so a later same-ID REQ or a CLOSE fences this one even + // while its handler is still in access checks. + let owner = match handlers::close::admit(&sub_id, &conn).await { + Ok(owner) => owner, + Err(not_admitted) => { + if not_admitted == handlers::close::NotAdmitted::TooManySubscriptions { + crate::access::ReadLog::refused_read( + "req", + &conn, + &sub_id, + &filters, + "too_many_subscriptions", + ); + } return; } }; let span = tracing::info_span!("ws.req", conn_id = %conn.conn_id, sub_id = %sub_id); tokio::spawn( async move { - handlers::req::handle_req(sub_id, filters, before_ids, conn, state).await; + handlers::req::handle_admitted_req( + sub_id, owner, filters, before_ids, conn, state, + ) + .await; drop(permit); } .instrument(span), ); } + ClientMessage::ArtifactSync { sub_id, filter } => { + let conn = Arc::clone(&conn); + let state = Arc::clone(&state); + let permit = match state.handler_semaphore.clone().try_acquire_owned() { + Ok(p) => p, + Err(_) => { + // Retires whatever held the ID before `CLOSED`. + handlers::close::refuse( + &sub_id, + "rate-limited: too many concurrent requests", + &conn, + &state, + ) + .await; + crate::access::ReadLog::refused_sync( + &conn, + &sub_id, + filter.as_ref().ok(), + "too_many_concurrent_requests", + ); + return; + } + }; + // Admitted before spawning, like a REQ. + let owner = match handlers::close::admit(&sub_id, &conn).await { + Ok(owner) => owner, + Err(not_admitted) => { + if not_admitted == handlers::close::NotAdmitted::TooManySubscriptions { + crate::access::ReadLog::refused_sync( + &conn, + &sub_id, + filter.as_ref().ok(), + "too_many_subscriptions", + ); + } + return; + } + }; + let span = + tracing::info_span!("ws.artifact_sync", conn_id = %conn.conn_id, sub_id = %sub_id); + tokio::spawn( + async move { + handlers::artifact_sync::handle_sync( + sub_id, owner, filter, conn, state, permit, + ) + .await; + } + .instrument(span), + ); + } ClientMessage::Count { sub_id, filters } => { let conn = Arc::clone(&conn); let state = Arc::clone(&state); @@ -1404,6 +1579,13 @@ async fn handle_text_message(text: String, conn: Arc, state: Ar RejectionTarget::Subscription(&sub_id), "rate-limited: too many concurrent requests", )); + crate::access::ReadLog::refused_read( + "count", + &conn, + &sub_id, + &filters, + "too_many_concurrent_requests", + ); return; } }; @@ -1422,12 +1604,67 @@ async fn handle_text_message(text: String, conn: Arc, state: Ar } } +/// One AUTH frame: cancellation can preempt the handler's dependency waits, +/// and a frame that ends without logging a decision logs `aborted`. +async fn handle_auth_frame( + event: nostr::Event, + conn: &Arc, + state: &Arc, +) { + let span = tracing::info_span!("ws.auth", conn_id = %conn.conn_id); + let claimed = event.pubkey; + AUTH_LINE_WRITTEN + .scope(Cell::new(false), async { + tokio::select! { + biased; + _ = conn.cancel.cancelled() => {} + _ = handlers::auth::handle_auth(event, Arc::clone(conn), Arc::clone(state)) + .instrument(span) => {} + } + if !AUTH_LINE_WRITTEN.with(Cell::get) { + log_aborted_auth(conn, claimed); + } + }) + .await; +} + +tokio::task_local! { + /// Whether the AUTH frame being handled has logged its access line. The + /// connection's auth state cannot answer this: the cancellation watcher + /// and the auth timeout end a pending attempt without logging it. + static AUTH_LINE_WRITTEN: Cell; +} + +/// Record that the current AUTH frame logged its line (no-op elsewhere). +pub(crate) fn note_auth_line_written() { + let _ = AUTH_LINE_WRITTEN.try_with(|written| written.set(true)); +} + +/// Log an AUTH frame that ended without a decision of its own: cut off by +/// cancellation, or finished after the watcher or timeout ended its attempt. +fn log_aborted_auth(conn: &ConnectionState, claimed: nostr::PublicKey) { + let reason = if conn.nip_fi_gate.deadline_passed() { + "session_expired" + } else { + "connection_closed" + }; + // Cut off after `authenticate()` succeeded: the close line will show + // this key as authenticated, so this line must not call it unverified. + let verified = matches!( + conn.auth_state_snapshot(), + AuthState::Authenticated(ctx) if ctx.pubkey == claimed + ); + crate::access::AuthAttempt::nip42(conn, claimed, verified) + .log(crate::access::AuthResult::Aborted(reason)); +} + #[cfg(test)] pub(crate) mod test_seam { use super::*; - pub(crate) type Hold = - tokio::sync::oneshot::Sender>>; + pub(crate) type Hold = tokio::sync::oneshot::Sender< + tokio::sync::OwnedMutexGuard>, + >; tokio::task_local! { /// Hands the test this connection's subscription lock, already held, @@ -1492,12 +1729,23 @@ pub(crate) mod tests { auth: AuthState, nip_fi_assertion: Option, community: buzz_core::tenant::CommunityId, + ) -> TestConn { + test_conn_gated(auth, nip_fi_assertion, community, None) + } + + /// [`test_conn_in`] whose effect gate has `deadline` (`None`: off mode). + pub(crate) fn test_conn_gated( + auth: AuthState, + nip_fi_assertion: Option, + community: buzz_core::tenant::CommunityId, + deadline: Option>, ) -> TestConn { let (send_tx, send_rx) = mpsc::channel(4); let (ctrl_tx, ctrl_rx) = mpsc::channel(8); let (terminal_ctrl_tx, terminal_rx) = mpsc::channel(1); let cancel = CancellationToken::new(); let conn = ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: TenantContext::resolved(community, "test.local".to_string()), remote_addr: "127.0.0.1:1234".parse().expect("socket addr"), @@ -1511,7 +1759,12 @@ pub(crate) mod tests { grace_limit: 3, nip_fi_assertion, session_deadline: None, - nip_fi_gate: crate::nip_fi_gate::SessionAdmissionGate::off_mode(cancel.clone()), + nip_fi_gate: match deadline { + Some(deadline) => { + crate::nip_fi_gate::SessionAdmissionGate::new(deadline, cancel.clone()) + } + None => crate::nip_fi_gate::SessionAdmissionGate::off_mode(cancel.clone()), + }, community_control: crate::state::CommunityConnectionControl::new(cancel.clone()), }; TestConn { @@ -1561,6 +1814,45 @@ pub(crate) mod tests { DebugValue, )>; + /// A connection that misses three pongs closes as `missed_pongs` and is + /// counted. Mutation: drop the counter or the `closed` call → RED. + #[test] + fn missed_pongs_close_with_their_reason_and_count() { + let recorder = metrics_util::debugging::DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let (_, out) = crate::access::tests::capture(|| { + metrics::with_local_recorder(&recorder, || { + tokio::runtime::Builder::new_current_thread() + .enable_time() + .start_paused(true) + .build() + .unwrap() + .block_on(async { + let close = crate::access::CloseLine::open( + Uuid::nil(), + buzz_core::CommunityId::from_uuid(Uuid::nil()), + "127.0.0.1:1".parse().unwrap(), + None, + ); + let (ctrl_tx, _ctrl_rx) = mpsc::channel(8); + let cancel = CancellationToken::new(); + heartbeat_loop(ctrl_tx, Arc::new(AtomicU8::new(0)), cancel.clone(), close) + .await; + assert!(cancel.is_cancelled()); + }); + }); + }); + let snapshot = snapshotter.snapshot().into_vec(); + assert_eq!( + counter_value(&snapshot, "buzz_ws_missed_pong_disconnects_total", None), + 1 + ); + let lines = out.lines(); + let close: Vec<_> = lines.iter().filter(|l| l["event"] == "close").collect(); + assert_eq!(close.len(), 1, "{lines:?}"); + assert_eq!(close[0]["close_reason"], "missed_pongs", "{lines:?}"); + } + fn counter_value(snapshot: &MetricSnapshot, name: &str, outcome: Option<&str>) -> u64 { snapshot .iter() @@ -1686,6 +1978,7 @@ pub(crate) mod tests { AuthOutcome::RelayMembershipCheckError, AuthOutcome::NotRelayMember, AuthOutcome::PairingMismatch, + AuthOutcome::ConcurrencyLimit, ] { crate::metrics::record_auth_attempt_started(); let (denied, _rx) = test_conn_with_auth(pending_state()); @@ -1698,7 +1991,12 @@ pub(crate) mod tests { crate::metrics::record_auth_attempt_started(); let (timed_out, _rx) = test_conn_with_auth(pending_state()); - assert!(timed_out.expire_auth()); + assert_eq!(timed_out.expire_auth(), Some("auth_timeout")); + assert_eq!( + timed_out.expire_auth(), + Some("auth_failed"), + "a failed connection closes as auth_failed" + ); assert!(timed_out .finish_auth_on_close(AuthOutcome::Disconnect) .is_none()); @@ -1796,6 +2094,321 @@ pub(crate) mod tests { ); } + /// The close lines `out` holds, once at least one is written. + async fn close_lines(out: &crate::access::tests::Captured) -> Vec { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let lines: Vec<_> = out + .lines() + .into_iter() + .filter(|l| l["event"] == "close") + .collect(); + if !lines.is_empty() { + // Let a duplicate, if any, land before counting. + tokio::task::yield_now().await; + break out + .lines() + .into_iter() + .filter(|l| l["event"] == "close") + .collect(); + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("a close line") + } + + /// Serve `upgrade` on a local WebSocket, connect once, read until the + /// server ends the socket, and return the data frames the client received + /// and the connection's close lines. + async fn close_lines_of( + upgrade: F, + ) -> ( + Vec, + Vec, + ) + where + F: Fn(axum::extract::ws::WebSocket) -> Fut + Clone + Send + Sync + 'static, + Fut: std::future::Future + Send + 'static, + { + use axum::{routing::get, Router}; + use futures_util::StreamExt as _; + let (_guard, out) = crate::access::tests::capture_scoped(); + let app = Router::new().route( + "/", + get(move |ws: axum::extract::ws::WebSocketUpgrade| { + let upgrade = upgrade.clone(); + async move { ws.on_upgrade(upgrade) } + }), + ); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("local addr"); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let (mut client, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/")) + .await + .expect("connect"); + let mut frames = Vec::new(); + while let Ok(Some(Ok(frame))) = + tokio::time::timeout(std::time::Duration::from_secs(3), client.next()).await + { + if frame.is_close() { + break; + } + if frame.is_text() || frame.is_binary() { + frames.push(frame); + } + } + let lines = close_lines(&out).await; + server.abort(); + (frames, lines) + } + + /// Serve one real active connection on `state`; once the client has its + /// AUTH challenge, run `server_close`, then close from the client, after + /// the server's own Close when `reply` is set. Returns the `close_reason`. + async fn close_reason_after( + state: Arc, + reply: bool, + server_close: impl FnOnce(Arc, &CommunityConnectionControl), + ) -> serde_json::Value { + use futures_util::{SinkExt as _, StreamExt as _}; + let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::new_v4()); + let conn_id = Uuid::new_v4(); + let control = CommunityConnectionControl::new(CancellationToken::new()); + let (_guard, out) = crate::access::tests::capture_scoped(); + let (served, served_control) = (Arc::clone(&state), control.clone()); + let app = Router::new().route( + "/", + get(move |ws: WebSocketUpgrade| { + let (state, control) = (Arc::clone(&served), served_control.clone()); + async move { + ws.on_upgrade(move |socket| async move { + let close = crate::access::CloseLine::open( + conn_id, + community, + "127.0.0.1:9999".parse().unwrap(), + None, + ); + handle_active_connection( + socket, + state, + "127.0.0.1:9999".parse().unwrap(), + TenantContext::resolved(community, "test.local".to_owned()), + close, + control, + None, + chrono::Utc::now(), + None, + ) + .await + }) + } + }), + ); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("local addr"); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let (mut client, _) = connect_async(format!("ws://{addr}/")) + .await + .expect("connect"); + assert!(matches!(client.next().await, Some(Ok(Message::Text(_))))); + while state.conn_manager.community_for_conn(conn_id).is_none() { + tokio::task::yield_now().await; + } + server_close(Arc::clone(&state), &control); + if reply { + while let Some(Ok(frame)) = client.next().await { + if frame.is_close() { + break; + } + } + } + // Send the Close, or flush the reply tungstenite queued to the server's. + let _ = client.close(None).await; + let _ = client.flush().await; + let lines = close_lines(&out).await; + server.abort(); + assert_eq!(lines.len(), 1, "{lines:?}"); + lines[0]["close_reason"].clone() + } + + /// A client answering the jittered restart's 1012 with its own Close + /// still closes as `shutdown`. Mutation: let the reader record + /// `client_closed` without consulting `server_close_reason` → RED. + #[tokio::test(flavor = "current_thread")] + async fn client_reply_to_a_jittered_restart_closes_as_shutdown() { + let state = crate::state::tests::test_state().await; + let reason = close_reason_after(state, true, |state, _| { + state.begin_shutdown(); + tokio::spawn(async move { state.conn_manager.drain_all_jittered(1).await }); + }) + .await; + assert_eq!(reason, "shutdown"); + } + + /// A client Close that arrives as a policy disconnect cancels keeps the + /// policy's reason, whichever the reader sees first. + #[tokio::test(flavor = "current_thread")] + async fn client_close_racing_a_policy_disconnect_keeps_the_policy_reason() { + let state = crate::state::tests::test_state().await; + let reason = close_reason_after(state, false, |_, control| { + let (frame_tx, _frame_rx) = mpsc::channel(1); + control.deny_authorization(&frame_tx, crate::nip_fi_session::NipFiWsRoute::Root); + }) + .await; + assert_eq!(reason, "authorization_denied"); + } + + /// The reasons the server ranks for a close it already decided on. + #[tokio::test(flavor = "current_thread")] + async fn server_close_reason_ranks_shutdown_policy_then_cancellation() { + let state = crate::state::tests::test_state().await; + let (open, _rx) = test_conn_with_auth(pending_state()); + assert_eq!(server_close_reason(&state, &open), None); + open.cancel.cancel(); + assert_eq!(server_close_reason(&state, &open), Some("server_closed")); + let (rejected, _rx) = test_conn_with_auth(AuthState::Failed); + rejected.cancel.cancel(); + assert_eq!(server_close_reason(&state, &rejected), Some("auth_failed")); + let (denied, _rx) = test_conn_with_auth(AuthState::Failed); + denied.community_control.deny_authorization( + &denied.terminal_ctrl_tx, + crate::nip_fi_session::NipFiWsRoute::Root, + ); + assert_eq!( + server_close_reason(&state, &denied), + Some("authorization_denied") + ); + state.begin_shutdown(); + assert_eq!(server_close_reason(&state, &denied), Some("shutdown")); + } + + /// An AUTH rejected without closing leaves the socket open, and its auth + /// timeout then closes it as `auth_failed`. + #[tokio::test(flavor = "current_thread")] + async fn auth_timeout_after_a_rejected_auth_closes_as_auth_failed() { + let state = crate::state::tests::test_state().await; + let (conn, _rx) = test_conn_with_auth(pending_state()); + let relay_url: RelayUrl = + crate::api::bridge::nip42_expected_relay_url(&state.config.relay_url, &conn.tenant) + .parse() + .expect("relay url"); + let event = EventBuilder::auth("wrong-challenge", relay_url) + .sign_with_keys(&Keys::generate()) + .expect("sign auth"); + let frame = serde_json::json!(["AUTH", event]).to_string(); + handle_text_message(frame, Arc::clone(&conn), state).await; + assert!(matches!(conn.auth_state_snapshot(), AuthState::Failed)); + assert!( + !conn.cancel.is_cancelled(), + "a bad challenge does not close" + ); + assert_eq!(conn.expire_auth(), Some("auth_failed")); + } + + /// A connection cancelled during the community-active startup check + /// still writes its one close line, marked not admitted. + #[tokio::test] + async fn startup_cancellation_writes_one_close_line() { + let key = nostr::Keys::generate(); + let deadline = chrono::Utc::now() - chrono::Duration::seconds(2); + let assertion = + buzz_auth::VerifiedAssertion::for_test(Some(key.public_key()), vec![deadline]); + let state = crate::state::tests::test_state().await; + let (_, lines) = close_lines_of(move |socket| { + let (state, assertion) = (Arc::clone(&state), assertion.clone()); + async move { + handle_connection( + socket, + state, + "127.0.0.1:9999".parse().unwrap(), + None, + TenantContext::resolved( + buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), + "test.local".to_owned(), + ), + Some(assertion), + None, + None, + chrono::Utc::now(), + ) + .await + } + }) + .await; + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["refused"], "not_admitted", "{}", lines[0]); + assert!(lines[0].get("pubkey").is_none(), "{}", lines[0]); + } + + /// A connection refused at the connection limit writes one close line + /// saying so. + #[tokio::test] + async fn connection_limit_refusal_writes_one_close_line() { + let mut state = (*crate::state::tests::test_state().await).clone(); + state.conn_semaphore = Arc::new(tokio::sync::Semaphore::new(0)); + let state = Arc::new(state); + let (frames, lines) = close_lines_of(move |socket| { + let state = Arc::clone(&state); + async move { + handle_connection( + socket, + state, + "127.0.0.1:9999".parse().unwrap(), + None, + TenantContext::resolved( + buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), + "test.local".to_owned(), + ), + None, + None, + None, + chrono::Utc::now(), + ) + .await + } + }) + .await; + assert!(frames.is_empty(), "refused socket was served: {frames:?}"); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["refused"], "connection_limit", "{}", lines[0]); + } + + /// Dropping an authenticated handler mid-connection writes its one + /// close line, with the identity it logged in as. + #[tokio::test(flavor = "current_thread")] + async fn dropped_authenticated_handler_writes_one_close_line() { + let (_guard, out) = crate::access::tests::capture_scoped(); + let (conn, _rx) = test_conn_with_auth(pending_state()); + let ctx = auth_context(); + let pubkey = ctx.pubkey; + assert!(conn.authenticate(ctx)); + let started = Arc::new(Notify::new()); + let task = { + let started = Arc::clone(&started); + tokio::spawn(async move { + let close = crate::access::CloseLine::open( + conn.conn_id, + conn.tenant.community(), + conn.remote_addr, + None, + ); + let _guard = AuthLifecycleGuard::new(conn, close); + started.notify_one(); + std::future::pending::<()>().await; + }) + }; + started.notified().await; + task.abort(); + let _ = task.await; + let lines = close_lines(&out).await; + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["pubkey"], pubkey.to_hex(), "{}", lines[0]); + assert!(lines[0].get("refused").is_none(), "{}", lines[0]); + assert_eq!(lines[0]["close_reason"], "handler_dropped", "{}", lines[0]); + } + /// Aborting the production lifecycle owner must synchronously terminalize /// pending accounting and release an authenticated gauge exactly once. #[tokio::test(flavor = "current_thread")] @@ -1812,7 +2425,13 @@ pub(crate) mod tests { let conn = Arc::clone(&authenticated); let started = Arc::clone(&authenticated_started); tokio::spawn(async move { - let _guard = AuthLifecycleGuard::new(conn); + let close = crate::access::CloseLine::open( + conn.conn_id, + conn.tenant.community(), + conn.remote_addr, + None, + ); + let _guard = AuthLifecycleGuard::new(conn, close); started.notify_one(); std::future::pending::<()>().await; }) @@ -1828,7 +2447,13 @@ pub(crate) mod tests { let conn = Arc::clone(&pending); let started = Arc::clone(&pending_started); tokio::spawn(async move { - let _guard = AuthLifecycleGuard::new(conn); + let close = crate::access::CloseLine::open( + conn.conn_id, + conn.tenant.community(), + conn.remote_addr, + None, + ); + let _guard = AuthLifecycleGuard::new(conn, close); started.notify_one(); std::future::pending::<()>().await; }) @@ -1918,12 +2543,18 @@ pub(crate) mod tests { ws.on_upgrade(move |socket| async move { let cancel = CancellationToken::new(); let control = CommunityConnectionControl::new(cancel); + let close = crate::access::CloseLine::open( + Uuid::new_v4(), + tenant.community(), + "127.0.0.1:1234".parse().expect("client address"), + None, + ); handle_active_connection( socket, state, "127.0.0.1:1234".parse().expect("client address"), tenant, - Uuid::new_v4(), + close, control, None, chrono::Utc::now(), @@ -2071,6 +2702,58 @@ pub(crate) mod tests { assert_eq!(frame[3], "rate-limited: too many concurrent requests"); } + /// The saturation refusal's write line records whether its OK was queued, + /// with the outbound channel open, full or closed. Mutation: pass `true` + /// instead of the send result at the refusal site → RED. + #[tokio::test] + async fn saturated_handler_write_line_records_whether_its_ok_was_queued() { + let state = crate::state::tests::test_state().await; + let permits = state.handler_semaphore.available_permits(); + let _held = Arc::clone(&state.handler_semaphore) + .acquire_many_owned(permits as u32) + .await + .expect("hold every handler permit"); + let mut got = Vec::new(); + for channel in ["open", "full", "closed"] { + let (conn, rx) = test_conn_with_auth(AuthState::Failed); + let _rx = match channel { + "full" => { + while conn.send(String::new()) {} + Some(rx) + } + "closed" => { + drop(rx); + None + } + _ => Some(rx), + }; + let event = EventBuilder::new(Kind::TextNote, "hello") + .sign_with_keys(&Keys::generate()) + .expect("sign event"); + let raw = serde_json::json!(["EVENT", event]).to_string(); + let (guard, out) = crate::access::tests::capture_access_only(tracing::Level::INFO); + handle_text_message(raw, Arc::clone(&conn), Arc::clone(&state)).await; + drop(guard); + let line = out + .lines() + .into_iter() + .find(|l| l["event"] == "write") + .expect("write line"); + got.push(format!( + "{channel}:{}/{}/{}", + line["outcome"], line["reason"], line["ok_queued"] + )); + } + assert_eq!( + got, + [ + r#"open:"rejected"/"rate-limited"/null"#, + r#"full:"rejected"/"rate-limited"/false"#, + r#"closed:"rejected"/"rate-limited"/false"#, + ] + ); + } + /// The REQ arm of the same branch still settles on CLOSED. #[tokio::test] async fn saturated_handler_rejects_a_req_on_the_closed_channel() { @@ -2112,11 +2795,393 @@ pub(crate) mod tests { assert_eq!(frame[2], "rate-limited: too many concurrent requests"); } + /// A sync or ordinary REQ refused before its handler runs still replaces + /// the old holder of its ID (NIP-01), whether that is a sync or a live + /// subscription: the `CLOSED` must not leave either one fanning out under + /// a closed ID. Covers handler saturation and WS admission, both through + /// production dispatch. Mutation: send any refusal without + /// `retire_locked` → RED. + #[tokio::test] + async fn pre_handler_req_refusal_retires_the_old_holder() { + use buzz_pubsub::EventTopic; + let cases = [ + ( + AuthState::Failed, + true, + "rate-limited: too many concurrent requests", + ), + ( + authenticated_state(), + false, + "rate-limited: shared admission unavailable", + ), + ]; + let shapes = [(true, true), (true, false), (false, true), (false, false)]; + for ((sync, sync_holder), (auth, saturate, reason)) in shapes + .into_iter() + .flat_map(|shape| cases.clone().map(|case| (shape, case))) + { + let case = format!("{reason}, sync REQ: {sync}, sync holder: {sync_holder}"); + // Redis is unreachable here, so authenticated admission is + // `Unavailable`; an unauthenticated connection skips admission. + let state = crate::state::tests::test_state().await; + let (conn, mut rx) = test_conn_with_auth(auth); + let channel = uuid::Uuid::new_v4(); + let topic = EventTopic::Channel(channel); + handlers::req::claim_live_subscription( + "s", + vec![( + nostr::Filter::new().kind(Kind::TextNote), + crate::subscription::SubscriptionScope::channels([channel]), + )], + &conn, + &state, + ) + .await + .expect("claim the old holder"); + if sync_holder { + state.artifact_syncs.insert_idle(conn.conn_id, "s"); + } + let _held = if saturate { + let permits = state.handler_semaphore.available_permits(); + Some( + Arc::clone(&state.handler_semaphore) + .acquire_many_owned(permits as u32) + .await + .expect("hold every handler permit"), + ) + } else { + None + }; + + let filter = if sync { + serde_json::json!({"artifact": "current", "#h": [channel.to_string()]}) + } else { + serde_json::json!({"kinds": [1], "#h": [channel.to_string()]}) + }; + let raw = serde_json::json!(["REQ", "s", filter]).to_string(); + handle_text_message(raw, Arc::clone(&conn), Arc::clone(&state)).await; + + assert!(conn.subscriptions.lock().await.is_empty(), "{case}"); + assert!( + state.sub_registry.get_filters(conn.conn_id, "s").is_none(), + "{case}" + ); + assert!(!state.artifact_syncs.contains(conn.conn_id, "s"), "{case}"); + assert_eq!( + state.pubsub.topic_refcount(&conn.tenant, topic).await, + 0, + "{case}" + ); + let frame = read_frame(&mut rx); + assert_eq!(frame, serde_json::json!(["CLOSED", "s", reason]), "{case}"); + assert!(rx.try_recv().is_err(), "{case}: only CLOSED is sent"); + } + } + + /// Let every spawned REQ handler finish: each holds a handler permit + /// until it returns. + async fn wait_for_handlers(state: &AppState, permits: usize) { + tokio::time::timeout(Duration::from_secs(5), async { + while state.handler_semaphore.available_permits() < permits { + tokio::task::yield_now().await; + } + }) + .await + .expect("spawned handlers finish"); + } + + fn frames(rx: &mut mpsc::Receiver) -> Vec { + std::iter::from_fn(|| rx.try_recv().ok()) + .map(|message| match message { + WsMessage::Text(text) => serde_json::from_str(&text).expect("valid JSON frame"), + other => panic!("unexpected websocket message: {other:?}"), + }) + .collect() + } + + /// `REQ x` whose handler has not run yet, then `CLOSE x`: the request is + /// retired with the ID. When its handler runs, it sends nothing after the + /// acknowledgement and registers nothing. The read loop admits before it + /// spawns, so this holds however the handler is scheduled. + /// Mutation: admit inside the spawned handler instead → the handler's + /// refusal follows `CLOSED` → RED. + #[tokio::test] + async fn close_fences_a_req_whose_handler_has_not_run() { + for sync in [false, true] { + let state = crate::state::tests::test_state().await; + let permits = state.handler_semaphore.available_permits(); + // Unauthenticated: admission quotas do not apply, and the handler + // refuses without a database. + let (conn, mut rx) = test_conn_with_auth(AuthState::Failed); + let filter = if sync { + serde_json::json!({"artifact": "current", "#h": [uuid::Uuid::new_v4().to_string()]}) + } else { + serde_json::json!({"kinds": [1]}) + }; + let req = serde_json::json!(["REQ", "x", filter]).to_string(); + handle_text_message(req, Arc::clone(&conn), Arc::clone(&state)).await; + let close = serde_json::json!(["CLOSE", "x"]).to_string(); + handle_text_message(close, Arc::clone(&conn), Arc::clone(&state)).await; + wait_for_handlers(&state, permits).await; + + assert_eq!( + frames(&mut rx), + vec![serde_json::json!(["CLOSED", "x", ""])], + "sync: {sync}" + ); + assert!(conn.subscriptions.lock().await.is_empty(), "sync: {sync}"); + assert!( + state.sub_registry.get_filters(conn.conn_id, "x").is_none(), + "sync: {sync}" + ); + } + } + + /// Two same-ID REQs whose handlers have not run: only the newer one may + /// answer. The older one's refusal must not close the ID the newer one + /// owns. Mutation: refuse in-handler with an unconditional retire → two + /// NOTICE/CLOSED pairs → RED. + #[tokio::test] + async fn only_the_newest_same_id_req_answers() { + let state = crate::state::tests::test_state().await; + let permits = state.handler_semaphore.available_permits(); + let (conn, mut rx) = test_conn_with_auth(AuthState::Failed); + for kind in [1, 7] { + let req = serde_json::json!(["REQ", "x", {"kinds": [kind]}]).to_string(); + handle_text_message(req, Arc::clone(&conn), Arc::clone(&state)).await; + } + wait_for_handlers(&state, permits).await; + + assert_eq!( + frames(&mut rx), + vec![ + serde_json::json!(["NOTICE", "auth-required: authenticate before subscribing"]), + serde_json::json!(["CLOSED", "x", "auth-required: not authenticated"]), + ] + ); + assert!(conn.subscriptions.lock().await.is_empty()); + } + + /// An ordinary REQ that `handle_req` itself refuses, before it claims its + /// ID, still replaces the old holder (NIP-01): a live subscription or an + /// artifact sync must not keep using an ID the client was told is closed. + /// Covers the auth, scope, channel-count and database-error refusals. + /// Mutation: send any of them as a bare `CLOSED` → RED. + #[tokio::test] + async fn in_handler_req_refusal_retires_the_old_holder() { + use buzz_pubsub::EventTopic; + let mut scoped = auth_context(); + scoped.scopes = vec![buzz_auth::Scope::ChannelsRead]; + let channel = uuid::Uuid::new_v4(); + let too_many: Vec = (0..=handlers::req::MAX_EXPLICIT_CHANNEL_VALUES) + .map(|_| uuid::Uuid::new_v4().to_string()) + .collect(); + let cases = [ + ( + AuthState::Failed, + serde_json::json!({"kinds": [1]}), + "auth-required: not authenticated", + ), + ( + AuthState::Authenticated(scoped), + serde_json::json!({"kinds": [1]}), + "restricted: insufficient scope", + ), + ( + authenticated_state(), + serde_json::json!({"kinds": [1], "#h": too_many}), + "restricted: too many explicit channels", + ), + ( + authenticated_state(), + serde_json::json!({"search": "x"}), + "error: database error", + ), + ]; + for ((auth, filter, reason), sync_holder) in cases + .into_iter() + .flat_map(|case| [(case.clone(), false), (case, true)]) + { + let case = format!("{reason}, sync holder: {sync_holder}"); + let state = crate::state::tests::test_state_with_unreachable_database_url( + "postgres://127.0.0.1:1/none", + ) + .await; + let (conn, mut rx) = test_conn_with_auth(auth); + let topic = EventTopic::Channel(channel); + handlers::req::claim_live_subscription( + "s", + vec![( + nostr::Filter::new().kind(Kind::TextNote), + crate::subscription::SubscriptionScope::channels([channel]), + )], + &conn, + &state, + ) + .await + .expect("claim the old holder"); + if sync_holder { + state.artifact_syncs.insert_idle(conn.conn_id, "s"); + } + + let filter = serde_json::from_value(filter).expect("filter"); + handlers::req::handle_req( + "s".into(), + vec![filter], + vec![None], + Arc::clone(&conn), + Arc::clone(&state), + ) + .await; + + assert!(conn.subscriptions.lock().await.is_empty(), "{case}"); + assert!( + state.sub_registry.get_filters(conn.conn_id, "s").is_none(), + "{case}" + ); + assert!(!state.artifact_syncs.contains(conn.conn_id, "s"), "{case}"); + assert_eq!( + state.pubsub.topic_refcount(&conn.tenant, topic).await, + 0, + "{case}" + ); + let mut frame = read_frame(&mut rx); + if frame[0] == "NOTICE" { + frame = read_frame(&mut rx); + } + assert_eq!(frame, serde_json::json!(["CLOSED", "s", reason]), "{case}"); + assert!(rx.try_recv().is_err(), "{case}: nothing follows CLOSED"); + } + } + + /// A REQ for a new ID refused at the subscription limit cancels the + /// connection when its `CLOSED` cannot be queued: the client would + /// otherwise wait on a request the relay refused. + /// Mutation: ignore the `send` result on that refusal → RED. + #[tokio::test] + async fn subscription_limit_refusal_with_a_full_queue_cancels_the_connection() { + let state = crate::state::tests::test_state().await; + let (conn, _rx) = test_conn_with_auth(authenticated_state()); + { + let mut subs = conn.subscriptions.lock().await; + for index in 0..handlers::req::MAX_SUBSCRIPTIONS { + subs.insert( + format!("held-{index}"), + handlers::close::SubOwner { + owner: 0, + claimed: true, + }, + ); + } + } + while conn + .send_tx + .try_send(WsMessage::Text("filler".into())) + .is_ok() + {} + + handlers::req::handle_req( + "s".into(), + vec![nostr::Filter::new().kind(Kind::TextNote)], + vec![None], + Arc::clone(&conn), + Arc::clone(&state), + ) + .await; + + assert!(conn.cancel.is_cancelled()); + assert!(!conn.subscriptions.lock().await.contains_key("s")); + } + + /// A pre-handler refusal whose `CLOSED` cannot be queued has already + /// retired the old holder, so it cancels the connection: the client + /// learns the ID is gone from the disconnect. The queue is full but + /// below the slow-client grace limit, which would not cancel by itself. + /// Covers a sync and an ordinary REQ through production dispatch. + /// Mutation: ignore the `send` result in `close::refuse` → RED. + #[tokio::test] + async fn pre_handler_refusal_with_a_full_queue_cancels_the_connection() { + for filter in [ + serde_json::json!({"artifact": "current", "#h": [uuid::Uuid::new_v4().to_string()]}), + serde_json::json!({"kinds": [1]}), + ] { + let state = crate::state::tests::test_state().await; + let (conn, _rx) = test_conn_with_auth(AuthState::Failed); + handlers::req::claim_live_subscription( + "s", + vec![( + nostr::Filter::new().kind(Kind::TextNote), + crate::subscription::SubscriptionScope::global(), + )], + &conn, + &state, + ) + .await + .expect("claim the old holder"); + state.artifact_syncs.insert_idle(conn.conn_id, "s"); + while conn + .send_tx + .try_send(WsMessage::Text("filler".into())) + .is_ok() + {} + let permits = state.handler_semaphore.available_permits(); + let _held = Arc::clone(&state.handler_semaphore) + .acquire_many_owned(permits as u32) + .await + .expect("hold every handler permit"); + + let raw = serde_json::json!(["REQ", "s", filter]).to_string(); + handle_text_message(raw, Arc::clone(&conn), Arc::clone(&state)).await; + + assert!(conn.subscriptions.lock().await.is_empty(), "{filter}"); + assert!( + !state.artifact_syncs.contains(conn.conn_id, "s"), + "{filter}" + ); + assert!(conn.cancel.is_cancelled(), "{filter}"); + } + } + + /// Each parsed REQ, sync and COUNT frame advances its read counter by exactly + /// one, even when refused; other frames count nothing. + #[tokio::test(flavor = "current_thread")] + async fn dispatcher_counts_each_req_and_count_frame_once() { + let (recorder, handle) = crate::metrics::readiness_test_recorder(); + let _recorder_guard = metrics::set_default_local_recorder(&recorder); + let state = crate::state::tests::test_state().await; + let (conn, _rx) = test_conn_with_auth(AuthState::Failed); + let permits = state.handler_semaphore.available_permits(); + let _held = Arc::clone(&state.handler_semaphore) + .acquire_many_owned(permits as u32) + .await + .expect("hold every handler permit"); + + for raw in [ + serde_json::json!(["REQ", "r", {"kinds": [1]}]), + serde_json::json!(["COUNT", "c", {"kinds": [1]}]), + serde_json::json!(["REQ", "y", {"artifact": "current", "#h": [uuid::Uuid::new_v4().to_string()]}]), + serde_json::json!(["CLOSE", "r"]), + ] { + handle_text_message(raw.to_string(), Arc::clone(&conn), Arc::clone(&state)).await; + } + + let scrape = handle.render(); + for kind in ["req", "count", "sync"] { + assert!( + scrape.contains(&format!("buzz_ws_reads_total{{type=\"{kind}\"}} 1\n")), + "{scrape}" + ); + } + } + #[derive(Debug, Default)] struct MockSinkState { messages: Vec, flush_count: usize, fail_after_flushes: Option, + reject_sends: bool, + pending_flushes: usize, } #[derive(Debug, Clone)] @@ -2150,11 +3215,14 @@ pub(crate) mod tests { } fn start_send(self: std::pin::Pin<&mut Self>, item: WsMessage) -> Result<(), Self::Error> { - self.state - .lock() - .expect("mock sink poisoned") - .messages - .push(item); + let mut state = self.state.lock().expect("mock sink poisoned"); + if state.reject_sends { + return Err(std::io::Error::new( + std::io::ErrorKind::BrokenPipe, + "mock send rejected", + )); + } + state.messages.push(item); Ok(()) } @@ -2164,6 +3232,10 @@ pub(crate) mod tests { ) -> std::task::Poll> { let mut state = self.state.lock().expect("mock sink poisoned"); state.flush_count += 1; + if state.pending_flushes > 0 { + state.pending_flushes -= 1; + return std::task::Poll::Pending; + } if state .fail_after_flushes .is_some_and(|limit| state.flush_count >= limit) @@ -2219,6 +3291,864 @@ pub(crate) mod tests { } } + /// Run the production writer over a counting `sink` for `frames`, then + /// return the close-line totals it recorded. + async fn queued_totals( + sink: MockSink, + state: &Arc>, + frames: &[&str], + ) -> Arc { + let (data_tx, data_rx) = mpsc::channel(frames.len().max(1)); + for frame in frames { + data_tx + .send(WsMessage::Text((*frame).into())) + .await + .expect("queue frame"); + } + let totals = Arc::new(crate::access::QueuedTotals::default()); + let cancel = CancellationToken::new(); + let writer = tokio::spawn(send_loop_inner( + crate::access::CountingSink::new(sink, Arc::clone(&totals)), + data_rx, + mpsc::channel(1).1, + mpsc::channel(1).1, + mpsc::channel(1).1, + cancel.clone(), + ordinary_disconnect_reason(), + )); + while state.lock().expect("mock sink poisoned").flush_count == 0 + && !state.lock().expect("mock sink poisoned").reject_sends + { + tokio::task::yield_now().await; + } + tokio::task::yield_now().await; + cancel.cancel(); + writer.await.expect("writer exits"); + totals + } + + const EVENT_FRAME: &str = r#"["EVENT","s",{}]"#; + + #[tokio::test] + async fn close_totals_count_frames_the_writer_flushed() { + let (sink, state) = MockSink::new(None); + let totals = + queued_totals(sink, &state, &[EVENT_FRAME, EVENT_FRAME, r#"["EOSE","s"]"#]).await; + assert_eq!(totals.events(), 2); + assert_eq!( + totals.bytes(), + (EVENT_FRAME.len() * 2 + r#"["EOSE","s"]"#.len()) as u64 + ); + } + + #[tokio::test] + async fn close_totals_skip_a_frame_the_socket_rejects() { + let (sink, state) = MockSink::new(None); + state.lock().expect("mock sink poisoned").reject_sends = true; + let totals = queued_totals(sink, &state, &[EVENT_FRAME]).await; + assert_eq!((totals.events(), totals.bytes()), (0, 0)); + } + + #[tokio::test] + async fn close_totals_skip_frames_stranded_by_a_failed_flush() { + let (sink, state) = MockSink::new(Some(1)); + let totals = queued_totals(sink, &state, &[EVENT_FRAME, EVENT_FRAME]).await; + assert_eq!(state.lock().expect("mock sink poisoned").messages.len(), 2); + assert_eq!((totals.events(), totals.bytes()), (0, 0)); + } + + /// Cancellation lands while the batch's flush is still pending; the + /// terminal drain then flushes it, so the batch counts once. + #[tokio::test] + async fn close_totals_count_a_batch_flushed_by_the_drain_after_cancellation() { + let (sink, state) = MockSink::new(None); + state.lock().expect("mock sink poisoned").pending_flushes = 1; + let totals = queued_totals(sink, &state, &[EVENT_FRAME, EVENT_FRAME]).await; + assert!(state.lock().expect("mock sink poisoned").flush_count >= 2); + assert_eq!(totals.events(), 2); + assert!(totals.bytes() >= (EVENT_FRAME.len() * 2) as u64); + } + + /// Feed `frame` through the production frame dispatcher and return the + /// read access lines it produced once every spawned handler finished. + async fn read_lines_for( + frame: &str, + auth: AuthState, + state: Arc, + ) -> Vec { + let (guard, out) = crate::access::tests::capture_scoped(); + let (conn, _rx) = test_conn_with_auth(auth); + handle_text_message(frame.to_owned(), conn, state).await; + let reads = |out: &crate::access::tests::Captured| -> Vec { + out.lines() + .into_iter() + .filter(|l| ["req", "count", "sync"].contains(&l["event"].as_str().unwrap_or(""))) + .collect() + }; + // A dispatched handler runs as a spawned task on this thread. + for _ in 0..1_000 { + if !reads(&out).is_empty() { + break; + } + tokio::task::yield_now().await; + } + // Let any duplicate line surface before counting. + for _ in 0..10 { + tokio::task::yield_now().await; + } + drop(guard); + reads(&out) + } + + /// A NIP-AR sync REQ for one channel. + const SYNC_FRAME: &str = + r##"["REQ","y",{"artifact":"current","#h":["4f4b2a3e-6c1d-4f0e-9a51-2d7c8e9b0a11"]}]"##; + + fn assert_one_denial(lines: &[serde_json::Value], event: &str, reason: &str) { + assert_eq!(lines.len(), 1, "one access line per read: {lines:?}"); + assert_eq!(lines[0]["event"], event); + assert_eq!(lines[0]["outcome"], "denied"); + assert_eq!(lines[0]["reason"], reason); + } + + #[tokio::test] + async fn read_refused_by_unavailable_admission_logs_one_denial() { + // The test state has no Redis, so shared admission fails closed. + let state = crate::state::tests::test_state().await; + for (frame, event) in [ + (r#"["REQ","s",{"kinds":[9]}]"#, "req"), + (r#"["COUNT","c",{"kinds":[9]}]"#, "count"), + (SYNC_FRAME, "sync"), + ] { + let lines = read_lines_for(frame, authenticated_state(), Arc::clone(&state)).await; + assert_one_denial(&lines, event, "admission_unavailable"); + } + } + + #[tokio::test] + async fn read_refused_by_a_full_handler_semaphore_logs_one_denial() { + let mut state = (*crate::state::tests::test_state().await).clone(); + state.handler_semaphore = Arc::new(tokio::sync::Semaphore::new(0)); + let state = Arc::new(state); + for (frame, event) in [ + (r#"["REQ","s",{"kinds":[9]}]"#, "req"), + (r#"["COUNT","c",{"kinds":[9]}]"#, "count"), + (SYNC_FRAME, "sync"), + ] { + let lines = read_lines_for(frame, AuthState::Failed, Arc::clone(&state)).await; + assert_one_denial(&lines, event, "too_many_concurrent_requests"); + } + } + + #[tokio::test] + async fn read_before_login_logs_one_denial_from_the_handler() { + let state = crate::state::tests::test_state().await; + for (frame, event) in [ + (r#"["REQ","s",{"kinds":[9]}]"#, "req"), + (r#"["COUNT","c",{"kinds":[9]}]"#, "count"), + (SYNC_FRAME, "sync"), + ] { + let lines = read_lines_for(frame, AuthState::Failed, Arc::clone(&state)).await; + assert_one_denial(&lines, event, "auth_required"); + } + } + + /// Root AUTH cut off mid-check, through the real connection lifecycle. + mod postgres_tests { + use super::*; + + /// Each decided AUTH frame, sent through the production dispatcher, + /// writes its decision's line exactly once, never also an `aborted`: + /// a success one INFO, a failure one WARN. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn decided_auth_frames_log_exactly_one_line_each() { + let mut state = (*crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres")) + .clone(); + Arc::make_mut(&mut state.config).require_relay_membership = false; + let state = Arc::new(state); + let keys = Keys::generate(); + let other = Keys::generate(); + for (good, outcome) in [(true, "success"), (false, "failed")] { + let (conn, _rx) = test_conn_with_auth(pending_state()); + let relay_url: RelayUrl = crate::api::bridge::nip42_expected_relay_url( + &state.config.relay_url, + &conn.tenant, + ) + .parse() + .expect("relay url"); + let event = EventBuilder::auth("test-challenge", relay_url.clone()) + .sign_with_keys(&keys) + .expect("sign auth"); + let mut frame = serde_json::json!(["AUTH", event]); + if !good { + // A well-formed signature over a different event. + let foreign = EventBuilder::auth("other", relay_url) + .sign_with_keys(&other) + .expect("sign foreign"); + frame[1]["sig"] = serde_json::json!(foreign.sig.to_string()); + } + let (guard, out) = crate::access::tests::capture_scoped(); + handle_text_message(frame.to_string(), Arc::clone(&conn), Arc::clone(&state)).await; + drop(guard); + let lines: Vec<_> = out + .lines() + .into_iter() + .filter(|l| l["event"] == "auth") + .collect(); + let outcomes: Vec<_> = lines.iter().map(|l| l["outcome"].clone()).collect(); + assert_eq!(outcomes, [outcome], "{lines:?}"); + let level = if good { "INFO" } else { "WARN" }; + assert_eq!(lines[0]["level"], level, "{lines:?}"); + assert_eq!(lines[0]["peer_addr"], conn.remote_addr.to_string()); + } + } + + /// The TCP peer of every [`ws_login_lines`] connection. + const PEER: &str = "127.0.0.1:9999"; + + /// A connection that logs in, reads, and closes writes its success + /// `auth` line when the login commits, its REQ line, and one close + /// line still carrying the login, and no `connect` line. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn logged_in_connection_writes_its_login_read_and_one_close_line() { + let (keys, lines) = ws_login_lines(true, None).await; + let events: Vec<_> = lines.iter().map(|l| l["event"].clone()).collect(); + assert_eq!(events, ["auth", "req", "close"], "{lines:?}"); + let auth = &lines[0]; + assert_eq!(auth["level"], "INFO", "{auth}"); + assert_eq!(auth["outcome"], "success", "{auth}"); + assert_eq!(auth["method"], "nip42", "{auth}"); + assert_eq!(auth["pubkey"], keys.public_key().to_hex(), "{auth}"); + assert_eq!(auth["pubkey_verified"], true, "{auth}"); + assert_eq!(auth["peer_addr"], PEER, "{auth}"); + assert_eq!(auth["conn_id"], lines[2]["conn_id"], "{lines:?}"); + assert_eq!(auth["community"], lines[2]["community"], "{lines:?}"); + assert!(auth.get("reason").is_none(), "{auth}"); + let close = &lines[2]; + assert_eq!(close["pubkey"], keys.public_key().to_hex(), "{close}"); + assert_eq!(close["method"], "nip42", "{close}"); + assert_eq!(close["pubkey_verified"], true, "{close}"); + assert_eq!(close["peer_addr"], PEER, "{close}"); + assert_eq!(lines[1]["outcome"], "served", "{lines:?}"); + assert_eq!(close["close_reason"], "client_closed", "{close}"); + } + + /// A refused login writes one WARN `auth` line, no success line, and a close line with no identity. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn refused_login_writes_one_warn_auth_line_and_no_success() { + let (keys, lines) = ws_login_lines(false, None).await; + let events: Vec<_> = lines.iter().map(|l| l["event"].clone()).collect(); + assert_eq!(events, ["auth", "close"], "{lines:?}"); + let auth = &lines[0]; + assert_eq!(auth["level"], "WARN", "{auth}"); + assert_eq!(auth["outcome"], "failed", "{auth}"); + assert_eq!(auth["pubkey"], keys.public_key().to_hex(), "{auth}"); + assert_eq!(auth["pubkey_verified"], false, "{auth}"); + assert_eq!(auth["peer_addr"], PEER, "{auth}"); + assert!(lines[1].get("pubkey").is_none(), "{lines:?}"); + } + + /// The `client_ip` the login's `auth` line and its close line log for + /// `setting` and the header value sent, with `peer_addr` unchanged. + async fn ws_client_ip( + setting: Option<(&'static str, &'static [&'static str])>, + ) -> Option { + let (_, lines) = ws_login_lines(true, setting).await; + let (auth, close) = (&lines[0], &lines[2]); + assert_eq!( + (&auth["event"], &close["event"]), + (&"auth".into(), &"close".into()) + ); + assert_eq!(auth["peer_addr"], PEER, "{auth}"); + assert_eq!(close["peer_addr"], PEER, "{close}"); + assert_eq!(auth.get("client_ip"), close.get("client_ip"), "{lines:?}"); + auth.get("client_ip") + .map(|ip| ip.as_str().unwrap().to_owned()) + } + + /// The configured header's IP rides the login and close lines; an + /// unset setting, a missing header or a non-IP value logs none, and + /// a list or repeated fields log the rightmost entry, with no + /// fallback past an invalid one. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn login_and_close_lines_log_the_configured_client_ip() { + const H: &str = "X-Real-IP"; + assert_eq!( + ws_client_ip(Some((H, &["203.0.113.7"]))).await.as_deref(), + Some("203.0.113.7") + ); + assert_eq!(ws_client_ip(None).await, None); + assert_eq!(ws_client_ip(Some((H, &[]))).await, None); + assert_eq!(ws_client_ip(Some((H, &["not-an-ip"]))).await, None); + assert_eq!( + ws_client_ip(Some((H, &["198.51.100.1, 10.0.0.2"]))) + .await + .as_deref(), + Some("10.0.0.2") + ); + assert_eq!( + ws_client_ip(Some((H, &["198.51.100.1", "10.0.0.2"]))) + .await + .as_deref(), + Some("10.0.0.2") + ); + assert_eq!( + ws_client_ip(Some((H, &["198.51.100.1", "not-an-ip"]))).await, + None + ); + } + + /// Drive a real upgraded root connection through one AUTH (signed for + /// the wrong challenge unless `good`), a REQ if it logged in, and a + /// client close; return the signer and every captured access line. + /// `client_ip` is the relay's header setting and the value the + /// upgrade request sends in it, if any. + async fn ws_login_lines( + good: bool, + client_ip: Option<(&'static str, &'static [&'static str])>, + ) -> (Keys, Vec) { + use futures_util::{SinkExt as _, StreamExt as _}; + use tokio_tungstenite::tungstenite::client::IntoClientRequest as _; + + let mut state = (*crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres")) + .clone(); + let config = Arc::make_mut(&mut state.config); + config.require_relay_membership = false; + config.client_ip_header = client_ip.map(|(name, _)| name.parse().unwrap()); + let state = Arc::new(state); + let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::new_v4()); + let tenant = TenantContext::resolved(community, "test.local".to_string()); + let relay_url = + crate::api::bridge::nip42_expected_relay_url(&state.config.relay_url, &tenant); + let keys = Keys::generate(); + + let (guard, out) = crate::access::tests::capture_scoped(); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("local addr"); + let server = tokio::spawn(async move { + let upgrade = move |headers: axum::http::HeaderMap, ws: WebSocketUpgrade| { + let (state, tenant) = (Arc::clone(&state), tenant.clone()); + // As the root route does before its upgrade. + let client_ip = + crate::access::client_ip(&headers, state.config.client_ip_header.as_ref()); + async move { + ws.on_upgrade(move |socket| async move { + let cancel = CancellationToken::new(); + let close = crate::access::CloseLine::open( + Uuid::new_v4(), + tenant.community(), + PEER.parse().unwrap(), + client_ip, + ); + handle_active_connection( + socket, + state, + PEER.parse().unwrap(), + tenant, + close, + crate::state::CommunityConnectionControl::new(cancel) + .with_client_ip(client_ip), + None, + chrono::Utc::now(), + None, + ) + .await + }) + } + }; + let app = Router::new().route("/", get(upgrade)); + axum::serve(listener, app).await.expect("test server"); + }); + + let mut request = format!("ws://{addr}/").into_client_request().unwrap(); + if let Some((name, values)) = client_ip { + for value in values { + request.headers_mut().append(name, value.parse().unwrap()); + } + } + let (mut client, _) = connect_async(request).await.expect("connect"); + async fn wait_for(client: &mut S, tag: &str) -> serde_json::Value + where + S: futures_util::Stream< + Item = Result, + > + Unpin, + { + loop { + let text = match client.next().await { + Some(Ok(Message::Text(text))) => text, + Some(Ok(_)) => continue, + other => panic!("socket ended before {tag}: {other:?}"), + }; + let frame: serde_json::Value = serde_json::from_str(&text).unwrap(); + if frame[0] == tag { + return frame; + } + } + } + let mut challenge = wait_for(&mut client, "AUTH").await[1] + .as_str() + .unwrap() + .to_owned(); + if !good { + challenge.push('x'); + } + let event = EventBuilder::new(Kind::Authentication, "") + .tag(nostr::Tag::parse(["relay", &relay_url]).unwrap()) + .tag(nostr::Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(&keys) + .expect("sign auth"); + client + .send(Message::Text( + serde_json::json!(["AUTH", event]).to_string().into(), + )) + .await + .expect("send AUTH"); + let ok = wait_for(&mut client, "OK").await; + assert_eq!(ok[2], good, "login result: {ok}"); + if good { + client + .send(Message::Text( + r#"["REQ","s",{"kinds":[9],"limit":1}]"#.into(), + )) + .await + .expect("send REQ"); + let _ = wait_for(&mut client, "EOSE").await; + } + let _ = client.close(None).await; + + let closed = tokio::time::timeout(Duration::from_secs(10), async { + loop { + if out.lines().iter().any(|l| l["event"] == "close") { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + drop(guard); + server.abort(); + closed.expect("connection must log its close"); + (keys, out.lines()) + } + + /// Drive a real upgraded root connection (watcher, timeout and expiry + /// tasks included) through an AUTH that stalls after its policy reads, + /// end the connection with `end` while it waits, and return the captured + /// access lines once the connection has logged its close. + async fn stalled_auth_lines( + deadline: Option>, + end: impl FnOnce(&CancellationToken), + ) -> Vec { + use futures_util::{SinkExt as _, StreamExt as _}; + + let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres"); + let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::new_v4()); + let tenant = TenantContext::resolved(community, "test.local".to_string()); + let relay_url = + crate::api::bridge::nip42_expected_relay_url(&state.config.relay_url, &tenant); + let keys = Keys::generate(); + let assertion = deadline + .map(|d| buzz_auth::VerifiedAssertion::for_test(Some(keys.public_key()), vec![d])); + let cancel = CancellationToken::new(); + let control = crate::state::CommunityConnectionControl::new(cancel.clone()); + + let (guard, out) = crate::access::tests::capture_scoped(); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("local addr"); + let server = tokio::spawn(async move { + let upgrade = move |ws: WebSocketUpgrade| { + let (state, tenant) = (Arc::clone(&state), tenant.clone()); + let (control, assertion) = (control.clone(), assertion.clone()); + async move { + ws.on_upgrade(move |socket| async move { + let close = crate::access::CloseLine::open( + Uuid::new_v4(), + tenant.community(), + "127.0.0.1:9999".parse().unwrap(), + None, + ); + handle_active_connection( + socket, + state, + "127.0.0.1:9999".parse().unwrap(), + tenant, + close, + control, + assertion, + chrono::Utc::now(), + None, + ) + .await + }) + } + }; + let app = Router::new().route("/", get(upgrade)); + axum::serve(listener, app).await.expect("test server"); + }); + + let (mut client, _) = connect_async(format!("ws://{addr}/")) + .await + .expect("connect"); + let challenge = loop { + let Some(Ok(Message::Text(text))) = client.next().await else { + panic!("socket ended before the AUTH challenge"); + }; + let frame: serde_json::Value = serde_json::from_str(&text).unwrap(); + if frame[0] == "AUTH" { + break frame[1].as_str().unwrap().to_owned(); + } + }; + let event = EventBuilder::new(Kind::Authentication, "") + .tag(nostr::Tag::parse(["relay", &relay_url]).unwrap()) + .tag(nostr::Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(&keys) + .expect("sign auth"); + let (arrived, _release) = crate::nip_fi_test_hooks::auth_commit_hook::arm(community); + client + .send(Message::Text( + serde_json::json!(["AUTH", event]).to_string().into(), + )) + .await + .expect("send AUTH"); + tokio::time::timeout(Duration::from_secs(5), arrived) + .await + .expect("AUTH must stall at the commit hook") + .expect("hook dropped"); + end(&cancel); + + let closed = tokio::time::timeout(Duration::from_secs(10), async { + loop { + if out.lines().iter().any(|l| l["event"] == "close") { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + drop(guard); + server.abort(); + closed.expect("connection must log its close"); + out.lines() + .into_iter() + .filter(|l| l["event"] == "auth") + .collect() + } + + fn assert_one_aborted(lines: &[serde_json::Value], reason: &str) { + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "aborted"); + assert_eq!(lines[0]["reason"], reason); + assert_eq!(lines[0]["pubkey_verified"], false); + assert_eq!(lines[0]["peer_addr"], "127.0.0.1:9999"); + } + + /// The cancellation watcher ends the pending attempt as the connection + /// closes; the AUTH frame still logs exactly one `aborted` line. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn auth_cut_off_by_a_closing_connection_logs_one_aborted_line() { + let lines = stalled_auth_lines(None, CancellationToken::cancel).await; + assert_one_aborted(&lines, "connection_closed"); + } + + /// The enterprise session lease expires while AUTH waits. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn auth_cut_off_by_session_expiry_logs_one_aborted_line() { + let deadline = chrono::Utc::now() + chrono::Duration::milliseconds(1500); + let lines = stalled_auth_lines(Some(deadline), |_| {}).await; + assert_one_aborted(&lines, "session_expired"); + } + + /// A disconnect racing a login's final step. + #[derive(Clone, Copy)] + enum LoginRace { + /// Session expiry's terminal transition lands at the decision. + ExpiryFirst, + /// A ban lands at the decision. + BanFirst, + /// A ban, then a NIP-FI denial, land at the decision before the + /// writer drains. + BanThenDenial, + /// A ban lands once the client has its `OK true`. + BanAfterLogin, + } + + /// Drive a real root connection through an AUTH raced by `race`; + /// return every frame the client received and every access line. + async fn raced_login(race: LoginRace) -> (Vec, Vec) { + use futures_util::{SinkExt as _, StreamExt as _}; + + let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres"); + let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::new_v4()); + let tenant = TenantContext::resolved(community, "test.local".to_string()); + let relay_url = + crate::api::bridge::nip42_expected_relay_url(&state.config.relay_url, &tenant); + let keys = Keys::generate(); + let pubkey = keys.public_key().to_bytes().to_vec(); + let ban = { + let (state, pubkey) = (Arc::clone(&state), pubkey.clone()); + move || { + let zero = "0".repeat(64); + let closed = state.disconnect_pubkey_local( + community, + &pubkey, + &zero, + "blocked: banned", + false, + ); + assert_eq!(closed, 1, "the ban reaches the login's socket"); + } + }; + let deny = |conn: &crate::connection::ConnectionState| { + conn.community_control.deny_authorization( + &conn.terminal_ctrl_tx, + crate::nip_fi_session::NipFiWsRoute::Root, + ); + conn.cancel.cancel(); + }; + let assertion = + matches!(race, LoginRace::ExpiryFirst | LoginRace::BanThenDenial).then(|| { + let deadline = chrono::Utc::now() + chrono::Duration::hours(1); + buzz_auth::VerifiedAssertion::for_test(Some(keys.public_key()), vec![deadline]) + }); + match race { + LoginRace::ExpiryFirst => { + crate::nip_fi_test_hooks::auth_decision_hook::arm(community, deny) + } + LoginRace::BanThenDenial => { + let ban = ban.clone(); + crate::nip_fi_test_hooks::auth_decision_hook::arm(community, move |conn| { + ban(); + deny(conn); + }); + } + LoginRace::BanFirst => { + let ban = ban.clone(); + crate::nip_fi_test_hooks::auth_decision_hook::arm(community, move |_| ban()); + } + LoginRace::BanAfterLogin => {} + } + + let (guard, out) = crate::access::tests::capture_scoped(); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("local addr"); + let server = tokio::spawn({ + let state = Arc::clone(&state); + async move { + let upgrade = move |ws: WebSocketUpgrade| { + let (state, tenant) = (Arc::clone(&state), tenant.clone()); + let assertion = assertion.clone(); + async move { + ws.on_upgrade(move |socket| async move { + let close = crate::access::CloseLine::open( + Uuid::new_v4(), + tenant.community(), + PEER.parse().unwrap(), + None, + ); + handle_active_connection( + socket, + state, + PEER.parse().unwrap(), + tenant, + close, + crate::state::CommunityConnectionControl::new( + CancellationToken::new(), + ), + assertion, + chrono::Utc::now(), + None, + ) + .await + }) + } + }; + let app = Router::new().route("/", get(upgrade)); + axum::serve(listener, app).await.expect("test server"); + } + }); + + let (mut client, _) = connect_async(format!("ws://{addr}/")) + .await + .expect("connect"); + let challenge = loop { + let Some(Ok(Message::Text(text))) = client.next().await else { + panic!("socket ended before the AUTH challenge"); + }; + let frame: serde_json::Value = serde_json::from_str(&text).unwrap(); + if frame[0] == "AUTH" { + break frame[1].as_str().unwrap().to_owned(); + } + }; + let event = EventBuilder::new(Kind::Authentication, "") + .tag(nostr::Tag::parse(["relay", &relay_url]).unwrap()) + .tag(nostr::Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(&keys) + .expect("sign auth"); + client + .send(Message::Text( + serde_json::json!(["AUTH", event]).to_string().into(), + )) + .await + .expect("send AUTH"); + let frames = tokio::time::timeout(Duration::from_secs(10), async { + let mut frames = Vec::new(); + while let Some(Ok(frame)) = client.next().await { + let ok_true = matches!(&frame, Message::Text(t) if t.contains("true")); + let closing = matches!(frame, Message::Close(_)); + frames.push(frame); + if ok_true && matches!(race, LoginRace::BanAfterLogin) { + ban(); + } + if closing { + break; + } + } + frames + }) + .await + .expect("the socket must close"); + + let closed = tokio::time::timeout(Duration::from_secs(10), async { + while !out.lines().iter().any(|l| l["event"] == "close") { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + drop(guard); + server.abort(); + closed.expect("connection must log its close"); + (frames, out.lines()) + } + + fn texts(frames: &[Message]) -> Vec { + frames + .iter() + .filter_map(|f| match f { + Message::Text(t) => Some(serde_json::from_str(t).unwrap()), + _ => None, + }) + .collect() + } + + /// Lines other than the connection's own `close`, by `event`/`outcome`. + fn auth_outcomes(lines: &[serde_json::Value]) -> Vec { + lines + .iter() + .filter(|l| l["event"] == "auth") + .map(|l| l["outcome"].clone()) + .collect() + } + + /// Expiry that chose its denial before the login decided wins: the + /// client gets only the denial and its 1008, and no success is logged. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn expiry_at_the_login_decision_wins_and_logs_no_success() { + let (frames, lines) = raced_login(LoginRace::ExpiryFirst).await; + let texts = texts(&frames); + assert_eq!(texts, [nip_fi_denial_notice()], "{texts:?}"); + assert!( + matches!(frames.last(), Some(Message::Close(Some(c))) + if u16::from(c.code) == 1008 && c.reason == "authorization denied"), + "{frames:?}" + ); + assert!( + !auth_outcomes(&lines).contains(&"success".into()), + "{lines:?}" + ); + } + + /// A ban that claimed the socket before the login decided wins: the + /// client gets only the ban's `OK false` and a bare close. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn ban_at_the_login_decision_wins_and_logs_no_success() { + let (frames, lines) = raced_login(LoginRace::BanFirst).await; + let oks: Vec<_> = texts(&frames) + .into_iter() + .filter(|f| f[0] == "OK") + .collect(); + assert_eq!(oks.len(), 1, "{oks:?}"); + assert_eq!(oks[0][2], false, "{oks:?}"); + assert_eq!(oks[0][3], "blocked: banned", "{oks:?}"); + assert!( + matches!(frames.last(), Some(Message::Close(None))), + "{frames:?}" + ); + assert!( + !auth_outcomes(&lines).contains(&"success".into()), + "{lines:?}" + ); + } + + /// The root NIP-FI denial frame, as the client parses it. + fn nip_fi_denial_notice() -> serde_json::Value { + serde_json::json!(["NOTICE", "restricted: authorization denied"]) + } + + /// A NIP-FI denial after a ban still sends what it did before the + /// ban claimed the slot: its NOTICE, the ban's `OK false`, and 1008. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn denial_after_a_ban_still_sends_the_denial_and_1008() { + let (frames, lines) = raced_login(LoginRace::BanThenDenial).await; + let texts = texts(&frames); + assert_eq!( + texts, + [ + nip_fi_denial_notice(), + serde_json::json!(["OK", "0".repeat(64), false, "blocked: banned"]), + ], + "{texts:?}" + ); + assert!( + matches!(frames.last(), Some(Message::Close(Some(c))) + if u16::from(c.code) == 1008 && c.reason == "authorization denied"), + "{frames:?}" + ); + assert!( + !auth_outcomes(&lines).contains(&"success".into()), + "{lines:?}" + ); + } + + /// A ban landing after the login won closes the admitted socket: one + /// success line, then the close line. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn ban_after_the_login_won_logs_success_then_close() { + let (frames, lines) = raced_login(LoginRace::BanAfterLogin).await; + let oks: Vec<_> = texts(&frames) + .into_iter() + .filter(|f| f[0] == "OK") + .collect(); + assert_eq!(oks.len(), 2, "{oks:?}"); + assert_eq!((&oks[0][2], &oks[1][2]), (&true.into(), &false.into())); + assert!( + matches!(frames.last(), Some(Message::Close(None))), + "{frames:?}" + ); + let events: Vec<_> = lines.iter().map(|l| l["event"].clone()).collect(); + assert_eq!(events, ["auth", "close"], "{lines:?}"); + assert_eq!(lines[0]["outcome"], "success", "{lines:?}"); + assert_eq!(lines[1]["close_reason"], "removed", "{lines:?}"); + } + } + fn ordinary_disconnect_reason() -> watch::Receiver> { let (_tx, rx) = watch::channel(None); rx @@ -2891,6 +4821,7 @@ pub(crate) mod tests { let (terminal_ctrl_tx, _terminal_ctrl_rx) = mpsc::channel::(1); let conn = Arc::new(ConnectionState { + refusal_budget: Default::default(), conn_id: uuid::Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()), @@ -3162,12 +5093,18 @@ pub(crate) mod tests { pre_tx.clone(), crate::nip_fi_session::NipFiWsRoute::Root, ); + let close = crate::access::CloseLine::open( + conn_id, + tenant_i.community(), + "127.0.0.1:9999".parse().unwrap(), + None, + ); handle_active_connection( socket, state_i, "127.0.0.1:9999".parse().unwrap(), tenant_i, - conn_id, + close, control, Some(assertion_i), conn_time, @@ -3292,9 +5229,11 @@ pub(crate) mod tests { socket, state_i, "127.0.0.1:9999".parse().unwrap(), + None, tenant_i, Some(assertion_i), None, + None, conn_time, ) .await @@ -3394,6 +5333,11 @@ pub(crate) mod terminal_close_delivery_tests { /// reader starts, so a frame handler that needs it blocks until the /// test drops it. subscriptions_hold: Option, + /// Attached to the connection's control and owned by the handler + /// task, as the outer handler would own it, until the handler ends. + shadow_line: Option>, + /// Notified once the handler has ended and released `shadow_line`. + ended: Option>, } /// Like `serve`, with the test hooks in `seams`. @@ -3404,10 +5348,13 @@ pub(crate) mod terminal_close_delivery_tests { cleanup_pause, effect_hold, subscriptions_hold, + shadow_line, + ended, }: Seams, ) -> (std::net::SocketAddr, RelayUrl, Arc, Uuid) { let effect_hold = Arc::new(std::sync::Mutex::new(effect_hold)); let subscriptions_hold = Arc::new(std::sync::Mutex::new(subscriptions_hold)); + let shadow_line = Arc::new(std::sync::Mutex::new(shadow_line)); let state = crate::state::tests::test_state().await; let served_state = Arc::clone(&state); let conn_id = Uuid::new_v4(); @@ -3422,18 +5369,21 @@ pub(crate) mod terminal_close_delivery_tests { let app = Router::new().route( "/", get(move |ws: WebSocketUpgrade| { - let (state, tenant, assertion, cleanup_pause) = ( + let (state, tenant, assertion, cleanup_pause, ended) = ( Arc::clone(&state), tenant.clone(), assertion.clone(), cleanup_pause.clone(), + ended.clone(), ); + let shadow_line = shadow_line.lock().expect("shadow line").take(); let effect_hold = effect_hold.lock().expect("effect hold").take(); let subscriptions_hold = subscriptions_hold.lock().expect("subs hold").take(); async move { ws.on_upgrade(move |socket| async move { let cancel = CancellationToken::new(); let control = CommunityConnectionControl::new(cancel.clone()); + control.attach_nip_fi_line(shadow_line.as_ref()); let offset = if effect_hold.is_some() { EFFECT_HOLD_EXPIRY } else { @@ -3457,12 +5407,18 @@ pub(crate) mod terminal_close_delivery_tests { let permit = gate.acquire_effect().await.expect("effect permit"); let _ = hold.send(permit); } + let close = crate::access::CloseLine::open( + conn_id, + tenant.community(), + "127.0.0.1:1234".parse().expect("client address"), + None, + ); let handler = handle_active_connection( socket, state, "127.0.0.1:1234".parse().expect("client address"), tenant, - conn_id, + close, control, Some(assertion), chrono::Utc::now(), @@ -3478,6 +5434,10 @@ pub(crate) mod terminal_close_delivery_tests { } None => handler.await, } + drop(shadow_line); + if let Some(ended) = ended { + ended.notify_one(); + } }) } }), @@ -3718,15 +5678,24 @@ pub(crate) mod terminal_close_delivery_tests { /// Final cleanup can block on Redis with no deadline (the pool has no /// wait timeout). The peer wait runs alongside it, so a stalled cleanup - /// still lets the socket end once the bounded wait expires. + /// still lets the socket end once the bounded wait expires, and an + /// unproven shadow line is written as `absent` before that cleanup. + /// Mutation: dropping `finish_nip_fi_line` leaves no line while the + /// cleanup is held. #[tokio::test] async fn stalled_cleanup_does_not_hold_socket_open() { + let log = crate::nip_fi_shadow::tests::WouldDenyLog::capture(); let pause = Arc::new(crate::handlers::close::test_seam::Pause::default()); + let line = crate::nip_fi_shadow::tests::upgrade_line("ws"); + let destroyed = Arc::downgrade(&line); + let ended = Arc::new(tokio::sync::Notify::new()); let (address, _, _, _) = serve_with_seams( expired_assertion(), true, Seams { cleanup_pause: Some(Arc::clone(&pause)), + shadow_line: Some(line), + ended: Some(Arc::clone(&ended)), ..Seams::default() }, ) @@ -3737,8 +5706,113 @@ pub(crate) mod terminal_close_delivery_tests { tokio::time::timeout(EOF_WATCHDOG, pause.reached.notified()) .await .expect("cleanup never reached the pause point"); + let lines = log.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!(lines[0].contains("pubkey=\"absent\""), "{lines:?}"); let elapsed = time_to_eof(&mut socket, started).await; assert!(elapsed >= WS_TERMINAL_FLUSH_TIMEOUT); + + pause.resume.notify_one(); + tokio::time::timeout(EOF_WATCHDOG, ended.notified()) + .await + .expect("the handler finishes once cleanup resumes"); + assert!( + destroyed.upgrade().is_none(), + "the line outlived its handler" + ); + assert_eq!(log.lines().len(), 1, "{:?}", log.lines()); + } + + mod postgres_tests { + use super::*; + + /// Through the real outer `handle_connection`, an upgrade would-deny's + /// line is written at the first verified AUTH, with that key, while the + /// socket stays open, and is not written again at close. Mutation: + /// deleting the outer `attach_nip_fi_line`, or AUTH's + /// `prove_nip_fi_line`, leaves no line while the socket is open. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn upgrade_would_deny_line_is_written_at_auth_while_open() { + let log = crate::nip_fi_shadow::tests::WouldDenyLog::capture(); + // sqlx's default acquire timeout: a first connect to a busy CI + // database can outlast the unreachable-target helper's 100 ms. + let state = crate::state::tests::test_state_with_database_url_and_pool_options( + &crate::test_support::database_url(), + sqlx::postgres::PgPoolOptions::new(), + ) + .await; + let community = Uuid::new_v4(); + let host = format!("shadow-line-{}.example", community.simple()); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community) + .bind(&host) + .execute(state.db.pool()) + .await + .expect("seed community"); + let tenant = + TenantContext::resolved(buzz_core::tenant::CommunityId::from_uuid(community), host); + let relay_url: RelayUrl = + crate::api::bridge::nip42_expected_relay_url(&state.config.relay_url, &tenant) + .parse() + .expect("expected NIP-42 relay URL"); + let line = crate::nip_fi_shadow::tests::upgrade_line("ws"); + let line = Arc::new(Mutex::new(Arc::into_inner(line))); + let ended = Arc::new(tokio::sync::Notify::new()); + let notify = Arc::clone(&ended); + let app = Router::new().route( + "/", + get(move |ws: WebSocketUpgrade| async move { + let line = line.lock().await.take(); + ws.on_upgrade(move |socket| async move { + let addr = "127.0.0.1:1234".parse().expect("client address"); + let now = chrono::Utc::now(); + handle_connection(socket, state, addr, None, tenant, None, None, line, now) + .await; + notify.notify_one(); + }) + }), + ); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("listener address"); + tokio::spawn(async move { axum::serve(listener, app).await.expect("serve") }); + let mut client = connect(address).await; + + let Some(Ok(Message::Text(challenge))) = client.next().await else { + panic!("expected AUTH challenge") + }; + let challenge: serde_json::Value = + serde_json::from_str(&challenge).expect("challenge json"); + let key = Keys::generate(); + let auth = EventBuilder::auth(challenge[1].as_str().expect("challenge"), relay_url) + .sign_with_keys(&key) + .expect("sign AUTH"); + client + .send(Message::Text( + serde_json::json!(["AUTH", auth]).to_string().into(), + )) + .await + .expect("send AUTH"); + let ok = loop { + match client.next().await { + Some(Ok(Message::Text(ok))) => break ok, + Some(Ok(Message::Ping(_))) => {} + other => panic!("expected AUTH OK, got {other:?}"), + } + }; + assert!(ok.contains("true"), "AUTH must succeed: {ok}"); + + let lines = log.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + let proven = format!("pubkey=\"{}\"", key.public_key().to_hex()); + assert!(lines[0].contains(&proven), "{lines:?}"); + + client.close(None).await.expect("send Close"); + tokio::time::timeout(EOF_WATCHDOG, ended.notified()) + .await + .expect("the connection ends after Close"); + assert_eq!(log.lines().len(), 1, "{:?}", log.lines()); + } } /// An established session's expiry task stalls at its quiescence barrier @@ -3794,6 +5868,7 @@ pub(crate) mod terminal_close_delivery_tests { cleanup_pause: Some(Arc::clone(&pause)), effect_hold: Some(effect_tx), subscriptions_hold: Some(subs_tx), + ..Seams::default() }, ) .await; @@ -3813,7 +5888,13 @@ pub(crate) mod terminal_close_delivery_tests { }); drop(effect_rx.await.expect("effect permit")); let mut subscriptions = subs_rx.await.expect("subscription lock"); - subscriptions.insert("s".to_owned(), 1); + subscriptions.insert( + "s".to_owned(), + handlers::close::SubOwner { + owner: 1, + claimed: true, + }, + ); let mut socket = connected.await.expect("raw client"); let elapsed = time_to_eof(&mut socket, std::time::Instant::now()).await; @@ -3905,9 +5986,11 @@ pub(crate) mod terminal_close_delivery_tests { socket, state, "127.0.0.1:1234".parse().expect("client address"), + None, tenant, assertion, None, + None, chrono::Utc::now(), ) }) @@ -4010,4 +6093,92 @@ pub(crate) mod terminal_close_delivery_tests { "the active handler must not have started" ); } + + /// Socket admission takes the community's lifecycle from the shared + /// cache: with the database unreachable, a cached "active" still admits + /// the socket, which then gets its AUTH challenge. + /// Mutation: read `is_community_active` uncached in `handle_connection` + /// → RED. + #[tokio::test] + async fn bootstrap_admits_from_the_cached_community_answer() { + let state = crate::state::tests::test_state_with_unreachable_database_url( + "postgres://127.0.0.1:1/none", + ) + .await; + state + .community_active + .seed(buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), true); + let address = serve_outer(state, None).await; + + let mut client = connect(address).await; + let frame = tokio::time::timeout(Duration::from_secs(5), client.next()) + .await + .expect("an admitted socket gets its challenge") + .expect("frame") + .expect("message"); + let Message::Text(text) = frame else { + panic!("expected the AUTH challenge, got {frame:?}"); + }; + let challenge: serde_json::Value = serde_json::from_str(&text).expect("json"); + assert_eq!(challenge[0], "AUTH", "got {text}"); + } + + // An upgrade would-deny's line is held by the real `handle_connection` + // and written once the socket ends; one that never proves a key by AUTH + // logs `absent`. The state's database is unreachable, so bootstrap + // refuses the socket before any AUTH. + #[test] + fn upgrade_would_deny_line_without_auth_logs_absent_at_close() { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let ((), lines) = crate::nip_fi_shadow::tests::would_deny_lines(|| { + rt.block_on(async { + let state = crate::state::tests::test_state_with_unreachable_database_url( + "postgres://127.0.0.1:1/none", + ) + .await; + let line = crate::nip_fi_shadow::tests::upgrade_line("ws"); + let line = Arc::into_inner(line).expect("sole owner"); + let line = Arc::new(Mutex::new(Some(line))); + let ended = Arc::new(tokio::sync::Notify::new()); + let tenant = TenantContext::resolved( + buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), + "test.local".to_owned(), + ); + let notify = Arc::clone(&ended); + let app = Router::new().route( + "/", + get(move |ws: WebSocketUpgrade| async move { + let line = line.lock().await.take(); + ws.on_upgrade(move |socket| async move { + let addr = "127.0.0.1:1234".parse().expect("client address"); + let now = chrono::Utc::now(); + handle_connection( + socket, state, addr, None, tenant, None, None, line, now, + ) + .await; + notify.notify_one(); + }) + }), + ); + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("listener address"); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let client = connect(address).await; + tokio::time::timeout(Duration::from_secs(10), ended.notified()) + .await + .expect("the connection ends without AUTH"); + drop(client); + server.abort(); + }) + }); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!( + lines[0].contains("reason=\"missing_assertion\""), + "{lines:?}" + ); + assert!(lines[0].contains("pubkey=\"absent\""), "{lines:?}"); + } } diff --git a/crates/buzz-relay/src/feature_flags.rs b/crates/buzz-relay/src/feature_flags.rs new file mode 100644 index 00000000000..7f207f59194 --- /dev/null +++ b/crates/buzz-relay/src/feature_flags.rs @@ -0,0 +1,359 @@ +//! The relay's feature-flag provider, chosen once at startup. +//! +//! `BUZZ_FEATURE_FLAGS_PROVIDER` selects exactly one evaluator for the life of +//! the process (see `crates/buzz-feature-flags/README.md`): +//! +//! | Value | Evaluator | +//! |-------|-----------| +//! | unset, `static` | every flag returns its declared default | +//! | `environment` | `BUZZ_FEATURE_FLAG_*` values, read once at startup | +//! | `launchdarkly` | LaunchDarkly, keyed by `BUZZ_LAUNCHDARKLY_SDK_KEY`, optionally through the Relay Proxy at `BUZZ_LAUNCHDARKLY_RELAY_PROXY_URL` | +//! +//! The variable is deliberately outside the `BUZZ_FEATURE_FLAG_` namespace the +//! environment evaluator reads, so it can never be mistaken for a flag. +//! +//! Local configuration errors (an unknown provider, a missing SDK key, a +//! malformed proxy URL) fail startup. LaunchDarkly itself being unreachable +//! does not: the relay starts on declared defaults and the SDK keeps +//! connecting in the background, because no safety invariant may depend on +//! remote flag availability. After LaunchDarkly first delivers data, a lost +//! connection leaves its last-known values in force until it reconnects. + +use std::sync::Arc; +use std::time::Duration; + +use buzz_feature_flags::launchdarkly::{LaunchDarklyEvaluator, LaunchDarklyRuntimeConfig}; +use buzz_feature_flags::{EnvironmentEvaluator, FlagEvaluator, StaticEvaluator}; +use tracing::{info, warn}; + +/// Environment variable naming the provider. +pub const PROVIDER_ENV: &str = "BUZZ_FEATURE_FLAGS_PROVIDER"; +const SDK_KEY_ENV: &str = "BUZZ_LAUNCHDARKLY_SDK_KEY"; +const RELAY_PROXY_ENV: &str = "BUZZ_LAUNCHDARKLY_RELAY_PROXY_URL"; + +/// How long startup waits for LaunchDarkly's first flag data before serving +/// on declared defaults. +const LAUNCHDARKLY_START_WAIT: Duration = Duration::from_secs(3); + +/// How long shutdown waits for LaunchDarkly's final analytics flush. The flush +/// has no deadline of its own, and an unreachable events endpoint must not +/// spend the pod's termination grace. +const LAUNCHDARKLY_CLOSE_WAIT: Duration = Duration::from_secs(2); + +/// The provider selected by [`PROVIDER_ENV`]. +#[derive(Debug)] +enum Provider { + Static, + Environment, + LaunchDarkly(LaunchDarklyRuntimeConfig), +} + +/// Parse the provider from `get`, which reads one environment variable. +fn provider_from(get: impl Fn(&str) -> Option) -> anyhow::Result { + let value = get(PROVIDER_ENV).unwrap_or_default(); + match value.trim() { + "" | "static" => Ok(Provider::Static), + "environment" => Ok(Provider::Environment), + "launchdarkly" => { + let sdk_key = get(SDK_KEY_ENV) + .filter(|key| !key.trim().is_empty()) + .ok_or_else(|| { + anyhow::anyhow!("{PROVIDER_ENV}=launchdarkly requires {SDK_KEY_ENV}") + })?; + let mut config = LaunchDarklyRuntimeConfig::new(sdk_key); + if let Some(endpoint) = get(RELAY_PROXY_ENV).filter(|url| !url.trim().is_empty()) { + config = config.with_relay_proxy_endpoint(endpoint); + } + Ok(Provider::LaunchDarkly(config)) + } + other => anyhow::bail!( + "{PROVIDER_ENV}={other:?} is not a feature flag provider; \ + use static, environment, or launchdarkly" + ), + } +} + +/// The process's one flag evaluator, plus the concrete handle its provider +/// needs for diagnostics and shutdown. +pub struct FeatureFlags { + evaluator: Arc, + provider: &'static str, + environment: Option>, + launchdarkly: Option>, +} + +impl FeatureFlags { + /// Build the provider [`PROVIDER_ENV`] selects. Fails only on local + /// configuration errors; see the module docs. + pub async fn from_env() -> anyhow::Result { + let provider = provider_from(|name| std::env::var(name).ok())?; + let flags = Self::build(provider, LAUNCHDARKLY_START_WAIT).await?; + info!(provider = flags.provider, "feature flag provider selected"); + Ok(flags) + } + + async fn build(provider: Provider, start_wait: Duration) -> anyhow::Result { + Ok(match provider { + Provider::Static => Self::from_evaluator("static", Arc::new(StaticEvaluator)), + Provider::Environment => { + let owner = Arc::new(EnvironmentEvaluator::from_process_environment()); + Self { + evaluator: owner.clone(), + provider: "environment", + environment: Some(owner), + launchdarkly: None, + } + } + Provider::LaunchDarkly(config) => { + let owner = Arc::new( + LaunchDarklyEvaluator::from_runtime_config(config) + .map_err(|e| anyhow::anyhow!("LaunchDarkly configuration: {e}"))?, + ); + if let Err(error) = owner.start_with_default_executor_and_wait(start_wait).await { + warn!( + %error, + "LaunchDarkly has not delivered flags; serving declared defaults until it does" + ); + } + Self { + evaluator: owner.clone(), + provider: "launchdarkly", + environment: None, + launchdarkly: Some(owner), + } + } + }) + } + + /// Flags backed by `evaluator` alone (tests, embedding). + pub fn from_evaluator(provider: &'static str, evaluator: Arc) -> Self { + Self { + evaluator, + provider, + environment: None, + launchdarkly: None, + } + } + + /// The evaluator every consumer shares. + pub fn evaluator(&self) -> &dyn FlagEvaluator { + self.evaluator.as_ref() + } + + /// Report provider health after a round of evaluations: log malformed + /// environment values once each, and publish whether the provider has + /// initialized (`buzz_feature_flags_ready`). It does not track the + /// connection afterwards: an initialized LaunchDarkly client keeps serving + /// its last-known values through an outage. + pub fn report(&self) { + if let Some(environment) = &self.environment { + for diagnostic in environment.take_diagnostics() { + warn!( + ?diagnostic, + "malformed feature flag environment value; using its default" + ); + } + } + let ready = self + .launchdarkly + .as_ref() + .is_none_or(|launchdarkly| launchdarkly.initialized()); + metrics::gauge!("buzz_feature_flags_ready", "provider" => self.provider).set(if ready { + 1.0 + } else { + 0.0 + }); + } + + /// Stop the provider's background work, waiting at most + /// [`LAUNCHDARKLY_CLOSE_WAIT`]. + pub async fn close(&self) { + self.close_within(LAUNCHDARKLY_CLOSE_WAIT).await; + } + + /// LaunchDarkly's close blocks while it flushes analytics, so it runs on + /// its own detached thread: past `wait`, shutdown moves on and process + /// exit ends the flush. (The blocking pool would not do: the runtime + /// waits for its tasks when it drops.) + async fn close_within(&self, wait: Duration) { + let Some(launchdarkly) = self.launchdarkly.clone() else { + return; + }; + let (closed_tx, closed_rx) = tokio::sync::oneshot::channel(); + let spawned = std::thread::Builder::new() + .name("launchdarkly-close".into()) + .spawn(move || { + launchdarkly.close(); + let _ = closed_tx.send(()); + }); + if let Err(error) = spawned { + warn!(%error, "LaunchDarkly shutdown failed"); + return; + } + match tokio::time::timeout(wait, closed_rx).await { + Ok(Ok(())) => {} + Ok(Err(_)) => warn!("LaunchDarkly shutdown failed"), + Err(_) => warn!( + ?wait, + "LaunchDarkly did not finish its final flush; shutting down without it" + ), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + fn parse(pairs: &[(&str, &str)]) -> anyhow::Result { + let env: HashMap = pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + provider_from(|name| env.get(name).cloned()) + } + + #[test] + fn provider_selection_is_one_explicit_choice() { + assert!(matches!(parse(&[]), Ok(Provider::Static))); + assert!(matches!( + parse(&[(PROVIDER_ENV, "static")]), + Ok(Provider::Static) + )); + assert!(matches!( + parse(&[(PROVIDER_ENV, " environment ")]), + Ok(Provider::Environment) + )); + // An SDK key alone never selects LaunchDarkly. + assert!(matches!( + parse(&[(SDK_KEY_ENV, "sdk-key")]), + Ok(Provider::Static) + )); + + let Ok(Provider::LaunchDarkly(config)) = parse(&[ + (PROVIDER_ENV, "launchdarkly"), + (SDK_KEY_ENV, "sdk-key"), + (RELAY_PROXY_ENV, "http://ld-proxy.example.org:8030"), + ]) else { + panic!("launchdarkly with a key selects LaunchDarkly"); + }; + assert_eq!(config.sdk_key, "sdk-key"); + assert_eq!( + config.relay_proxy_endpoint.as_deref(), + Some("http://ld-proxy.example.org:8030") + ); + let Ok(Provider::LaunchDarkly(config)) = parse(&[ + (PROVIDER_ENV, "launchdarkly"), + (SDK_KEY_ENV, "sdk-key"), + (RELAY_PROXY_ENV, ""), + ]) else { + panic!("an empty proxy URL means no proxy"); + }; + assert_eq!(config.relay_proxy_endpoint, None); + } + + #[test] + fn provider_misconfiguration_fails_startup() { + for (pairs, needle) in [ + (&[(PROVIDER_ENV, "launchdarkly")][..], SDK_KEY_ENV), + ( + &[(PROVIDER_ENV, "launchdarkly"), (SDK_KEY_ENV, " ")][..], + SDK_KEY_ENV, + ), + ( + &[(PROVIDER_ENV, "LaunchDarkly")][..], + "not a feature flag provider", + ), + ( + &[(PROVIDER_ENV, "flagsmith")][..], + "not a feature flag provider", + ), + ] { + let error = parse(pairs) + .expect_err("misconfiguration must fail") + .to_string(); + assert!(error.contains(needle), "{pairs:?}: {error}"); + } + } + + #[tokio::test] + async fn an_unreachable_launchdarkly_starts_on_defaults() { + // The relay installs its rustls provider before building flags; the + // SDK's HTTP client needs one, and several are compiled in. + let _already_installed = rustls::crypto::ring::default_provider().install_default(); + // Nothing listens on the discard port, so the SDK never initializes. + let provider = parse(&[ + (PROVIDER_ENV, "launchdarkly"), + (SDK_KEY_ENV, "sdk-key"), + (RELAY_PROXY_ENV, "http://127.0.0.1:9"), + ]) + .expect("valid configuration"); + let flags = FeatureFlags::build(provider, Duration::from_millis(50)) + .await + .expect("an unreachable provider must not fail startup"); + let flag = buzz_feature_flags::IntegerFlag::new("buzz.relay.concurrency.auth", 0); + assert_eq!( + flags + .evaluator() + .evaluate_int(flag, &buzz_feature_flags::EvaluationContext::for_process()), + 0, + "an uninitialized provider serves the declared default" + ); + flags.close().await; + } + + #[tokio::test] + async fn close_is_bounded_when_launchdarkly_hangs() { + let _already_installed = rustls::crypto::ring::default_provider().install_default(); + // A proxy that accepts connections and never answers: every SDK + // request, the final analytics flush included, hangs. + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let address = listener.local_addr().expect("address"); + std::thread::spawn(move || { + let mut held = Vec::new(); + for stream in listener.incoming().flatten() { + held.push(stream); + } + }); + let provider = parse(&[ + (PROVIDER_ENV, "launchdarkly"), + (SDK_KEY_ENV, "sdk-key"), + (RELAY_PROXY_ENV, &format!("http://{address}")), + ]) + .expect("valid configuration"); + let flags = FeatureFlags::build(provider, Duration::from_millis(50)) + .await + .expect("a hanging provider must not fail startup"); + // An evaluation queues an analytics event for the final flush. + let flag = buzz_feature_flags::IntegerFlag::new("buzz.relay.concurrency.auth", 0); + flags + .evaluator() + .evaluate_int(flag, &buzz_feature_flags::EvaluationContext::for_process()); + + let started = std::time::Instant::now(); + flags.close_within(Duration::from_millis(200)).await; + assert!( + started.elapsed() < Duration::from_secs(2), + "close returns at its deadline, not when the flush gives up: {:?}", + started.elapsed() + ); + } + + #[tokio::test] + async fn a_malformed_proxy_url_fails_startup() { + let provider = parse(&[ + (PROVIDER_ENV, "launchdarkly"), + (SDK_KEY_ENV, "sdk-key"), + (RELAY_PROXY_ENV, "ld-proxy.example.org"), + ]) + .expect("parses"); + let Err(error) = FeatureFlags::build(provider, Duration::from_millis(50)).await else { + panic!("a relative proxy URL must fail startup"); + }; + assert!( + error.to_string().contains("LaunchDarkly configuration"), + "{error}" + ); + } +} diff --git a/crates/buzz-relay/src/fenced_cache.rs b/crates/buzz-relay/src/fenced_cache.rs new file mode 100644 index 00000000000..809b8b3eebb --- /dev/null +++ b/crates/buzz-relay/src/fenced_cache.rs @@ -0,0 +1,369 @@ +//! Short-lived read caches for connect and auth paths, fenced against +//! invalidation. +//! +//! An entry is served for the cache's `max_age` after the read that produced +//! it checked out its connection (see [`buzz_db::ReadAt`]), and concurrent +//! misses for one key share one read through [`SharedReads`]. +//! +//! A read that began before an invalidation must not refill the entry the +//! invalidation dropped: it can return the state the invalidating write just +//! replaced. Every invalidation bumps an epoch, and a fill is published only +//! if the epoch it observed before its read is still current. A later caller +//! therefore reads afresh instead of taking a pre-invalidation answer from the +//! cache or from a shared in-flight read. + +use std::future::Future; +use std::hash::Hash; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use crate::shared_reads::SharedReads; + +#[derive(Clone)] +struct Entry { + value: V, + read_at: Instant, +} + +/// A bounded read cache whose fills are fenced by invalidation. +pub(crate) struct FencedCache { + entries: moka::sync::Cache>, + reads: SharedReads, + // Serializes invalidation with fill publication. One epoch for every key + // keeps no per-key tombstones; an unrelated invalidation only skips + // publishing an in-flight fill. + epoch: Mutex, + max_age: Duration, + hits: &'static str, + misses: &'static str, +} + +impl FencedCache +where + K: Hash + Eq + Clone + Send + Sync + 'static, + V: Clone + Send + Sync + 'static, +{ + /// Up to `capacity` entries, each served for `max_age` after its read's + /// connection checkout. Concurrent misses wait at most `shared_read_wait` + /// for a shared read (see [`SharedReads::new`]). `hits` and `misses` name + /// the counters this cache reports. + pub(crate) fn new( + capacity: u64, + max_age: Duration, + shared_read_wait: Duration, + (hits, misses): (&'static str, &'static str), + ) -> Self { + Self { + // Readers use an entry only for `max_age` after its read began, + // which is never later than its insert; the TTL just reclaims + // memory. + entries: moka::sync::Cache::builder() + .max_capacity(capacity) + .time_to_live(max_age) + .support_invalidation_closures() + .build(), + reads: SharedReads::new(capacity, shared_read_wait), + epoch: Mutex::new(0), + max_age, + hits, + misses, + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, u64> { + self.epoch + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn fresh(&self, key: &K) -> Option { + self.entries + .get(key) + .filter(|entry| entry.read_at.elapsed() < self.max_age) + .map(|entry| entry.value) + } + + /// `key`'s value from the cache while it is fresh, else from `read`. + /// Errors are not cached. + /// + /// The first concurrent miss reads; the rest wait for it and use its + /// entry. A waiter whose leader failed, was cancelled, was fenced by an + /// invalidation or is still reading after the gate's wait reads on its + /// own. + pub(crate) async fn get( + &self, + key: K, + read: Read, + ) -> Result + where + Read: FnOnce() -> ReadFuture, + ReadFuture: Future, buzz_db::DbError>>, + { + if let Some(value) = self.fresh(&key) { + metrics::counter!(self.hits).increment(1); + return Ok(value); + } + let _turn = self.reads.turn(key.clone()).await; + if let Some(value) = self.fresh(&key) { + metrics::counter!(self.hits).increment(1); + return Ok(value); + } + metrics::counter!(self.misses).increment(1); + // Observed before the read checks out its connection, so a read that + // could predate an invalidation always sees a newer epoch. + let observed = *self.lock(); + let read = read().await?; + let epoch = self.lock(); + if *epoch == observed { + self.entries.insert( + key, + Entry { + value: read.value.clone(), + read_at: read.read_at, + }, + ); + } + Ok(read.value) + } + + /// Drops `key`'s entry and fences every fill begun before this. + pub(crate) fn invalidate(&self, key: &K) { + let mut epoch = self.lock(); + *epoch = epoch.wrapping_add(1); + self.entries.invalidate(key); + } + + /// Drops every entry whose key matches `predicate` and fences every fill + /// begun before this. + pub(crate) fn invalidate_if(&self, predicate: impl Fn(&K) -> bool + Send + Sync + 'static) { + let mut epoch = self.lock(); + *epoch = epoch.wrapping_add(1); + if let Err(error) = self + .entries + .invalidate_entries_if(move |key, _| predicate(key)) + { + // Invalidation closures are enabled at construction. If that ever + // regresses, over-invalidate rather than serve stale state. + tracing::error!( + ?error, + "scoped cache invalidation unavailable; dropping all entries" + ); + self.entries.invalidate_all(); + } + } + + /// Seeds a fresh entry without touching the database. + #[cfg(test)] + pub(crate) fn seed(&self, key: K, value: V) { + self.seed_read_at(key, value, Instant::now()); + } + + /// Seeds an entry whose read checked out its connection at `read_at`. + #[cfg(test)] + pub(crate) fn seed_read_at(&self, key: K, value: V, read_at: Instant) { + self.entries.insert(key, Entry { value, read_at }); + } + + /// The cached value and its read time, fresh or not. + #[cfg(test)] + pub(crate) fn entry(&self, key: &K) -> Option<(V, Instant)> { + self.entries + .get(key) + .map(|entry| (entry.value, entry.read_at)) + } + + /// The shared-read gates, so tests can hold or count a key's gate. + #[cfg(test)] + pub(crate) fn reads(&self) -> &SharedReads { + &self.reads + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + use super::*; + + const MAX_AGE: Duration = Duration::from_secs(10); + + fn cache() -> Arc> { + Arc::new(FencedCache::new( + 16, + MAX_AGE, + Duration::from_secs(5), + ( + "test_fenced_cache_hits_total", + "test_fenced_cache_misses_total", + ), + )) + } + + fn read_at(value: bool) -> Result, buzz_db::DbError> { + Ok(buzz_db::ReadAt { + value, + read_at: Instant::now(), + }) + } + + /// Tasks holding or waiting on `key`'s gate: its leader and every waiter + /// queued behind it (the cache's own clone and this probe's are + /// excluded). + fn gate_holders(cache: &FencedCache, key: u8) -> usize { + cache + .reads + .gate(&key) + .map_or(0, |gate| Arc::strong_count(&gate) - 2) + } + + /// Waits, at most 5 s, until `ready` holds. + async fn until(ready: impl Fn() -> bool) { + tokio::time::timeout(Duration::from_secs(5), async { + while !ready() { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .expect("readiness"); + } + + #[tokio::test] + async fn concurrent_misses_share_one_read_and_expire_after_max_age() { + let cache = cache(); + let reads = Arc::new(AtomicUsize::new(0)); + let (release, released) = tokio::sync::watch::channel(false); + + let tasks: Vec<_> = (0..16) + .map(|_| { + let cache = Arc::clone(&cache); + let reads = Arc::clone(&reads); + let mut released = released.clone(); + tokio::spawn(async move { + cache + .get(1, || async move { + reads.fetch_add(1, Ordering::SeqCst); + let _ = released.wait_for(|go| *go).await; + read_at(true) + }) + .await + }) + }) + .collect(); + // The leader is in its read and the other 15 wait behind its gate. + until(|| reads.load(Ordering::SeqCst) == 1 && gate_holders(&cache, 1) == 16).await; + release.send_replace(true); + for task in tasks { + assert!(task.await.expect("task").expect("read")); + } + assert_eq!(reads.load(Ordering::SeqCst), 1, "misses must share a read"); + + // Just inside the max age the entry is served without a read. + cache.seed_read_at(1, true, Instant::now() - (MAX_AGE - Duration::from_secs(1))); + assert!(cache + .get(1, || async { panic!("a fresh entry must be served") }) + .await + .expect("hit")); + + // Past the max age the entry is stale and the next caller reads. + cache.seed_read_at(1, true, Instant::now() - MAX_AGE); + let refreshed = cache + .get(1, || async { + reads.fetch_add(1, Ordering::SeqCst); + read_at(false) + }) + .await + .expect("read"); + assert!(!refreshed, "an expired entry must not be served"); + assert_eq!(reads.load(Ordering::SeqCst), 2); + } + + /// Mutation: drop the epoch check from `get` → RED. + #[tokio::test] + async fn invalidation_fences_an_in_flight_fill_and_its_waiters() { + let cache = cache(); + let (release, mut released) = tokio::sync::watch::channel(false); + let leader_reading = Arc::new(AtomicUsize::new(0)); + + // A leader reads `true` from a snapshot that predates the write. + let leader = { + let cache = Arc::clone(&cache); + let leader_reading = Arc::clone(&leader_reading); + tokio::spawn(async move { + cache + .get(1, || async move { + leader_reading.fetch_add(1, Ordering::SeqCst); + let _ = released.wait_for(|go| *go).await; + read_at(true) + }) + .await + }) + }; + // In its read, so it observed the epoch before the invalidation. + until(|| leader_reading.load(Ordering::SeqCst) == 1).await; + // A caller that arrives after the write joins the in-flight read. + let fresh_reads = Arc::new(AtomicUsize::new(0)); + let waiter = { + let cache = Arc::clone(&cache); + let fresh_reads = Arc::clone(&fresh_reads); + tokio::spawn(async move { + cache + .get(1, || async move { + fresh_reads.fetch_add(1, Ordering::SeqCst); + read_at(false) + }) + .await + }) + }; + // Queued behind the leader's gate before the invalidation. + until(|| gate_holders(&cache, 1) == 2).await; + cache.invalidate(&1); + release.send_replace(true); + + assert!(leader.await.expect("leader").expect("read")); + assert!( + !waiter.await.expect("waiter").expect("read"), + "a post-invalidation caller must not take a pre-invalidation answer", + ); + assert_eq!(fresh_reads.load(Ordering::SeqCst), 1); + assert_eq!( + cache.entry(&1).map(|(value, _)| value), + Some(false), + "only the post-invalidation read may fill the cache", + ); + } + + /// A scoped invalidation drops only matching keys and also fences fills. + /// Mutation: bump no epoch in `invalidate_if` → RED. + #[tokio::test] + async fn scoped_invalidation_drops_matches_and_fences_fills() { + let cache = cache(); + cache.seed(1, true); + cache.seed(2, true); + cache.invalidate_if(|key| *key == 1); + cache.entries.run_pending_tasks(); + assert!(cache.entry(&1).is_none(), "the matching key is dropped"); + assert!(cache.entry(&2).is_some(), "other keys stay"); + + // A fill that began before a scoped invalidation is not published. + let filled = cache + .get(3, || async { + cache.invalidate_if(|key| *key == 9); + read_at(true) + }) + .await + .expect("read"); + assert!(filled, "the caller still gets its own read"); + assert!(cache.entry(&3).is_none(), "the fenced fill is not cached"); + } + + #[tokio::test] + async fn errors_are_not_cached() { + let cache = cache(); + let failed = cache + .get(1, || async { Err(buzz_db::DbError::AuthEventRejected) }) + .await; + assert!(failed.is_err()); + assert!(cache.entry(&1).is_none()); + } +} diff --git a/crates/buzz-relay/src/handlers/artifact.rs b/crates/buzz-relay/src/handlers/artifact.rs index 772e032e75f..c52e71d6d4d 100644 --- a/crates/buzz-relay/src/handlers/artifact.rs +++ b/crates/buzz-relay/src/handlers/artifact.rs @@ -73,26 +73,18 @@ fn head_unavailable() -> IngestError { } /// Live delivery only; unlike kind 9 there are no audit, workflow, or thread -/// side effects. Missed deliveries are recovered by replaying stored events. +/// side effects. A failed publish is retried, because syncs depend on it. async fn publish(state: &Arc, tenant: &TenantContext, stored: &StoredEvent) { let Some(channel) = stored.channel_id else { return; }; - state.mark_local_event(tenant.community(), &stored.event.id); - if let Err(e) = state - .pubsub - .publish_event( - tenant, - buzz_pubsub::EventTopic::Channel(channel), - &stored.event, - ) - .await - { - state - .local_event_ids - .invalidate(&(tenant.community(), stored.event.id.to_bytes())); - tracing::warn!(error=%e, "artifact Redis publish failed"); - } + super::artifact_sync::publish_reliably( + state, + tenant, + buzz_pubsub::EventTopic::Channel(channel), + stored, + ) + .await; super::event::fan_out_event_to_local_subscribers(state, tenant.community(), stored).await; } diff --git a/crates/buzz-relay/src/handlers/artifact_sync.rs b/crates/buzz-relay/src/handlers/artifact_sync.rs new file mode 100644 index 00000000000..fa0cadf57e2 --- /dev/null +++ b/crates/buzz-relay/src/handlers/artifact_sync.rs @@ -0,0 +1,1090 @@ +//! NIP-AR Sync: a `REQ` that keeps an exact copy of a set of artifacts. +//! +//! The relay never forwards the published event to a sync. A live entry only +//! says that one `d` changed; the sync task then reads that artifact's current +//! head and sends it (NIP-AR Sync rules 3 and 4). Any possible loss of a live +//! entry ends the sync with `CLOSED "resync: ..."` (rule 5). +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex as StdMutex, PoisonError}; +use std::time::Duration; + +use axum::extract::ws::Message as WsMessage; +use buzz_auth::Scope; +use buzz_core::artifact_sync::{ArtifactSyncFilter, MAX_SYNC_EVENTS}; +use buzz_core::StoredEvent; +use buzz_pubsub::EventTopic; +use dashmap::DashMap; +use nostr::{Alphabet, Event, Filter, JsonUtil, Kind, SingleLetterTag}; +use tokio::sync::{Notify, OwnedSemaphorePermit}; +use tokio_util::sync::CancellationToken; +use tracing::warn; +use uuid::Uuid; + +use crate::access::ReadLog; +use crate::connection::{AuthState, ConnectionState}; +use crate::protocol::RelayMessage; +use crate::state::AppState; +use crate::subscription::{ConnId, SubId}; + +/// Heads read per snapshot page. One page is the most the relay buffers. +const SNAPSHOT_PAGE: i64 = 256; +/// The longest the relay holds one sync's snapshot open, including the time +/// a slow reader takes to receive it (rule 2). Not advertised. +const SNAPSHOT_BUDGET: Duration = Duration::from_secs(30); +/// How long a new sync waits for Redis to confirm its live interest (rule 1). +const CONFIRM_TIMEOUT: Duration = Duration::from_secs(5); +/// The most bytes of kind-45011 removals one sync holds (rule 5). Other +/// held changes are a `d` only, so `MAX_SYNC_EVENTS` bounds them. Not +/// advertised: a sync past either bound resyncs. +const MAX_HELD_BYTES: usize = 4 << 20; +/// Kind-9005 redaction; it can retire a head that is in scope (rule 6). +const KIND_REDACTION: u16 = 9005; +/// NIP-29 kinds that can change a reader's access to a channel: remove user, +/// edit metadata (visibility), delete group, leave (rule 9). +const ACCESS_KINDS: [u16; 4] = [9001, 9002, 9008, 9022]; +/// Every kind a sync consumes from live fan-out. A failed publish of one of +/// these is retried (rule 5). +pub(crate) const LIVE_KINDS: [u16; 7] = [45010, 45011, KIND_REDACTION, 9001, 9002, 9008, 9022]; + +/// Live changes held for one sync until its task reads their heads. +#[derive(Default)] +struct Pending { + /// Changed artifacts, with the latest kind-45011 removal seen for each. + changed: HashMap>, + /// Serialized size of the removals in `changed`. + held_bytes: usize, + /// The first reason this sync must resync, if any. Once set, nothing + /// more is held: the sync ends without reading its changes. + resync: Option<&'static str>, +} + +impl Pending { + fn end(&mut self, reason: &'static str) { + self.resync.get_or_insert(reason); + self.changed = HashMap::new(); + self.held_bytes = 0; + } + + /// Hold one change, refusing it before it is stored when it would pass + /// a bound. + fn hold(&mut self, d: Uuid, removal: Option) { + if self.resync.is_some() { + return; + } + if !self.changed.contains_key(&d) && self.changed.len() >= MAX_SYNC_EVENTS { + return self.end("resync: too many changes"); + } + let Some(removal) = removal else { + self.changed.entry(d).or_default(); + return; + }; + let size = removal.as_json().len(); + let replaced = self + .changed + .get(&d) + .and_then(Option::as_ref) + .map_or(0, |old| old.as_json().len()); + let held = self.held_bytes - replaced + size; + if held > MAX_HELD_BYTES { + return self.end("resync: too many changes"); + } + self.held_bytes = held; + self.changed.insert(d, Some(removal)); + } +} + +/// The artifact identity (`d`) of a revision or removal. +fn artifact_id(event: &Event) -> Option { + event + .tags + .iter() + .find(|tag| tag.as_slice().first().map(String::as_str) == Some("d")) + .and_then(|tag| tag.as_slice().get(1)?.parse().ok()) +} + +/// One live sync's signal inbox. Fan-out and loss detection write to it; the +/// sync's own task is its only reader. +pub struct SyncHandle { + pending: StdMutex, + notify: Notify, + cancel: CancellationToken, +} + +impl SyncHandle { + fn new() -> Self { + Self { + pending: StdMutex::new(Pending::default()), + notify: Notify::new(), + cancel: CancellationToken::new(), + } + } + + fn update(&self, change: impl FnOnce(&mut Pending)) { + change(&mut self.pending.lock().unwrap_or_else(PoisonError::into_inner)); + self.notify.notify_one(); + } + + /// Record a fanned-out event that falls in this sync's channels. + fn signal(&self, stored: &StoredEvent) { + let kind = stored.event.kind.as_u16(); + if kind == KIND_REDACTION { + // The redacted head is withheld, so only a new sync can show the + // client that the artifact left the set. Any redaction in the + // channels counts: telling which ones retire a head needs a read. + return self.resync("resync: redaction"); + } + if ACCESS_KINDS.contains(&kind) { + return self.resync("resync: channel access changed"); + } + let Some(d) = artifact_id(&stored.event) else { + return; + }; + let removal = (kind == 45011).then(|| stored.event.clone()); + self.update(|pending| pending.hold(d, removal)); + } + + /// Ask the sync to end with `CLOSED reason`, where reason is `resync: ...`. + pub fn resync(&self, reason: &'static str) { + self.update(|pending| pending.end(reason)); + } + + fn take(&self) -> Pending { + std::mem::take(&mut *self.pending.lock().unwrap_or_else(PoisonError::into_inner)) + } +} + +/// Every live sync this node serves, by connection and subscription ID. +#[derive(Default)] +pub struct ArtifactSyncs { + syncs: DashMap<(ConnId, SubId), Arc>, +} + +impl ArtifactSyncs { + fn insert(&self, conn: ConnId, sub: &str, handle: Arc) { + if let Some(old) = self.syncs.insert((conn, sub.to_owned()), handle) { + old.cancel.cancel(); + } + } + + /// Stop the sync that holds `sub` on `conn`, if one does. Called wherever + /// the subscription ID is retired or replaced. + /// Returns whether `sub` was a sync. + pub fn remove(&self, conn: ConnId, sub: &str) -> bool { + match self.syncs.remove(&(conn, sub.to_owned())) { + Some((_, handle)) => { + handle.cancel.cancel(); + true + } + None => false, + } + } + + /// Whether `sub` on `conn` is a sync. + pub fn contains(&self, conn: ConnId, sub: &str) -> bool { + self.syncs.contains_key(&(conn, sub.to_owned())) + } + + /// Stop every sync of a closed connection. + pub fn remove_connection(&self, conn: ConnId) { + self.syncs.retain(|(owner, _), handle| { + if *owner == conn { + handle.cancel.cancel(); + } + *owner != conn + }); + } + + /// End every sync on this node: a loss here can affect any of them. + pub fn resync_all(&self, reason: &'static str) { + for entry in self.syncs.iter() { + entry.value().resync(reason); + } + } + + /// Signal syncs among the fan-out matches *before* the access filter. A + /// reader who just lost access to a channel no longer passes that filter, + /// yet the change that removed it must still resync its syncs (rule 9). + /// Only kinds that resync are signalled here; nothing is sent. + pub fn signal_access_change(&self, stored: &StoredEvent, matches: &[(ConnId, SubId)]) { + let kind = stored.event.kind.as_u16(); + if self.syncs.is_empty() || !(kind == KIND_REDACTION || ACCESS_KINDS.contains(&kind)) { + return; + } + for key in matches { + if let Some(handle) = self.syncs.get(key) { + handle.signal(stored); + } + } + } + + /// End the syncs among `matches` with `reason`: a change reached them, + /// but this node cannot deliver its signal (rule 5). + pub fn resync_matches(&self, matches: &[(ConnId, SubId)], reason: &'static str) { + if self.syncs.is_empty() { + return; + } + for key in matches { + if let Some(handle) = self.syncs.get(key) { + handle.resync(reason); + } + } + } + + /// Divert fan-out matches that are syncs into their signal inboxes, and + /// return the matches that receive the event itself. + pub fn divert( + &self, + stored: &StoredEvent, + matches: Vec<(ConnId, SubId)>, + ) -> Vec<(ConnId, SubId)> { + if self.syncs.is_empty() { + return matches; + } + matches + .into_iter() + .filter(|key| match self.syncs.get(key) { + Some(handle) => { + handle.signal(stored); + false + } + None => true, + }) + .collect() + } +} + +#[cfg(test)] +impl ArtifactSyncs { + /// Install an idle sync on `sub`, as a sync claim does. + pub(crate) fn insert_idle(&self, conn: ConnId, sub: &str) { + self.insert(conn, sub, Arc::new(SyncHandle::new())); + } + + /// The resync reason recorded for the sync on `sub`, if any. + pub(crate) fn pending_resync(&self, conn: ConnId, sub: &str) -> Option<&'static str> { + let handle = self.syncs.get(&(conn, sub.to_owned()))?; + let pending = handle + .pending + .lock() + .unwrap_or_else(PoisonError::into_inner); + pending.resync + } +} + +/// Resync every sync on this node whenever its Redis link may have lost a +/// message (rule 5). A sync records the epoch its interest was confirmed on, +/// so any later change reaches it here. Runs until the link owner stops. +pub async fn watch_link(state: Arc) { + let mut link = state.pubsub.link_state(); + let mut seen = link.borrow_and_update().epoch; + while link.changed().await.is_ok() { + let epoch = link.borrow_and_update().epoch; + if epoch != seen { + seen = epoch; + state + .artifact_syncs + .resync_all("resync: live delivery interrupted"); + } + } +} + +/// Publish `stored` to Redis. A failed publish of a kind that syncs consume +/// is retried in the background until it succeeds or the node stops (rule +/// 5): order does not matter, because a sync reads the current head. +pub(crate) async fn publish_reliably( + state: &Arc, + tenant: &buzz_core::TenantContext, + topic: EventTopic, + stored: &StoredEvent, +) { + if publish_once(state, tenant, topic, &stored.event).await { + return; + } + if !LIVE_KINDS.contains(&stored.event.kind.as_u16()) { + return; + } + metrics::counter!("buzz_artifact_sync_publish_retry_total").increment(1); + let state = Arc::clone(state); + let tenant = tenant.clone(); + let event = stored.event.clone(); + tokio::spawn(async move { + let mut delay = Duration::from_millis(100); + loop { + tokio::time::sleep(delay).await; + if publish_once(&state, &tenant, topic, &event).await { + return; + } + delay = (delay * 2).min(Duration::from_secs(5)); + } + }); +} + +/// One publish attempt. The local-echo mark is set first, so this node does +/// not fan the event out a second time when Redis echoes it back. +async fn publish_once( + state: &AppState, + tenant: &buzz_core::TenantContext, + topic: EventTopic, + event: &Event, +) -> bool { + state.mark_local_event(tenant.community(), &event.id); + #[cfg(test)] + crate::nip_fi_test_hooks::before_event_publish(tenant.community()); + match state.pubsub.publish_event(tenant, topic, event).await { + Ok(_) => true, + Err(e) => { + state + .local_event_ids + .invalidate(&(tenant.community(), event.id.to_bytes())); + warn!(event_id = %event.id.to_hex(), "Redis publish failed: {e}"); + false + } + } +} + +/// The fan-out filter a sync registers: every change signal in its channels. +pub(crate) fn live_filter(channels: &[Uuid]) -> Filter { + Filter::new() + .kinds(LIVE_KINDS.map(Kind::Custom)) + .custom_tags( + SingleLetterTag::lowercase(Alphabet::H), + channels.iter().map(Uuid::to_string), + ) +} + +/// Serve one sync `REQ` that `close::admit` admitted with `owner`. `permit` +/// is the handler slot; it is held only for the initial read. Every exit +/// before the claim refuses through `close_if_owner`, so a sync that a newer +/// same-ID request or a `CLOSE` superseded sends nothing and registers +/// nothing. +pub async fn handle_sync( + sub_id: String, + owner: u64, + filter: Result, + conn: Arc, + state: Arc, + permit: OwnedSemaphorePermit, +) { + let filter = match filter { + Ok(filter) => filter, + Err(reason) => { + super::close::close_if_owner( + &sub_id, + owner, + Some(&format!("invalid: {reason}")), + &conn, + &state, + ) + .await; + ReadLog::refused_sync(&conn, &sub_id, None, "invalid_filter"); + return; + } + }; + // Written when the initial set ends, not when live delivery does. + let mut access = ReadLog::sync(&conn, &sub_id, &filter.channels); + let (reader, bound) = match conn.auth_state_snapshot() { + AuthState::Authenticated(ctx) => { + if !ctx.scopes.is_empty() && !ctx.scopes.contains(&Scope::MessagesRead) { + super::close::close_if_owner( + &sub_id, + owner, + Some("restricted: insufficient scope"), + &conn, + &state, + ) + .await; + access.deny("insufficient_scope"); + return; + } + // A channel-scoped token reaches only its own channels; outside + // them the answer matches an unreadable channel. + if let Some(allowed) = ctx.channel_ids.as_deref() { + if filter.channels.iter().any(|id| !allowed.contains(id)) { + super::close::close_if_owner(&sub_id, owner, Some(RESTRICTED), &conn, &state) + .await; + access.deny("not_channel_member"); + return; + } + } + (ctx.pubkey.to_bytes().to_vec(), ctx.channel_ids) + } + _ => { + super::close::close_if_owner( + &sub_id, + owner, + Some("auth-required: not authenticated"), + &conn, + &state, + ) + .await; + access.deny("auth_required"); + return; + } + }; + let _effect = match conn.nip_fi_gate.acquire_effect().await { + Ok(permit) => permit, + Err(crate::nip_fi_gate::SessionExpired) => { + super::close::close_if_owner( + &sub_id, + owner, + Some("restricted: authorization denied"), + &conn, + &state, + ) + .await; + access.deny("session_expired"); + return; + } + }; + + // Rule 1: live interest first, confirmed by Redis on an unbroken link. + let start = *state.pubsub.link_state().borrow(); + let handle = Arc::new(SyncHandle::new()); + let Some(owner) = claim(&sub_id, owner, &filter.channels, &handle, &conn, &state).await else { + return; + }; + if !start.up || !confirm(&filter.channels, start.epoch, &conn, &state).await { + close( + &sub_id, + owner, + "error: live delivery unavailable", + &conn, + &state, + ) + .await; + access.error("live_delivery_unavailable"); + return; + } + + // Rule 2: the initial set from one snapshot and its EOSE, all inside the + // time budget and the cancellation race, so a slow reader cannot hold + // the handler slot past the budget or get EOSE after retirement. + let initial = async { + let sent = + send_initial_set(&sub_id, owner, &filter, &reader, &mut access, &conn, &state).await?; + // A resync requested before EOSE is queued ends the sync without it. + send_eose(&sub_id, owner, &handle, &conn).await?; + Ok::<_, Stop>(sent) + }; + let outcome = tokio::select! { + biased; + () = conn.nip_fi_gate.cancelled() => None, + () = handle.cancel.cancelled() => return, + out = tokio::time::timeout(SNAPSHOT_BUDGET, initial) => Some(out), + }; + let in_set = match outcome { + None => { + super::close::close_if_owner(&sub_id, owner, None, &conn, &state).await; + return; + } + Some(Err(_)) => { + let reason = "error: sync snapshot budget exceeded"; + close(&sub_id, owner, reason, &conn, &state).await; + access.error("query_timed_out"); + return; + } + Some(Ok(Err(Stop::Retired))) => return, + Some(Ok(Err(Stop::Close(reason)))) => { + close(&sub_id, owner, reason, &conn, &state).await; + match reason { + RESTRICTED => access.deny("not_channel_member"), + OVER_MAX_EVENTS => access.deny("sync_set_too_large"), + READ_FAILED => access.error("database_error"), + // A resync or a closed connection: the client retries. + _ => {} + } + return; + } + Some(Ok(Ok(sent))) => sent, + }; + access.served(); + drop(access); + drop(_effect); + drop(permit); + + run_live( + &sub_id, + owner, + &filter, + &reader, + bound.as_deref(), + in_set, + &handle, + &conn, + &state, + ) + .await; +} + +const RESTRICTED: &str = "restricted: channel not readable"; +const OVER_MAX_EVENTS: &str = "error: sync set exceeds max_events"; +const READ_FAILED: &str = "error: sync read failed"; + +/// Why a sync stops sending. +enum Stop { + /// End with `CLOSED reason`. + Close(&'static str), + /// Another request now owns the ID, or it was closed: say nothing. + Retired, +} + +/// Claim `sub_id` for the sync admitted with `owner`, under the lifecycle +/// lock, retiring the previous holder. The sync's inbox is installed before +/// fan-out registration, so no event frame is ever sent to it. `None` once the +/// connection is closing or this sync was superseded. +async fn claim( + sub_id: &str, + owner: u64, + channels: &[Uuid], + handle: &Arc, + conn: &ConnectionState, + state: &AppState, +) -> Option { + let mut subs = conn.subscriptions.lock().await; + if !super::close::claim_locked(&mut subs, sub_id, owner, conn) { + return None; + } + super::close::retire_holder_locked(sub_id, conn, state).await; + state + .artifact_syncs + .insert(conn.conn_id, sub_id, Arc::clone(handle)); + state.sub_registry.register_channels_scoped( + conn.tenant.community(), + conn.conn_id, + sub_id.to_owned(), + vec![live_filter(channels)], + channels.to_vec(), + ); + for &channel in channels { + state + .pubsub + .retain_topic(&conn.tenant, EventTopic::Channel(channel)) + .await; + } + Some(owner) +} + +/// Wait until Redis confirms every channel topic on link epoch `epoch`. A +/// later change of the epoch resyncs this sync through `resync_all`. +async fn confirm(channels: &[Uuid], epoch: u64, conn: &ConnectionState, state: &AppState) -> bool { + let confirm_all = async { + for &channel in channels { + match state + .pubsub + .confirm_topic(&conn.tenant, EventTopic::Channel(channel)) + .await + { + Ok(confirmed) if confirmed == epoch => {} + _ => return false, + } + } + true + }; + tokio::time::timeout(CONFIRM_TIMEOUT, confirm_all) + .await + .unwrap_or(false) +} + +/// Read and send every head in scope from one snapshot, and return their +/// `d`. After an `Err` nothing more is sent. +async fn send_initial_set( + sub_id: &str, + owner: u64, + filter: &ArtifactSyncFilter, + reader: &[u8], + access: &mut ReadLog, + conn: &ConnectionState, + state: &AppState, +) -> Result, Stop> { + let mut snapshot = match state + .db + .open_artifact_snapshot(conn.tenant.community(), reader, &filter.channels) + .await + { + Ok(Ok(snapshot)) => snapshot, + Ok(Err(buzz_db::SnapshotDenied::Restricted)) => return Err(Stop::Close(RESTRICTED)), + Err(e) => { + warn!(conn_id = %conn.conn_id, error_kind = %e.kind(), "artifact sync snapshot failed"); + return Err(Stop::Close(READ_FAILED)); + } + }; + let mut sent = HashSet::new(); + loop { + let page = snapshot + .next_page(&filter.tags, SNAPSHOT_PAGE) + .await + .map_err(|e| { + warn!(conn_id = %conn.conn_id, error_kind = %e.kind(), "artifact sync page failed"); + Stop::Close(READ_FAILED) + })?; + if page.is_empty() { + break; + } + if sent.len() + page.len() > MAX_SYNC_EVENTS { + return Err(Stop::Close(OVER_MAX_EVENTS)); + } + for stored in page { + sent.extend(artifact_id(&stored.event)); + send_owned( + sub_id, + owner, + RelayMessage::event(sub_id, &stored.event), + conn, + ) + .await?; + access.queued_one(); + } + } + snapshot + .finish() + .await + .map_err(|_| Stop::Close(READ_FAILED))?; + Ok(sent) +} + +/// Queue a frame while this request owns `sub_id`, waiting for room: the +/// snapshot budget, not the slow-client grace limit, bounds a slow reader +/// during the initial set. The slot is reserved first and the owner checked +/// under the lifecycle lock, so the lock is never held while waiting, and a +/// CLOSE or replacing REQ (which retire under that lock) fences the frame. +async fn send_owned( + sub_id: &str, + owner: u64, + frame: String, + conn: &ConnectionState, +) -> Result<(), Stop> { + send_reserved(sub_id, owner, frame, None, conn).await +} + +/// Queue `EOSE` like `send_owned`, unless the sync must resync. The pending +/// resync is checked under the inbox lock while the frame is queued, so a +/// resync recorded at any time before `EOSE` enters the queue ends the sync +/// with `CLOSED` and no `EOSE` (rule 1); a later one closes after it. +async fn send_eose( + sub_id: &str, + owner: u64, + handle: &SyncHandle, + conn: &ConnectionState, +) -> Result<(), Stop> { + send_reserved( + sub_id, + owner, + RelayMessage::eose(sub_id), + Some(handle), + conn, + ) + .await +} + +async fn send_reserved( + sub_id: &str, + owner: u64, + frame: String, + unless_resync: Option<&SyncHandle>, + conn: &ConnectionState, +) -> Result<(), Stop> { + let slot = conn + .send_tx + .reserve() + .await + .map_err(|_| Stop::Close("error: connection closed"))?; + let subs = conn.subscriptions.lock().await; + if !super::close::owns(&subs, sub_id, owner) { + return Err(Stop::Retired); + } + let pending = unless_resync.map(|handle| { + handle + .pending + .lock() + .unwrap_or_else(PoisonError::into_inner) + }); + if let Some(reason) = pending.as_ref().and_then(|pending| pending.resync) { + return Err(Stop::Close(reason)); + } + slot.send(WsMessage::Text(frame.into())); + Ok(()) +} + +/// Queue a live frame without waiting, fenced like `send_owned`. A full +/// queue is a lost frame. +async fn try_send_owned( + sub_id: &str, + owner: u64, + frame: String, + conn: &ConnectionState, +) -> Result<(), Stop> { + let subs = conn.subscriptions.lock().await; + if !super::close::owns(&subs, sub_id, owner) { + return Err(Stop::Retired); + } + conn.send_tx + .try_send(WsMessage::Text(frame.into())) + .map_err(|_| Stop::Close("resync: send queue full")) +} + +/// Rules 3–5 after `EOSE`: read each changed head, one read at a time, and +/// send it. A dropped frame or a resync request ends the sync. `in_set` is +/// the client's copy as this sync sent it: the `d` of each artifact in scope. +/// `bound` is a channel-scoped token's channels: the reader reads no head +/// outside them, even where its pubkey could. +#[allow(clippy::too_many_arguments)] +async fn run_live( + sub_id: &str, + owner: u64, + filter: &ArtifactSyncFilter, + reader: &[u8], + bound: Option<&[Uuid]>, + mut in_set: HashSet, + handle: &SyncHandle, + conn: &ConnectionState, + state: &AppState, +) { + loop { + let pending = handle.take(); + if let Some(reason) = pending.resync { + close(sub_id, owner, reason, conn, state).await; + return; + } + for (d, removal) in pending.changed { + // A retired sync reads nothing more. + if handle.cancel.is_cancelled() { + return; + } + let head = match state + .db + .artifact_head(conn.tenant.community(), reader, d, &filter.channels) + .await + { + Ok(head) => head.filter(|(head, _)| { + bound.is_none_or(|allowed| { + head.channel_id.is_some_and(|id| allowed.contains(&id)) + }) + }), + Err(e) => { + warn!(conn_id = %conn.conn_id, error_kind = %e.kind(), "artifact sync head read failed"); + close(sub_id, owner, "error: sync read failed", conn, state).await; + return; + } + }; + // Rule 3: send a change only for an artifact in scope before it + // (in the client's copy) or after it (a live head that matches + // every predicate). The change signal is per channel, so it + // reaches syncs that never matched this artifact. + let in_scope = head + .as_ref() + .is_some_and(|(head, deleted)| !deleted && filter.matches(&head.event)); + if !in_scope && !in_set.contains(&d) { + continue; + } + // A head the reader cannot read leaves only the source removal. + // Without one, nothing the reader may read can remove the + // artifact from its copy, so the copy is no longer exact. + let Some(event) = head.map(|(head, _)| head.event).or(removal) else { + close(sub_id, owner, "resync: artifact left scope", conn, state).await; + return; + }; + #[cfg(test)] + super::close::test_seam::pause_at(&test_seam::LIVE_SEND_PAUSE).await; + match try_send_owned(sub_id, owner, RelayMessage::event(sub_id, &event), conn).await { + Ok(()) => {} + Err(Stop::Retired) => return, + // One lost frame breaks the copy; the slow-client grace limit + // does not apply. `close` drops the connection when even the + // CLOSED frame cannot be queued. + Err(Stop::Close(reason)) => { + close(sub_id, owner, reason, conn, state).await; + return; + } + } + if !in_scope { + in_set.remove(&d); + } else if in_set.insert(d) && in_set.len() > MAX_SYNC_EVENTS { + // A new sync of this set would be refused the same way. + close(sub_id, owner, OVER_MAX_EVENTS, conn, state).await; + return; + } + } + tokio::select! { + () = handle.cancel.cancelled() => return, + () = conn.cancel.cancelled() => return, + () = handle.notify.notified() => {} + } + } +} + +/// End the sync with `CLOSED reason` if this request still owns its ID. +async fn close(sub_id: &str, owner: u64, reason: &str, conn: &ConnectionState, state: &AppState) { + super::close::close_if_owner(sub_id, owner, Some(reason), conn, state).await; +} + +#[cfg(test)] +pub(crate) mod test_seam { + use std::sync::Arc; + + use super::super::close::test_seam::Pause; + + tokio::task_local! { + /// After a live head read, before its frame is queued. + pub(crate) static LIVE_SEND_PAUSE: Arc; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use nostr::{EventBuilder, Keys, Tag}; + + fn stored(kind: u16, d: Uuid) -> StoredEvent { + let event = EventBuilder::new(Kind::Custom(kind), "") + .tags([Tag::parse(["d", &d.to_string()]).unwrap()]) + .sign_with_keys(&Keys::generate()) + .unwrap(); + StoredEvent::new(event, Some(Uuid::new_v4())) + } + + #[test] + fn divert_signals_syncs_and_keeps_ordinary_matches() { + let syncs = ArtifactSyncs::default(); + let conn = Uuid::new_v4(); + let handle = Arc::new(SyncHandle::new()); + syncs.insert(conn, "sync", Arc::clone(&handle)); + let d = Uuid::new_v4(); + let rest = syncs.divert( + &stored(45010, d), + vec![(conn, "sync".into()), (conn, "plain".into())], + ); + assert_eq!(rest, vec![(conn, "plain".to_string())]); + let removal = stored(45011, d); + syncs.divert(&removal, vec![(conn, "sync".into())]); + // A later revision keeps the removal: only the head read decides. + syncs.divert(&stored(45010, d), vec![(conn, "sync".into())]); + let pending = handle.take(); + assert_eq!(pending.changed.len(), 1); + assert_eq!( + pending.changed[&d].as_ref().map(|e| e.id), + Some(removal.event.id) + ); + assert!(pending.resync.is_none()); + + syncs.divert(&stored(KIND_REDACTION, d), vec![(conn, "sync".into())]); + assert_eq!(handle.take().resync, Some("resync: redaction")); + + syncs.remove(conn, "sync"); + assert!(handle.cancel.is_cancelled()); + assert_eq!( + syncs + .divert(&stored(45010, d), vec![(conn, "sync".into())]) + .len(), + 1 + ); + } + + /// The access-change signal runs before the access filter, so a reader + /// who already lost access still gets its resync. Content kinds wait for + /// the filtered `divert`. Mutation: drop the `ACCESS_KINDS` check in + /// `signal_access_change` → the 45010 is recorded unfiltered → RED. + #[test] + fn access_changes_signal_before_the_access_filter() { + let syncs = ArtifactSyncs::default(); + let conn = Uuid::new_v4(); + let handle = Arc::new(SyncHandle::new()); + syncs.insert(conn, "sync", Arc::clone(&handle)); + let matches = vec![(conn, "sync".to_string())]; + syncs.signal_access_change(&stored(45010, Uuid::new_v4()), &matches); + let pending = handle.take(); + assert!(pending.changed.is_empty() && pending.resync.is_none()); + for kind in ACCESS_KINDS { + syncs.signal_access_change(&stored(kind, Uuid::new_v4()), &matches); + assert_eq!( + handle.take().resync, + Some("resync: channel access changed"), + "{kind}" + ); + } + } + + #[test] + fn held_changes_past_max_events_resync() { + let handle = SyncHandle::new(); + for _ in 0..=MAX_SYNC_EVENTS { + handle.signal(&stored(45010, Uuid::new_v4())); + } + assert_eq!(handle.take().resync, Some("resync: too many changes")); + } + + /// The held list is a hard bound: a change past the limit is refused + /// before it is stored, and nothing is held after the sync must resync. + /// Mutation: insert before the size check, or keep holding after + /// `resync` → `changed` grows past `MAX_SYNC_EVENTS` → RED. + #[test] + fn held_list_holds_nothing_past_its_limit() { + let handle = SyncHandle::new(); + for _ in 0..MAX_SYNC_EVENTS { + handle.signal(&stored(45010, Uuid::new_v4())); + } + { + let pending = handle.pending.lock().unwrap(); + assert_eq!(pending.changed.len(), MAX_SYNC_EVENTS); + assert!(pending.resync.is_none()); + } + for _ in 0..100 { + handle.signal(&stored(45010, Uuid::new_v4())); + handle.signal(&stored(45011, Uuid::new_v4())); + } + let pending = handle.pending.lock().unwrap(); + assert_eq!(pending.resync, Some("resync: too many changes")); + assert!(pending.changed.is_empty()); + assert_eq!(pending.held_bytes, 0); + } + + fn removal(d: Uuid, size: usize) -> StoredEvent { + let event = EventBuilder::new(Kind::Custom(45011), "x".repeat(size)) + .tags([Tag::parse(["d", &d.to_string()]).unwrap()]) + .sign_with_keys(&Keys::generate()) + .unwrap(); + StoredEvent::new(event, Some(Uuid::new_v4())) + } + + /// Held removals are whole events, so their bytes have their own bound. + /// A newer removal for the same `d` replaces the older one's bytes. + #[test] + fn held_removals_have_a_byte_bound() { + let handle = SyncHandle::new(); + let d = Uuid::new_v4(); + for _ in 0..2 * (MAX_HELD_BYTES >> 16) { + handle.signal(&removal(d, 1 << 16)); + } + { + let pending = handle.pending.lock().unwrap(); + assert!(pending.resync.is_none()); + assert!(pending.held_bytes < 1 << 17, "{}", pending.held_bytes); + } + for _ in 0..=MAX_HELD_BYTES >> 16 { + handle.signal(&removal(Uuid::new_v4(), 1 << 16)); + } + let pending = handle.pending.lock().unwrap(); + assert_eq!(pending.resync, Some("resync: too many changes")); + assert!(pending.changed.is_empty()); + } + + fn conn_with_sub(owner: u64) -> (Arc, tokio::sync::mpsc::Receiver) { + let tenant = buzz_core::TenantContext::resolved( + buzz_core::CommunityId::from_uuid(Uuid::new_v4()), + "relay.example", + ); + let (conn, rx) = + super::super::group_state_postgres_tests::test_conn(&tenant, &Keys::generate()); + conn.subscriptions + .try_lock() + .unwrap() + .insert("s".into(), held(owner)); + (conn, rx) + } + + fn held(owner: u64) -> super::super::close::SubOwner { + super::super::close::SubOwner { + owner, + claimed: true, + } + } + + /// A live frame goes out only while its request still owns the ID. + /// Mutation: drop the owner check in `try_send_owned` → RED. + #[tokio::test] + async fn live_frame_is_fenced_by_the_owner() { + let (conn, mut rx) = conn_with_sub(1); + assert!(matches!( + try_send_owned("s", 2, "x".into(), &conn).await, + Err(Stop::Retired) + )); + conn.subscriptions.lock().await.remove("s"); + assert!(matches!( + try_send_owned("s", 1, "x".into(), &conn).await, + Err(Stop::Retired) + )); + assert!(rx.try_recv().is_err()); + conn.subscriptions.lock().await.insert("s".into(), held(1)); + assert!(try_send_owned("s", 1, "x".into(), &conn).await.is_ok()); + assert!(rx.try_recv().is_ok()); + } + + /// A frame (such as `EOSE`) waiting for queue room is checked against + /// the owner after the room appears, not before it waited. Mutation: + /// check the owner before `reserve` → the stale frame is queued → RED. + #[tokio::test] + async fn waiting_frame_is_fenced_when_replaced_during_the_wait() { + let (conn, mut rx) = conn_with_sub(1); + let capacity = conn.send_tx.capacity(); + for _ in 0..capacity { + conn.send_tx + .try_send(WsMessage::Text("fill".into())) + .unwrap(); + } + let mut waiting = std::pin::pin!(send_owned("s", 1, "eose".into(), &conn)); + // Polled once, the frame is now waiting in `reserve`. + assert!(futures_util::poll!(&mut waiting).is_pending()); + // A replacing REQ takes the ID while the frame waits. + conn.subscriptions.lock().await.insert("s".into(), held(2)); + rx.recv().await.unwrap(); + assert!(matches!(waiting.await, Err(Stop::Retired))); + let mut rest = 0; + while let Ok(WsMessage::Text(text)) = rx.try_recv() { + assert_eq!(text.as_str(), "fill"); + rest += 1; + } + assert_eq!(rest, capacity - 1); + } + + /// A resync recorded while `EOSE` waits for queue room ends the sync + /// without `EOSE` (rule 1). Mutation: check the pending resync before + /// `reserve` instead of while queueing → `EOSE` is queued → RED. + #[tokio::test] + async fn resync_during_the_eose_wait_sends_no_eose() { + let (conn, mut rx) = conn_with_sub(1); + let handle = SyncHandle::new(); + let capacity = conn.send_tx.capacity(); + for _ in 0..capacity { + conn.send_tx + .try_send(WsMessage::Text("fill".into())) + .unwrap(); + } + let mut waiting = std::pin::pin!(send_eose("s", 1, &handle, &conn)); + assert!(futures_util::poll!(&mut waiting).is_pending()); + // The held list overflows while EOSE waits. + for _ in 0..=MAX_SYNC_EVENTS { + handle.signal(&stored(45010, Uuid::new_v4())); + } + rx.recv().await.unwrap(); + assert!(matches!( + waiting.await, + Err(Stop::Close("resync: too many changes")) + )); + while let Ok(WsMessage::Text(text)) = rx.try_recv() { + assert_eq!(text.as_str(), "fill"); + } + + // Without a pending resync, EOSE is queued. + let clean = SyncHandle::new(); + assert!(send_eose("s", 1, &clean, &conn).await.is_ok()); + let Ok(WsMessage::Text(text)) = rx.try_recv() else { + panic!("no EOSE"); + }; + assert!(text.as_str().starts_with(r#"["EOSE""#), "{text}"); + } + + #[test] + fn resync_all_reaches_every_sync() { + let syncs = ArtifactSyncs::default(); + let handles: Vec<_> = (0..3).map(|_| Arc::new(SyncHandle::new())).collect(); + for (i, handle) in handles.iter().enumerate() { + syncs.insert(Uuid::new_v4(), &i.to_string(), Arc::clone(handle)); + } + syncs.resync_all("resync: live delivery interrupted"); + for handle in handles { + assert_eq!( + handle.take().resync, + Some("resync: live delivery interrupted") + ); + } + } +} diff --git a/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs new file mode 100644 index 00000000000..9c8e3c5936c --- /dev/null +++ b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs @@ -0,0 +1,693 @@ +//! Postgres- and Redis-backed tests for NIP-AR Sync over the real REQ +//! handler, ingest pipeline, fan-out and pub/sub link. + +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::ws::Message as WsMessage; +use buzz_core::TenantContext; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use serde_json::{json, Value}; +use tokio::sync::mpsc; +use uuid::Uuid; + +use super::group_state_postgres_tests::{create_channel, http_auth, test_conn}; +use crate::connection::ConnectionState; +use crate::handlers::ingest::ingest_event; +use crate::state::AppState; + +struct Fixture { + state: Arc, + tenant: TenantContext, +} + +async fn fixture() -> Fixture { + let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres and Redis"); + let host = format!("artifact-sync-{}.local", Uuid::new_v4().simple()); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community") + .id; + state + .db + .maintain_partitions( + 1, + buzz_db::partition::PartitionMaintenancePolicy { + create_enabled: true, + advance_enabled: false, + }, + ) + .await + .expect("partitions"); + // The real Redis link: rule 1 waits for it to confirm live interest. + tokio::spawn(Arc::clone(&state.pubsub).run_subscriber()); + state + .pubsub + .link_state() + .wait_for(|link| link.up) + .await + .expect("link up"); + Fixture { + state, + tenant: TenantContext::resolved(community, &host), + } +} + +async fn ingest(f: &Fixture, keys: &Keys, event: Event) { + let kind = event.kind.as_u16(); + let result = ingest_event(&f.state, &f.tenant, event, http_auth(keys)) + .await + .unwrap_or_else(|error| panic!("ingest kind:{kind}: {error:?}")); + assert!(result.accepted, "kind:{kind} refused: {}", result.message); +} + +/// Accept one `buzz.task` revision and return it. +async fn revision( + f: &Fixture, + keys: &Keys, + home: Uuid, + d: Uuid, + op: &str, + prev: Option<&Event>, +) -> Event { + typed_revision(f, keys, home, d, "buzz.task", op, prev).await +} + +/// Accept one artifact revision of type `ty` and return it. +async fn typed_revision( + f: &Fixture, + keys: &Keys, + home: Uuid, + d: Uuid, + ty: &str, + op: &str, + prev: Option<&Event>, +) -> Event { + let mut tags = vec![ + vec!["ar".to_owned(), "1".into()], + vec!["d".into(), d.to_string()], + vec!["h".into(), home.to_string()], + vec!["type".into(), ty.into()], + vec!["op".into(), op.into()], + ]; + if op != "delete" { + tags.push(vec!["title".into(), "Sync task".into()]); + } + if let Some(prev) = prev { + tags.push(vec!["prev".into(), prev.id.to_hex()]); + } + let event = EventBuilder::new( + Kind::Custom(45010), + if op == "delete" { "" } else { "body" }, + ) + .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) + .sign_with_keys(keys) + .unwrap(); + ingest(f, keys, event.clone()).await; + event +} + +async fn membership(f: &Fixture, owner: &Keys, kind: u16, channel: Uuid, member: &Keys) { + let event = EventBuilder::new(Kind::Custom(kind), "") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["p", &member.public_key().to_hex()]).unwrap(), + ]) + .sign_with_keys(owner) + .unwrap(); + ingest(f, owner, event).await; +} + +/// A connection for `reader`, registered so fan-out can reach it. +fn connect(f: &Fixture, reader: &Keys) -> (Arc, mpsc::Receiver) { + let (conn, rx) = test_conn(&f.tenant, reader); + f.state.conn_manager.register( + conn.conn_id, + conn.send_tx.clone(), + conn.ctrl_tx.clone(), + mpsc::channel(1).0, + None, + conn.cancel.clone(), + conn.tenant.community(), + Arc::clone(&conn.backpressure_count), + Arc::clone(&conn.subscriptions), + 3, + crate::state::CommunityConnectionControl::new(conn.cancel.clone()), + ); + (conn, rx) +} + +fn start_sync( + f: &Fixture, + conn: &Arc, + filter: Value, +) -> tokio::task::JoinHandle<()> { + let filter = buzz_core::artifact_sync::parse_sync(&filter); + let permit = f + .state + .handler_semaphore + .clone() + .try_acquire_owned() + .expect("permit"); + let (conn, state) = (Arc::clone(conn), Arc::clone(&f.state)); + tokio::spawn(async move { + let owner = super::close::admit("s", &conn).await.expect("admit"); + super::artifact_sync::handle_sync("s".into(), owner, filter, conn, state, permit).await; + }) +} + +async fn frame(rx: &mut mpsc::Receiver) -> Value { + loop { + let message = tokio::time::timeout(Duration::from_secs(10), rx.recv()) + .await + .expect("relay frame in time") + .expect("connection open"); + if let WsMessage::Text(text) = message { + return serde_json::from_str(&text).expect("json frame"); + } + } +} + +/// Collect the initial set up to `EOSE`; panics on any other terminal frame. +async fn initial_set(rx: &mut mpsc::Receiver) -> Vec { + let mut ids = vec![]; + loop { + let message = frame(rx).await; + match message[0].as_str() { + Some("EVENT") => ids.push(message[2]["id"].as_str().unwrap().to_owned()), + Some("EOSE") => return ids, + _ => panic!("unexpected frame before EOSE: {message}"), + } + } +} + +async fn no_frame(rx: &mut mpsc::Receiver) { + if let Ok(Some(message)) = tokio::time::timeout(Duration::from_millis(300), rx.recv()).await { + panic!("unexpected frame: {message:?}"); + } +} + +const PRIVATE: &[&[&str]] = &[&["visibility", "private"]]; + +fn sync_filter(channels: &[Uuid]) -> Value { + json!({"artifact": "current", "#h": channels, "#type": ["buzz.task"]}) +} + +/// Accept one `buzz.task` revision with a `status` tag and return it. +async fn status_revision( + f: &Fixture, + keys: &Keys, + home: Uuid, + d: Uuid, + status: &str, + prev: Option<&Event>, +) -> Event { + let op = if prev.is_some() { "update" } else { "create" }; + let mut tags = vec![ + vec!["ar".to_owned(), "1".into()], + vec!["d".into(), d.to_string()], + vec!["h".into(), home.to_string()], + vec!["type".into(), "buzz.task".into()], + vec!["op".into(), op.into()], + vec!["title".into(), "Sync task".into()], + vec!["status".into(), status.into()], + ]; + if let Some(prev) = prev { + tags.push(vec!["prev".into(), prev.id.to_hex()]); + } + let event = EventBuilder::new(Kind::Custom(45010), "body") + .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) + .sign_with_keys(keys) + .unwrap(); + ingest(f, keys, event.clone()).await; + event +} + +async fn live_event(rx: &mut mpsc::Receiver) -> String { + let message = frame(rx).await; + assert_eq!(message[0].as_str(), Some("EVENT"), "{message}"); + message[2]["id"].as_str().unwrap().to_owned() +} + +/// Rule 3 with a mutable predicate: a live head goes out only for an +/// artifact in scope before the change (in the client's copy) or after it. +/// A head that never matched never crosses the socket; one that stops +/// matching is sent once, so the client can drop it. Mutation: send every +/// same-type head (the old `never_in_scope` check) → the `done` task is +/// sent → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn live_heads_follow_every_predicate() { + let f = fixture().await; + let owner = Keys::generate(); + let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let open = status_revision(&f, &owner, home, Uuid::new_v4(), "open", None).await; + + let (conn, mut rx) = connect(&f, &owner); + let filter = + json!({"artifact": "current", "#h": [home], "#type": ["buzz.task"], "#status": ["open"]}); + let task = start_sync(&f, &conn, filter); + assert_eq!(initial_set(&mut rx).await, vec![open.id.to_hex()]); + + // Never in scope: not sent. + let other = Uuid::new_v4(); + let done = status_revision(&f, &owner, home, other, "done", None).await; + no_frame(&mut rx).await; + // Leaves the set: sent once. + let d = open + .tags + .iter() + .find_map(|t| match t.as_slice() { + [name, value, ..] if name == "d" => value.parse().ok(), + _ => None, + }) + .unwrap(); + let closed = status_revision(&f, &owner, home, d, "done", Some(&open)).await; + assert_eq!(live_event(&mut rx).await, closed.id.to_hex()); + let again = status_revision(&f, &owner, home, d, "done", Some(&closed)).await; + no_frame(&mut rx).await; + // Enters the set: sent. + let reopened = status_revision(&f, &owner, home, other, "open", Some(&done)).await; + assert_eq!(live_event(&mut rx).await, reopened.id.to_hex()); + let back = status_revision(&f, &owner, home, d, "open", Some(&again)).await; + assert_eq!(live_event(&mut rx).await, back.id.to_hex()); + + super::close::handle_close("s".into(), Arc::clone(&conn), Arc::clone(&f.state)).await; + assert_eq!(frame(&mut rx).await, json!(["CLOSED", "s", ""])); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("sync task ends on CLOSE") + .unwrap(); +} + +/// Rules 2–4 over the real pipeline: the initial set in `d` order, `EOSE`, +/// then the current head of each later change (including a deletion), and +/// no live entry ever arrives as the published event before `EOSE`. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn sync_sends_one_cut_then_current_heads() { + let f = fixture().await; + let owner = Keys::generate(); + let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let mut ds = [Uuid::new_v4(), Uuid::new_v4()]; + ds.sort(); + let first = revision(&f, &owner, home, ds[0], "create", None).await; + let second = revision(&f, &owner, home, ds[1], "create", None).await; + + let (conn, mut rx) = connect(&f, &owner); + let task = start_sync(&f, &conn, sync_filter(&[home])); + assert_eq!( + initial_set(&mut rx).await, + vec![first.id.to_hex(), second.id.to_hex()] + ); + + let updated = revision(&f, &owner, home, ds[0], "update", Some(&first)).await; + let message = frame(&mut rx).await; + assert_eq!( + (message[0].as_str(), message[2]["id"].as_str()), + (Some("EVENT"), Some(updated.id.to_hex().as_str())) + ); + let deleted = revision(&f, &owner, home, ds[1], "delete", Some(&second)).await; + let message = frame(&mut rx).await; + assert_eq!( + (message[0].as_str(), message[2]["id"].as_str()), + (Some("EVENT"), Some(deleted.id.to_hex().as_str())) + ); + // An artifact of another type in the same channel is never in scope. + typed_revision( + &f, + &owner, + home, + Uuid::new_v4(), + "buzz.note", + "create", + None, + ) + .await; + no_frame(&mut rx).await; + // An ordinary chat message in the channel is not a change. + let chat = EventBuilder::new(Kind::Custom(9), "hi") + .tags([Tag::parse(["h", &home.to_string()]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + ingest(&f, &owner, chat).await; + no_frame(&mut rx).await; + + super::close::handle_close("s".into(), Arc::clone(&conn), Arc::clone(&f.state)).await; + assert_eq!(frame(&mut rx).await, json!(["CLOSED", "s", ""])); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("sync task ends on CLOSE") + .unwrap(); + assert!(!f.state.artifact_syncs.contains(conn.conn_id, "s")); +} + +/// Rule 9: losing access to one named channel ends the whole sync with a +/// resync, and leaves no fan-out entry for its other channel. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn membership_removal_resyncs_the_whole_sync() { + let f = fixture().await; + let owner = Keys::generate(); + let reader = Keys::generate(); + let shared = create_channel(&f.state, &f.tenant, &owner, PRIVATE).await; + membership(&f, &owner, 9000, shared, &reader).await; + let own = create_channel(&f.state, &f.tenant, &reader, &[]).await; + + let (conn, mut rx) = connect(&f, &reader); + let task = start_sync(&f, &conn, sync_filter(&[shared, own])); + assert!(initial_set(&mut rx).await.is_empty()); + + membership(&f, &owner, 9001, shared, &reader).await; + let message = frame(&mut rx).await; + assert_eq!(message[0], "CLOSED", "{message}"); + assert!( + message[2].as_str().unwrap().starts_with("resync: "), + "{message}" + ); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("sync task ends") + .unwrap(); + no_frame(&mut rx).await; + assert!(!f.state.artifact_syncs.contains(conn.conn_id, "s")); + assert!(f + .state + .sub_registry + .channel_subscriber_conns_scoped(f.tenant.community(), own) + .is_empty()); +} + +/// Rule 3 under a channel-scoped token: the token bounds what the reader +/// can read, so a move to a channel outside it sends the source removal, +/// never the destination head, even though the pubkey can read that +/// channel. Mutation: drop the token bound on the live head read → the +/// moved head is sent → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn scoped_token_gets_only_the_removal_for_a_move_outside_it() { + let f = fixture().await; + let owner = Keys::generate(); + let source = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let destination = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let d = Uuid::new_v4(); + let created = revision(&f, &owner, source, d, "create", None).await; + + let (conn, mut rx) = connect(&f, &owner); + match &mut *conn.auth_state.lock().unwrap() { + crate::connection::AuthState::Authenticated(ctx) => { + ctx.channel_ids = Some(vec![source]); + } + _ => unreachable!("test connections are authenticated"), + } + let task = start_sync(&f, &conn, sync_filter(&[source])); + assert_eq!(initial_set(&mut rx).await, vec![created.id.to_hex()]); + + let moved = revision(&f, &owner, destination, d, "move", Some(&created)).await; + let message = frame(&mut rx).await; + assert_eq!( + (message[0].as_str(), message[2]["kind"].as_u64()), + (Some("EVENT"), Some(45011)), + "{message}" + ); + assert_ne!(message[2]["id"].as_str(), Some(moved.id.to_hex().as_str())); + no_frame(&mut rx).await; + + super::close::handle_close("s".into(), Arc::clone(&conn), Arc::clone(&f.state)).await; + assert_eq!(frame(&mut rx).await, json!(["CLOSED", "s", ""])); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("sync task ends on CLOSE") + .unwrap(); +} + +/// Rule 2: an unreadable or unknown channel gets `CLOSED restricted` and +/// no `EOSE`, with the same reason for both. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn unreadable_channel_is_restricted_without_eose() { + let f = fixture().await; + let owner = Keys::generate(); + let private = create_channel(&f.state, &f.tenant, &owner, PRIVATE).await; + let stranger = Keys::generate(); + for channel in [private, Uuid::new_v4()] { + let (conn, mut rx) = connect(&f, &stranger); + start_sync(&f, &conn, sync_filter(&[channel])) + .await + .unwrap(); + assert_eq!( + frame(&mut rx).await, + json!(["CLOSED", "s", "restricted: channel not readable"]) + ); + no_frame(&mut rx).await; + assert!(!f.state.artifact_syncs.contains(conn.conn_id, "s")); + } +} + +/// Rule 5: a node-wide loss (fan-out lag or a link epoch change) ends a live +/// sync with a resync. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn node_loss_resyncs_a_live_sync() { + let f = fixture().await; + let owner = Keys::generate(); + let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let (conn, mut rx) = connect(&f, &owner); + let task = start_sync(&f, &conn, sync_filter(&[home])); + assert!(initial_set(&mut rx).await.is_empty()); + f.state + .artifact_syncs + .resync_all("resync: live delivery lagged"); + assert_eq!( + frame(&mut rx).await, + json!(["CLOSED", "s", "resync: live delivery lagged"]) + ); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("sync task ends") + .unwrap(); + assert!(!f.state.artifact_syncs.contains(conn.conn_id, "s")); +} + +/// A CLOSE while a live head read is in flight retires the sync: the head +/// it read is never sent under the closed ID. Mutation: drop the owner +/// check in `try_send_owned` → the EVENT follows `CLOSED` → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn close_during_a_live_head_read_sends_nothing_more() { + let f = fixture().await; + let owner = Keys::generate(); + let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let d = Uuid::new_v4(); + let first = revision(&f, &owner, home, d, "create", None).await; + + let (conn, mut rx) = connect(&f, &owner); + let filter = buzz_core::artifact_sync::parse_sync(&sync_filter(&[home])); + let permit = f + .state + .handler_semaphore + .clone() + .try_acquire_owned() + .expect("permit"); + let pause = Arc::new(super::close::test_seam::Pause::default()); + let token = super::close::admit("s", &conn).await.expect("admit"); + let task = tokio::spawn(super::artifact_sync::test_seam::LIVE_SEND_PAUSE.scope( + Arc::clone(&pause), + super::artifact_sync::handle_sync( + "s".into(), + token, + filter, + Arc::clone(&conn), + Arc::clone(&f.state), + permit, + ), + )); + assert_eq!(initial_set(&mut rx).await, vec![first.id.to_hex()]); + + revision(&f, &owner, home, d, "update", Some(&first)).await; + tokio::time::timeout(Duration::from_secs(10), pause.reached.notified()) + .await + .expect("live head read reached"); + super::close::handle_close("s".into(), Arc::clone(&conn), Arc::clone(&f.state)).await; + assert_eq!(frame(&mut rx).await, json!(["CLOSED", "s", ""])); + pause.resume.notify_one(); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("sync task ends") + .unwrap(); + no_frame(&mut rx).await; +} + +/// Run an ordinary `REQ "s"` through the real handler. +async fn ordinary_req(f: &Fixture, conn: &Arc, filters: Vec) { + let filters: Vec = filters + .into_iter() + .map(|filter| serde_json::from_value(filter).expect("filter")) + .collect(); + let before_ids = vec![None; filters.len()]; + super::req::handle_req( + "s".into(), + filters, + before_ids, + Arc::clone(conn), + Arc::clone(&f.state), + ) + .await; +} + +/// An ordinary `REQ` that replaces a live sync or a live subscription with +/// the same ID retires it, also when `handle_req` refuses the new request +/// (mixed search) or answers it once (huddle liveness) without registering +/// it. A later change in the channel then sends nothing under that ID. +/// Mutation: refuse mixed search with a bare `CLOSED`, or answer liveness +/// without claiming the ID → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn refused_or_one_shot_replacement_retires_the_old_holder() { + let f = fixture().await; + let owner = Keys::generate(); + let mixed: fn(Uuid) -> Vec = |home| { + vec![ + json!({"search": "x", "#h": [home]}), + json!({"kinds": [45010], "#h": [home]}), + ] + }; + let liveness: fn(Uuid) -> Vec = + |home| vec![json!({"kinds": [buzz_core::kind::KIND_HUDDLE_LIVENESS], "#h": [home]})]; + for (sync_holder, replacement, terminal) in [ + ( + true, + mixed, + json!([ + "CLOSED", + "s", + "error: mixed search and non-search filters not supported" + ]), + ), + ( + false, + mixed, + json!([ + "CLOSED", + "s", + "error: mixed search and non-search filters not supported" + ]), + ), + (true, liveness, json!(["EOSE", "s"])), + (false, liveness, json!(["EOSE", "s"])), + ] { + let case = format!("sync holder: {sync_holder}, replacement: {terminal}"); + let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let (conn, mut rx) = connect(&f, &owner); + let sync = if sync_holder { + Some(start_sync(&f, &conn, sync_filter(&[home]))) + } else { + ordinary_req( + &f, + &conn, + vec![json!({"kinds": [45010], "#h": [home], "limit": 0})], + ) + .await; + None + }; + assert!(initial_set(&mut rx).await.is_empty(), "{case}"); + + ordinary_req(&f, &conn, replacement(home)).await; + assert_eq!(frame(&mut rx).await, terminal, "{case}"); + if let Some(sync) = sync { + tokio::time::timeout(Duration::from_secs(5), sync) + .await + .expect("the replaced sync ends") + .unwrap(); + } + assert!(conn.subscriptions.lock().await.is_empty(), "{case}"); + assert!( + !f.state.artifact_syncs.contains(conn.conn_id, "s"), + "{case}" + ); + assert!( + f.state + .sub_registry + .get_filters(conn.conn_id, "s") + .is_none(), + "{case}" + ); + + revision(&f, &owner, home, Uuid::new_v4(), "create", None).await; + no_frame(&mut rx).await; + } +} + +/// A same-ID sync that replaces a history, search or huddle-liveness `REQ` +/// while that request waits to send gets only its own frames: the old +/// request's late frames, `EOSE` included, must not reach the sync's +/// client. The old request pauses just before its first frame. +/// Mutation: drop the owner check in `close::send_if_owner` → stale frames +/// follow the sync's `EOSE` → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_replaced_req_sends_nothing_under_a_sync_that_took_its_id() { + use super::close::test_seam::{Pause, SEND_PAUSE}; + let f = fixture().await; + let owner = Keys::generate(); + let history: fn(Uuid) -> Vec = |home| vec![json!({"kinds": [45010], "#h": [home]})]; + let search: fn(Uuid) -> Vec = |home| vec![json!({"search": "x", "#h": [home]})]; + let liveness: fn(Uuid) -> Vec = + |home| vec![json!({"kinds": [buzz_core::kind::KIND_HUDDLE_LIVENESS], "#h": [home]})]; + for (name, old_req) in [ + ("history", history), + ("search", search), + ("liveness", liveness), + ] { + let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let created = revision(&f, &owner, home, Uuid::new_v4(), "create", None).await; + let (conn, mut rx) = connect(&f, &owner); + let pause = Arc::new(Pause::default()); + let stale = tokio::spawn({ + let (f_conn, state) = (Arc::clone(&conn), Arc::clone(&f.state)); + let filters: Vec = old_req(home) + .into_iter() + .map(|filter| serde_json::from_value(filter).expect("filter")) + .collect(); + let before_ids = vec![None; filters.len()]; + SEND_PAUSE.scope( + Arc::clone(&pause), + super::req::handle_req("s".into(), filters, before_ids, f_conn, state), + ) + }); + tokio::time::timeout(Duration::from_secs(10), pause.reached.notified()) + .await + .unwrap_or_else(|_| panic!("{name}: the old REQ reaches its first send")); + + let sync = start_sync(&f, &conn, sync_filter(&[home])); + assert_eq!( + initial_set(&mut rx).await, + vec![created.id.to_hex()], + "{name}" + ); + // The seam pauses before every send; release each one. + tokio::time::timeout(Duration::from_secs(10), async { + while !stale.is_finished() { + pause.resume.notify_one(); + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("{name}: the old REQ ends")); + stale.await.unwrap(); + no_frame(&mut rx).await; + assert!( + f.state.artifact_syncs.contains(conn.conn_id, "s"), + "{name}: the sync still holds the ID" + ); + super::close::handle_close("s".into(), Arc::clone(&conn), Arc::clone(&f.state)).await; + tokio::time::timeout(Duration::from_secs(5), sync) + .await + .expect("sync task ends on CLOSE") + .unwrap(); + } +} diff --git a/crates/buzz-relay/src/handlers/auth.rs b/crates/buzz-relay/src/handlers/auth.rs index 474edf227a0..ecbc7d9e0d0 100644 --- a/crates/buzz-relay/src/handlers/auth.rs +++ b/crates/buzz-relay/src/handlers/auth.rs @@ -12,8 +12,9 @@ use std::sync::Arc; use axum::extract::ws::Message as WsMessage; -use tracing::{debug, info, warn}; +use tracing::{debug, warn}; +use crate::access::{AuthAttempt, AuthResult}; use crate::connection::{AuthState, ConnectionState}; use crate::metrics::{AuthOutcome, AuthPostTerminalState}; use crate::protocol::RelayMessage; @@ -63,10 +64,12 @@ fn classify_relay_membership( /// on the principal blocks it directly; if the principal is clear, a ban on /// its proven owner (extracted from the self-proving auth tag) blocks it too. /// -/// `cached` reads the restriction rows through the 30-second ephemeral-path -/// cache ([`AppState::restriction_state_cached`]); only per-pulse ephemeral -/// traffic sets it. Socket auth and every other HTTP request read fresh. -pub(crate) async fn community_ban_outcome( +/// `cached` reads the restriction rows through +/// [`AppState::restriction_state_cached`], for per-request gates whose grant +/// ends with the request (HTTP requests, ephemeral pulses). Socket admission +/// reads fresh: an admitted socket outlives the cache's staleness bound. +/// Returns the outcome with the row that decided it. +pub(crate) async fn community_ban_verdict( state: &AppState, community: buzz_core::CommunityId, pubkey: nostr::PublicKey, @@ -74,10 +77,18 @@ pub(crate) async fn community_ban_outcome( signed_auth_created_at: Option, token_owner: Option, cached: bool, -) -> BanOutcome { - let outcome = principal_ban_outcome(state, community, &pubkey, cached).await; - if outcome != BanOutcome::Clear { - return outcome; +) -> BanVerdict { + let verdict = principal_ban_verdict(state, community, &pubkey, cached).await; + // A failed read leaves a token owner unchecked too: the refusal is that + // owner's unavailable ban state, as shadow's owner read would record. + if verdict.outcome == BanOutcome::DbError && token_owner.is_some() { + return BanVerdict { + source: BanSource::Owner, + ..verdict + }; + } + if verdict.outcome != BanOutcome::Clear { + return verdict; } // A NIP-FI agent assertion's verified owner cascades unconditionally, // whether the agent is a member itself or admitted through that owner. @@ -89,18 +100,76 @@ pub(crate) async fn community_ban_outcome( ) }); match owner { - Some(owner) => principal_ban_outcome(state, community, &owner, cached).await, - None => BanOutcome::Clear, + Some(owner) => BanVerdict { + outcome: principal_ban_outcome(state, community, &owner, cached).await, + source: BanSource::Owner, + }, + None => verdict, + } +} + +/// Whose ban row decided a [`BanOutcome`]: the key's own, or an owner's +/// (its stored agent owner, or the NIP-OA or token owner checked after it). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BanSource { + /// The key's own row. + Own, + /// Its owner's row. + Owner, +} + +impl BanSource { + /// Whose row decided a banned restriction snapshot. + pub(crate) fn of(restriction: &buzz_db::moderation::RestrictionState) -> Self { + if restriction.own_banned { + Self::Own + } else { + Self::Owner + } + } +} + +/// A ban decision with the row that decided it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct BanVerdict { + pub(crate) outcome: BanOutcome, + pub(crate) source: BanSource, +} + +impl BanVerdict { + pub(crate) const CLEAR: Self = Self { + outcome: BanOutcome::Clear, + source: BanSource::Own, + }; + + /// Shadow's `owner` reason when an owner's row decided the refusal. + pub(crate) fn owner_reason(self) -> Option<&'static str> { + match (self.source, self.outcome) { + (BanSource::Owner, BanOutcome::Banned) => Some("owner_banned"), + (BanSource::Owner, BanOutcome::DbError) => Some("owner_ban_unavailable"), + _ => None, + } } } -/// Ban verdict for one key, without any owner cascade. +/// Ban verdict for one key: its own row and its stored agent owner's. async fn principal_ban_outcome( state: &AppState, community: buzz_core::CommunityId, key: &nostr::PublicKey, cached: bool, ) -> BanOutcome { + principal_ban_verdict(state, community, key, cached) + .await + .outcome +} + +async fn principal_ban_verdict( + state: &AppState, + community: buzz_core::CommunityId, + key: &nostr::PublicKey, + cached: bool, +) -> BanVerdict { let restriction = if cached { state .restriction_state_cached(community, key.as_bytes()) @@ -111,14 +180,16 @@ async fn principal_ban_outcome( .moderation_restriction_state(community, key.as_bytes()) .await }; - match restriction { - Ok(restriction) if restriction.banned => BanOutcome::Banned, - Ok(_) => BanOutcome::Clear, + let (outcome, source) = match restriction { + Ok(r) if r.banned && !r.own_banned => (BanOutcome::Banned, BanSource::Owner), + Ok(r) if r.banned => (BanOutcome::Banned, BanSource::Own), + Ok(_) => (BanOutcome::Clear, BanSource::Own), Err(e) => { warn!(pubkey = %key.to_hex(), error = %e, "ban-state DB lookup failed, denying (fail-closed)"); - BanOutcome::DbError + (BanOutcome::DbError, BanSource::Own) } - } + }; + BanVerdict { outcome, source } } /// Shadow only: the refusal enforce's token-owner rules would give `agent`, @@ -130,16 +201,56 @@ pub(crate) async fn token_owner_denial( community: buzz_core::CommunityId, agent: nostr::PublicKey, owner: nostr::PublicKey, -) -> Option { +) -> Option<(buzz_auth::DenialClass, &'static str)> { let ban = principal_ban_outcome(state, community, &owner, false).await; if let Some(denial) = ban_admission_denial(ban) { - return Some(denial.class); + let reason = match ban { + BanOutcome::Banned => "owner_banned", + _ => "owner_ban_unavailable", + }; + return Some((denial.class, reason)); } // No stored owner yet: enforce would link this one. let link = crate::api::relay_members::stored_owner_link(state, community, &agent, &owner) .await .unwrap_or(crate::api::relay_members::OwnerLink::Linked); - owner_link_denial(link, true).map(|denial| denial.class) + let reason = match link { + crate::api::relay_members::OwnerLink::Conflict => "not_stored_owner", + _ => "owner_link_unavailable", + }; + owner_link_denial(link, true).map(|denial| (denial.class, reason)) +} + +/// Enforce's `owner` refusal of an agent assertion's key, when `denial` was +/// decided by its owner: the owner's ban or the owner link. +pub(crate) fn owner_refusal( + denial: &AdmissionDenial, + assertion: Option<&buzz_auth::VerifiedAssertion>, +) -> Option { + let assertion = assertion.filter(|a| a.owner().is_some())?; + let deny = crate::nip_fi_shadow::WouldDeny::new( + crate::nip_fi_shadow::Stage::Owner, + denial.class, + denial.owner_reason?, + ); + Some(deny.by(assertion.asserted_key())) +} + +/// Claim enforce's verdict for a refused socket before its frames are +/// awaited: an owner-decided refusal of an agent assertion is recorded with +/// shadow's `owner` reason; any other refusal retires the session unrecorded. +pub(crate) fn record_enforce_refusal( + control: &crate::state::CommunityConnectionControl, + denial: Option<&AdmissionDenial>, + assertion: Option<&buzz_auth::VerifiedAssertion>, +) { + let Some(session) = control.nip_fi_enforce() else { + return; + }; + match denial.and_then(|d| owner_refusal(d, assertion)) { + Some(deny) => session.deny(deny), + None => session.retire(), + } } fn ban_denial(outcome: BanOutcome) -> Option<(&'static str, &'static str, AuthOutcome)> { @@ -164,6 +275,17 @@ pub(crate) struct AdmissionDenial { pub(crate) reason: &'static str, pub(crate) outcome: AuthOutcome, pub(crate) class: buzz_auth::DenialClass, + /// Shadow's `owner` reason when an agent's owner decided the refusal. + pub(crate) owner_reason: Option<&'static str>, +} + +/// [`ban_admission_denial`] carrying the deciding owner, if any. +pub(crate) fn ban_verdict_denial(verdict: BanVerdict) -> Option { + let denial = ban_admission_denial(verdict.outcome)?; + Some(AdmissionDenial { + owner_reason: verdict.owner_reason(), + ..denial + }) } /// The refusal for a ban outcome other than [`BanOutcome::Clear`]. @@ -178,6 +300,7 @@ pub(crate) fn ban_admission_denial(ban: BanOutcome) -> Option { reason, outcome, class, + owner_reason: None, }) } @@ -197,7 +320,7 @@ pub(crate) async fn final_admission_denial( signed_auth_created_at: Option, token_owner: Option, ) -> Option { - let ban = community_ban_outcome( + let ban = community_ban_verdict( state, community, pubkey, @@ -207,7 +330,7 @@ pub(crate) async fn final_admission_denial( false, ) .await; - if let Some(denial) = ban_admission_denial(ban) { + if let Some(denial) = ban_verdict_denial(ban) { return Some(denial); } match crate::api::relay_members::check_relay_membership_authoritative( @@ -225,6 +348,7 @@ pub(crate) async fn final_admission_denial( reason: "restricted: not a relay member", outcome: AuthOutcome::NotRelayMember, class: buzz_auth::DenialClass::AuthorizationDenied, + owner_reason: None, }), Ok(_) => None, Err(e) => { @@ -234,6 +358,7 @@ pub(crate) async fn final_admission_denial( reason: "error: internal error checking relay membership", outcome: AuthOutcome::RelayMembershipCheckError, class: buzz_auth::DenialClass::AuthorizationUnavailable, + owner_reason: None, }) } } @@ -271,6 +396,7 @@ pub(crate) async fn admitted_owner( reason: OWNER_LINK_ERROR, outcome: AuthOutcome::RelayMembershipCheckError, class: buzz_auth::DenialClass::AuthorizationUnavailable, + owner_reason: None, }) } } @@ -295,12 +421,14 @@ pub(crate) fn owner_link_denial( reason: crate::api::relay_members::OWNER_MISMATCH, outcome: AuthOutcome::NotRelayMember, class: buzz_auth::DenialClass::AuthorizationDenied, + owner_reason: Some("not_stored_owner"), }), OwnerLink::Conflict | OwnerLink::Unavailable => Some(AdmissionDenial { metric: "agent_owner_link_error", reason: OWNER_LINK_ERROR, outcome: AuthOutcome::RelayMembershipCheckError, class: buzz_auth::DenialClass::AuthorizationUnavailable, + owner_reason: token_owner.then_some("owner_link_unavailable"), }), } } @@ -341,9 +469,19 @@ fn deny_nip_fi_auth(conn: &ConnectionState, class: buzz_auth::DenialClass) { /// Refuse a root AUTH that passed the early gates but failed admission: record /// the outcome, send the denial (the canonical NOTICE under NIP-FI, else an /// OK false on the control channel so it drains before the Close), and close. -fn deny_admission(conn: &ConnectionState, event_id_hex: &str, denial: AdmissionDenial) { +fn deny_admission( + conn: &ConnectionState, + attempt: &AuthAttempt<'_>, + event_id_hex: &str, + denial: AdmissionDenial, +) { + record_enforce_refusal( + &conn.community_control, + Some(&denial), + conn.nip_fi_assertion.as_ref(), + ); metrics::counter!("buzz_auth_failures_total", "reason" => denial.metric).increment(1); - if !conn.reject_auth(denial.outcome) { + if !attempt.reject(conn, denial.outcome) { return; } if conn.nip_fi_assertion.is_some() { @@ -373,6 +511,10 @@ pub fn extract_auth_tag_json(event: &nostr::Event) -> Option { serde_json::to_string(first.as_slice()).ok() } +/// How long a verified AUTH waits for an [`AppState::auth_gate`] permit before +/// it is shed. Well inside every client's own AUTH timeout. +const AUTH_PERMIT_WAIT: std::time::Duration = std::time::Duration::from_secs(2); + /// Handle a NIP-42 AUTH message: verify the challenge response and transition /// the connection to authenticated state. /// @@ -385,6 +527,10 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: AuthState::Pending { challenge, .. } => (challenge, conn.conn_id), AuthState::Authenticated(_) => { debug!(conn_id = %conn.conn_id, "AUTH received but already authenticated"); + AuthAttempt::nip42(&conn, event.pubkey, false).log_after_decision( + &conn, + AuthResult::Denied(crate::access::AuthReason::AlreadyAuthenticated), + ); crate::metrics::record_post_terminal_auth_frame( AuthPostTerminalState::Authenticated, ); @@ -397,6 +543,10 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: } AuthState::Failed => { debug!(conn_id = %conn.conn_id, "AUTH received after failed auth"); + AuthAttempt::nip42(&conn, event.pubkey, false).log_after_decision( + &conn, + AuthResult::Denied(crate::access::AuthReason::AlreadyFailed), + ); crate::metrics::record_post_terminal_auth_frame(AuthPostTerminalState::Failed); conn.send(RelayMessage::ok( &event_id_hex, @@ -417,14 +567,14 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: // The tag is integrity-protected by the event's Schnorr signature — if // tampered, NIP-42 verification will fail before we ever inspect it. let auth_tag_json = extract_auth_tag_json(&event); + let claimed_pubkey = event.pubkey; let signed_auth_created_at = event.created_at.as_secs(); let relay_url = crate::api::bridge::nip42_expected_relay_url(&state.config.relay_url, &conn.tenant); let auth_svc = Arc::clone(&state.auth); - let _shadow_attempt = - crate::nip_fi_shadow_session::AuthAttempt(conn.community_control.nip_fi_shadow()); + let _shadow_attempt = crate::nip_fi_shadow_session::AuthAttempt::new(&conn.community_control); // Pure NIP-42 verification — crypto only, no DB lookups. match auth_svc .verify_auth_event(event, &challenge, &relay_url) @@ -432,7 +582,23 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: { Ok(mut auth_ctx) => { let pubkey = auth_ctx.pubkey; + let attempt = AuthAttempt::nip42(&conn, pubkey, true); + // Concurrency cap (`buzz.relay.concurrency.auth`, unbounded unless set). + // The signature is proven, so only real logins queue for the + // database checks below, and the permit is held through them. A + // shed login gets a bare close, as an auth timeout does: clients + // reconnect from that on their jittered backoff, while an `OK + // false` parks some clients and retries others in lockstep. + let Some(_concurrency_permit) = state.auth_gate.admit(AUTH_PERMIT_WAIT).await else { + metrics::counter!("buzz_auth_failures_total", "reason" => "concurrency_limit") + .increment(1); + if attempt.reject(&conn, AuthOutcome::ConcurrencyLimit) { + conn.cancel.cancel(); + } + return; + }; + conn.community_control.prove_nip_fi_line(pubkey); let shadow = conn.community_control.nip_fi_shadow(); if let Some(shadow) = shadow { shadow.observe_pairing(pubkey); @@ -482,7 +648,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: // pinning `Failed` for the connection's life on a false premise. // `Banned` claims the ban; `DbError` denies with `error: internal` // (mirrors the ingest write-path gate). - let outcome = community_ban_outcome( + let verdict = community_ban_verdict( &state, conn.tenant.community(), pubkey, @@ -492,12 +658,17 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: false, ) .await; + let outcome = verdict.outcome; if let Some((metric_reason, deny_reason, auth_outcome)) = ban_denial(outcome) { - warn!(conn_id = %conn_id, pubkey = %pubkey.to_hex(), reason = deny_reason, "principal denied at ban seam"); + record_enforce_refusal( + &conn.community_control, + ban_verdict_denial(verdict).as_ref(), + conn.nip_fi_assertion.as_ref(), + ); metrics::counter!("buzz_auth_failures_total", "reason" => metric_reason) .increment(1); - if !conn.reject_auth(auth_outcome) { + if !attempt.reject(&conn, auth_outcome) { return; } // Decision 4: banned ⇒ OK false + immediate WebSocket close. @@ -540,10 +711,9 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: match classify_allowlist(allowlist) { PolicyCheck::Allowed(()) => {} PolicyCheck::Denied => { - warn!(conn_id = %conn_id, pubkey = %pubkey.to_hex(), "pubkey not in allowlist"); metrics::counter!("buzz_auth_failures_total", "reason" => "allowlist_denied") .increment(1); - if !conn.reject_auth(AuthOutcome::AllowlistDenied) { + if !attempt.reject(&conn, AuthOutcome::AllowlistDenied) { return; } // Fix 4a: when an FI assertion is present, use the uniform @@ -565,7 +735,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: PolicyCheck::DependencyError => { metrics::counter!("buzz_auth_failures_total", "reason" => "allowlist_check_error") .increment(1); - if !conn.reject_auth(AuthOutcome::AllowlistCheckError) { + if !attempt.reject(&conn, AuthOutcome::AllowlistCheckError) { return; } if conn.nip_fi_assertion.is_some() { @@ -602,10 +772,9 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: let nip_oa_owner = match classify_relay_membership(membership) { PolicyCheck::Allowed(owner) => owner, PolicyCheck::Denied => { - warn!(conn_id = %conn_id, pubkey = %pubkey.to_hex(), "not a relay member"); metrics::counter!("buzz_auth_failures_total", "reason" => "not_relay_member") .increment(1); - if !conn.reject_auth(AuthOutcome::NotRelayMember) { + if !attempt.reject(&conn, AuthOutcome::NotRelayMember) { return; } // With an FI assertion, membership status must not be @@ -624,7 +793,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: PolicyCheck::DependencyError => { metrics::counter!("buzz_auth_failures_total", "reason" => "relay_membership_check_error") .increment(1); - if !conn.reject_auth(AuthOutcome::RelayMembershipCheckError) { + if !attempt.reject(&conn, AuthOutcome::RelayMembershipCheckError) { return; } if conn.nip_fi_assertion.is_some() { @@ -685,7 +854,10 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: crate::nip_fi_test_hooks::before_auth_commit(conn.tenant.community()).await; let _auth_permit = match conn.nip_fi_gate.acquire_effect().await { Ok(permit) => permit, - Err(crate::nip_fi_gate::SessionExpired) => return, + Err(crate::nip_fi_gate::SessionExpired) => { + _shadow_attempt.effect_refused(&conn.nip_fi_gate); + return; + } }; // Record the NIP-OA owner link before admission: revoking the @@ -710,7 +882,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: ?link, "agent owner could not be linked, denying" ); - deny_admission(&conn, &event_id_hex, denial); + deny_admission(&conn, &attempt, &event_id_hex, denial); return; } auth_ctx.agent_owner_pubkey = Some(owner); @@ -741,14 +913,20 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: .as_ref() .map(crate::nip_fi_core::NipFiSession::from_assertion), ); - match admitted_owner(&state, conn.tenant.community(), pubkey, nip_oa_owner).await { - Ok(Some(owner)) => state.conn_manager.set_admitted_owner(conn_id, owner), - Ok(None) => {} - Err(denial) => { - deny_admission(&conn, &event_id_hex, denial); - return; - } - } + // An admitted owner (NIP-OA, a NIP-FI agent token, or a stored + // `agent_owner_pubkey`) makes this socket an agent's. + let admitted_agent = + match admitted_owner(&state, conn.tenant.community(), pubkey, nip_oa_owner).await { + Ok(Some(owner)) => { + state.conn_manager.set_admitted_owner(conn_id, owner); + true + } + Ok(None) => false, + Err(denial) => { + deny_admission(&conn, &attempt, &event_id_hex, denial); + return; + } + }; let denial = match final_admission_denial( &state, conn.tenant.community(), @@ -764,21 +942,22 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: reason: "blocked: access revoked", outcome: AuthOutcome::Banned, class: buzz_auth::DenialClass::AuthorizationDenied, + owner_reason: None, }), denial => denial, }; if let Some(denial) = denial { - warn!(conn_id = %conn_id, pubkey = %pubkey.to_hex(), reason = denial.reason, "denied at final admission check"); - deny_admission(&conn, &event_id_hex, denial); + deny_admission(&conn, &attempt, &event_id_hex, denial); return; } - info!(conn_id = %conn_id, pubkey = %pubkey.to_hex(), "NIP-42 auth successful"); if !conn.authenticate(auth_ctx) { return; } - // The permit is held through the deny-set check and the OK send so - // the auth commit is atomic with respect to expiry. + // The login commits only if the close-reason slot is still empty + // when read under its lock (`is_open` below): a disconnect that + // chose a reason first wins, one that comes later closes the + // admitted socket. // // The proven key was registered with its NIP-FI issuer before the // final admission check: a concurrent disconnect either finds this @@ -790,16 +969,14 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: if let Some(deny_map) = state.nip_fi_deny_map.as_deref() { if crate::nip_fi_core::assertion_denied(deny_map, assertion, chrono::Utc::now()) { - warn!( - conn_id = %conn_id, - pubkey = %pubkey.to_hex(), - "NIP-FI deny-set hit at post-registration check — denying" - ); + attempt.log(AuthResult::Denied(crate::access::AuthReason::DenySet)); metrics::counter!( "buzz_nip_fi_admission_denied_total", "reason" => "deny_set_post_registration" ) .increment(1); + conn.community_control + .deny_nip_fi_enforce(crate::nip_fi_shadow::DENY_SET.by(Some(pubkey))); deny_nip_fi_auth(&conn, buzz_auth::DenialClass::AuthorizationDenied); return; } @@ -814,16 +991,66 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: if conn.cancel.is_cancelled() { return; } + #[cfg(test)] + crate::nip_fi_test_hooks::before_auth_decision(&conn); + // A disconnect that chose its reply before this point (expiry, + // ban, revoke) wins: its refusal is the only answer. One that + // lands after closes an admitted socket. + if !conn.community_control.is_open() { + return; + } + // Only the frame that won `authenticate` reaches here, once. + attempt.log(AuthResult::Success); state.conn_manager.mark_admitted(conn_id); + if let Some(session) = conn.community_control.nip_fi_enforce() { + session.admit(pubkey); + } conn.send(RelayMessage::ok(&event_id_hex, true, "")); + crate::verified_profiles::admitted( + &state, + &conn.tenant, + conn.nip_fi_assertion.as_ref(), + ); + // A community without a membership roster has no roster insert to + // join default channels at, so a person is joined on admission to + // the ones they have never been in, under this socket's effect + // permits. Agents are not. + let auto_join = !state.config.require_relay_membership && !admitted_agent; + { + let state = Arc::clone(&state); + let tenant = conn.tenant.clone(); + let gate = Arc::clone(&conn.nip_fi_gate); + tokio::spawn(async move { + crate::handlers::side_effects::auto_join_default_channels( + &tenant, + &state, + &pubkey.to_hex(), + Some(&gate), + ) + .await; + if auto_join { + crate::handlers::side_effects::auto_join_never_joined_channels( + &tenant, + &state, + &pubkey.to_bytes(), + &gate, + ) + .await; + } else { + #[cfg(test)] + crate::nip_fi_test_hooks::after_auto_join(tenant.community()).await; + } + }); + } // _auth_permit drops here — expiry's write guard may proceed. } Err(e) => { - warn!(conn_id = %conn_id, error = %e, "NIP-42 auth failed"); metrics::counter!("buzz_auth_failures_total", "reason" => "nip42_invalid").increment(1); if !conn.reject_auth(AuthOutcome::Invalid) { return; } + AuthAttempt::nip42(&conn, claimed_pubkey, false) + .log(AuthResult::Failed(crate::access::auth_error_code(&e))); if conn.nip_fi_assertion.is_some() { deny_nip_fi_auth(&conn, nip42_denial_class(&e)); return; @@ -881,6 +1108,100 @@ mod tests { .unwrap_or_default() } + /// The AUTH cap sheds a verified login with a bare close once its bounded + /// wait runs out; a free permit lets the next login through to its + /// database checks. + #[tokio::test] + async fn auth_cap_sheds_a_verified_login_with_a_bare_close() { + let recorder = metrics_util::debugging::DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let _recorder_guard = metrics::set_default_local_recorder(&recorder); + let state = auth_test_state().await; + assert_eq!(state.auth_gate.set_limit(1), 1); + let held = state + .auth_gate + .admit(super::AUTH_PERMIT_WAIT) + .await + .expect("the only permit"); + + let mut shed = AuthHarness::new(false); + let started = std::time::Instant::now(); + shed.run(shed.auth_event(), std::sync::Arc::clone(&state)) + .await; + assert!( + started.elapsed() >= super::AUTH_PERMIT_WAIT, + "a login waits for a permit before it is shed" + ); + assert!(matches!(shed.conn.auth_state_snapshot(), AuthState::Failed)); + assert_eq!( + crate::connection::server_close_reason(&state, &shed.conn), + Some("auth_failed"), + "a shed login closes as auth_failed" + ); + assert!( + shed.send_rx.try_recv().is_err(), + "no OK on the data channel" + ); + assert!( + shed.ctrl_rx.try_recv().is_err(), + "no OK on the ctrl channel" + ); + assert_eq!( + shed.wire_frames().await, + vec![WsMessage::Close(None)], + "a shed login sees only a bare close, as on an auth timeout" + ); + + drop(held); + let admitted = AuthHarness::new(false); + admitted + .run(admitted.auth_event(), std::sync::Arc::clone(&state)) + .await; + // Every AUTH records exactly one outcome. The admitted login's is the + // stub database's failure, so it got past the gate to its checks. + let mut outcomes: Vec<(String, u64)> = snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, ..)| key.key().name() == "buzz_auth_outcomes_total") + .map(|(key, _, _, value)| { + let outcome = key + .key() + .labels() + .find(|label| label.key() == "outcome") + .map(|label| label.value().to_owned()) + .unwrap_or_default(); + let DebugValue::Counter(count) = value else { + panic!("buzz_auth_outcomes_total must be a counter"); + }; + (outcome, count) + }) + .filter(|(_, count)| *count > 0) + .collect(); + outcomes.sort(); + assert_eq!(outcomes.len(), 2, "one outcome per login: {outcomes:?}"); + assert!( + outcomes + .iter() + .any(|(outcome, count)| outcome == "concurrency_limit" && *count == 1), + "the first login is shed: {outcomes:?}" + ); + assert!( + outcomes + .iter() + .any(|(outcome, count)| outcome != "concurrency_limit" && *count == 1), + "the second login, with a free permit, passes the gate: {outcomes:?}" + ); + assert!( + state + .auth_gate + .admit(std::time::Duration::from_millis(10)) + .await + .is_some(), + "the admitted login returns its permit" + ); + } + fn pending(challenge: &str) -> AuthState { AuthState::Pending { challenge: challenge.to_owned(), @@ -966,9 +1287,7 @@ mod tests { .connect_lazy(&config.database_url) .expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1023,6 +1342,7 @@ mod tests { let cancel = CancellationToken::new(); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), @@ -1047,6 +1367,14 @@ mod tests { }); let state = auth_test_state().await; + conn.community_control + .attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "ws", + crate::nip_fi_shadow::BOUND.into(), + conn.nip_fi_assertion + .as_ref() + .and_then(|a| a.asserted_key()), + )); // relay_url = ws:// where scheme prefix is from config // (default ws://), and host is "test.local". @@ -1057,8 +1385,20 @@ mod tests { .sign_with_keys(&key_b) .unwrap(); - // Drive the production handle_auth path. - handle_auth(auth_event, Arc::clone(&conn), state).await; + // Drive the production handle_auth path. Enforce records the + // refusal once, naming the proven key, and the deadline that fires + // after it records nothing more. Mutation: dropping the pairing + // seam's `deny_nip_fi_enforce` call → RED. + let ((), lines, counts) = crate::nip_fi_shadow::tests::enforce_records(async { + handle_auth(auth_event, Arc::clone(&conn), state).await; + conn.community_control.nip_fi_enforce().unwrap().expire(); + }) + .await; + assert_eq!(lines.len(), 1, "{lines:?}"); + let proven = format!("pubkey=\"{}\"", key_b.public_key().to_hex()); + assert!(lines[0].contains(&proven), "{lines:?}"); + assert_eq!(counts.len(), 1, "{counts:?}"); + assert_eq!(counts[0][..3], ["ws", "pairing", "denied"]); assert!( cancel.is_cancelled(), @@ -1152,6 +1492,7 @@ mod tests { cancel.cancel(); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), @@ -1241,6 +1582,7 @@ mod tests { } }); let conn = std::sync::Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: uuid::Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::new_v4()), @@ -1361,9 +1703,7 @@ mod tests { config.require_relay_membership = false; config.redis_url = "redis://127.0.0.1:1".to_string(); configure(&mut config); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -1596,6 +1936,60 @@ mod tests { assert_eq!(records, ["pairing/denied"]); } + // The pairing would-deny names the key AUTH proved, not the one the + // token asserts. Mutation: attributing the asserted key, or none, fails. + #[test] + fn shadow_root_pairing_denial_logs_the_proven_key() { + use crate::nip_fi_shadow_session::tests::{shadow_logged, shadow_state}; + let signer = Keys::generate(); + let asserted = Keys::generate().public_key(); + let (records, lines) = shadow_logged(async { + let state = std::sync::Arc::new(shadow_state(None).await); + let (t, event) = shadow_root_conn(&state, asserted, &signer, HOUR); + handle_auth(event, std::sync::Arc::clone(&t.conn), state).await; + }); + assert_eq!(records, ["pairing/denied"]); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!(lines[0].contains("reason=\"key_mismatch\""), "{lines:?}"); + let proven = format!("pubkey=\"{}\"", signer.public_key().to_hex()); + assert!(lines[0].contains(&proven), "{lines:?}"); + } + + // An upgrade would-deny's line names the key the connection's AUTH + // verifies, and is counted once, at the upgrade. Mutation: deleting + // root's `prove_nip_fi_line` logs `absent`. + #[test] + fn shadow_upgrade_would_deny_logs_the_root_auth_key() { + use crate::nip_fi_shadow_session::tests::{shadow_logged, shadow_state}; + let signer = Keys::generate(); + let (records, lines) = shadow_logged(async { + let state = std::sync::Arc::new(shadow_state(None).await); + let line = crate::nip_fi_shadow::tests::upgrade_line("ws"); + let challenge = "upgrade-would-deny-challenge".to_owned(); + let pending = AuthState::Pending { + challenge: challenge.clone(), + started_at: Instant::now(), + }; + let nil = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()); + let t = crate::connection::tests::test_conn_in(pending, None, nil); + t.conn.community_control.attach_nip_fi_line(Some(&line)); + let event = EventBuilder::new(Kind::Authentication, "") + .tag(Tag::parse(["relay", "ws://test.local"]).unwrap()) + .tag(Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(&signer) + .unwrap(); + handle_auth(event, std::sync::Arc::clone(&t.conn), state).await; + }); + assert_eq!(records, ["assertion/missing"]); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!( + lines[0].contains("reason=\"missing_assertion\""), + "{lines:?}" + ); + let proven = format!("pubkey=\"{}\"", signer.public_key().to_hex()); + assert!(lines[0].contains(&proven), "{lines:?}"); + } + // A failed owner read records `owner` as unavailable, as enforce fails // closed, and changes nothing else. The state's database is unreachable. // Mutation: deleting root's `observe_owner` call loses the record. @@ -1618,6 +2012,28 @@ mod tests { assert_eq!(records, ["owner/unavailable"]); } + // The deciding row names the reason: an owner's ban or failed lookup is + // shadow's `owner` reason, the key's own is none. Mutation: reporting an + // own-row ban as the owner's → RED. + #[test] + fn ban_verdict_owner_reason_follows_the_deciding_row() { + use super::{BanSource, BanVerdict}; + let verdict = |outcome, source| BanVerdict { outcome, source }; + assert_eq!( + verdict(BanOutcome::Banned, BanSource::Owner).owner_reason(), + Some("owner_banned") + ); + assert_eq!( + verdict(BanOutcome::DbError, BanSource::Owner).owner_reason(), + Some("owner_ban_unavailable") + ); + assert_eq!( + verdict(BanOutcome::Banned, BanSource::Own).owner_reason(), + None + ); + assert_eq!(BanVerdict::CLEAR.owner_reason(), None); + } + const HOUR: chrono::Duration = chrono::Duration::hours(1); /// Fires the connection's shadow deadline once its AUTH has finished, @@ -1813,6 +2229,278 @@ mod tests { } } + /// An enforced root socket in `community` under `assertion`, with its + /// enforce lifecycle attached as the upgrade attaches it, and an AUTH + /// event `signer` signs for it. + fn enforce_root_conn( + community: buzz_core::tenant::CommunityId, + assertion: buzz_auth::VerifiedAssertion, + signer: &Keys, + ) -> (crate::connection::tests::TestConn, nostr::Event) { + enforce_root_conn_gated(community, assertion, signer, None) + } + + /// [`enforce_root_conn`] whose effect gate has `deadline`. + fn enforce_root_conn_gated( + community: buzz_core::tenant::CommunityId, + assertion: buzz_auth::VerifiedAssertion, + signer: &Keys, + deadline: Option>, + ) -> (crate::connection::tests::TestConn, nostr::Event) { + let challenge = "enforce-root-challenge".to_owned(); + let pending = AuthState::Pending { + challenge: challenge.clone(), + started_at: Instant::now(), + }; + let asserted = assertion.asserted_key(); + let t = crate::connection::tests::test_conn_gated( + pending, + Some(assertion), + community, + deadline, + ); + t.conn.community_control.attach_nip_fi_enforce( + crate::nip_fi_shadow::EnforceSession::new( + "ws", + crate::nip_fi_shadow::BOUND.into(), + asserted, + ), + ); + let event = EventBuilder::new(Kind::Authentication, "") + .tag(Tag::parse(["relay", "ws://test.local"]).unwrap()) + .tag(Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(signer) + .unwrap(); + (t, event) + } + + /// Runs the production expiry worker for `t`'s socket with its + /// deadline already passed, to completion. + async fn run_expiry_worker(t: &crate::connection::tests::TestConn) { + let gate = crate::nip_fi_gate::SessionAdmissionGate::new( + chrono::Utc::now(), + t.conn.cancel.clone(), + ); + crate::nip_fi_session::spawn_nip_fi_expiry_task( + chrono::Utc::now(), + gate, + t.conn.community_control.clone(), + t.conn.terminal_ctrl_tx.clone(), + crate::nip_fi_session::NipFiWsRoute::Root, + ) + .await + .expect("expiry worker"); + } + + /// Enforce records each root owner refusal once, with shadow's + /// reason, from the single ban decision that refused it: a stored + /// owner's ban (the agent's own read cascades to it) costs exactly + /// one authorization read, so a reread cannot change the reason. An + /// admitted session counts one admit and, through the real expiry + /// worker, one `expired` end and no pending `deadline`. + /// Mutations: deleting root's `session.admit(pubkey)` leaves `Clean` + /// with no record (the attempt retires it); reverting to reread the owner + /// after the refusal raises `StoredOwnerBanned`'s reads above 1. + #[test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + fn enforce_root_auth_records_owner_refusals_from_one_decision() { + use crate::nip_fi_shadow_session::tests::owned_assertion; + #[derive(Clone, Copy, Debug)] + enum Case { + Clean, + BannedTokenOwner, + StoredOwnerBanned, + OtherStoredOwner, + BanReadFails, + } + for (case, expected, reason, reads) in [ + ( + Case::Clean, + &["ws admit/admit", "ws end/expired"][..], + None, + None, + ), + ( + Case::BannedTokenOwner, + &["ws owner/denied"][..], + Some("owner_banned"), + Some(2), + ), + ( + Case::StoredOwnerBanned, + &["ws owner/denied"][..], + Some("owner_banned"), + Some(1), + ), + ( + Case::OtherStoredOwner, + &["ws owner/denied"][..], + Some("not_stored_owner"), + None, + ), + ( + Case::BanReadFails, + &["ws owner/unavailable"][..], + Some("owner_ban_unavailable"), + None, + ), + ] { + let (records, lines, auth_reads, ok_true) = + crate::nip_fi_shadow::tests::enforce_observed( + async { + let state = auth_test_state_real_db_expect().await; + let (agent, owner) = (Keys::generate(), Keys::generate()); + let community = seeded_community(&state).await; + let link = |stored: nostr::PublicKey| { + let state = std::sync::Arc::clone(&state); + let agent = agent.public_key(); + async move { + for key in [agent, stored] { + state + .db + .ensure_user(community, key.as_bytes()) + .await + .expect("ensure user"); + } + assert!(state + .db + .set_agent_owner( + community, + agent.as_bytes(), + stored.as_bytes() + ) + .await + .expect("seed stored owner")); + } + }; + let ban = |key: nostr::PublicKey| { + let state = std::sync::Arc::clone(&state); + async move { + let bytes = key.to_bytes(); + state + .db + .ban_community_member(community, &bytes, &bytes, None, None) + .await + .expect("ban owner"); + } + }; + match case { + Case::Clean => {} + Case::BannedTokenOwner => ban(owner.public_key()).await, + Case::StoredOwnerBanned => { + link(owner.public_key()).await; + ban(owner.public_key()).await; + } + Case::OtherStoredOwner => link(Keys::generate().public_key()).await, + // The agent's own ban read fails: its token + // owner is left unchecked, so the refusal is the + // owner's unavailable ban state. + Case::BanReadFails => state.db.pool().close().await, + } + let conn = enforce_root_conn( + community, + owned_assertion(agent.public_key(), owner.public_key()), + &agent, + ); + (state, conn) + }, + |(state, (mut t, event))| async move { + handle_auth(event, std::sync::Arc::clone(&t.conn), state).await; + let mut ok_true = false; + while let Ok(WsMessage::Text(text)) = t.send_rx.try_recv() { + ok_true |= is_ok_true(text.as_str()); + } + run_expiry_worker(&t).await; + ok_true + }, + ); + assert_eq!(records, expected, "{case:?}: {lines:?}"); + assert_eq!(ok_true, reason.is_none(), "{case:?}: admission unchanged"); + let denials: Vec<_> = lines + .iter() + .filter(|l| l.contains("enforce deny")) + .collect(); + match reason { + Some(reason) => { + assert_eq!(denials.len(), 1, "{case:?}: {lines:?}"); + assert!( + denials[0].contains(&format!("reason=\"{reason}\"")), + "{case:?}: {lines:?}" + ); + assert!( + denials[0].contains("stage=\"owner\""), + "{case:?}: {lines:?}" + ); + assert!(denials[0].contains("route=\"ws\""), "{case:?}: {lines:?}"); + } + None => assert!(denials.is_empty(), "{case:?}: {lines:?}"), + } + if let Some(reads) = reads { + assert_eq!(auth_reads, reads, "{case:?}: authorization reads"); + } + } + } + + /// A deadline the AUTH commit's effect gate sees before the expiry + /// worker runs is recorded once, as the pending session's + /// `session_deadline` denial: in either order, the attempt's own + /// retirement cannot end it unrecorded, and the worker that follows + /// adds nothing. Admission is unchanged: no `OK true`. + /// Mutation: deleting root's `effect_refused` call records nothing + /// for `GateFirst`. + #[test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + fn enforce_root_deadline_seen_by_the_gate_first_is_recorded_once() { + for worker_first in [false, true] { + let (records, lines, _, ok_true) = crate::nip_fi_shadow::tests::enforce_observed( + async { + let state = auth_test_state_real_db_expect().await; + let agent = Keys::generate(); + let community = seeded_community(&state).await; + state + .db + .ensure_user(community, agent.public_key().as_bytes()) + .await + .expect("ensure user"); + let conn = enforce_root_conn_gated( + community, + buzz_auth::VerifiedAssertion::for_test( + Some(agent.public_key()), + vec![chrono::Utc::now() + chrono::Duration::hours(1)], + ), + &agent, + Some(chrono::Utc::now() - chrono::Duration::seconds(1)), + ); + (state, conn) + }, + |(state, (mut t, event))| async move { + if worker_first { + run_expiry_worker(&t).await; + } + handle_auth(event, std::sync::Arc::clone(&t.conn), state).await; + run_expiry_worker(&t).await; + let mut ok_true = false; + while let Ok(WsMessage::Text(text)) = t.send_rx.try_recv() { + ok_true |= is_ok_true(text.as_str()); + } + ok_true + }, + ); + assert_eq!( + records, + ["ws deadline/rejected"], + "worker_first={worker_first}: {lines:?}" + ); + assert!( + lines + .iter() + .any(|l| l.contains("reason=\"session_deadline\"")), + "{lines:?}" + ); + assert!(!ok_true, "admission unchanged"); + } + } + /// A community whose row exists, so bans and users can reference it. async fn seeded_community( state: &crate::state::AppState, @@ -1846,6 +2534,7 @@ mod tests { let backpressure = Arc::new(std::sync::atomic::AtomicU8::new(0)); let subscriptions = Arc::new(tokio::sync::Mutex::new(HashMap::new())); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: uuid::Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( community, @@ -2278,6 +2967,326 @@ mod tests { assert!(!conns[2].cancel.is_cancelled(), "the bystander stays"); } + /// Flags `names` as default channels in `community`, oldest first. + async fn default_channels( + state: &crate::state::AppState, + community: buzz_core::tenant::CommunityId, + owner: &Keys, + names: &[&str], + ) -> Vec { + use buzz_db::channel::{ChannelType, ChannelUpdate, ChannelVisibility}; + state + .db + .ensure_user_for_authorization(community, owner.public_key().as_bytes()) + .await + .expect("seed owner"); + let mut channels = Vec::new(); + for name in names { + let channel = state + .db + .create_channel( + community, + name, + ChannelType::Stream, + ChannelVisibility::Open, + None, + &owner.public_key().to_bytes(), + None, + ) + .await + .expect("create channel") + .id; + state + .db + .update_channel( + community, + channel, + ChannelUpdate { + auto_join: Some(true), + ..Default::default() + }, + ) + .await + .expect("flag channel"); + channels.push(channel); + } + channels + } + + /// Admits `keys` on a fresh root socket and waits for the admission's + /// auto-join outcome: the spawned task finishing, or the skip. + /// Panics if neither arrives. Returns the socket. + async fn admit_and_settle( + state: &std::sync::Arc, + community: buzz_core::tenant::CommunityId, + keys: &Keys, + challenge: &str, + tag: Option>, + ) -> std::sync::Arc { + use crate::nip_fi_test_hooks::auto_join_done_hook; + let (done, release) = auto_join_done_hook::arm(community); + let (conn, _ctrl) = registered_pending_conn(state, community, challenge); + // A skip reports inside `handle_auth`, so wait alongside it. + tokio::join!( + handle_auth( + signed_auth(keys, challenge, tag), + std::sync::Arc::clone(&conn), + std::sync::Arc::clone(state), + ), + async { + tokio::time::timeout(std::time::Duration::from_secs(10), done) + .await + .unwrap_or_else(|_| panic!("{challenge}: no auto-join outcome")) + .expect("auto-join hook dropped"); + release.notify_one(); + }, + ); + assert!( + matches!(conn.auth_state_snapshot(), AuthState::Authenticated(_)), + "{challenge} is admitted" + ); + conn + } + + /// On a community without a membership roster, a person's admission + /// joins them to the default channels they have never been in. An + /// agent's (NIP-OA) admission runs no join, and a person who left is + /// not joined back when they are admitted again. Each check waits for + /// that admission's own auto-join outcome (skip or finished task). + /// + /// Mutations: delete the `auto_join_never_joined_channels` spawn → + /// no outcome arrives (RED); drop `!admitted_agent` → the agent is + /// joined (RED); drop the row check in `put_first_member` → the + /// leave is undone (RED). + #[tokio::test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn root_auth_joins_people_to_default_channels_without_a_roster() { + let state = auth_test_state_real_db_expect().await; + let community = seeded_community(&state).await; + let (owner, agent, person) = (Keys::generate(), Keys::generate(), Keys::generate()); + let channel = default_channels(&state, community, &owner, &["general"]).await[0]; + let role = |keys: &Keys| { + let state = std::sync::Arc::clone(&state); + let pubkey = keys.public_key().to_bytes(); + async move { + state + .db + .get_member_role(community, channel, &pubkey) + .await + .expect("member role") + } + }; + let auth_tag = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "") + .expect("sign NIP-OA credential"); + let auth_tag: Vec = serde_json::from_str(&auth_tag).expect("tag JSON"); + + admit_and_settle(&state, community, &agent, "auto-join-agent", Some(auth_tag)).await; + assert_eq!(role(&agent).await, None, "an agent is not joined"); + + admit_and_settle(&state, community, &person, "auto-join-person", None).await; + assert_eq!(role(&person).await.as_deref(), Some("member")); + + let person_key = person.public_key().to_bytes(); + state + .db + .remove_member(community, channel, &person_key, &person_key) + .await + .expect("leave"); + admit_and_settle(&state, community, &person, "auto-join-again", None).await; + assert_eq!(role(&person).await, None, "a leave stands"); + } + + /// Durable roster work is retried by real AUTH admission, including + /// agents. Completed work must not enroll members in defaults added later. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn root_auth_recovers_pending_roster_default_joins() { + let mut state = auth_test_state_real_db_expect().await; + std::sync::Arc::make_mut( + &mut std::sync::Arc::get_mut(&mut state) + .expect("unique test state") + .config, + ) + .require_relay_membership = true; + let community = seeded_community(&state).await; + let (owner, person, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + let channel = default_channels(&state, community, &owner, &["recovered"]).await[0]; + for keys in [&person, &agent] { + let _ = state + .db + .add_relay_member_with_default_channels( + community, + &keys.public_key().to_hex(), + "member", + "invite", + &state.relay_keypair, + ) + .await + .expect("admit with pending work"); + } + let credential = buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "") + .expect("credential"); + let tag: Vec = serde_json::from_str(&credential).expect("tag"); + for (keys, tag, challenge) in [ + (&person, None, "recover-person"), + (&agent, Some(tag), "recover-agent"), + ] { + admit_and_settle(&state, community, keys, challenge, tag).await; + assert_eq!( + state + .db + .get_member_role(community, channel, &keys.public_key().to_bytes()) + .await + .expect("membership") + .as_deref(), + Some("member") + ); + assert!(state + .db + .pending_default_channel_join(community, &keys.public_key().to_hex()) + .await + .expect("pending") + .is_none()); + } + // The operator CLI uses roster-only admission. AUTH must not + // turn that into default-channel enrollment. + let roster_only = Keys::generate(); + let _ = state + .db + .add_relay_member( + community, + &roster_only.public_key().to_hex(), + "member", + None, + &state.relay_keypair, + ) + .await + .expect("roster-only add"); + assert!(state + .db + .pending_default_channel_join(community, &roster_only.public_key().to_hex()) + .await + .expect("pending") + .is_none()); + admit_and_settle(&state, community, &roster_only, "roster-only", None).await; + assert!(state + .db + .get_member_role(community, channel, &roster_only.public_key().to_bytes()) + .await + .expect("membership") + .is_none()); + let later = default_channels(&state, community, &owner, &["later"]).await[0]; + admit_and_settle(&state, community, &person, "recover-completed", None).await; + assert!( + state + .db + .get_member_role(community, later, &person.public_key().to_bytes()) + .await + .expect("membership") + .is_none(), + "completed work must not become ongoing auto-enrollment" + ); + } + + /// The admission auto-join holds the socket's effect permit for each + /// channel, so a session that ends before a channel's write joins + /// nothing more: cancelled before the first channel, nothing; between + /// the two channels, only the first. The next admission then joins + /// the channel that was skipped. + /// + /// Mutation: drop the per-channel `acquire_effect` → the cancelled + /// session is joined anyway (RED). + #[tokio::test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn admission_auto_join_stops_when_the_session_ends() { + use crate::nip_fi_test_hooks::{auto_join_channel_hook, auto_join_done_hook}; + for roster in [false, true] { + let mut state = auth_test_state_real_db_expect().await; + std::sync::Arc::make_mut( + &mut std::sync::Arc::get_mut(&mut state) + .expect("unique test state") + .config, + ) + .require_relay_membership = roster; + let community = seeded_community(&state).await; + let owner = Keys::generate(); + let channels = + default_channels(&state, community, &owner, &["general", "announcements"]) + .await; + let roles = |keys: &Keys| { + let state = std::sync::Arc::clone(&state); + let pubkey = keys.public_key().to_bytes(); + let channels = channels.clone(); + async move { + let mut roles = Vec::new(); + for channel in channels { + roles.push( + state + .db + .get_member_role(community, channel, &pubkey) + .await + .expect("member role"), + ); + } + roles + } + }; + let member = Some("member".to_string()); + + // `stop_before` channels pass, then the socket is cancelled. + for (stop_before, expected) in [(0, [None, None]), (1, [member.clone(), None])] { + let person = Keys::generate(); + if roster { + let _ = state + .db + .add_relay_member_with_default_channels( + community, + &person.public_key().to_hex(), + "member", + "invite", + &state.relay_keypair, + ) + .await + .expect("pending roster work"); + } + let (done, done_release) = auto_join_done_hook::arm(community); + let (mut reached, mut release) = auto_join_channel_hook::arm(community); + let (conn, _ctrl) = + registered_pending_conn(&state, community, "auto-join-stop"); + handle_auth( + signed_auth(&person, "auto-join-stop", None), + std::sync::Arc::clone(&conn), + std::sync::Arc::clone(&state), + ) + .await; + assert!(matches!( + conn.auth_state_snapshot(), + AuthState::Authenticated(_) + )); + for _ in 0..stop_before { + reached.await.expect("task reaches a channel"); + // Re-arm before the task can run again: this task does + // not yield between the release and the arm. + release.notify_one(); + (reached, release) = auto_join_channel_hook::arm(community); + } + reached.await.expect("task reaches the stop channel"); + conn.cancel.cancel(); + release.notify_one(); + done.await.expect("task finishes"); + done_release.notify_one(); + assert_eq!(roles(&person).await, expected, "stop before {stop_before}"); + + admit_and_settle(&state, community, &person, "auto-join-resume", None).await; + assert_eq!( + roles(&person).await, + [member.clone(), member.clone()], + "the next admission joins what was skipped" + ); + } + } + } + /// AUTH with NIP-OA records a previously ownerless agent's owner. That /// closes the agent's earlier ownerless socket so it reconnects with /// the owner attached, but not the socket being admitted, even when @@ -2415,9 +3424,7 @@ mod tests { config.database_url = db_url.clone(); config.redis_url = "redis://127.0.0.1:1".to_string(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -2530,6 +3537,7 @@ mod tests { crate::state::CommunityConnectionControl::new(cancel.clone()); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( community, @@ -2736,6 +3744,7 @@ mod tests { let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::new_v4()); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( community, @@ -2925,6 +3934,7 @@ mod tests { let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::new_v4()); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( community, @@ -3103,6 +4113,7 @@ mod tests { let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( community, @@ -3221,6 +4232,7 @@ mod tests { let (terminal_ctrl_tx, _terminal_ctrl_rx) = mpsc::channel::(1); let cancel = CancellationToken::new(); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( community, @@ -3331,9 +4343,7 @@ mod tests { config.database_url = db_url.clone(); config.redis_url = "redis://127.0.0.1:1".to_string(); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -3376,6 +4386,7 @@ mod tests { let cancel = CancellationToken::new(); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()), @@ -3876,7 +4887,7 @@ mod tests { let recorder = metrics_util::debugging::DebuggingRecorder::new(); let snapshotter = recorder.snapshotter(); let _recorder_guard = metrics::set_default_local_recorder(&recorder); - let state = crate::state::tests::test_state_with_database_url( + let state = crate::state::tests::test_state_with_unreachable_database_url( "postgres://buzz:buzz_dev@127.0.0.1:1/buzz", ) .await; @@ -3918,4 +4929,37 @@ mod tests { 1 ); } + + #[tokio::test(flavor = "current_thread")] + async fn repeat_auth_after_a_terminal_logs_one_denial() { + let state = auth_test_state().await; + for (auth, reason) in [ + ( + crate::connection::tests::authenticated_state(), + "already_authenticated", + ), + (AuthState::Failed, "already_failed"), + ] { + let (conn, _rx) = test_conn_with_auth(auth); + let event = EventBuilder::new(Kind::Authentication, "") + .sign_with_keys(&Keys::generate()) + .unwrap(); + let (guard, out) = crate::access::tests::capture_scoped(); + handle_auth( + event, + std::sync::Arc::clone(&conn), + std::sync::Arc::clone(&state), + ) + .await; + drop(guard); + let lines: Vec<_> = out + .lines() + .into_iter() + .filter(|l| l["event"] == "auth") + .collect(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["outcome"], "denied"); + assert_eq!(lines[0]["reason"], reason); + } + } } diff --git a/crates/buzz-relay/src/handlers/close.rs b/crates/buzz-relay/src/handlers/close.rs index 33b8b6020f0..395aacfe4da 100644 --- a/crates/buzz-relay/src/handlers/close.rs +++ b/crates/buzz-relay/src/handlers/close.rs @@ -25,28 +25,153 @@ pub async fn handle_close(sub_id: String, conn: Arc, state: Arc debug!(conn_id = %conn.conn_id, sub_id = %sub_id, "Subscription closed"); } -/// Monotonic source of subscription owner tokens. Each REQ claims its sub ID -/// with a fresh token, so a superseded request can tell it no longer owns it. +/// Refuse a `REQ` or sync `REQ` as it arrives, before it is admitted, with +/// `CLOSED reason`. A `REQ` replaces whatever held its ID (NIP-01), and +/// `CLOSED` tells the client the ID is closed, so the old holder and any +/// request still pending for the ID are retired before the frame, under the +/// lifecycle lock. Only the connection's read loop calls this, in arrival +/// order; an admitted request refuses with `close_if_owner`. If the frame +/// cannot be queued, the connection is cancelled: the client would otherwise +/// never learn that the old holder is gone. +pub(crate) async fn refuse(sub_id: &str, reason: &str, conn: &ConnectionState, state: &AppState) { + let mut subs = conn.subscriptions.lock().await; + retire_locked(&mut subs, sub_id, conn, state).await; + if !conn.send(RelayMessage::closed(sub_id, reason)) { + conn.cancel.cancel(); + } +} + +/// Queue `frame` for `sub_id` only while the request holding `owner` still +/// owns the ID. A request that a newer same-ID REQ replaced sends nothing: +/// its late `EOSE` would otherwise tell a replacing sync that a set it never +/// sent is complete. Returns whether the frame was queued. +pub(crate) async fn send_if_owner( + sub_id: &str, + owner: u64, + frame: String, + conn: &ConnectionState, +) -> bool { + #[cfg(test)] + test_seam::pause_at(&test_seam::SEND_PAUSE).await; + let subs = conn.subscriptions.lock().await; + owns(&subs, sub_id, owner) && conn.send(frame) +} + +/// Monotonic source of subscription owner tokens. Each REQ takes its sub ID +/// with a fresh token when it arrives, so a request that a later same-ID REQ +/// or a `CLOSE` superseded can tell it no longer owns the ID. static NEXT_OWNER: AtomicU64 = AtomicU64::new(1); pub(crate) fn next_owner() -> u64 { NEXT_OWNER.fetch_add(1, Ordering::Relaxed) } +/// What the lifecycle map holds for a subscription ID: the token of the +/// newest admitted request, and whether that request has claimed the ID. +/// Until it claims, whatever is registered for the ID belongs to an older +/// request it is replacing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SubOwner { + /// The request's token from `next_owner`. + pub owner: u64, + /// The request has claimed the ID: what is registered for it is its own. + pub claimed: bool, +} + +/// Whether the request holding `owner` still owns `sub_id`. The caller holds +/// the lifecycle lock. +pub(crate) fn owns(subs: &HashMap, sub_id: &str, owner: u64) -> bool { + subs.get(sub_id).is_some_and(|held| held.owner == owner) +} + +/// Claim `sub_id` for the request holding `owner`: `false` once the +/// connection is closing or a `CLOSE` or newer same-ID REQ superseded it. +/// The caller holds the lifecycle lock and, on `true`, replaces whatever is +/// registered for the ID in the same critical section. +pub(crate) fn claim_locked( + subs: &mut HashMap, + sub_id: &str, + owner: u64, + conn: &ConnectionState, +) -> bool { + if conn.cancel.is_cancelled() { + return false; + } + match subs.get_mut(sub_id) { + Some(held) if held.owner == owner => { + held.claimed = true; + true + } + _ => false, + } +} + +/// Why `admit` did not admit a request. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum NotAdmitted { + /// The connection is closing; the request exits silently. + Closing, + /// A new ID past `MAX_SUBSCRIPTIONS`; `CLOSED` was queued. + TooManySubscriptions, +} + +/// Admit a `REQ` or sync `REQ` for `sub_id` as it arrives, before its handler +/// is spawned, and return its owner token. Admission order is arrival order: +/// the newest request owns the ID from this point, so an older request still +/// in its access checks can no longer claim, refuse, or send for the ID, and a +/// `CLOSE` retires a request that has not yet claimed. The previous holder +/// stays registered until this request claims or is refused. +pub(crate) async fn admit(sub_id: &str, conn: &ConnectionState) -> Result { + let mut subs = conn.subscriptions.lock().await; + if conn.cancel.is_cancelled() { + return Err(NotAdmitted::Closing); + } + if !subs.contains_key(sub_id) && subs.len() >= super::req::MAX_SUBSCRIPTIONS { + // A new ID has no old holder to retire, but a lost CLOSED would leave + // the client waiting on a refused request. + if !conn.send(RelayMessage::closed( + sub_id, + "error: too many subscriptions", + )) { + conn.cancel.cancel(); + } + return Err(NotAdmitted::TooManySubscriptions); + } + let owner = next_owner(); + subs.insert( + sub_id.to_owned(), + SubOwner { + owner, + claimed: false, + }, + ); + Ok(owner) +} + // Lifecycle lock: `conn.subscriptions` serializes every change to a // connection's subscription state — map token, registry entry, topic // retention, and the terminal CLOSED frame. Neither the registry nor pubsub -// takes it, so holding it across their awaits cannot invert lock order. +// takes it, so holding it across their awaits cannot invert lock order. The +// map holds, per ID, the newest admitted request's `SubOwner`, whether it has +// claimed (registered) yet or is still pending. /// Drop `sub_id` from the map, the fan-out index, and its topic retention. /// The caller holds the lifecycle lock (`subs`). pub(crate) async fn retire_locked( - subs: &mut HashMap, + subs: &mut HashMap, sub_id: &str, conn: &ConnectionState, state: &AppState, ) { subs.remove(sub_id); + retire_holder_locked(sub_id, conn, state).await; +} + +/// Drop the registered holder of `sub_id` from the fan-out index and its topic +/// retention, but keep the map token: the newer request that owns the ID is +/// replacing it. The caller holds the lifecycle lock. +pub(crate) async fn retire_holder_locked(sub_id: &str, conn: &ConnectionState, state: &AppState) { + state.artifact_syncs.remove(conn.conn_id, sub_id); if let Some(removed) = state.sub_registry.remove_subscription(conn.conn_id, sub_id) { #[cfg(test)] test_seam::pause_at(&test_seam::RELEASE_PAUSE).await; @@ -58,18 +183,47 @@ pub(crate) async fn retire_locked( /// send `closed` (if any) before releasing the lifecycle lock, so a replacing /// REQ can never claim the ID between the teardown and its terminal frame. /// Returns whether this request still owned the ID. A superseded request -/// touches nothing and says nothing. +/// touches nothing and says nothing. An admitted request refuses through here: +/// owning the ID, it retires the previous holder (NIP-01 replacement) before +/// its `CLOSED`. pub(crate) async fn close_if_owner( sub_id: &str, owner: u64, closed: Option<&str>, conn: &ConnectionState, state: &AppState, +) -> bool { + close_owned(sub_id, owner, None, closed, conn, state).await +} + +/// `close_if_owner` with `CLOSED reason`, preceded by `NOTICE notice` in the +/// same critical section, so a superseded request sends neither. +pub(crate) async fn refuse_if_owner_with_notice( + sub_id: &str, + owner: u64, + notice: &str, + reason: &str, + conn: &ConnectionState, + state: &AppState, +) -> bool { + close_owned(sub_id, owner, Some(notice), Some(reason), conn, state).await +} + +async fn close_owned( + sub_id: &str, + owner: u64, + notice: Option<&str>, + closed: Option<&str>, + conn: &ConnectionState, + state: &AppState, ) -> bool { let mut subs = conn.subscriptions.lock().await; - if subs.get(sub_id) != Some(&owner) { + if !owns(&subs, sub_id, owner) { return false; } + if let Some(notice) = notice { + conn.send(RelayMessage::notice(notice)); + } retire_locked(&mut subs, sub_id, conn, state).await; #[cfg(test)] test_seam::pause_at(&test_seam::PAUSE).await; @@ -93,6 +247,7 @@ pub(crate) async fn release_connection_subscriptions(conn: &ConnectionState, sta test_seam::pause_at(&test_seam::CLEANUP_PAUSE).await; let mut subs = conn.subscriptions.lock().await; subs.clear(); + state.artifact_syncs.remove_connection(conn.conn_id); for removed in state.sub_registry.remove_connection(conn.conn_id) { release_scope_topics(state, &conn.tenant, &removed.scope).await; } @@ -135,9 +290,10 @@ pub(crate) mod test_seam { pub(crate) static PAUSE: Arc; pub(crate) static RELEASE_PAUSE: Arc; pub(crate) static CLEANUP_PAUSE: Arc; + pub(crate) static SEND_PAUSE: Arc; } - pub(super) async fn pause_at(point: &'static tokio::task::LocalKey>) { + pub(crate) async fn pause_at(point: &'static tokio::task::LocalKey>) { if let Ok(pause) = point.try_with(Arc::clone) { pause.reached.notify_one(); pause.resume.notified().await; diff --git a/crates/buzz-relay/src/handlers/coalesced_refresh.rs b/crates/buzz-relay/src/handlers/coalesced_refresh.rs new file mode 100644 index 00000000000..0110af2fa05 --- /dev/null +++ b/crates/buzz-relay/src/handlers/coalesced_refresh.rs @@ -0,0 +1,287 @@ +//! Per-key single-flight refresh with a minimum interval. +//! +//! A refresh for a key runs at once when none is in flight. Requests that +//! arrive while one is running or cooling down collapse into one trailing +//! rerun, so a key refreshes at most once per interval per process and the +//! last request is always covered by a refresh that started after it. Each +//! run is bounded by a timeout, so a hung refresh can't wedge its key. + +use std::future::Future; +use std::hash::Hash; +use std::sync::Arc; +use std::time::Duration; + +use dashmap::mapref::entry::Entry; +use dashmap::DashMap; + +/// Coalesces refresh requests per key. The map holds only keys with a +/// refresh in flight; the value is "another request arrived since it began". +pub struct CoalescedRefresh { + pending: DashMap, + min_interval: Duration, + run_timeout: Duration, +} + +impl CoalescedRefresh +where + K: Eq + Hash + Clone + Send + Sync + 'static, +{ + /// A coalescer that refreshes each key at most once per `min_interval`, + /// abandoning any single run that takes longer than `run_timeout`. + pub fn new(min_interval: Duration, run_timeout: Duration) -> Self { + Self { + pending: DashMap::new(), + min_interval, + run_timeout, + } + } + + /// Request a refresh of `key`. Runs `refresh` on a spawned task now when + /// `key` is idle; otherwise marks the in-flight refresh to run once more + /// after its interval elapses. + pub fn request(self: &Arc, key: K, refresh: F) + where + F: Fn() -> Fut + Send + 'static, + Fut: Future + Send, + { + match self.pending.entry(key.clone()) { + Entry::Occupied(mut rerun) => { + *rerun.get_mut() = true; + return; + } + Entry::Vacant(slot) => { + slot.insert(false); + } + } + // Frees the key if the task panics or is cancelled, including before + // its first poll, so a failed refresh can't block the key forever. + let mut release = Release { + owner: Arc::clone(self), + key: Some(key.clone()), + }; + tokio::spawn(async move { + let this = Arc::clone(&release.owner); + loop { + if tokio::time::timeout(this.run_timeout, refresh()) + .await + .is_err() + { + tracing::warn!( + timeout_ms = this.run_timeout.as_millis() as u64, + "coalesced refresh timed out" + ); + } + tokio::time::sleep(this.min_interval).await; + if !this.rerun_or_release(&key) { + break; + } + } + // Finished normally: rerun_or_release already freed the key. + release.key.take(); + }); + } + + /// Clear the rerun flag and report it, or free the key when no request + /// arrived. Atomic with [`Self::request`]'s entry check, so a request + /// either sets the flag before this reads it or finds the key free. + fn rerun_or_release(&self, key: &K) -> bool { + match self.pending.entry(key.clone()) { + Entry::Occupied(mut entry) if *entry.get() => { + *entry.get_mut() = false; + true + } + Entry::Occupied(entry) => { + entry.remove(); + false + } + Entry::Vacant(_) => false, + } + } +} + +struct Release { + owner: Arc>, + key: Option, +} + +impl Drop for Release { + fn drop(&mut self) { + if let Some(key) = self.key.take() { + self.owner.pending.remove(&key); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + const INTERVAL: Duration = Duration::from_secs(1); + const TIMEOUT: Duration = Duration::from_secs(5); + + fn counting(runs: &Arc) -> impl Fn() -> std::future::Ready<()> + Send + 'static { + let runs = Arc::clone(runs); + move || { + runs.fetch_add(1, Ordering::SeqCst); + std::future::ready(()) + } + } + + /// Let spawned tasks run up to their next timer. + async fn settle() { + for _ in 0..10 { + tokio::task::yield_now().await; + } + } + + #[tokio::test(start_paused = true)] + async fn burst_runs_once_now_and_once_trailing_then_frees_the_key() { + let refresh = Arc::new(CoalescedRefresh::new(INTERVAL, TIMEOUT)); + let runs = Arc::new(AtomicUsize::new(0)); + + for _ in 0..100 { + refresh.request("root", counting(&runs)); + } + settle().await; + assert_eq!(runs.load(Ordering::SeqCst), 1, "first request runs at once"); + + tokio::time::advance(INTERVAL).await; + settle().await; + assert_eq!( + runs.load(Ordering::SeqCst), + 2, + "the burst gets one trailing run" + ); + + tokio::time::advance(INTERVAL).await; + settle().await; + assert_eq!(runs.load(Ordering::SeqCst), 2, "no request, no rerun"); + assert!(refresh.pending.is_empty(), "idle key is released"); + + refresh.request("root", counting(&runs)); + settle().await; + assert_eq!( + runs.load(Ordering::SeqCst), + 3, + "a later request runs at once" + ); + } + + #[tokio::test(start_paused = true)] + async fn request_during_a_run_gets_a_trailing_run_that_sees_its_state() { + let refresh = Arc::new(CoalescedRefresh::new(INTERVAL, TIMEOUT)); + let state = Arc::new(AtomicUsize::new(1)); + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let gate = Arc::new(tokio::sync::Semaphore::new(0)); + // Records the state it reads, then holds until the gate opens. + let reader = { + let (state, seen, gate) = (Arc::clone(&state), Arc::clone(&seen), Arc::clone(&gate)); + move || { + let (state, seen, gate) = + (Arc::clone(&state), Arc::clone(&seen), Arc::clone(&gate)); + async move { + seen.lock().unwrap().push(state.load(Ordering::SeqCst)); + let _permit = gate.acquire().await; + } + } + }; + + refresh.request("root", reader.clone()); + settle().await; + assert_eq!(*seen.lock().unwrap(), [1], "the first run read state 1"); + + state.store(2, Ordering::SeqCst); + refresh.request("root", reader.clone()); + settle().await; + assert_eq!( + *seen.lock().unwrap(), + [1], + "no second run while one is in flight" + ); + + gate.add_permits(1); + settle().await; + tokio::time::advance(INTERVAL).await; + settle().await; + assert_eq!( + *seen.lock().unwrap(), + [1, 2], + "the trailing run reads the state written mid-run" + ); + + tokio::time::advance(INTERVAL).await; + settle().await; + assert_eq!(*seen.lock().unwrap(), [1, 2], "no further run"); + assert!(refresh.pending.is_empty(), "idle key is released"); + } + + #[test] + fn a_task_dropped_before_its_first_poll_releases_the_key() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + let refresh = Arc::new(CoalescedRefresh::new(INTERVAL, TIMEOUT)); + let runs = Arc::new(AtomicUsize::new(0)); + // `block_on` returns without yielding, so the spawned task is never + // polled; dropping the runtime drops it unpolled. + runtime.block_on(async { refresh.request("root", counting(&runs)) }); + assert!(!refresh.pending.is_empty(), "the queued task holds the key"); + + drop(runtime); + assert_eq!(runs.load(Ordering::SeqCst), 0, "the task never ran"); + assert!( + refresh.pending.is_empty(), + "an unpolled task must not wedge the key" + ); + } + + #[tokio::test(start_paused = true)] + async fn keys_refresh_independently() { + let refresh = Arc::new(CoalescedRefresh::new(INTERVAL, TIMEOUT)); + let runs = Arc::new(AtomicUsize::new(0)); + + refresh.request("a", counting(&runs)); + refresh.request("b", counting(&runs)); + settle().await; + assert_eq!(runs.load(Ordering::SeqCst), 2); + } + + #[tokio::test(start_paused = true)] + async fn panicking_refresh_releases_the_key() { + let refresh = Arc::new(CoalescedRefresh::new(INTERVAL, TIMEOUT)); + refresh.request("root", || async { panic!("refresh failed") }); + settle().await; + assert!(refresh.pending.is_empty(), "panic must not wedge the key"); + + let runs = Arc::new(AtomicUsize::new(0)); + refresh.request("root", counting(&runs)); + settle().await; + assert_eq!(runs.load(Ordering::SeqCst), 1); + } + + #[tokio::test(start_paused = true)] + async fn hung_refresh_times_out_and_releases_the_key() { + let refresh = Arc::new(CoalescedRefresh::new(INTERVAL, TIMEOUT)); + refresh.request("root", std::future::pending::<()>); + settle().await; + assert!(!refresh.pending.is_empty(), "the hung run holds the key"); + + // Step one timer at a time: the cooldown sleep is armed only after + // the timeout fires, so a single jump would overshoot it. + tokio::time::advance(TIMEOUT).await; + settle().await; + tokio::time::advance(INTERVAL).await; + settle().await; + assert!( + refresh.pending.is_empty(), + "a hung run must not wedge the key" + ); + + let runs = Arc::new(AtomicUsize::new(0)); + refresh.request("root", counting(&runs)); + settle().await; + assert_eq!(runs.load(Ordering::SeqCst), 1); + } +} diff --git a/crates/buzz-relay/src/handlers/command_executor.rs b/crates/buzz-relay/src/handlers/command_executor.rs index 2c5a8ff5b5c..98d87549e11 100644 --- a/crates/buzz-relay/src/handlers/command_executor.rs +++ b/crates/buzz-relay/src/handlers/command_executor.rs @@ -153,7 +153,7 @@ async fn persist_command_event( ) .await .map_err(|e| { - IngestError::Internal(format!("error: replace parameterized event: {e}")) + IngestError::Internal(format!("error: replace parameterized event: {}", e.kind())) })?; return match result.status { @@ -184,7 +184,7 @@ async fn persist_command_event( let (_, was_inserted) = buzz_db::event::insert_event_in_transaction(&mut tx, event, channel_id) .await - .map_err(|e| IngestError::Internal(format!("error: insert event: {e}")))?; + .map_err(|e| IngestError::Internal(format!("error: insert event: {}", e.kind())))?; if was_inserted { Ok(PersistResult::Inserted(tx)) } else { @@ -697,7 +697,7 @@ async fn handle_workflow_def( .map_err(|e| IngestError::Internal(format!("error: role check: {e}")))?; if !matches!(role.as_deref(), Some("owner") | Some("admin")) { return Err(IngestError::Rejected( - "forbidden: workflows with call_webhook actions require the owner or admin role" + "forbidden: workflows with call_webhook actions require the channel owner or admin role" .into(), )); } @@ -933,6 +933,7 @@ async fn handle_workflow_trigger( workflow_id, Some(&event_id_bytes), trigger_ctx_json.as_ref(), + &buzz_db::workflow::RunCause::Manual(self_bytes.clone()), ) .await .map_err(|e| IngestError::Internal(format!("error: db create_workflow_run: {e}")))?; @@ -972,14 +973,12 @@ async fn handle_workflow_trigger( } }; - let result = buzz_workflow::executor::execute_from_step( + let result = buzz_workflow::executor::execute_run( &engine, community_id, run_id, &def, &trigger_ctx_clone, - 0, - None, ) .await; engine @@ -1285,7 +1284,7 @@ async fn handle_approval_deny( } /// Resume a suspended workflow run after an approval gate has been granted. -async fn resume_workflow_after_approval( +pub(crate) async fn resume_workflow_after_approval( engine: Arc, db: buzz_db::Db, community_id: CommunityId, diff --git a/crates/buzz-relay/src/handlers/community_provisioning.rs b/crates/buzz-relay/src/handlers/community_provisioning.rs index 6c45c5800e1..2d0626e09cd 100644 --- a/crates/buzz-relay/src/handlers/community_provisioning.rs +++ b/crates/buzz-relay/src/handlers/community_provisioning.rs @@ -30,14 +30,11 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use tracing::info; -use buzz_core::tenant::{normalize_host, TenantContext}; +use buzz_core::tenant::{normalize_host, TenantContext, MAX_HOST_LEN}; use url::{Host, Url}; use crate::state::AppState; -/// Maximum accepted authority length. Matches `communities.host VARCHAR(255)`. -const MAX_HOST_LEN: usize = 255; - /// JSON body for `POST /operator/communities`. #[derive(Debug, Deserialize)] pub struct ProvisionCommunityRequest { @@ -51,6 +48,9 @@ pub struct ProvisionCommunityRequest { /// host instead of converging or rotating ownership. #[serde(default)] pub create_only: bool, + /// Initial policy for an atomic create only; absent/null preserves legacy behavior. + #[serde(default)] + pub initial_requires_nip_fi: Option, } /// JSON response from `POST /operator/communities`. @@ -66,6 +66,9 @@ pub struct ProvisionCommunityResponse { /// Echoes the validated owner pubkey when an owner bootstrap/rotation ran. #[serde(skip_serializing_if = "Option::is_none")] pub owner_pubkey: Option, + /// Current stored policy, present for the create-only writer. + #[serde(skip_serializing_if = "Option::is_none")] + pub requires_nip_fi: Option, } pub(crate) fn validate_pubkey_hex(value: &str) -> Option { @@ -256,7 +259,16 @@ pub async fn provision_community( return Err("actor not authorized: not a relay operator".to_string()); } + if request.initial_requires_nip_fi.is_some() && !request.create_only { + return Err( + "initial_policy_requires_create_only: initial_requires_nip_fi requires create_only" + .to_owned(), + ); + } validate_host(&request.host)?; + if !crate::single_community::serves_host(&state.config, &request.host) { + return Err("community_creation_disabled".to_owned()); + } let nip_fi_policy = state.config.nip_fi_provision_binding.as_ref(); // Unbound either way: `issuers_for_new_host` binds nothing on a reserved host. let nip_fi_issuers = @@ -273,6 +285,9 @@ pub async fn provision_community( .transpose()?; if request.create_only { + if !state.config.multi_community_relay { + return Err("community_creation_disabled".to_string()); + } if nip_fi_policy.is_some_and(|policy| policy.is_reserved(&request.host)) { return Err(buzz_auth::BindRefusal::ReservedHost.to_string()); } @@ -281,14 +296,18 @@ pub async fn provision_community( })?; let write = state .db - .create_community_with_owner_and_nip_fi_issuers( + .create_community_with_owner_and_nip_fi_policy( &request.host, owner_hex, nip_fi_issuers, + request.initial_requires_nip_fi.unwrap_or(false), &state.relay_keypair, ) .await - .map_err(|e| format!("failed to create community: {e}"))?; + .map_err(|e| match e { + buzz_db::DbError::NipFiBindingRequired => format!("nip_fi_binding_required: {e}"), + _ => format!("failed to create community: {e}"), + })?; let record = match write.outcome { buzz_db::CreateCommunityWithOwnerResult::Created(record) => record, buzz_db::CreateCommunityWithOwnerResult::HostExists => { @@ -304,30 +323,46 @@ pub async fn provision_community( community = %record.id, host = %record.host, owner = %owner_hex, - "community created via operator endpoint" + created = record.created, + requires_nip_fi = record.requires_nip_fi, + "community provisioned via operator endpoint" ); record_binding_creation( state.nip_fi_resolver.as_deref(), &record.host, nip_fi_issuers, ); + state.invalidate_community_host(&TenantContext::resolved(record.id, &record.host)); fan_out_membership_snapshot(state, record.id, &record.host, write.snapshot).await; return Ok(ProvisionCommunityResponse { community_id: record.id.to_string(), host: record.host, - status: "created", + status: if record.created { "created" } else { "existed" }, owner_pubkey: initial_owner, + requires_nip_fi: Some(record.requires_nip_fi), }); } // Legacy convergence mode remains available to deployment operators and // startup tooling. Clients provisioning on behalf of end users must use // create_only so an existing owner can never be rotated by a create race. - let record = state - .db - .ensure_configured_community_with_nip_fi_issuers(&request.host, nip_fi_issuers) - .await - .map_err(|e| format!("failed to create community: {e}"))?; + let record = if state.config.multi_community_relay { + state + .db + .ensure_configured_community_with_nip_fi_issuers(&request.host, nip_fi_issuers) + .await + .map_err(|e| format!("failed to create community: {e}"))? + } else { + // Never call an inserting ensure/upsert after an existence check: the + // disabled path must be unable to create even if the host disappears. + state + .db + .existing_configured_community(&request.host) + .await + .map_err(|e| format!("failed to create community: {e}"))? + .ok_or_else(|| "community_creation_disabled".to_string())? + }; + state.invalidate_community_host(&TenantContext::resolved(record.id, &record.host)); if record.created { record_binding_creation( state.nip_fi_resolver.as_deref(), @@ -370,6 +405,7 @@ pub async fn provision_community( host: record.host, status: if record.created { "created" } else { "existed" }, owner_pubkey: initial_owner, + requires_nip_fi: None, }) } diff --git a/crates/buzz-relay/src/handlers/count.rs b/crates/buzz-relay/src/handlers/count.rs index 5c2794a1645..3672ce6b300 100644 --- a/crates/buzz-relay/src/handlers/count.rs +++ b/crates/buzz-relay/src/handlers/count.rs @@ -10,6 +10,7 @@ use crate::connection::{AuthState, ConnectionState}; use crate::handlers::req::{ event_visible_to_reader, filter_can_match_result_gated_kinds, filter_can_match_shared_gated_kinds, result_gated_count_safe_for_pushdown, + DATABASE_ERROR_CLOSED, }; use crate::protocol::RelayMessage; use crate::state::AppState; @@ -22,6 +23,7 @@ pub async fn handle_count( conn: Arc, state: Arc, ) { + let mut access = crate::access::ReadLog::count(&conn, &sub_id, &filters); // Require auth let (pubkey_bytes, token_channel_ids) = { match conn.auth_state_snapshot() { @@ -33,6 +35,7 @@ pub async fn handle_count( &sub_id, "auth-required: not authenticated", )); + access.deny("auth_required"); return; } } @@ -46,6 +49,7 @@ pub async fn handle_count( &sub_id, "restricted: p-gated kinds require #p tag matching your pubkey", )); + access.deny("p_gated"); return; } if !super::req::engram_filters_authorized(&filters, &authed_pubkey_hex) { @@ -53,6 +57,7 @@ pub async fn handle_count( &sub_id, "restricted: agent-engram reads require authors=[self] or #p=[self]", )); + access.deny("engram_gated"); return; } if !super::req::author_only_filters_authorized(&filters, &authed_pubkey_hex) { @@ -60,6 +65,7 @@ pub async fn handle_count( &sub_id, "restricted: author-only kinds require authors=[self]", )); + access.deny("author_only"); return; } @@ -76,6 +82,7 @@ pub async fn handle_count( &sub_id, "restricted: too many explicit channels", )); + access.deny("too_many_channels"); return; } }; @@ -87,8 +94,9 @@ pub async fn handle_count( { Ok(ids) => ids, Err(e) => { - warn!(sub_id = %sub_id, "Failed to get accessible channels: {e}"); - conn.send(RelayMessage::closed(&sub_id, "error: database error")); + warn!(sub_id = %sub_id, error_kind = %e.kind(), "Failed to get accessible channels"); + conn.send(RelayMessage::closed(&sub_id, DATABASE_ERROR_CLOSED)); + access.error("database_error"); return; } }; @@ -115,8 +123,9 @@ pub async fn handle_count( { Ok(ids) => ids, Err(e) => { - warn!(sub_id = %sub_id, "Failed to get readable named-only channels: {e}"); - conn.send(RelayMessage::closed(&sub_id, "error: database error")); + warn!(sub_id = %sub_id, error_kind = %e.kind(), "Failed to get readable named-only channels"); + conn.send(RelayMessage::closed(&sub_id, DATABASE_ERROR_CLOSED)); + access.error("database_error"); return; } }; @@ -139,6 +148,7 @@ pub async fn handle_count( &sub_id, "restricted: authorization denied", )); + access.deny("session_expired"); return; } }; @@ -177,8 +187,9 @@ pub async fn handle_count( ) .await { - warn!(sub_id = %sub_id, "Channel membership confirmation failed: {e}"); - conn.send(RelayMessage::closed(&sub_id, "error: database error")); + warn!(sub_id = %sub_id, error_kind = %e.kind(), "Channel membership confirmation failed"); + conn.send(RelayMessage::closed(&sub_id, DATABASE_ERROR_CLOSED)); + access.error("database_error"); return; } if let Err(e) = super::system_channels::keep_repaired_named_only_channels_named( @@ -190,8 +201,9 @@ pub async fn handle_count( ) .await { - warn!(sub_id = %sub_id, "Failed to classify repaired channels: {e}"); - conn.send(RelayMessage::closed(&sub_id, "error: database error")); + warn!(sub_id = %sub_id, error_kind = %e.kind(), "Failed to classify repaired channels"); + conn.send(RelayMessage::closed(&sub_id, DATABASE_ERROR_CLOSED)); + access.error("database_error"); return; } let filter_scope = super::system_channels::filter_channel_scope( @@ -245,13 +257,14 @@ pub async fn handle_count( &sub_id, &super::req::db_read_closed_reason(&e), )); + access.db_failed(&e); return; } } } else { // Fallback: query + post-filter for non-pushable constraints. let mut q = query; - super::req::apply_count_fallback_limit(&mut q); + super::req::prepare_count_fallback(&mut q); match state .db .query_events_routed_bounded("count_req_fallback", &q) @@ -264,6 +277,7 @@ pub async fn handle_count( &sub_id, "restricted: count filter requires narrower constraints", )); + access.deny("count_too_broad"); return; } for se in stored_events { @@ -282,6 +296,7 @@ pub async fn handle_count( &sub_id, &super::req::db_read_closed_reason(&e), )); + access.db_failed(&e); return; } } @@ -332,12 +347,13 @@ pub async fn handle_count( &sub_id, &super::req::db_read_closed_reason(&e), )); + access.db_failed(&e); return; } } } else { // Fallback: query a bounded candidate set + post-filter. - super::req::apply_count_fallback_limit(&mut query); + super::req::prepare_count_fallback(&mut query); match state .db .query_events_routed_bounded("count_req_fallback", &query) @@ -350,6 +366,7 @@ pub async fn handle_count( &sub_id, "restricted: count filter requires narrower constraints", )); + access.deny("count_too_broad"); return; } for se in stored_events { @@ -368,6 +385,7 @@ pub async fn handle_count( &sub_id, &super::req::db_read_closed_reason(&e), )); + access.db_failed(&e); return; } } @@ -375,6 +393,7 @@ pub async fn handle_count( } } conn.send(RelayMessage::count(&sub_id, total)); + access.counted(total); } #[cfg(test)] @@ -424,6 +443,7 @@ mod tests { let (terminal_ctrl_tx, _terminal_ctrl_rx) = mpsc::channel::(1); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved(community, "test.local".to_string()), remote_addr: "127.0.0.1:1234".parse().unwrap(), diff --git a/crates/buzz-relay/src/handlers/deletion_postgres_tests.rs b/crates/buzz-relay/src/handlers/deletion_postgres_tests.rs new file mode 100644 index 00000000000..7e616c7057c --- /dev/null +++ b/crates/buzz-relay/src/handlers/deletion_postgres_tests.rs @@ -0,0 +1,199 @@ +//! Postgres-backed tests for kind 5 / 9005 deletions of `e` targets: the +//! deletion and its target's soft-delete commit together, or not at all. + +use std::sync::Arc; + +use buzz_core::TenantContext; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use uuid::Uuid; + +use crate::handlers::group_state_postgres_tests::{community, create_channel, http_auth, state}; +use crate::handlers::ingest::ingest_event; +use crate::state::AppState; + +/// Ingest a kind 9 message from `keys` in `channel_id`. +async fn post_message( + state: &Arc, + tenant: &TenantContext, + keys: &Keys, + channel_id: Uuid, +) -> Event { + let event = EventBuilder::new(Kind::Custom(9), "delete me") + .tags([Tag::parse(["h", &channel_id.to_string()]).unwrap()]) + .sign_with_keys(keys) + .expect("sign message"); + let result = ingest_event(state, tenant, event.clone(), http_auth(keys)) + .await + .unwrap_or_else(|error| panic!("post message: {error:?}")); + assert!(result.accepted, "{:?}", result.message); + event +} + +/// A deletion of `target` of `kind` (5 or 9005), signed by `keys`. +fn deletion(kind: u16, keys: &Keys, channel_id: Uuid, target: &Event) -> Event { + let mut tags = vec![Tag::parse(["e", &target.id.to_hex()]).unwrap()]; + if kind == 9005 { + tags.push(Tag::parse(["h", &channel_id.to_string()]).unwrap()); + } + EventBuilder::new(Kind::Custom(kind), "") + .tags(tags) + .sign_with_keys(keys) + .expect("sign deletion") +} + +/// `(stored, soft-deleted)` for event `id`. +async fn row_state(state: &AppState, tenant: &TenantContext, id: &Event) -> (bool, bool) { + let deleted_at: Option>> = + sqlx::query_scalar("SELECT deleted_at FROM events WHERE community_id = $1 AND id = $2") + .bind(tenant.community().as_uuid()) + .bind(id.id.as_bytes().as_slice()) + .fetch_optional(state.db.pool()) + .await + .expect("read event row"); + match deleted_at { + None => (false, false), + Some(deleted_at) => (true, deleted_at.is_some()), + } +} + +/// A target soft-delete that fails inside the write stores nothing: the +/// deletion is refused, the target stays live, and the same signed deletion +/// applies once the failure is gone. A test trigger makes the target's +/// soft-delete fail. Before, the relay stored the deletion, logged the failed +/// side effect, reported success, and answered a resend with `duplicate:`, +/// leaving the target live for good. Mutation: route the deletion through the +/// generic insert → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn failed_target_soft_delete_stores_nothing() { + for kind in [5u16, 9005] { + let state = state().await; + let tenant = community(&state, &format!("deletion-atomic-fail-{kind}")).await; + let owner = Keys::generate(); + let channel_id = create_channel(&state, &tenant, &owner, &[]).await; + let target = post_message(&state, &tenant, &owner, channel_id).await; + let deletion = deletion(kind, &owner, channel_id, &target); + + // Scoped to this target, so no other test's writes can trip it. + for statement in [ + "CREATE OR REPLACE FUNCTION deletion_atomic_fail() RETURNS trigger \ + LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected soft-delete failure'; END $$" + .to_owned(), + format!( + "CREATE TRIGGER deletion_atomic_fail BEFORE UPDATE ON events FOR EACH ROW \ + WHEN (OLD.id = '\\x{}'::bytea AND OLD.deleted_at IS NULL \ + AND NEW.deleted_at IS NOT NULL) EXECUTE FUNCTION deletion_atomic_fail()", + target.id.to_hex() + ), + ] { + sqlx::raw_sql(sqlx::AssertSqlSafe(statement)) + .execute(state.db.pool()) + .await + .expect("install failure trigger"); + } + + for attempt in ["first send", "resend"] { + match ingest_event(&state, &tenant, deletion.clone(), http_auth(&owner)).await { + Ok(result) => assert!( + !result.accepted, + "kind {kind} {attempt}: a failed deletion was reported as accepted: {:?}", + result.message + ), + Err(error) => assert!( + format!("{error:?}").contains("deletion failed"), + "kind {kind} {attempt}: {error:?}" + ), + } + assert_eq!( + row_state(&state, &tenant, &deletion).await, + (false, false), + "kind {kind} {attempt}: the deletion is not stored" + ); + assert_eq!( + row_state(&state, &tenant, &target).await, + (true, false), + "kind {kind} {attempt}: the target stays live" + ); + } + + sqlx::query("DROP TRIGGER deletion_atomic_fail ON events") + .execute(state.db.pool()) + .await + .expect("drop failure trigger"); + let retry = ingest_event(&state, &tenant, deletion.clone(), http_auth(&owner)) + .await + .unwrap_or_else(|error| panic!("kind {kind} retry: {error:?}")); + assert!(retry.accepted, "kind {kind}: {:?}", retry.message); + assert!( + !retry.message.starts_with("duplicate:"), + "kind {kind}: {:?}", + retry.message + ); + assert_eq!(row_state(&state, &tenant, &deletion).await, (true, false)); + assert_eq!( + row_state(&state, &tenant, &target).await, + (true, true), + "kind {kind}: the target is soft-deleted with the deletion" + ); + } +} + +/// A resend of a deletion stored without its target's soft-delete (a row an +/// earlier, non-atomic write left torn) applies it and is not answered as a +/// bare duplicate; a further resend changes nothing. Only a resend inside the +/// ingest timestamp window gets here; older torn rows rely on the read path +/// (`torn_deletions_still_cancel_live_targets_in_both_windows`). Mutation: skip the +/// target soft-delete for a duplicate deletion → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn resent_deletion_repairs_a_live_target() { + for kind in [5u16, 9005] { + let state = state().await; + let tenant = community(&state, &format!("deletion-repair-{kind}")).await; + let owner = Keys::generate(); + let channel_id = create_channel(&state, &tenant, &owner, &[]).await; + let target = post_message(&state, &tenant, &owner, channel_id).await; + let deletion = deletion(kind, &owner, channel_id, &target); + state + .db + .insert_event(tenant.community(), &deletion, Some(channel_id)) + .await + .expect("store a torn deletion"); + assert_eq!(row_state(&state, &tenant, &target).await, (true, false)); + + let repair = ingest_event(&state, &tenant, deletion.clone(), http_auth(&owner)) + .await + .unwrap_or_else(|error| panic!("kind {kind} repair: {error:?}")); + assert!(repair.accepted, "kind {kind}: {:?}", repair.message); + assert!( + !repair.message.starts_with("duplicate:"), + "kind {kind}: a repairing resend reaches dispatch: {:?}", + repair.message + ); + assert_eq!( + row_state(&state, &tenant, &target).await, + (true, true), + "kind {kind}: the resend soft-deletes the live target" + ); + + // Once applied, a kind 5 resend is a duplicate. Kind 9005 validation + // reads a tombstoned target as missing, so its resend is refused + // before storage, as it was before deletions became atomic. + let again = ingest_event(&state, &tenant, deletion.clone(), http_auth(&owner)).await; + match (kind, again) { + (5, Ok(result)) => assert!( + result.accepted && result.message.starts_with("duplicate:"), + "an applied kind 5 deletion is a duplicate: {:?}", + result.message + ), + (9005, Err(error)) => assert!( + format!("{error:?}").contains("deletion target not found"), + "{error:?}" + ), + (kind, Ok(result)) => panic!("kind {kind} resend: {:?}", result.message), + (kind, Err(error)) => panic!("kind {kind} resend: {error:?}"), + } + assert_eq!(row_state(&state, &tenant, &deletion).await, (true, false)); + assert_eq!(row_state(&state, &tenant, &target).await, (true, true)); + } +} diff --git a/crates/buzz-relay/src/handlers/edit_metadata_postgres_tests.rs b/crates/buzz-relay/src/handlers/edit_metadata_postgres_tests.rs index 806e740b9a4..54283d5f86c 100644 --- a/crates/buzz-relay/src/handlers/edit_metadata_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/edit_metadata_postgres_tests.rs @@ -6,7 +6,7 @@ use nostr::{EventBuilder, Keys, Kind, Tag}; use uuid::Uuid; use crate::handlers::group_state_postgres_tests::{ - community, create_channel, edit_channel, http_auth, state, + community, create_channel, edit_channel, group_state_tags, http_auth, state, }; use crate::handlers::ingest::ingest_event; @@ -350,6 +350,281 @@ async fn join_role_edit_is_applied_and_announced() { assert!(announced, "one join_role_changed system message"); } +/// `auto_join` is a community setting: only a relay owner or admin may set +/// it, on an open, unarchived stream channel, and kind:39000 advertises it +/// only while it is effective. Mutations: drop the relay-role tier → the +/// channel owner's edit is accepted (RED); drop the in-transaction guard → +/// `true` on a private or archived channel is accepted (RED); guard only +/// `true` again → the relay admin's `false` is stored in the private +/// channel (RED); mirror the column instead of the effective state in +/// `group_metadata_tags` → the tag survives the flip to private (RED). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn auto_join_is_relay_admin_only_and_advertised_while_effective() { + let state = state().await; + let tenant = community(&state, "edit-auto-join").await; + let owner = Keys::generate(); + let channel_id = create_channel(&state, &tenant, &owner, &[]).await; + let notices_before = count_kind(&state, &tenant, channel_id, 40099).await; + let advertised = |tags: Vec>| tags.contains(&vec!["auto_join".to_string()]); + + // The channel owner is not a relay owner or admin: refused, nothing changes. + let refused = edit_channel( + &state, + &tenant, + &owner, + channel_id, + &[&["auto_join", "true"]], + ) + .await + .expect_err("channel owner must not set auto_join"); + assert!( + refused.contains("relay owner or admin"), + "channel owner refusal: {refused}" + ); + assert!( + !state + .db + .get_channel(tenant.community(), channel_id) + .await + .expect("channel") + .auto_join + ); + assert!(!advertised( + group_state_tags(&state, &tenant, channel_id, 39000).await + )); + + // A relay admin who is not a channel member sets it. One transaction + // stores the event, the column and one `auto_join_changed` notice, and + // the republished kind:39000 advertises it. + let admin = Keys::generate(); + state + .db + .add_relay_member( + tenant.community(), + &admin.public_key().to_hex(), + "admin", + None, + &Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("seed relay admin"); + edit_channel( + &state, + &tenant, + &admin, + channel_id, + &[&["auto_join", "true"]], + ) + .await + .expect("relay admin sets auto_join"); + assert!( + state + .db + .get_channel(tenant.community(), channel_id) + .await + .expect("channel") + .auto_join + ); + assert!(advertised( + group_state_tags(&state, &tenant, channel_id, 39000).await + )); + let notices = state + .db + .query_events(&EventQuery { + kinds: Some(vec![40099]), + channel_id: Some(channel_id), + ..EventQuery::for_community(tenant.community()) + }) + .await + .expect("query events"); + assert_eq!(notices.len(), notices_before + 1); + assert!( + notices + .iter() + .filter_map( + |stored| serde_json::from_str::(&stored.event.content).ok() + ) + .any(|content| content["type"] == "auto_join_changed" && content["auto_join"] == true), + "one auto_join_changed system message" + ); + let listed = state + .db + .list_auto_join_channels(tenant.community()) + .await + .expect("list auto_join channels"); + assert_eq!( + listed.iter().map(|c| c.id).collect::>(), + [channel_id] + ); + + // Private: the stored value stays, but it is no longer effective, so the + // tag disappears and the relay would not join anyone. + edit_channel( + &state, + &tenant, + &owner, + channel_id, + &[&["visibility", "private"]], + ) + .await + .expect("make private"); + assert!( + state + .db + .get_channel(tenant.community(), channel_id) + .await + .expect("channel") + .auto_join + ); + assert!(!advertised( + group_state_tags(&state, &tenant, channel_id, 39000).await + )); + assert!(state + .db + .list_auto_join_channels(tenant.community()) + .await + .expect("list auto_join channels") + .is_empty()); + + // Both values are refused on a private channel, the same way, and + // nothing of either event is stored: the relay admin is not a member, + // so storing even a `false` would write into a channel they cannot + // read. Opening and flagging in one event is accepted: the guard sees + // the event's result. `visibility` still needs the channel owner, so + // that event comes from the owner once they are also on the relay + // roster: both tiers run. The nonce keeps the `true` from signing the + // same event id as the accepted edit above, which the relay would drop + // as a duplicate. + let (events_before, notices_before) = ( + count_kind(&state, &tenant, channel_id, 9002).await, + count_kind(&state, &tenant, channel_id, 40099).await, + ); + let refused_edits: [&[&[&str]]; 2] = [ + &[&["auto_join", "true"], &["nonce", "private"]], + &[&["auto_join", "false"]], + ]; + for tags in refused_edits { + let refused = edit_channel(&state, &tenant, &admin, channel_id, tags) + .await + .expect_err("auto_join on a private channel"); + assert!( + refused.contains("open, unarchived"), + "private refusal of {tags:?}: {refused}" + ); + } + assert_eq!( + count_kind(&state, &tenant, channel_id, 9002).await, + events_before, + "a refused auto_join event is not stored" + ); + assert_eq!( + count_kind(&state, &tenant, channel_id, 40099).await, + notices_before, + "a refused auto_join event announces nothing" + ); + assert!( + state + .db + .get_channel(tenant.community(), channel_id) + .await + .expect("channel") + .auto_join, + "the refused `false` leaves the stored value in place" + ); + state + .db + .add_relay_member( + tenant.community(), + &owner.public_key().to_hex(), + "owner", + None, + &Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("seed relay owner"); + edit_channel( + &state, + &tenant, + &owner, + channel_id, + &[&["visibility", "open"], &["auto_join", "true"]], + ) + .await + .expect("open and flag in one event"); + assert!(advertised( + group_state_tags(&state, &tenant, channel_id, 39000).await + )); + + // Archived and forum channels cannot be default channels. Archiving and + // flagging in one event is refused by the guard on the event's result, + // and nothing of that event applies; on a channel that is already + // archived the archive fence refuses the edit first. + let archived_id = create_channel(&state, &tenant, &owner, &[]).await; + let refused = edit_channel( + &state, + &tenant, + &owner, + archived_id, + &[&["archived", "true"], &["auto_join", "true"]], + ) + .await + .expect_err("archive and flag in one event"); + assert!( + refused.contains("open, unarchived"), + "archive-and-flag refusal: {refused}" + ); + assert!( + state + .db + .get_channel(tenant.community(), archived_id) + .await + .expect("channel") + .archived_at + .is_none(), + "a refused event archives nothing" + ); + edit_channel( + &state, + &tenant, + &owner, + archived_id, + &[&["archived", "true"]], + ) + .await + .expect("archive"); + let refused = edit_channel( + &state, + &tenant, + &admin, + archived_id, + &[&["auto_join", "true"]], + ) + .await + .expect_err("auto_join=true on an archived channel"); + assert!(refused.contains("archived"), "archived refusal: {refused}"); + let forum_id = create_channel(&state, &tenant, &owner, &[&["channel_type", "forum"]]).await; + let refused = edit_channel(&state, &tenant, &admin, forum_id, &[&["auto_join", "true"]]) + .await + .expect_err("auto_join=true on a forum"); + assert!( + refused.contains("stream channels"), + "forum refusal: {refused}" + ); + for id in [archived_id, forum_id] { + assert!( + !state + .db + .get_channel(tenant.community(), id) + .await + .expect("channel") + .auto_join + ); + } +} + /// Sign a kind:9002 that sets `archived` to `value` on `channel_id`. fn archive_event(owner: &Keys, channel_id: Uuid, value: &str) -> nostr::Event { EventBuilder::new(Kind::Custom(9002), "") @@ -361,6 +636,55 @@ fn archive_event(owner: &Keys, channel_id: Uuid, value: &str) -> nostr::Event { .expect("sign 9002") } +/// The loader returns every effective default channel. It used to stop at 32 +/// while kind:9002 kept accepting the flag past that, so the kind:39000 tag +/// promised a join the relay never made for the newest channels. Mutation: +/// put a `LIMIT` back on `list_auto_join_channels` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn every_default_channel_is_listed() { + let state = state().await; + let tenant = community(&state, "auto-join-all").await; + let admin = Keys::generate(); + state + .db + .add_relay_member( + tenant.community(), + &admin.public_key().to_hex(), + "admin", + None, + &Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("seed relay admin"); + + let mut flagged = Vec::new(); + for _ in 0..33 { + let channel_id = create_channel(&state, &tenant, &admin, &[]).await; + edit_channel( + &state, + &tenant, + &admin, + channel_id, + &[&["auto_join", "true"]], + ) + .await + .expect("relay admin sets auto_join"); + flagged.push(channel_id); + } + + let listed: Vec = state + .db + .list_auto_join_channels(tenant.community()) + .await + .expect("list auto_join channels") + .iter() + .map(|channel| channel.id) + .collect(); + assert_eq!(listed, flagged, "every flagged channel, oldest first"); +} + /// A resend checked after its first copy committed is a duplicate. /// Validation runs on the new archive state and must not refuse the resend; /// the write must then report it as a duplicate, with no change and no diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index 6ee506f9e57..781b3541c01 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -21,7 +21,6 @@ use buzz_pubsub::EventTopic; use nostr::{Event, PublicKey}; use crate::connection::{AuthState, ConnectionState}; -use crate::protocol::RelayMessage; use crate::state::AppState; use super::ingest::{reject_with_transport, IngestAuth, IngestError}; @@ -52,6 +51,15 @@ pub(crate) fn bounded_kind_label(kind: u32) -> String { } } +/// Time one persistent WebSocket EVENT from frame to OK under `outcome`: +/// `accepted`, `not_accepted` (for example a duplicate), or the ingest error +/// class (`invalid`, `auth`, `error`). Failures are timed too, so a slow +/// failing store shows in the latency instead of hiding from it. +fn record_event_processing(start: std::time::Instant, outcome: &'static str) { + metrics::histogram!("buzz_event_processing_seconds", "outcome" => outcome) + .record(start.elapsed().as_secs_f64()); +} + fn event_frame_for_sub(sub_id: &str, event_json: &str) -> String { format!(r#"["EVENT","{}",{}]"#, sub_id, event_json) } @@ -119,6 +127,33 @@ pub async fn filter_fanout_by_access( matches: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, threaded: Option<&crate::state::ThreadedChannelVisibility>, ) -> Vec<(crate::subscription::ConnId, crate::subscription::SubId)> { + check_fanout_access(state, community_id, stored_event, matches, threaded) + .await + .allowed +} + +/// The result of the fan-out access gate. +struct FanoutAccess { + /// Recipients that may receive the event. + allowed: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, + /// Recipients dropped because a visibility or membership lookup failed, + /// not because they lack access. + unverified: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, +} + +/// `filter_fanout_by_access`, also reporting the recipients it dropped +/// only because a lookup failed. +async fn check_fanout_access( + state: &AppState, + community_id: CommunityId, + stored_event: &StoredEvent, + matches: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, + threaded: Option<&crate::state::ThreadedChannelVisibility>, +) -> FanoutAccess { + let verified = |allowed| FanoutAccess { + allowed, + unverified: Vec::new(), + }; // First enforce the receiver-side tenant label. Subscription indexes are // community-scoped, but stale/injected matches and future fan-out helpers // must still fail closed at the send chokepoint: a connection bound to @@ -200,7 +235,7 @@ pub async fn filter_fanout_by_access( }; let Some(channel_id) = stored_event.channel_id else { - return matches; + return verified(matches); }; // Fence 3 (§4.8 phase-2): the threaded value is used only when it was // resolved under exactly this (community_id, channel_id); anything else @@ -217,33 +252,75 @@ pub async fn filter_fanout_by_access( } }; match visibility { - Ok(v) if v != "private" => return matches, + Ok(v) if v != "private" => return verified(matches), Ok(_) => {} + // A deleted channel grants no one access. That is an answer, not a + // failed check, so its recipients are not unverified. + Err(buzz_db::DbError::ChannelNotFound(_)) => return verified(Vec::new()), Err(e) => { // Fail closed: if we cannot determine visibility, do not leak a // possibly-private channel's events. warn!(%channel_id, "fan-out access filter: visibility lookup failed: {e}"); - return Vec::new(); + return FanoutAccess { + allowed: Vec::new(), + unverified: matches, + }; } } - let mut allowed = Vec::with_capacity(matches.len()); - for (conn_id, sub_id) in matches { - let Some(pubkey) = state.conn_manager.pubkey_for_conn(conn_id) else { - continue; - }; - match state - .is_member_cached(community_id, channel_id, &pubkey) - .await - { - Ok(true) => allowed.push((conn_id, sub_id)), - Ok(false) => {} - Err(e) => { - warn!(%channel_id, "fan-out access filter: membership lookup failed: {e}"); - } + // One membership read for every recipient the cache lacks, not one per + // recipient: each read would wait on the pool in turn. + let recipients: Vec<_> = matches + .into_iter() + .filter_map(|(conn_id, sub_id)| { + Some(( + conn_id, + sub_id, + state.conn_manager.pubkey_for_conn(conn_id)?, + )) + }) + .collect(); + let members = state + .members_cached( + community_id, + channel_id, + recipients.iter().map(|(.., pubkey)| pubkey.clone()), + ) + .await; + let mut allowed = Vec::with_capacity(recipients.len()); + let mut unverified = Vec::new(); + for (conn_id, sub_id, pubkey) in recipients { + if members.members.contains(&pubkey) { + allowed.push((conn_id, sub_id)); + } else if members.unverified.contains(&pubkey) { + unverified.push((conn_id, sub_id)); } } - allowed + FanoutAccess { + allowed, + unverified, + } +} + +/// Pass fan-out matches through the access gate, and return the ones that +/// receive the event itself. Syncs among the matches get its change signal +/// instead (NIP-AR rule 5), and each fan-out path calls this, so none of them +/// can skip a sync. +pub(crate) async fn route_fanout_matches( + state: &AppState, + community_id: CommunityId, + stored: &StoredEvent, + matches: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, + threaded: Option<&crate::state::ThreadedChannelVisibility>, +) -> Vec<(crate::subscription::ConnId, crate::subscription::SubId)> { + state.artifact_syncs.signal_access_change(stored, &matches); + let access = check_fanout_access(state, community_id, stored, matches, threaded).await; + // A sync that the gate could not check loses this change, so its copy is + // no longer exact. It must not stay open as if it were. + state + .artifact_syncs + .resync_matches(&access.unverified, "resync: access check failed"); + state.artifact_syncs.divert(stored, access.allowed) } /// Deliver one event to this relay's local subscribers through the access gate. @@ -267,7 +344,7 @@ pub(crate) async fn fan_out_event_to_local_subscribers( stored: &StoredEvent, ) { let matches = state.sub_registry.fan_out_scoped(community_id, stored); - let matches = filter_fanout_by_access(state, community_id, stored, matches, None).await; + let matches = route_fanout_matches(state, community_id, stored, matches, None).await; metrics::histogram!("buzz_fanout_recipients").record(matches.len() as f64); if matches.is_empty() { return; @@ -303,36 +380,59 @@ pub(crate) async fn fan_out_event_to_local_subscribers( /// Fan out one event received from Redis pub/sub to this relay's local subscribers. #[tracing::instrument(skip_all)] pub async fn fan_out_pubsub_event(state: &Arc, channel_event: buzz_pubsub::ChannelEvent) { - // The Redis topic carries the tenant-local routing scope explicitly: - // `Channel(id)` for a per-channel event, `Global` for a channel-less one. - // Convert back to the `Option` channel id `fan_out()` indexes on — - // `Global` selects the global subscriber index. - let channel_id = match channel_event.topic { - buzz_pubsub::EventTopic::Channel(id) => Some(id), - buzz_pubsub::EventTopic::Global => None, - }; + if take_local_echo(state, &channel_event) { + return; + } let community_id = channel_event.community_id; - let stored = StoredEvent::new(channel_event.event, channel_id); - - // Skip events that were already fanned out in-process (local echo). The - // dedup key is `(community_id, event_id)` — a same-id event arriving for a - // *different* community is a distinct delivery and must not be suppressed. - // The cache has TTL-based eviction (60s) so entries are bounded regardless - // of subscriber health. - let event_id_bytes = stored.event.id.to_bytes(); - let echo_key = (community_id, event_id_bytes); + deliver_pubsub_event(state, community_id, &pubsub_stored_event(channel_event)).await; +} + +/// Report whether `channel_event` is the Redis echo of an event this relay +/// already fanned out in-process, consuming the echo record if so. +/// +/// The dedup key is `(community_id, event_id)` — a same-id event arriving for a +/// *different* community is a distinct delivery and must not be suppressed. +/// The cache has TTL-based eviction (60s) so entries are bounded regardless of +/// subscriber health. +pub(crate) fn take_local_echo(state: &AppState, channel_event: &buzz_pubsub::ChannelEvent) -> bool { + let echo_key = ( + channel_event.community_id, + channel_event.event.id.to_bytes(), + ); if state.local_event_ids.get(&echo_key).is_some() { state.local_event_ids.invalidate(&echo_key); - return; + return true; } + false +} - let matches = state.sub_registry.fan_out_scoped(community_id, &stored); - let matches = filter_fanout_by_access(state, community_id, &stored, matches, None).await; +/// The `StoredEvent` a Redis event fans out as. +/// +/// The Redis topic carries the tenant-local routing scope explicitly: +/// `Channel(id)` for a per-channel event, `Global` for a channel-less one. +/// Convert back to the `Option` channel id `fan_out()` indexes on — +/// `Global` selects the global subscriber index. +pub(crate) fn pubsub_stored_event(channel_event: buzz_pubsub::ChannelEvent) -> StoredEvent { + let channel_id = match channel_event.topic { + buzz_pubsub::EventTopic::Channel(id) => Some(id), + buzz_pubsub::EventTopic::Global => None, + }; + StoredEvent::new(channel_event.event, channel_id) +} + +/// Deliver one Redis event that is not a local echo to this relay's local +/// subscribers, through the access gate. +pub(crate) async fn deliver_pubsub_event( + state: &Arc, + community_id: CommunityId, + stored: &StoredEvent, +) { + let matches = state.sub_registry.fan_out_scoped(community_id, stored); + let matches = route_fanout_matches(state, community_id, stored, matches, None).await; metrics::counter!("buzz_multinode_fanout_total").increment(1); if matches.is_empty() { return; } - let event_json = match serde_json::to_string(&stored.event) { Ok(json) => json, Err(e) => { @@ -437,24 +537,12 @@ async fn dispatch_persistent_event_inner( Some(channel_id) => EventTopic::Channel(channel_id), None => EventTopic::Global, }; - state.mark_local_event(tenant.community(), &stored_event.event.id); - #[cfg(test)] - crate::nip_fi_test_hooks::before_event_publish(tenant.community()); - if let Err(e) = state - .pubsub - .publish_event(tenant, topic, &stored_event.event) - .await - { - state - .local_event_ids - .invalidate(&(tenant.community(), stored_event.event.id.to_bytes())); - warn!(event_id = %event_id_hex, "Redis publish failed: {e}"); - } + super::artifact_sync::publish_reliably(state, tenant, topic, stored_event).await; let matches = state .sub_registry .fan_out_scoped(tenant.community(), stored_event); - let matches = filter_fanout_by_access( + let matches = route_fanout_matches( state, tenant.community(), stored_event, @@ -603,6 +691,7 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc, state: Arc { reject("auth"); - conn.send(RelayMessage::ok( + write.ok( + &conn, &event_id_hex, false, "auth-required: not authenticated", - )); + ); return; } } @@ -652,38 +742,36 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc, state: Arc (m, "auth"), }; reject(reason); - conn.send(RelayMessage::ok(&event_id_hex, false, &message)); + write.ok(&conn, &event_id_hex, false, &message); return; } } @@ -704,11 +792,12 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc, state: Arc, state: Arc {} Ok(false) => { reject("restricted"); - conn.send(RelayMessage::ok( + write.ok( + &conn, &event_id_hex, false, "restricted: community writes are fenced", - )); + ); return; } Err(error) => { reject("error"); tracing::warn!(%error, event_id = %event_id_hex, "failed to check ephemeral-event community lifecycle"); - conn.send(RelayMessage::ok( - &event_id_hex, - false, - "error: internal server error", - )); + write.ok(&conn, &event_id_hex, false, "error: internal server error"); return; } } @@ -792,11 +880,12 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc permit, Err(crate::nip_fi_gate::SessionExpired) => { // Fix 4: [FI-TRACE-DENIAL-ORACLE] - conn.send(RelayMessage::ok( + write.ok( + &conn, &event_id_hex, false, "restricted: authorization denied", - )); + ); return; } }; @@ -811,7 +900,7 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc { - conn.send(RelayMessage::ok(&event_id_hex, true, "")); + write.ok(&conn, &event_id_hex, true, ""); } Err(e) => { // Rejections carry the ingest taxonomy so backend failures @@ -833,7 +922,7 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc, state: Arc permit, Err(crate::nip_fi_gate::SessionExpired) => { // Fix 4: [FI-TRACE-DENIAL-ORACLE] - conn.send(RelayMessage::ok( + write.ok( + &conn, &event_id_hex, false, "restricted: authorization denied", - )); + ); return; } }; @@ -881,13 +971,15 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc { let e = e.into_legacy(); @@ -901,8 +993,9 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc return Err(IngestError::Rejected(format!("invalid: {e}"))), Err(_) => return Err(IngestError::Internal("error: internal error".into())), } - // Same short-TTL caches as the WebSocket ephemeral path: this runs per - // typing pulse, and persistent ingest keeps the uncached durable fence. - super::ingest::enforce_cached_write_restriction( - state, - tenant, - KIND_TYPING_INDICATOR, - &auth_pubkey, - ) - .await?; + // Same restriction gate and serving-fence cache as the WebSocket + // ephemeral path: this runs per typing pulse. + super::ingest::enforce_write_restriction(state, tenant, KIND_TYPING_INDICATOR, &auth_pubkey) + .await?; super::ingest::map_serving_fence_state( - state.is_serving_active_cached(tenant.community()).await, + state.is_community_active_cached(tenant.community()).await, )?; publish_channel_ephemeral(state, tenant, event, ch_id, auth_pubkey.as_bytes()).await } @@ -1271,25 +1359,18 @@ async fn handle_agent_observer_event( event_id_hex: &str, conn: Arc, state: Arc, + write: &mut crate::access::WriteLog, ) { let event_clone = event.clone(); let verify_result = tokio::task::spawn_blocking(move || verify_event(&event_clone)).await; match verify_result { Ok(Ok(())) => {} Ok(Err(e)) => { - conn.send(RelayMessage::ok( - event_id_hex, - false, - &format!("invalid: {e}"), - )); + write.ok(&conn, event_id_hex, false, &format!("invalid: {e}")); return; } Err(_) => { - conn.send(RelayMessage::ok( - event_id_hex, - false, - "error: internal error", - )); + write.ok(&conn, event_id_hex, false, "error: internal error"); return; } } @@ -1298,11 +1379,12 @@ async fn handle_agent_observer_event( let now = chrono::Utc::now().timestamp(); let event_ts = event.created_at.as_secs() as i64; if (event_ts - now).unsigned_abs() > 300 { - conn.send(RelayMessage::ok( + write.ok( + &conn, event_id_hex, false, "invalid: observer frame timestamp outside ±5 minute freshness window", - )); + ); return; } @@ -1310,12 +1392,12 @@ async fn handle_agent_observer_event( Ok(Some(route)) => route, Ok(None) => { // Unknown frame value — silently drop, no error to publisher. - conn.send(RelayMessage::ok(event_id_hex, true, "")); + write.ok(&conn, event_id_hex, true, ""); return; } Err(message) => { reject("invalid"); - conn.send(RelayMessage::ok(event_id_hex, false, &message)); + write.ok(&conn, event_id_hex, false, &message); return; } }; @@ -1354,11 +1436,7 @@ async fn handle_agent_observer_event( } Err(e) => { warn!(conn_id = %conn_id, event_id = %event_id_hex, "agent observer owner check failed: {e}"); - conn.send(RelayMessage::ok( - event_id_hex, - false, - "error: internal server error", - )); + write.ok(&conn, event_id_hex, false, "error: internal server error"); return; } } @@ -1367,11 +1445,12 @@ async fn handle_agent_observer_event( }; if !is_owner { reject("auth"); - conn.send(RelayMessage::ok( + write.ok( + &conn, event_id_hex, false, "restricted: observer frame is not authorized for this agent owner", - )); + ); return; } @@ -1381,11 +1460,12 @@ async fn handle_agent_observer_event( if matches!(route.direction, AgentObserverDirection::Telemetry) { let agent_key: [u8; 32] = agent_bytes.as_slice().try_into().unwrap_or([0u8; 32]); if observer_frame_rate_limited(&state, conn.tenant.community(), agent_key) { - conn.send(RelayMessage::ok( + write.ok( + &conn, event_id_hex, false, "rate-limited: observer frame rate exceeded (100/sec per agent)", - )); + ); return; } } @@ -1412,7 +1492,7 @@ async fn handle_agent_observer_event( ); fan_out_event_to_local_subscribers(&state, conn.tenant.community(), &stored_event).await; - conn.send(RelayMessage::ok(event_id_hex, true, "")); + write.ok(&conn, event_id_hex, true, ""); } fn agent_observer_route(event: &Event) -> Result, String> { @@ -1750,6 +1830,7 @@ mod tests { let (ctrl_tx, _ctrl_rx) = mpsc::channel(1); let (terminal_ctrl_tx, _terminal_ctrl_rx) = mpsc::channel(1); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::TenantContext::resolved(community_b, "b.example"), remote_addr: "127.0.0.1:1234".parse().expect("socket addr"), @@ -1779,12 +1860,14 @@ mod tests { ), }); + let mut write = crate::access::WriteLog::new(&conn, &event); super::handle_agent_observer_event( event.clone(), conn.conn_id, &event.id.to_hex(), conn, state, + &mut write, ) .await; @@ -1837,6 +1920,7 @@ mod tests { let (send_tx, mut send_rx) = mpsc::channel(10); let (ctrl_tx, _ctrl_rx) = mpsc::channel(10); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: tenant.clone(), remote_addr: "127.0.0.1:1234".parse().unwrap(), @@ -1998,6 +2082,7 @@ mod tests { } let (send_tx, _send_rx) = mpsc::channel(10); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: tenant.clone(), remote_addr: "127.0.0.1:1234".parse().unwrap(), @@ -2120,6 +2205,7 @@ mod tests { let (send_tx, mut send_rx) = mpsc::channel(10); let (ctrl_tx, _ctrl_rx) = mpsc::channel(10); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: tenant.clone(), remote_addr: "127.0.0.1:1234".parse().unwrap(), @@ -2622,10 +2708,8 @@ mod tests { async fn redis_url_if_available() -> Option { let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string()); - let pool = deadpool_redis::Config::from_url(&redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; - let mut conn = pool.get().await.ok()?; + let pool = buzz_pubsub::redis_connection(&redis_url).ok()?; + let mut conn = pool.clone(); redis::cmd("PING") .query_async::(&mut conn) .await @@ -2976,9 +3060,7 @@ mod tests { config.redis_url = redis_url.to_string(); let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool"); + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -3024,11 +3106,9 @@ mod tests { config.redis_url = "redis://127.0.0.1:6379".to_string(); let pool = sqlx::PgPool::connect(&config.database_url).await.ok()?; // Require a real Redis so dispatch's publish_event doesn't error-log. - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; redis::cmd("PING") - .query_async::(&mut redis_pool.get().await.ok()?) + .query_async::(&mut redis_pool.clone()) .await .ok()?; let db = buzz_db::Db::from_pool(pool.clone()); @@ -3179,10 +3259,10 @@ mod tests { let non_member_pk = vec![2u8; 32]; state .membership_cache - .insert((community_id, channel_id, member_pk.clone()), true); + .seed_member((community_id, channel_id, member_pk.clone()), true); state .membership_cache - .insert((community_id, channel_id, non_member_pk.clone()), false); + .seed_member((community_id, channel_id, non_member_pk.clone()), false); let member = register_conn(&state, Some(member_pk)); let non_member = register_conn(&state, Some(non_member_pk)); @@ -3298,10 +3378,10 @@ mod tests { let non_member_pk = vec![2u8; 32]; state .membership_cache - .insert((community_id, channel_id, member_pk.clone()), true); + .seed_member((community_id, channel_id, member_pk.clone()), true); state .membership_cache - .insert((community_id, channel_id, non_member_pk.clone()), false); + .seed_member((community_id, channel_id, non_member_pk.clone()), false); let threaded = crate::state::ThreadedChannelVisibility { community_id, @@ -3351,6 +3431,126 @@ mod tests { .await; assert_eq!(out, matches); } + /// A sync among the fan-out matches must resync when the access gate + /// cannot check it: the gate drops the change, so the sync's copy is + /// no longer exact. Runs through both production fan-out entries. + /// Mutation: drop the `resync_matches` call in `route_fanout_matches` + /// → the failed lookups leave every sync open with no resync → RED. + #[tokio::test] + async fn failed_access_lookup_resyncs_the_syncs_it_drops() { + let state = test_state().await; + // Every database lookup now fails at once. + state.db.pool().close().await; + let community_id = buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()); + let pk = vec![1u8; 32]; + let artifact = |channel_id| { + let event = EventBuilder::new(Kind::Custom(45010), "{}") + .tags([nostr::Tag::parse(["d", &Uuid::new_v4().to_string()]).expect("d")]) + .sign_with_keys(&Keys::generate()) + .expect("sign"); + StoredEvent::new(event, Some(channel_id)) + }; + let sync_on = |channel_id| { + let conn = register_conn(&state, Some(pk.clone())); + state.sub_registry.register_channels_scoped( + community_id, + conn, + "s".to_string(), + vec![nostr::Filter::new()], + vec![channel_id], + ); + state.artifact_syncs.insert_idle(conn, "s"); + conn + }; + let private = |channel_id| { + state + .channel_visibility_cache + .insert((community_id, channel_id), "private".to_string()); + }; + + // Control: a member whose access is known gets the change signal. + let known = Uuid::new_v4(); + private(known); + state + .membership_cache + .seed_member((community_id, known, pk.clone()), true); + let conn = sync_on(known); + super::super::fan_out_event_to_local_subscribers( + &state, + community_id, + &artifact(known), + ) + .await; + assert_eq!(state.artifact_syncs.pending_resync(conn, "s"), None); + + // The visibility lookup fails (local fan-out). + let channel_id = Uuid::new_v4(); + let conn = sync_on(channel_id); + super::super::fan_out_event_to_local_subscribers( + &state, + community_id, + &artifact(channel_id), + ) + .await; + assert_eq!( + state.artifact_syncs.pending_resync(conn, "s"), + Some("resync: access check failed"), + "visibility lookup" + ); + + // Drop the known user's whole snapshot so this must read the DB. + state.membership_cache.invalidate(community_id, &pk); + // The membership lookup fails (Redis fan-out). + let channel_id = Uuid::new_v4(); + private(channel_id); + let conn = sync_on(channel_id); + super::super::fan_out_pubsub_event( + &state, + buzz_pubsub::ChannelEvent { + community_id, + topic: buzz_pubsub::EventTopic::Channel(channel_id), + event: artifact(channel_id).event, + }, + ) + .await; + assert_eq!( + state.artifact_syncs.pending_resync(conn, "s"), + Some("resync: access check failed"), + "membership lookup" + ); + } + + /// A refused WebSocket EVENT writes one `write` access line with the + /// OK's fixed prefix as its reason, and never the event's content or + /// tag values. + #[tokio::test] + async fn refused_ws_event_writes_one_access_line_without_its_content() { + let state = test_state().await; + let (conn, mut send_rx) = + crate::connection::tests::test_conn_with_auth(crate::connection::AuthState::Failed); + let event = EventBuilder::new(Kind::Custom(9), "secret words") + .tag(nostr::Tag::parse(["h", "secret-channel"]).unwrap()) + .sign_with_keys(&Keys::generate()) + .unwrap(); + let (guard, out) = crate::access::tests::capture_scoped(); + super::super::handle_event(event.clone(), conn, state).await; + drop(guard); + + let axum::extract::ws::Message::Text(ack) = send_rx.try_recv().expect("OK") else { + panic!("expected text OK"); + }; + assert!(ack.contains("auth-required"), "{ack}"); + assert!(!out.raw().contains("secret"), "{}", out.raw()); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + let line = &lines[0]; + assert_eq!(line["event"], "write", "{line}"); + assert_eq!(line["outcome"], "rejected", "{line}"); + assert_eq!(line["reason"], "auth-required", "{line}"); + assert_eq!(line["kind"], 9, "{line}"); + assert_eq!(line["event_id"], event.id.to_hex(), "{line}"); + assert!(line.get("pubkey").is_none(), "{line}"); + } } // --------------------------------------------------------------------- @@ -3548,6 +3748,7 @@ mod tests { let (ctrl_tx, _) = mpsc::channel(8); let (terminal_ctrl_tx, _) = mpsc::channel(1); let conn = std::sync::Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: uuid::Uuid::new_v4(), tenant, remote_addr: "127.0.0.1:1234".parse().unwrap(), @@ -3740,10 +3941,11 @@ mod tests { let (state, tenant, user) = unrestricted_fixture().await; let key = (tenant.community(), user.public_key().to_bytes().to_vec()); - state.restriction_cache.insert( + state.seed_restriction( key.clone(), buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }, ); @@ -3753,10 +3955,11 @@ mod tests { "a cached ban must refuse the ephemeral event; got {frame}" ); - state.restriction_cache.insert( + state.seed_restriction( key, buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: Some(chrono::Utc::now() - chrono::Duration::seconds(1)), }, ); @@ -3768,12 +3971,12 @@ mod tests { } /// The ephemeral community fence reads the cached serving state. - /// Mutation: call the uncached `is_serving_active` → RED. + /// Mutation: call the uncached `is_community_active` → RED. #[tokio::test] #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] async fn ephemeral_fence_uses_cached_serving_state() { let (state, tenant, user) = unrestricted_fixture().await; - state.serving_active_cache.insert(tenant.community(), false); + state.community_active.seed(tenant.community(), false); let frame = ok_frame(&state, &tenant, &user, typing_event(&user)).await; assert!( frame.contains("false") && frame.contains("community writes are fenced"), @@ -3788,13 +3991,17 @@ mod tests { let (state, tenant, user) = unrestricted_fixture().await; ok_frame(&state, &tenant, &user, typing_event(&user)).await; assert_eq!( - state.serving_active_cache.get(&tenant.community()), + state + .community_active + .entry(&tenant.community()) + .map(|(active, _)| active), Some(true) ); assert_eq!( state .restriction_cache - .get(&(tenant.community(), user.public_key().to_bytes().to_vec())), + .entry(&(tenant.community(), user.public_key().to_bytes().to_vec())) + .map(|(state, _)| state), Some(buzz_db::moderation::RestrictionState::default()) ); } @@ -3805,53 +4012,115 @@ mod tests { .expect("sign text note") } - /// Stored writes, and NIP-43 leave, skip the cached restriction row: - /// a cached ban on a sender Postgres has never restricted refuses - /// neither. The leave reaches ingest's later membership check, past - /// its uncached restriction check. - /// Mutation: make ingest call `enforce_cached_write_restriction`, or - /// drop the 28936 carve-out from the `handle_event` gate → RED. + /// Stored writes read the restriction through the cache, and only + /// while the entry is younger than 10 s: a cached ban on a sender + /// Postgres has never restricted refuses a stored write while fresh + /// and 9 s old, and the same row 10 s old is reread and admits it. + /// The ages are literals, so the bound a pod that misses an + /// invalidation serves stale rows for is pinned independently of + /// `RESTRICTION_CACHE_MAX_AGE`. + /// Mutation: make ingest read the restriction uncached, drop the + /// max-age check, or raise `RESTRICTION_CACHE_MAX_AGE` above 10 s + /// → RED. #[tokio::test] #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] - async fn stored_writes_ignore_cached_ban() { + async fn stored_writes_honor_cached_ban_until_it_ages_out() { let (state, tenant, user) = unrestricted_fixture().await; - state.restriction_cache.insert( - (tenant.community(), user.public_key().to_bytes().to_vec()), - buzz_db::moderation::RestrictionState { - banned: true, - muted_until: None, - }, - ); + let key = (tenant.community(), user.public_key().to_bytes().to_vec()); + let banned = buzz_db::moderation::RestrictionState { + banned: true, + own_banned: true, + muted_until: None, + }; let scopes = buzz_auth::Scope::all_non_admin(); + state.seed_restriction(key.clone(), banned.clone()); let frame = ok_frame_scoped(&state, &tenant, &user, text_note(&user), scopes.clone()).await; assert!( - frame.contains(",true,"), - "a stored write must read the restriction from Postgres; got {frame}" + frame.contains("blocked: you are banned"), + "a fresh cached ban must refuse a stored write; got {frame}" ); - let leave = nostr::EventBuilder::new( - nostr::Kind::Custom(buzz_core::kind::KIND_NIP43_LEAVE_REQUEST as u16), - "", - ) - .sign_with_keys(&user) - .expect("sign leave"); - let frame = ok_frame_scoped(&state, &tenant, &user, leave, scopes).await; + let aged = |secs| { + std::time::Instant::now() + .checked_sub(std::time::Duration::from_secs(secs)) + .expect("instant in the past") + }; + state + .restriction_cache + .seed_read_at(key.clone(), banned.clone(), aged(9)); + let frame = + ok_frame_scoped(&state, &tenant, &user, text_note(&user), scopes.clone()).await; + assert!( + frame.contains("blocked: you are banned"), + "a 9 s old cached ban must still refuse a stored write; got {frame}" + ); + + state.restriction_cache.seed_read_at(key, banned, aged(10)); + let frame = ok_frame_scoped(&state, &tenant, &user, text_note(&user), scopes).await; assert!( - frame.contains("relay membership is not enabled"), - "NIP-43 leave must skip the cached gate and pass ingest's uncached one; got {frame}" + frame.contains(",true,"), + "an aged-out cached ban must be reread from Postgres; got {frame}" ); } + /// Every persistent ingest is timed under its outcome, failures + /// included, so a failing store cannot hide from the latency. + /// Mutation: drop `record_event_processing` from the `Err` arm → RED. + #[tokio::test(flavor = "current_thread")] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn event_processing_is_timed_for_accepted_and_refused_ingest() { + let (state, tenant, user) = unrestricted_fixture().await; + let scopes = buzz_auth::Scope::all_non_admin(); + let recorder = metrics_util::debugging::DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + { + let _guard = metrics::set_default_local_recorder(&recorder); + let frame = + ok_frame_scoped(&state, &tenant, &user, text_note(&user), scopes.clone()).await; + assert!(frame.contains(",true,"), "{frame}"); + state.seed_restriction( + (tenant.community(), user.public_key().to_bytes().to_vec()), + buzz_db::moderation::RestrictionState { + banned: true, + own_banned: true, + muted_until: None, + }, + ); + let frame = ok_frame_scoped(&state, &tenant, &user, text_note(&user), scopes).await; + assert!(frame.contains("blocked: you are banned"), "{frame}"); + } + let mut timed: Vec<(String, usize)> = snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, ..)| key.key().name() == "buzz_event_processing_seconds") + .map(|(key, _, _, value)| { + let metrics_util::debugging::DebugValue::Histogram(samples) = value else { + panic!("buzz_event_processing_seconds must be a histogram"); + }; + let outcome = key + .key() + .labels() + .find(|l| l.key() == "outcome") + .map(|l| l.value().to_owned()) + .unwrap_or_default(); + (outcome, samples.len()) + }) + .collect(); + timed.sort(); + assert_eq!(timed, [("accepted".to_owned(), 1), ("auth".to_owned(), 1)]); + } + /// Stored writes skip the cached serving state: a cached "fenced" /// for a community Postgres says is active does not refuse them. - /// Mutation: make ingest's fence call `is_serving_active_cached` → RED. + /// Mutation: make ingest's fence call `is_community_active_cached` → RED. #[tokio::test] #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] async fn stored_writes_ignore_cached_fence() { let (state, tenant, user) = unrestricted_fixture().await; - state.serving_active_cache.insert(tenant.community(), false); + state.community_active.seed(tenant.community(), false); let frame = ok_frame_scoped( &state, &tenant, @@ -3903,6 +4172,7 @@ mod tests { mpsc::channel::(1); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( community, @@ -4096,6 +4366,7 @@ mod tests { mpsc::channel::(1); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved( community, diff --git a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs index 89c38355ea0..010240aeb45 100644 --- a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs @@ -8,12 +8,20 @@ use buzz_db::event::EventQuery; use nostr::{EventBuilder, Keys, Kind, Tag}; use uuid::Uuid; -use crate::handlers::ingest::{ingest_event, HttpAuthMethod, IngestAuth}; +use crate::handlers::ingest::{ingest_event, HttpAuthMethod, IngestAuth, IngestError}; use crate::state::AppState; use buzz_auth::Scope; +/// Test state on the shared test database. The pool keeps sqlx's default +/// acquire timeout: `test_state_with_unreachable_database_url` waits only +/// 100 ms so closed-port tests fail fast, and a first connect to a busy CI +/// database can take longer than that (`PoolTimedOut`). pub(crate) async fn state() -> Arc { - crate::state::tests::test_state_with_database_url(&crate::test_support::database_url()).await + crate::state::tests::test_state_with_database_url_and_pool_options( + &crate::test_support::database_url(), + sqlx::postgres::PgPoolOptions::new(), + ) + .await } pub(crate) async fn community(state: &AppState, label: &str) -> TenantContext { @@ -620,6 +628,7 @@ pub(crate) fn test_conn( let (ctrl_tx, _ctrl_rx) = tokio::sync::mpsc::channel(4); let cancel = tokio_util::sync::CancellationToken::new(); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: tenant.clone(), remote_addr: "127.0.0.1:1234".parse().expect("addr"), @@ -877,79 +886,49 @@ async fn system_channel_defaults_private_and_hidden() { assert!(!has_marker(&tags, "hidden"), "{tags:?}"); } -/// A kind:9007 without an `h` tag is created by the side-effect handler, not -/// by the ingest pre-create. That path must give a system channel the same -/// private default, so strangers can neither read nor write it. -/// Mutation: default visibility to open in `handle_create_group` → RED. +/// A kind:9007 without an `h` tag is refused before it is stored. Its channel +/// would be created only after the event committed, so a refused create (a +/// taken name, for example) would still answer accepted. +/// Mutation: drop the `h`-tag refusal in `ingest_event` → RED. #[tokio::test] #[ignore = "requires Postgres"] -async fn system_channel_without_h_tag_defaults_private() { +async fn create_without_h_tag_is_refused_before_it_is_stored() { let state = state().await; - let tenant = community(&state, "group-state-system-no-h").await; + let tenant = community(&state, "group-state-create-no-h").await; let creator = Keys::generate(); - let stranger = Keys::generate(); - let name = format!("system-no-h-{}", Uuid::new_v4().simple()); + let name = format!("no-h-{}", Uuid::new_v4().simple()); let create = EventBuilder::new(Kind::Custom(9007), "") - .tags([ - Tag::parse(["name", &name]).unwrap(), - Tag::parse(["channel_type", "system"]).unwrap(), - ]) + .tags([Tag::parse(["name", &name]).unwrap()]) .sign_with_keys(&creator) .expect("sign 9007"); - let result = ingest_event(&state, &tenant, create, http_auth(&creator)) - .await - .unwrap_or_else(|error| panic!("create channel: {error:?}")); - assert!(result.accepted, "{}", result.message); - - let (channel_id, visibility): (Uuid, String) = sqlx::query_as( - "SELECT id, visibility::text FROM channels WHERE community_id = $1 AND name = $2", - ) - .bind(*tenant.community().as_uuid()) - .bind(&name) - .fetch_one(state.db.pool()) - .await - .expect("created channel"); - assert_eq!(visibility, "private"); - - let tags = group_state_tags(&state, &tenant, channel_id, 39000).await; - assert!(has_marker(&tags, "private"), "{tags:?}"); - assert!(has_marker(&tags, "hidden"), "{tags:?}"); - assert!(!has_marker(&tags, "public"), "{tags:?}"); + let event_id = create.id; + match ingest_event(&state, &tenant, create, http_auth(&creator)).await { + Err(IngestError::Rejected(message)) => assert_eq!( + message, + "invalid: create-group must include an h tag with the new channel id" + ), + Err(other) => panic!("expected a refusal, got {other:?}"), + Ok(result) => panic!("expected a refusal, got {:?}", result.message), + } - let stranger_bytes = stranger.public_key().to_bytes().to_vec(); + let channels: i64 = + sqlx::query_scalar("SELECT count(*) FROM channels WHERE community_id = $1 AND name = $2") + .bind(*tenant.community().as_uuid()) + .bind(&name) + .fetch_one(state.db.pool()) + .await + .unwrap(); + assert_eq!(channels, 0, "no channel is created"); assert!( - crate::handlers::ingest::check_channel_membership( - tenant.community(), - &state, - channel_id, - &stranger_bytes, - None, - crate::handlers::ingest::ChannelWrite::Membership, - ) - .await - .is_err(), - "a stranger must not pass the channel access check" + state + .db + .get_event_by_id(tenant.community(), event_id.as_bytes()) + .await + .unwrap() + .is_none(), + "the refused create is not stored" ); - let readable = state - .db - .get_accessible_channel_ids(tenant.community(), &stranger_bytes) - .await - .expect("accessible channels"); - assert!(!readable.contains(&channel_id), "stranger can read it"); - - let message = EventBuilder::new(Kind::Custom(9), "hello") - .tags([Tag::parse(["h", &channel_id.to_string()]).unwrap()]) - .sign_with_keys(&stranger) - .unwrap(); - match ingest_event(&state, &tenant, message, http_auth(&stranger)).await { - Ok(result) => assert!( - !result.accepted, - "stranger wrote to a private system channel: {}", - result.message - ), - Err(error) => assert!(format!("{error:?}").contains("restricted"), "{error:?}"), - } } /// A removed creator's kind:9021 that passes the open-channel check while the @@ -1066,3 +1045,611 @@ async fn removed_creator_join_racing_a_private_switch_is_refused() { "a removed creator must not rejoin a channel that became private" ); } + +/// Where a join's kind:39000 publisher is held while a kind:9002 edit races it. +#[derive(Clone, Copy, Debug)] +enum HoldPublisher { + /// Before it takes the replacement lock: the edit publishes in full + /// while the join is held, so anything the join read before the lock is + /// stale by the time it stores. + BeforeLock, + /// After it has read behind the lock: the edit's publisher waits for the + /// join's, then must still win with the edit's state. + AfterRead, +} + +/// A join's kind:39000 publisher cannot replace a racing edit's kind:39000 +/// with state read before the edit. In the e2e +/// `test_nip29_announce_channel_wire`, an admission auto-joined a default +/// channel while a relay admin's kind:9002 cleared `auto_join`; the join read +/// `auto_join` first, stored after the edit at a later second, and the stale +/// tag stayed live. +/// +/// Two legs. `BeforeLock` holds the join immediately before it takes the +/// lock, lets the edit publish in full, then releases it: a channel or +/// member read done before the lock (`get_channel_for_event_write`, +/// `get_members_for_event_write`) stores stale tags last → RED. `AfterRead` +/// holds the join after its read behind the lock until the edit is waiting +/// for that lock, so the edit must still win with its own state. +/// +/// Both legs also check the timestamps: every kind:39000 publication for +/// the coordinate, replaced rows included, leaves exactly one row, and +/// their `created_at` strictly increase in storage order. The live event is +/// first pinned an hour ahead, so each publication's timestamp is the live +/// one plus a second and the clock cannot separate the two publishers. +/// Mutation: take the live `created_at` before the lock → RED every time: +/// the publisher that locks second computes the same second as the first, +/// and either loses the id tie and leaves no row, or wins it and repeats +/// the second. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_publisher_that_read_before_an_edit_cannot_replace_it() { + for hold in [HoldPublisher::BeforeLock, HoldPublisher::AfterRead] { + join_publisher_held_against_an_auto_join_edit(hold).await; + } +} + +/// `created_at` of every relay-signed kind:39000 row for `channel_id`, +/// replaced rows included, in storage order. +async fn stored_metadata_created_at( + state: &AppState, + tenant: &TenantContext, + channel_id: Uuid, +) -> Vec> { + sqlx::query_scalar( + "SELECT created_at FROM events WHERE community_id = $1 AND kind = 39000 \ + AND pubkey = $2 AND channel_id = $3 ORDER BY received_at ASC", + ) + .bind(tenant.community().as_uuid()) + .bind(state.relay_keypair.public_key().to_bytes().as_slice()) + .bind(channel_id) + .fetch_all(state.db.pool()) + .await + .expect("read every kind:39000 row") +} + +async fn join_publisher_held_against_an_auto_join_edit(hold: HoldPublisher) { + let state = state().await; + let tenant = community(&state, "group-state-stale-publisher").await; + let owner = Keys::generate(); + let channel_id = create_channel(&state, &tenant, &owner, &[]).await; + let admin = Keys::generate(); + state + .db + .add_relay_member( + tenant.community(), + &admin.public_key().to_hex(), + "admin", + None, + &Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("seed relay admin"); + edit_channel( + &state, + &tenant, + &admin, + channel_id, + &[&["auto_join", "true"]], + ) + .await + .expect("set auto_join"); + // Pin the live event an hour ahead: from here on every publication is + // stored at the live `created_at` plus one, whatever the clock says. + let pinned = EventBuilder::new(Kind::Custom(39000), "") + .tags( + group_state_tags(&state, &tenant, channel_id, 39000) + .await + .into_iter() + .map(|tag| Tag::parse(tag).expect("tag")), + ) + .custom_created_at(nostr::Timestamp::now() + 3600) + .sign_with_keys(&state.relay_keypair) + .expect("sign pinned kind:39000"); + assert!( + state + .db + .replace_addressable_event(tenant.community(), &pinned, Some(channel_id)) + .await + .expect("store pinned kind:39000") + .1 + ); + let rows_before = stored_metadata_created_at(&state, &tenant, channel_id) + .await + .len(); + + let (arrived, release) = match hold { + HoldPublisher::BeforeLock => { + crate::nip_fi_test_hooks::group_state_lock_hook::arm(tenant.community()) + } + HoldPublisher::AfterRead => { + crate::nip_fi_test_hooks::group_state_read_hook::arm(tenant.community()) + } + }; + let joiner = Keys::generate(); + let join = EventBuilder::new(Kind::Custom(9021), "") + .tags([Tag::parse(["h", &channel_id.to_string()]).unwrap()]) + .sign_with_keys(&joiner) + .unwrap(); + let join_task = tokio::spawn({ + let state = Arc::clone(&state); + let tenant = tenant.clone(); + let auth = http_auth(&joiner); + async move { ingest_event(&state, &tenant, join, auth).await } + }); + tokio::time::timeout(std::time::Duration::from_secs(10), arrived) + .await + .unwrap_or_else(|_| panic!("{hold:?}: the join publishes kind:39000")) + .unwrap_or_else(|_| panic!("{hold:?}: the hook stays armed until the join reaches it")); + + let edit_task = tokio::spawn({ + let state = Arc::clone(&state); + let tenant = tenant.clone(); + async move { + edit_channel( + &state, + &tenant, + &admin, + channel_id, + &[&["auto_join", "false"]], + ) + .await + } + }); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !edit_task.is_finished() { + if matches!(hold, HoldPublisher::AfterRead) { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND NOT granted \ + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()))", + ) + .fetch_one(state.db.pool()) + .await + .expect("read lock waiters"); + if waiting { + break; + } + } + assert!( + std::time::Instant::now() < deadline, + "{hold:?}: the edit neither finished nor waited for the held publisher" + ); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + release.notify_one(); + + let joined = join_task + .await + .expect("join task must not panic") + .unwrap_or_else(|error| panic!("{hold:?}: join: {error:?}")); + assert!(joined.accepted, "{hold:?}: join: {}", joined.message); + edit_task + .await + .expect("edit task must not panic") + .unwrap_or_else(|error| panic!("{hold:?}: clear auto_join: {error}")); + let tags = group_state_tags(&state, &tenant, channel_id, 39000).await; + assert!( + !tags.contains(&vec!["auto_join".to_string()]), + "{hold:?}: the join's stale kind:39000 replaced the edit's: {tags:?}" + ); + let created_at = stored_metadata_created_at(&state, &tenant, channel_id).await; + assert_eq!( + created_at.len(), + rows_before + 2, + "{hold:?}: the join and the edit each leave one kind:39000 row: {created_at:?}" + ); + assert!( + created_at.windows(2).all(|pair| pair[0] < pair[1]), + "{hold:?}: kind:39000 timestamps must strictly increase in storage order: {created_at:?}" + ); +} + +/// A create or rename that would list a second open channel under a taken +/// name is refused with its reason as a client error, and stores nothing. +/// Mutation: let `ChannelNameTaken` fall through to the internal-error arm +/// of either kind → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_taken_open_name_is_refused_as_a_client_error() { + let state = state().await; + let tenant = community(&state, "group-state-name-taken").await; + let owner = Keys::generate(); + let create = |name: &str| { + let channel_id = Uuid::new_v4(); + let event = EventBuilder::new(Kind::Custom(9007), "") + .tags([ + Tag::parse(["h", &channel_id.to_string()]).unwrap(), + Tag::parse(["name", name]).unwrap(), + ]) + .sign_with_keys(&owner) + .expect("sign 9007"); + (channel_id, event) + }; + + let (_, first) = create("launch"); + assert!( + ingest_event(&state, &tenant, first, http_auth(&owner)) + .await + .expect("first create") + .accepted + ); + + let (second, event) = create("Launch"); + match ingest_event(&state, &tenant, event, http_auth(&owner)).await { + Err(IngestError::Rejected(message)) => assert_eq!( + message, + "invalid: an open channel named \"Launch\" already exists" + ), + Err(other) => panic!("expected a refusal, got {other:?}"), + Ok(result) => panic!("expected a refusal, got {:?}", result.message), + } + assert!( + state + .db + .get_channel(tenant.community(), second) + .await + .is_err(), + "the refused create stores no channel" + ); + + let other = create_channel(&state, &tenant, &owner, &[]).await; + let before = state + .db + .get_channel(tenant.community(), other) + .await + .expect("channel") + .name; + let rename = EventBuilder::new(Kind::Custom(9002), "") + .tags([ + Tag::parse(["h", &other.to_string()]).unwrap(), + Tag::parse(["name", "LAUNCH"]).unwrap(), + ]) + .sign_with_keys(&owner) + .expect("sign 9002"); + let rename_id = rename.id; + match ingest_event(&state, &tenant, rename, http_auth(&owner)).await { + Err(IngestError::Rejected(message)) => assert_eq!( + message, + "invalid: an open channel named \"LAUNCH\" already exists" + ), + Err(other) => panic!("expected a refusal, got {other:?}"), + Ok(result) => panic!("expected a refusal, got {:?}", result.message), + } + assert_eq!( + state + .db + .get_channel(tenant.community(), other) + .await + .expect("channel") + .name, + before, + "the refused rename keeps the name" + ); + let stored: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM events WHERE community_id = $1 AND id = $2)", + ) + .bind(tenant.community().as_uuid()) + .bind(rename_id.as_bytes().as_slice()) + .fetch_one(state.db.pool()) + .await + .expect("look up the 9002"); + assert!(!stored, "the refused 9002 is not stored"); +} + +/// A relay operator who is not a channel member may rename the channel, and +/// the relay publishes the new name in kind:39000. The operator may change +/// nothing else, and a relay moderator may not rename it. +/// An operator who owns an archived listed channel may rename it as well, but +/// not an archived unlisted one. +/// Mutation: drop the operator branch in `validate_admin_event`, or drop its +/// `is_rename_only` or operator-role condition, or set `operator_rename` only +/// without channel authority, or drop `locked.listed()` from the archived +/// exemption → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_relay_operator_may_only_rename_a_channel() { + let state = state().await; + let tenant = community(&state, "group-state-operator-rename").await; + let owner = Keys::generate(); + let channel = create_channel(&state, &tenant, &owner, &[]).await; + let operator = Keys::generate(); + let moderator = Keys::generate(); + for (keys, role) in [(&operator, "operator"), (&moderator, "moderator")] { + state + .db + .upsert_relay_operator( + &keys.public_key().to_bytes(), + role, + &owner.public_key().to_bytes(), + true, + ) + .await + .expect("grant relay role"); + } + let edit = |keys: &Keys, tags: &[&[&str]]| { + let mut all = vec![Tag::parse(["h", &channel.to_string()]).unwrap()]; + all.extend( + tags.iter() + .map(|tag| Tag::parse(tag.iter().copied()).unwrap()), + ); + EventBuilder::new(Kind::Custom(9002), "") + .tags(all) + .sign_with_keys(keys) + .expect("sign 9002") + }; + let community_id = tenant.community(); + let name = |state: Arc| async move { + state + .db + .get_channel(community_id, channel) + .await + .expect("channel") + .name + }; + let before = name(state.clone()).await; + + for (keys, tags) in [ + (&moderator, &[&["name", "by-moderator"][..]][..]), + ( + &operator, + &[&["name", "by-operator"][..], &["about", "changed"][..]][..], + ), + ] { + match ingest_event(&state, &tenant, edit(keys, tags), http_auth(keys)).await { + Err(IngestError::Rejected(message)) => { + assert!(message.contains("not authorized"), "{message}") + } + Err(other) => panic!("expected a refusal, got {other:?}"), + Ok(result) => panic!("expected a refusal, got {:?}", result.message), + } + assert_eq!(name(state.clone()).await, before); + } + + // The rename repairs archived duplicates too, so archive the channel. An + // owner still may not edit it while it is archived. + state + .db + .archive_channel(community_id, channel) + .await + .expect("archive"); + match ingest_event( + &state, + &tenant, + edit(&owner, &[&["name", "by-owner"]]), + http_auth(&owner), + ) + .await + { + Err(IngestError::Rejected(message)) => assert!(message.contains("archived"), "{message}"), + Err(other) => panic!("expected a refusal, got {other:?}"), + Ok(result) => panic!("expected a refusal, got {:?}", result.message), + } + assert_eq!(name(state.clone()).await, before); + + let renamed = ingest_event( + &state, + &tenant, + edit(&operator, &[&["name", "renamed-by-operator"]]), + http_auth(&operator), + ) + .await + .unwrap_or_else(|error| panic!("operator rename: {error:?}")); + assert!(renamed.accepted, "{}", renamed.message); + assert_eq!(name(state.clone()).await, "renamed-by-operator"); + assert!( + state + .db + .get_channel(community_id, channel) + .await + .expect("channel") + .archived_at + .is_some(), + "the rename keeps the channel archived" + ); + let tags = group_state_tags(&state, &tenant, channel, 39000).await; + assert!( + tags.iter() + .any(|tag| tag.len() >= 2 && tag[0] == "name" && tag[1] == "renamed-by-operator"), + "{tags:?}" + ); + + // An operator who owns an archived listed channel may rename it too, and + // it stays archived: the operator rule holds whatever the channel role. + let owned = create_channel(&state, &tenant, &operator, &[]).await; + state + .db + .archive_channel(community_id, owned) + .await + .expect("archive"); + let rename = EventBuilder::new(Kind::Custom(9002), "") + .tags([ + Tag::parse(["h", &owned.to_string()]).unwrap(), + Tag::parse(["name", "renamed-by-owning-operator"]).unwrap(), + ]) + .sign_with_keys(&operator) + .expect("sign 9002"); + let renamed = ingest_event(&state, &tenant, rename, http_auth(&operator)) + .await + .unwrap_or_else(|error| panic!("owning operator rename: {error:?}")); + assert!(renamed.accepted, "{}", renamed.message); + let owned = state + .db + .get_channel(community_id, owned) + .await + .expect("channel"); + assert_eq!(owned.name, "renamed-by-owning-operator"); + assert!(owned.archived_at.is_some(), "the rename keeps it archived"); + + // The archived exemption covers only a listed channel: the same operator + // may not rename an archived unlisted channel it owns. + let hidden = create_channel(&state, &tenant, &operator, &[&["unlisted", "true"]]).await; + state + .db + .archive_channel(community_id, hidden) + .await + .expect("archive"); + let rename = EventBuilder::new(Kind::Custom(9002), "") + .tags([ + Tag::parse(["h", &hidden.to_string()]).unwrap(), + Tag::parse(["name", "hidden-renamed"]).unwrap(), + ]) + .sign_with_keys(&operator) + .expect("sign 9002"); + match ingest_event(&state, &tenant, rename, http_auth(&operator)).await { + Err(IngestError::Rejected(message)) => assert!(message.contains("archived"), "{message}"), + Err(other) => panic!("expected a refusal, got {other:?}"), + Ok(result) => panic!("expected a refusal, got {:?}", result.message), + } + assert_ne!( + state + .db + .get_channel(community_id, hidden) + .await + .expect("channel") + .name, + "hidden-renamed" + ); +} + +/// An owner may make a channel private or unlisted after the relay has +/// validated an operator's rename and before the rename is stored. The store +/// decides under the channel row lock, so the rename is refused then and the +/// name is unchanged. +/// Mutation: drop the `operator_rename && !locked.listed()` check in +/// `apply_channel_metadata_event`, or never set `operator_rename` in +/// `persist_edit_metadata` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_operator_rename_is_refused_when_the_channel_stops_being_listed() { + let state = state().await; + let tenant = community(&state, "group-state-operator-race").await; + let owner = Keys::generate(); + let operator = Keys::generate(); + state + .db + .upsert_relay_operator( + &operator.public_key().to_bytes(), + "operator", + &owner.public_key().to_bytes(), + true, + ) + .await + .expect("grant relay role"); + let edit = |keys: &Keys, channel: Uuid, tag: [&str; 2]| { + EventBuilder::new(Kind::Custom(9002), "") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(tag).unwrap(), + ]) + .sign_with_keys(keys) + .expect("sign 9002") + }; + + for change in [["visibility", "private"], ["unlisted", "true"]] { + let channel = create_channel(&state, &tenant, &owner, &[]).await; + let before = state + .db + .get_channel(tenant.community(), channel) + .await + .expect("channel") + .name; + let rename = edit(&operator, channel, ["name", "by-operator"]); + super::side_effects::validate_admin_event(&tenant, 9002, &rename, &state) + .await + .unwrap_or_else(|error| panic!("{change:?}: the listed channel validates: {error}")); + + let hidden = ingest_event( + &state, + &tenant, + edit(&owner, channel, change), + http_auth(&owner), + ) + .await + .unwrap_or_else(|error| panic!("{change:?}: owner change: {error:?}")); + assert!(hidden.accepted, "{change:?}: {}", hidden.message); + + let error = super::side_effects::persist_edit_metadata(&tenant, &rename, &state) + .await + .err() + .unwrap_or_else(|| panic!("{change:?}: the rename must be refused")); + assert!( + format!("{error:#}").contains("only a listed channel"), + "{change:?}: {error:#}" + ); + let after = state + .db + .get_channel(tenant.community(), channel) + .await + .expect("channel") + .name; + assert_eq!(after, before, "{change:?}"); + } +} + +/// The operator rename covers only listed channels: open, not unlisted, a +/// stream or forum. A relay operator may not rename a private channel, an +/// unlisted channel or a DM. +/// Mutation: drop the listed check in `operator_may_rename` → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_relay_operator_may_not_rename_an_unlisted_channel() { + let state = state().await; + let tenant = community(&state, "group-state-operator-unlisted").await; + let owner = Keys::generate(); + let other = Keys::generate(); + let operator = Keys::generate(); + state + .db + .upsert_relay_operator( + &operator.public_key().to_bytes(), + "operator", + &owner.public_key().to_bytes(), + true, + ) + .await + .expect("grant relay role"); + let private = create_channel(&state, &tenant, &owner, &[&["visibility", "private"]]).await; + let unlisted = create_channel(&state, &tenant, &owner, &[&["unlisted", "true"]]).await; + let (dm, _) = state + .db + .open_dm( + tenant.community(), + &[ + &owner.public_key().to_bytes(), + &other.public_key().to_bytes(), + ], + &owner.public_key().to_bytes(), + ) + .await + .expect("open dm"); + + for (label, channel) in [("private", private), ("unlisted", unlisted), ("dm", dm.id)] { + let before = state + .db + .get_channel(tenant.community(), channel) + .await + .expect("channel"); + if label == "unlisted" { + assert!(before.unlisted, "the channel is unlisted"); + } + let event = EventBuilder::new(Kind::Custom(9002), "") + .tags([ + Tag::parse(["h", &channel.to_string()]).unwrap(), + Tag::parse(["name", "by-operator"]).unwrap(), + ]) + .sign_with_keys(&operator) + .expect("sign 9002"); + match ingest_event(&state, &tenant, event, http_auth(&operator)).await { + Err(IngestError::Rejected(_)) => {} + Err(other) => panic!("{label}: expected a refusal, got {other:?}"), + Ok(result) => panic!("{label}: expected a refusal, got {:?}", result.message), + } + let after = state + .db + .get_channel(tenant.community(), channel) + .await + .expect("channel"); + assert_eq!(after.name, before.name, "{label}"); + } +} diff --git a/crates/buzz-relay/src/handlers/identity_archive.rs b/crates/buzz-relay/src/handlers/identity_archive.rs index 919c1467b69..0daa80b4099 100644 --- a/crates/buzz-relay/src/handlers/identity_archive.rs +++ b/crates/buzz-relay/src/handlers/identity_archive.rs @@ -437,16 +437,14 @@ mod tests { async fn test_pool() -> Option { let url = std::env::var("DATABASE_URL") - .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".into()); + .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".into()); // sadscan:disable np.postgres.1 -- local test fixture sqlx::PgPool::connect(&url).await.ok() } async fn test_state(pool: sqlx::PgPool) -> Option> { let db = buzz_db::Db::from_pool(pool.clone()); let config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE] - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .ok()?; + let redis_pool = buzz_pubsub::redis_connection(&config.redis_url).ok()?; let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -702,6 +700,59 @@ mod tests { ); } + mod postgres_tests { + use super::*; + + /// NIP-IA: every snapshot's `created_at` is strictly past the previous + /// one's, even when publishers race on one head. Concurrent publishers + /// each read the head behind the replacement lock. RED-on-revert: with the + /// head read before the lock, publishers keep tying on head + 1 and one + /// exhausts its replacement attempts. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "requires Postgres and Redis"] + async fn concurrent_archival_publishers_stamp_strictly_increasing_snapshots() { + // Ignored, so it runs only where Postgres and Redis are provided: a + // missing one is a failure, never a silent pass. + let pool = test_pool().await.expect("Postgres for an ignored test"); + let state = test_state(pool.clone()) + .await + .expect("Redis for an ignored test"); + let tenant = seed_test_community(&pool).await; + + let publishers: Vec<_> = (0..16) + .map(|_| { + let tenant = tenant.clone(); + let state = state.clone(); + tokio::spawn(async move { publish_nipia_archival_list(&tenant, &state).await }) + }) + .collect(); + for publisher in publishers { + publisher + .await + .expect("join publisher") + .expect("publisher succeeds"); + } + + // Superseded snapshots stay as soft-deleted rows, so every snapshot + // ever stored is visible here. + let stamps: Vec> = sqlx::query_scalar( + "SELECT created_at FROM events WHERE community_id = $1 AND kind = $2 \ + AND pubkey = $3 ORDER BY created_at", + ) + .bind(tenant.community().as_uuid()) + .bind(buzz_core::kind::KIND_IA_ARCHIVED_LIST as i32) + .bind(state.relay_keypair.public_key().to_bytes().as_slice()) + .fetch_all(&pool) + .await + .expect("read stored snapshots"); + assert_eq!(stamps.len(), 16, "every publisher stores its own snapshot"); + assert!( + stamps.windows(2).all(|pair| pair[0] < pair[1]), + "snapshots must never share a created_at: {stamps:?}" + ); + } + } + #[tokio::test] async fn owner_archive_rejects_stale_request_after_live_kind0_owner_flip() { let Some(pool) = test_pool().await else { diff --git a/crates/buzz-relay/src/handlers/imeta.rs b/crates/buzz-relay/src/handlers/imeta.rs index e3d564e448a..b191437b26d 100644 --- a/crates/buzz-relay/src/handlers/imeta.rs +++ b/crates/buzz-relay/src/handlers/imeta.rs @@ -1,6 +1,7 @@ //! imeta tag validation helpers — shared between ingest pipeline and bridge. use buzz_core::tenant::TenantContext; +use buzz_media::thumbnail::Thumb; use buzz_media::validation::mime_to_ext; /// Validate imeta tags for correctness and safety. @@ -100,9 +101,8 @@ pub fn validate_imeta_tags(tags: &[Vec], media_base_url: &str) -> Result has_size = true; } "thumb" => { - if !is_local_media_url(value, media_base_url) || !value.ends_with(".thumb.jpg") - { - return Err("imeta thumb must be a local .thumb.jpg path".into()); + if !is_local_media_url(value, media_base_url) || !value.contains(".thumb.") { + return Err("imeta thumb must be a local thumbnail path".into()); } thumb_value = value.to_string(); } @@ -277,7 +277,12 @@ pub async fn verify_imeta_blobs( // 4. If thumb is claimed, HEAD the thumbnail object too. if !thumb_value.is_empty() { - let thumb_key = format!("{x_value}.thumb.jpg"); + let (_, thumb) = thumb_value + .rsplit('/') + .next() + .and_then(Thumb::parse) + .ok_or_else(|| format!("imeta thumb is not a thumbnail path: {thumb_value}"))?; + let thumb_key = thumb.key(&x_value); let thumb_exists = storage .head(&thumb_key) .await @@ -458,8 +463,7 @@ fn is_local_media_url(url: &str, media_base_url: &str) -> bool { let hash = segments[0]; hash.len() == 64 && hash.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f')) - && segments[1] == "thumb" - && segments[2] == "jpg" + && Thumb::parse(path_after_media).is_some() } _ => false, } @@ -558,6 +562,27 @@ mod tests { assert!(validate_imeta_tags(&[tag], BASE).is_ok()); } + #[test] + fn test_imeta_thumb_accepts_stored_variants_only() { + let tag = |thumb: &str| { + vec![ + "imeta".into(), + format!("url /media/{HASH}.png"), + "m image/png".into(), + format!("x {HASH}"), + "size 100".into(), + format!("thumb /media/{HASH}.thumb.{thumb}"), + ] + }; + assert!(validate_imeta_tags(&[tag("webp")], BASE).is_ok()); + assert!(validate_imeta_tags(&[tag("jpg")], BASE).is_ok()); + let err = validate_imeta_tags(&[tag("png")], BASE).unwrap_err(); + assert!( + err.contains("thumb must be a local thumbnail path"), + "{err}" + ); + } + #[test] fn test_imeta_url_hash_must_match_x() { let other = "b".repeat(64); diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index f886b900b08..46a1c81f282 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -15,26 +15,26 @@ use buzz_core::kind::{ is_relay_admin_kind, KIND_AGENT_ENGRAM, KIND_AGENT_PROFILE, KIND_AGENT_TURN_METRIC, KIND_APPROVAL_DENY, KIND_APPROVAL_GRANT, KIND_AUTH, KIND_BOOKMARK_LIST, KIND_BOOKMARK_SET, KIND_CANVAS, KIND_CONTACT_LIST, KIND_DELETION, KIND_DM_ADD_MEMBER, KIND_DM_HIDE, KIND_DM_OPEN, - KIND_EMOJI_LIST, KIND_EMOJI_SET, KIND_EVENT_REMINDER, KIND_FOLLOW_SET, KIND_FORUM_COMMENT, - KIND_FORUM_POST, KIND_FORUM_VOTE, KIND_GIFT_WRAP, KIND_GIT_ISSUE, KIND_GIT_PATCH, - KIND_GIT_PR_UPDATE, KIND_GIT_PULL_REQUEST, KIND_GIT_REPO_ANNOUNCEMENT, KIND_GIT_REPO_STATE, - KIND_GIT_STATUS_CLOSED, KIND_GIT_STATUS_DRAFT, KIND_GIT_STATUS_MERGED, KIND_GIT_STATUS_OPEN, - KIND_HUDDLE_ENDED, KIND_HUDDLE_GUIDELINES, KIND_HUDDLE_PARTICIPANT_JOINED, - KIND_HUDDLE_PARTICIPANT_LEFT, KIND_HUDDLE_STARTED, KIND_IA_ARCHIVE_REQUEST, - KIND_IA_UNARCHIVE_REQUEST, KIND_LONG_FORM, KIND_MANAGED_AGENT, KIND_MEMBER_ADDED_NOTIFICATION, - KIND_MEMBER_REMOVED_NOTIFICATION, KIND_MODERATION_BAN, KIND_MODERATION_RESOLVE_REPORT, - KIND_MODERATION_TIMEOUT, KIND_MODERATION_UNBAN, KIND_MODERATION_UNTIMEOUT, KIND_MUTE_LIST, - KIND_NIP29_CREATE_GROUP, KIND_NIP29_DELETE_EVENT, KIND_NIP29_DELETE_GROUP, - KIND_NIP29_EDIT_METADATA, KIND_NIP29_JOIN_REQUEST, KIND_NIP29_LEAVE_REQUEST, - KIND_NIP29_PUT_USER, KIND_NIP29_REMOVE_USER, KIND_NIP43_LEAVE_REQUEST, - KIND_NIP65_RELAY_LIST_METADATA, KIND_PERSONA, KIND_PIN_LIST, KIND_PRESENCE_UPDATE, - KIND_PRIVATE_MANAGED_AGENT, KIND_PRODUCT_FEEDBACK, KIND_PROFILE, KIND_PROJECT, KIND_REACTION, - KIND_READ_STATE, KIND_REPORT, KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_BOOKMARKED, - KIND_STREAM_MESSAGE_DIFF, KIND_STREAM_MESSAGE_EDIT, KIND_STREAM_MESSAGE_PINNED, - KIND_STREAM_MESSAGE_SCHEDULED, KIND_STREAM_MESSAGE_V2, KIND_STREAM_REMINDER, KIND_TEAM, - KIND_TEAM_CATALOG, KIND_TEXT_NOTE, KIND_USER_STATUS, KIND_WORKFLOW_DEF, KIND_WORKFLOW_TRIGGER, - RELAY_ADMIN_ADD_MEMBER, RELAY_ADMIN_CHANGE_ROLE, RELAY_ADMIN_REMOVE_MEMBER, - RELAY_ADMIN_SET_WORKSPACE_PROFILE, + KIND_EMOJI_ENTRY, KIND_EMOJI_LIST, KIND_EMOJI_SET, KIND_EVENT_REMINDER, KIND_FOLLOW_SET, + KIND_FORUM_COMMENT, KIND_FORUM_POST, KIND_FORUM_VOTE, KIND_GIFT_WRAP, KIND_GIT_ISSUE, + KIND_GIT_PATCH, KIND_GIT_PR_UPDATE, KIND_GIT_PULL_REQUEST, KIND_GIT_REPO_ANNOUNCEMENT, + KIND_GIT_REPO_STATE, KIND_GIT_STATUS_CLOSED, KIND_GIT_STATUS_DRAFT, KIND_GIT_STATUS_MERGED, + KIND_GIT_STATUS_OPEN, KIND_HUDDLE_ENDED, KIND_HUDDLE_GUIDELINES, + KIND_HUDDLE_PARTICIPANT_JOINED, KIND_HUDDLE_PARTICIPANT_LEFT, KIND_HUDDLE_STARTED, + KIND_IA_ARCHIVE_REQUEST, KIND_IA_UNARCHIVE_REQUEST, KIND_LONG_FORM, KIND_MANAGED_AGENT, + KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, KIND_MODERATION_BAN, + KIND_MODERATION_RESOLVE_REPORT, KIND_MODERATION_TIMEOUT, KIND_MODERATION_UNBAN, + KIND_MODERATION_UNTIMEOUT, KIND_MUTE_LIST, KIND_NIP29_CREATE_GROUP, KIND_NIP29_DELETE_EVENT, + KIND_NIP29_DELETE_GROUP, KIND_NIP29_EDIT_METADATA, KIND_NIP29_JOIN_REQUEST, + KIND_NIP29_LEAVE_REQUEST, KIND_NIP29_PUT_USER, KIND_NIP29_REMOVE_USER, + KIND_NIP43_LEAVE_REQUEST, KIND_NIP65_RELAY_LIST_METADATA, KIND_PERSONA, KIND_PIN_LIST, + KIND_PRESENCE_UPDATE, KIND_PRIVATE_MANAGED_AGENT, KIND_PRODUCT_FEEDBACK, KIND_PROFILE, + KIND_PROJECT, KIND_REACTION, KIND_READ_STATE, KIND_REPORT, KIND_STREAM_MESSAGE, + KIND_STREAM_MESSAGE_BOOKMARKED, KIND_STREAM_MESSAGE_DIFF, KIND_STREAM_MESSAGE_EDIT, + KIND_STREAM_MESSAGE_PINNED, KIND_STREAM_MESSAGE_SCHEDULED, KIND_STREAM_MESSAGE_V2, + KIND_STREAM_REMINDER, KIND_TEAM, KIND_TEAM_CATALOG, KIND_TEXT_NOTE, KIND_USER_STATUS, + KIND_WORKFLOW_DEF, KIND_WORKFLOW_TRIGGER, RELAY_ADMIN_ADD_MEMBER, RELAY_ADMIN_CHANGE_ROLE, + RELAY_ADMIN_REMOVE_MEMBER, RELAY_ADMIN_SET_WORKSPACE_PROFILE, }; use buzz_core::tenant::TenantContext; use buzz_core::verification::verify_event; @@ -157,6 +157,51 @@ fn validate_custom_emoji_tags(event: &Event) -> Result<(), IngestError> { Ok(()) } +/// Validate a kind:30180 custom emoji entry (see `docs/nips/NIP-CE.md`). +/// +/// Requires exactly one `d` tag, exactly one `emoji` tag, no `h` tag, a `d` equal +/// to the normalized shortcode in the `emoji` tag, an `http(s)` image URL, and +/// `content` equal to [`buzz_sdk::emoji_entry_search_text`] of that shortcode. +fn validate_emoji_entry(event: &Event) -> Result<(), IngestError> { + let reject = |message: &str| IngestError::Rejected(format!("invalid: {message}")); + let mut d_tags = Vec::new(); + let mut emoji_tags = Vec::new(); + for tag in event.tags.iter() { + match tag.as_slice().first().map(String::as_str) { + Some("h") => return Err(reject("emoji entry must not carry an h tag")), + Some("d") => d_tags.push(tag.as_slice()), + Some("emoji") => emoji_tags.push(tag.as_slice()), + _ => {} + } + } + let [d_tag] = d_tags.as_slice() else { + return Err(reject("emoji entry must have exactly one d tag")); + }; + let [emoji_tag] = emoji_tags.as_slice() else { + return Err(reject("emoji entry must have exactly one emoji tag")); + }; + let (Some(d), Some(shortcode), Some(url)) = (d_tag.get(1), emoji_tag.get(1), emoji_tag.get(2)) + else { + return Err(reject( + "emoji entry emoji tag must be [emoji, shortcode, url]", + )); + }; + let normalized = buzz_sdk::normalize_custom_emoji_shortcode(shortcode) + .map_err(|err| reject(&err.to_string()))?; + if *d != normalized || *shortcode != normalized { + return Err(reject( + "emoji entry d tag and emoji shortcode must equal the normalized shortcode", + )); + } + buzz_sdk::check_custom_emoji_url(url).map_err(|err| reject(&err.to_string()))?; + if event.content != buzz_sdk::emoji_entry_search_text(&normalized) { + return Err(reject( + "emoji entry content must equal the shortcode with _ and - replaced by spaces", + )); + } + Ok(()) +} + fn validate_reaction_emoji(event: &Event, emoji: &str) -> Result<(), IngestError> { let emoji_char_count = emoji.chars().count(); if emoji_char_count <= 64 { @@ -466,12 +511,19 @@ pub enum IngestError { /// Which admission outcome an [`IngestError::Ban`] carries. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BanRefusal { - /// The principal or its owner is banned. - Banned, + /// The principal is banned; the source says whose row decided it. + Banned(crate::handlers::auth::BanSource), /// The restriction lookup failed, so no ban decision could be made. Unavailable, } +impl BanRefusal { + /// The ban refusal for a banned restriction snapshot. + pub(crate) fn banned(restriction: &buzz_db::moderation::RestrictionState) -> Self { + Self::Banned(crate::handlers::auth::BanSource::of(restriction)) + } +} + impl IngestError { /// A ban refusal answered with `legacy` outside NIP-FI agent HTTP. pub(crate) fn ban(refusal: BanRefusal, legacy: IngestError) -> Self { @@ -517,8 +569,8 @@ fn map_relay_admin_error(error: super::relay_admin::RelayAdminError) -> IngestEr match error { // Same wire prefix and HTTP status (403) as every other durable // restriction refusal — see the write-path gate below and `auth.rs`. - RelayAdminError::Banned => IngestError::ban( - BanRefusal::Banned, + RelayAdminError::Banned(source) => IngestError::ban( + BanRefusal::Banned(source), IngestError::AuthFailed("blocked: you are banned from this community".to_string()), ), RelayAdminError::Rejected(reason) => IngestError::Rejected(format!("invalid: {reason}")), @@ -574,6 +626,8 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result Ok(Scope::UsersWrite), KIND_DELETION | KIND_REACTION @@ -612,12 +666,13 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result Ok(Scope::UsersWrite), KIND_NIP29_EDIT_METADATA => { - // kind:9002 scope split: archived tag → AdminChannels, else ChannelsWrite - let has_archived = event - .tags - .iter() - .any(|t| t.kind().to_string() == "archived"); - if has_archived { + // kind:9002 scope split: archived or auto_join tag → AdminChannels, + // else ChannelsWrite + let has_admin_tag = event.tags.iter().any(|t| { + let k = t.kind().to_string(); + k == "archived" || k == "auto_join" + }); + if has_admin_tag { Ok(Scope::AdminChannels) } else { Ok(Scope::ChannelsWrite) @@ -762,6 +817,8 @@ pub(crate) fn is_global_only_kind(kind: u32) -> bool { // keyed by (pubkey, kind[, d_tag]). A stray `h` tag must not channel-scope them. | KIND_EMOJI_SET | KIND_EMOJI_LIST + // Custom emoji entry (30180): same ownership shape, never channel-scoped. + | KIND_EMOJI_ENTRY // NIP-AE agent engrams are addressed by (pubkey_a, kind, d_tag); never channel-scoped. | KIND_AGENT_ENGRAM // NIP-ER event reminders are addressed by (pubkey, kind, d_tag); never channel-scoped. @@ -1403,26 +1460,8 @@ async fn validate_edit_ownership( event: &Event, state: &AppState, ) -> Result<(), String> { - let target_hex = event - .tags - .iter() - .find_map(|t| { - if t.kind().to_string() == "e" { - t.content().and_then(|v| { - if v.len() == 64 && v.chars().all(|c| c.is_ascii_hexdigit()) { - Some(v.to_string()) - } else { - None - } - }) - } else { - None - } - }) + let target_bytes = buzz_core::media::first_edit_target(event) .ok_or_else(|| "missing e tag for edit target".to_string())?; - - let target_bytes = - hex::decode(&target_hex).map_err(|_| "invalid target event ID".to_string())?; // Kind 40003 skips the generic membership gate, so this validator is the // only authority: a target outside the edit's `h` channel, unreadable, or // not the actor's to edit is denied exactly like a missing one. @@ -2350,7 +2389,7 @@ fn write_restriction_denial( ) -> Option { if restriction.banned { return Some(IngestError::ban( - BanRefusal::Banned, + BanRefusal::banned(restriction), IngestError::AuthFailed("blocked: you are banned from this community".to_string()), )); } @@ -2373,39 +2412,18 @@ fn write_restriction_denial( /// by its owner's (`users.agent_owner_pubkey`). A ban is normally enforced by /// the auth seam and the live disconnect; this gate is the durable backstop /// for a missed disconnect and for HTTP writes. A timeout has no auth-seam -/// presence, so this is where it is enforced. Fails closed on a DB error. +/// presence, so this is where it is enforced. It runs per write, so it reads +/// through [`AppState::restriction_state_cached`]: a restriction change takes +/// effect when its write invalidates the cache, or within +/// [`crate::state::RESTRICTION_CACHE_MAX_AGE`] on a pod that misses that +/// notification. The verdict is +/// still taken at `now`, so a cached timeout lifts on time. Fails closed on a +/// DB error. pub(crate) async fn enforce_write_restriction( state: &AppState, tenant: &TenantContext, kind: u32, pubkey: &nostr::PublicKey, -) -> Result<(), IngestError> { - #[cfg(test)] - crate::nip_fi_test_hooks::before_write_ban_check(tenant.community()).await; - let restriction = state - .db - .moderation_restriction_state(tenant.community(), pubkey.as_bytes()) - .await - .map_err(|e| { - IngestError::ban( - BanRefusal::Unavailable, - IngestError::Internal(format!( - "error: internal error checking restriction state: {e}" - )), - ) - })?; - write_restriction_denial(kind, &restriction, Utc::now()).map_or(Ok(()), Err) -} - -/// [`enforce_write_restriction`] over a 30-second cached restriction row, for -/// the WebSocket ephemeral and observer paths. Those run per typing pulse and -/// observer frame; persistent ingest keeps the uncached read. The verdict is -/// still taken at `now`, so a cached timeout lifts on time. -pub(crate) async fn enforce_cached_write_restriction( - state: &AppState, - tenant: &TenantContext, - kind: u32, - pubkey: &nostr::PublicKey, ) -> Result<(), IngestError> { #[cfg(test)] crate::nip_fi_test_hooks::before_write_ban_check(tenant.community()).await; @@ -2530,6 +2548,28 @@ struct ChannelCreateRequest { members: Vec>, } +async fn validate_event_imeta( + tenant: &TenantContext, + state: &AppState, + event: &Event, + tenant_media_base: &str, +) -> Result<(), IngestError> { + let imeta_tags: Vec> = event + .tags + .iter() + .filter(|t| t.kind().to_string() == "imeta") + .map(|t| t.as_slice().iter().map(|s| s.to_string()).collect()) + .collect(); + if !imeta_tags.is_empty() { + crate::api::validate_imeta_tags(&imeta_tags, tenant_media_base) + .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?; + crate::api::verify_imeta_blobs(tenant, &imeta_tags, &state.media_storage) + .await + .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?; + } + Ok(()) +} + async fn ingest_event_inner( state: &Arc, tracer: &Arc, @@ -2691,6 +2731,8 @@ async fn ingest_event_inner( // (commands, feedback, reports, moderation) so no write returns ahead of it. enforce_write_restriction(state, tenant, kind_u32, auth.pubkey()).await?; + super::media_access::validate_media_references(tenant, state, &event).await?; + // Command kinds are routed AFTER signature verification, timestamp check, // pubkey/auth match, and scope validation — never before. if buzz_core::kind::is_command_kind(kind_u32) { @@ -2847,7 +2889,7 @@ async fn ingest_event_inner( // Channel-scoped tokens cannot publish global events — that would bypass // the token's channel restriction. This covers kind:1 (global text notes), // kind:3 (contact lists), kind:0 (profiles), and kind:9007 (create-group - // without an h-tag, which would auto-assign a server UUID). + // without an h-tag, which the create path also refuses). return Err(IngestError::AuthFailed( "restricted: channel-scoped tokens cannot publish global events".into(), )); @@ -3053,7 +3095,7 @@ async fn ingest_event_inner( validate_huddle_lifecycle_event(tenant, state, &event, kind_u32).await?; // kind:9000 is checked person by person; the plan carries each result - // through storage to `apply_put_user`. + // to `persist_put_user`, which stores the event and applies it. let put_user = if kind_u32 == KIND_NIP29_PUT_USER { Some( crate::handlers::side_effects::validate_put_user(tenant, &event, state) @@ -3119,6 +3161,9 @@ async fn ingest_event_inner( // Artifact revisions passed the same home-channel write gates as kind 9 // above; they are stored and published without conversation side effects. if kind_u32 == buzz_core::kind::KIND_ARTIFACT { + let base = + crate::api::media::media_base_url_for_tenant(&state.config.relay_url, tenant.host()); + validate_event_imeta(tenant, state, &event, &base).await?; let result = super::artifact::accept(state, tenant, &event, &auth).await?; if let Some(ch_id) = channel_id { emit( @@ -3212,8 +3257,9 @@ async fn ingest_event_inner( .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?; } - // A kind:9007 with an `h` tag creates its channel when it is stored, in the - // same transaction (see the storage dispatch below). + // A kind:9007 must carry the new channel's id in its `h` tag. It creates + // its channel when it is stored, in the same transaction (see the storage + // dispatch below). let mut channel_create: Option = None; if kind_u32 == KIND_NIP29_CREATE_GROUP { @@ -3290,6 +3336,12 @@ async fn ingest_event_inner( unlisted, members, }); + } else { + // The channel is created in the same commit as its event, so a + // refused create (a taken name, for example) reaches the client. + return Err(IngestError::Rejected( + "invalid: create-group must include an h tag with the new channel id".into(), + )); } } @@ -3370,19 +3422,7 @@ async fn ingest_event_inner( .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?; } - let imeta_tags: Vec> = event - .tags - .iter() - .filter(|t| t.kind().to_string() == "imeta") - .map(|t| t.as_slice().iter().map(|s| s.to_string()).collect()) - .collect(); - if !imeta_tags.is_empty() { - crate::api::validate_imeta_tags(&imeta_tags, &tenant_media_base) - .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?; - crate::api::verify_imeta_blobs(tenant, &imeta_tags, &state.media_storage) - .await - .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?; - } + validate_event_imeta(tenant, state, &event, &tenant_media_base).await?; let thread_meta = if requires_h_channel_scope(kind_u32) { if let Some(ch_id) = channel_id { @@ -3409,6 +3449,9 @@ async fn ingest_event_inner( if kind_u32 == KIND_EMOJI_SET || kind_u32 == KIND_EMOJI_LIST { validate_custom_emoji_tags(&event)?; } + if kind_u32 == KIND_EMOJI_ENTRY { + validate_emoji_entry(&event)?; + } // Resolve the target reference, then use one DB transaction to upsert the // reaction row (dedup via ON CONFLICT) with reaction_event_id already set and @@ -3466,7 +3509,7 @@ async fn ingest_event_inner( emoji, ) .await - .map_err(|e| IngestError::Internal(format!("error: {e}")))? + .map_err(|e| IngestError::Internal(format!("error: {}", e.kind())))? { buzz_db::ReactionEventInsertOutcome::TargetMissing => { return Err(IngestError::Rejected(format!( @@ -3522,7 +3565,6 @@ async fn ingest_event_inner( ) .await; - info!(event_id = %event_id_hex, kind = kind_u32, "Event ingested via pipeline"); return Ok(IngestResult { event_id: event_id_hex, accepted: true, @@ -3540,6 +3582,8 @@ async fn ingest_event_inner( }; let workflow_deletion = crate::handlers::side_effects::is_workflow_deletion(&event); + let atomic_deletion = crate::handlers::side_effects::is_atomic_deletion(kind_u32, &event); + let mut message = String::new(); let (stored_event, was_inserted) = if let Some(create) = channel_create.as_ref() { let creator = event.pubkey.to_bytes(); let channel = buzz_db::channel::NewChannel { @@ -3557,8 +3601,12 @@ async fn ingest_event_inner( .db .create_channel_with_event(tenant.community(), create.channel_id, channel, &event) .await - .map_err(|e| IngestError::Internal(format!("error: {e}")))? - { + .map_err(|e| match e { + buzz_db::DbError::ChannelNameTaken(_) => { + IngestError::Rejected(format!("invalid: {e}")) + } + _ => IngestError::Internal(format!("error: {}", e.kind())), + })? { buzz_db::channel::ChannelCreate::Created(stored) => { metrics::counter!( "buzz_channels_created_total", @@ -3590,6 +3638,42 @@ async fn ingest_event_inner( crate::handlers::side_effects::persist_workflow_deletion(tenant, &event, state) .await .map_err(|e| IngestError::Internal(format!("error: workflow deletion failed: {e}")))? + } else if atomic_deletion { + // One commit stores the deletion and soft-deletes its targets, so an + // accepted deletion never leaves its target live. Failure stores + // nothing; the client is told and can resend. + let thread_params = thread_meta.as_ref().map(|m| m.as_params()); + crate::handlers::side_effects::persist_deletion( + tenant, + &event, + state, + channel_id, + thread_params, + ) + .await + .map_err(|e| IngestError::Internal(format!("error: deletion failed: {e}")))? + } else if let Some(plan) = put_user { + // One commit stores the event and applies its membership changes. A + // failure stores nothing, so the client is told and can resend it. + // Refusing everyone under the membership lock is the client's error; + // anything else is ours. + let thread_params = thread_meta.as_ref().map(|m| m.as_params()); + let (stored, inserted, ok_message) = crate::handlers::side_effects::persist_put_user( + tenant, + &event, + state, + plan, + thread_params, + ) + .await + .map_err(|e| match e.downcast_ref::() { + Some(buzz_db::DbError::AccessDenied(reason)) => { + IngestError::Rejected(format!("invalid: {reason}")) + } + _ => IngestError::Internal(format!("error: membership write failed: {e}")), + })?; + message = ok_message; + (stored, inserted) } else if kind_u32 == KIND_NIP29_EDIT_METADATA { // One commit stores the event and applies its channel changes. A // failure stores nothing, so the client is told and can resend it. @@ -3601,6 +3685,9 @@ async fn ingest_event_inner( Some(buzz_db::DbError::AccessDenied(reason)) => { IngestError::Rejected(format!("invalid: {reason}")) } + Some(taken @ buzz_db::DbError::ChannelNameTaken(_)) => { + IngestError::Rejected(format!("invalid: {taken}")) + } _ => IngestError::Internal(format!("error: channel update failed: {e}")), })? } else if buzz_core::kind::is_replaceable(kind_u32) { @@ -3610,7 +3697,7 @@ async fn ingest_event_inner( .db .replace_addressable_event(tenant.community(), &event, channel_id) .await - .map_err(|e| IngestError::Internal(format!("error: {e}")))? + .map_err(|e| IngestError::Internal(format!("error: {}", e.kind())))? } else if is_parameterized_replaceable(kind_u32) { // NIP-33 parameterized replaceable — keyed by (kind, pubkey, d_tag). let d_tag = buzz_db::event::extract_d_tag(&event).unwrap_or_default(); @@ -3625,7 +3712,7 @@ async fn ingest_event_inner( .db .replace_parameterized_event(tenant.community(), &event, &d_tag, channel_id) .await - .map_err(|e| IngestError::Internal(format!("error: {e}")))? + .map_err(|e| IngestError::Internal(format!("error: {}", e.kind())))? } else if let Some(spec) = canvas_revision_spec.as_ref() { // Canvas write carrying an optimistic-concurrency precondition. Plain // canvas writes (no `expected-revision` tag) fall through to the generic @@ -3642,7 +3729,7 @@ async fn ingest_event_inner( .db .insert_canvas_head_checked(tenant.community(), &event, channel, precondition) .await - .map_err(|e| IngestError::Internal(format!("error: {e}")))?; + .map_err(|e| IngestError::Internal(format!("error: {}", e.kind())))?; match status { buzz_db::ChannelHeadWriteStatus::RevisionMissing => { return Err(IngestError::CanvasConflict( @@ -3680,7 +3767,9 @@ async fn ingest_event_inner( buzz_db::DbError::AuthEventRejected => { IngestError::Rejected("invalid: AUTH events cannot be stored".into()) } - other => IngestError::Internal(format!("error: database error: {other}")), + other => { + IngestError::Internal(format!("error: database error: {}", other.kind())) + } }); } } @@ -3694,14 +3783,13 @@ async fn ingest_event_inner( }); } - // Workflow deletion and kind:9002 applied their changes in the insert's - // own transaction above. - let persisted_atomically = workflow_deletion || kind_u32 == KIND_NIP29_EDIT_METADATA; - let mut message = String::new(); - if let Some(plan) = put_user { - message = crate::handlers::side_effects::apply_put_user(tenant, &event, state, plan).await; - } else if !persisted_atomically && crate::handlers::side_effects::is_side_effect_kind(kind_u32) - { + // Workflow deletion, kind 5 / 9005 deletions of `e` targets, kind:9000 and + // kind:9002 applied their changes in the insert's own transaction above. + let persisted_atomically = workflow_deletion + || atomic_deletion + || kind_u32 == KIND_NIP29_PUT_USER + || kind_u32 == KIND_NIP29_EDIT_METADATA; + if !persisted_atomically && crate::handlers::side_effects::is_side_effect_kind(kind_u32) { if let Err(e) = crate::handlers::side_effects::handle_side_effects(tenant, kind_u32, &event, state) .await @@ -3769,8 +3857,6 @@ async fn ingest_event_inner( ) .await; - info!(event_id = %event_id_hex, kind = kind_u32, "Event ingested via pipeline"); - Ok(IngestResult { event_id: event_id_hex, accepted: true, @@ -3797,7 +3883,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] async fn check_channel_write_denies_when_channel_lookup_fails() { - let state = crate::state::tests::test_state_with_database_url( + let state = crate::state::tests::test_state_with_unreachable_database_url( "postgres://buzz:buzz_dev@127.0.0.1:1/buzz", // sadscan:disable np.postgres.1 ) .await; @@ -3805,7 +3891,7 @@ mod postgres_tests { let tenant = TenantContext::resolved(community, "archive.test"); let keys = nostr::Keys::generate(); let channel_id = Uuid::new_v4(); - state.membership_cache.insert( + state.membership_cache.seed_member( (community, channel_id, keys.public_key().to_bytes().to_vec()), true, ); @@ -3959,6 +4045,350 @@ mod postgres_tests { )); } + fn emoji_entry_event(tags: &[&[&str]], content: &str) -> nostr::Event { + EventBuilder::new(Kind::Custom(KIND_EMOJI_ENTRY as u16), content) + .tags( + tags.iter() + .map(|t| nostr::Tag::parse(t.iter().copied()).expect("tag")), + ) + .sign_with_keys(&nostr::Keys::generate()) + .expect("sign emoji entry") + } + + #[test] + fn emoji_entry_validation_table() { + const URL: &str = "https://example.com/p.gif"; + let ok_tags: &[&[&str]] = &[&["d", "party_parrot"], &["emoji", "party_parrot", URL]]; + assert!(validate_emoji_entry(&emoji_entry_event(ok_tags, "party parrot")).is_ok()); + let dashed_tags: &[&[&str]] = + &[&["d", "party-parrot-2"], &["emoji", "party-parrot-2", URL]]; + assert!(validate_emoji_entry(&emoji_entry_event(dashed_tags, "party parrot 2")).is_ok()); + let max_shortcode = "a".repeat(buzz_sdk::MAX_CUSTOM_EMOJI_SHORTCODE_LEN); + let max_tags: &[&[&str]] = &[&["d", &max_shortcode], &["emoji", &max_shortcode, URL]]; + assert!(validate_emoji_entry(&emoji_entry_event(max_tags, &max_shortcode)).is_ok()); + + let cases: Vec<(&str, Vec<&[&str]>, &str, &str)> = vec![ + ("no d", vec![&["emoji", "a", URL]], "", "exactly one d tag"), + ( + "two d", + vec![&["d", "a"], &["d", "a"], &["emoji", "a", URL]], + "", + "exactly one d tag", + ), + ("no emoji", vec![&["d", "a"]], "", "exactly one emoji tag"), + ( + "two emoji", + vec![&["d", "a"], &["emoji", "a", URL], &["emoji", "b", URL]], + "", + "exactly one emoji tag", + ), + ( + "h tag", + vec![&["d", "a"], &["emoji", "a", URL], &["h", "chan"]], + "", + "must not carry an h tag", + ), + ( + "emoji tag without url", + vec![&["d", "a"], &["emoji", "a"]], + "", + "[emoji, shortcode, url]", + ), + ( + "bad shortcode", + vec![&["d", "bad name"], &["emoji", "bad name", URL]], + "", + "may only contain", + ), + ( + "d differs from shortcode", + vec![&["d", "other"], &["emoji", "a", URL]], + "", + "must equal the normalized shortcode", + ), + ( + "uppercase shortcode", + vec![&["d", "a"], &["emoji", "A", URL]], + "", + "must equal the normalized shortcode", + ), + ( + "non-http url", + vec![&["d", "a"], &["emoji", "a", "ftp://example.com/a.gif"]], + "", + "http:// or https://", + ), + ( + "arbitrary content", + vec![&["d", "a"], &["emoji", "a", URL]], + "x", + "content must equal", + ), + ( + "empty content", + vec![&["d", "party_parrot"], &["emoji", "party_parrot", URL]], + "", + "content must equal", + ), + ( + "keyword-stuffed content", + vec![&["d", "party_parrot"], &["emoji", "party_parrot", URL]], + "party parrot cat dog", + "content must equal", + ), + ( + "content keeps underscores", + vec![&["d", "party_parrot"], &["emoji", "party_parrot", URL]], + "party_parrot", + "content must equal", + ), + ]; + for (name, tags, content, needle) in cases { + match validate_emoji_entry(&emoji_entry_event(&tags, content)) { + Err(IngestError::Rejected(msg)) => assert!( + msg.starts_with("invalid: ") && msg.contains(needle), + "{name}: unexpected rejection {msg:?}" + ), + other => panic!("{name}: expected rejection, got {other:?}"), + } + } + } + + #[test] + fn emoji_entry_is_a_global_users_write_kind() { + assert!(is_global_only_kind(KIND_EMOJI_ENTRY)); + assert!(!requires_h_channel_scope(KIND_EMOJI_ENTRY)); + let event = emoji_entry_event(&[], ""); + assert_eq!( + required_scope_for_kind(KIND_EMOJI_ENTRY, &event).ok(), + Some(Scope::UsersWrite) + ); + } + + async fn publish_emoji_entry( + state: &Arc, + tenant: &TenantContext, + keys: &nostr::Keys, + tags: &[&[&str]], + content: &str, + created_at: u64, + ) -> Result { + let event = EventBuilder::new(Kind::Custom(KIND_EMOJI_ENTRY as u16), content) + .tags( + tags.iter() + .map(|t| nostr::Tag::parse(t.iter().copied()).expect("tag")), + ) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(keys) + .expect("sign emoji entry"); + let auth = IngestAuth::Http { + pubkey: keys.public_key(), + scopes: vec![Scope::UsersWrite], + auth_method: HttpAuthMethod::Nip98, + }; + ingest_event(state, tenant, event, auth).await + } + + async fn publish_built_emoji_entry( + state: &Arc, + tenant: &TenantContext, + keys: &nostr::Keys, + shortcode: &str, + url: &str, + created_at: u64, + ) -> Result { + let event = buzz_sdk::build_emoji_entry(shortcode, url) + .expect("build emoji entry") + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(keys) + .expect("sign emoji entry"); + let auth = IngestAuth::Http { + pubkey: keys.public_key(), + scopes: vec![Scope::UsersWrite], + auth_method: HttpAuthMethod::Nip98, + }; + ingest_event(state, tenant, event, auth).await + } + + async fn emoji_tenant( + state: &Arc, + keys: &[&nostr::Keys], + ) -> TenantContext { + let host = format!("emoji-entry-{}.test", Uuid::new_v4().simple()); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("community") + .id; + for k in keys { + state + .db + .ensure_user(community, k.public_key().as_bytes()) + .await + .expect("ensure user"); + } + TenantContext::resolved(community, &host) + } + + /// Production-path regression for kind:30180: invalid entries are refused by + /// `ingest_event` and never stored; a valid entry is stored; a second publish + /// under the same `d` leaves one live event (the newer one). + /// Mutations: drop the `validate_emoji_entry` call, the `KIND_EMOJI_ENTRY` + /// scope arm, or the replace path → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn emoji_entry_ingest_validates_and_replaces() { + let state = ingest_state().await; + let author = nostr::Keys::generate(); + let tenant = emoji_tenant(&state, &[&author]).await; + let now = chrono::Utc::now().timestamp() as u64; + const URL: &str = "https://example.com/p.gif"; + let url = URL; + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect test Postgres"); + let live_count = |d: &'static str| { + let pool = pool.clone(); + let community = *tenant.community().as_uuid(); + async move { + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM events WHERE community_id = $1 AND kind = $2 \ + AND d_tag = $3 AND deleted_at IS NULL", + ) + .bind(community) + .bind(KIND_EMOJI_ENTRY as i32) + .bind(d) + .fetch_one(&pool) + .await + .expect("count") + } + }; + + let rejected: Vec<(&str, Vec<&[&str]>)> = vec![ + ( + "bad shortcode", + vec![&["d", "bad name"], &["emoji", "bad name", URL]], + ), + ( + "d != shortcode", + vec![&["d", "other"], &["emoji", "party_parrot", URL]], + ), + ( + "h tag", + vec![ + &["d", "party_parrot"], + &["emoji", "party_parrot", URL], + &["h", "11111111-1111-1111-1111-111111111111"], + ], + ), + ( + "non-http url", + vec![ + &["d", "party_parrot"], + &["emoji", "party_parrot", "javascript:alert(1)"], + ], + ), + ]; + for (name, tags) in rejected { + match publish_emoji_entry(&state, &tenant, &author, &tags, "party parrot", now).await { + Err(IngestError::Rejected(msg)) => { + assert!(msg.starts_with("invalid: "), "{name}: {msg}") + } + Err(other) => panic!("{name}: expected Rejected, got {other:?}"), + Ok(_) => panic!("{name}: must be rejected"), + } + } + assert_eq!( + live_count("party_parrot").await, + 0, + "rejected entries are not stored" + ); + + let first = + publish_built_emoji_entry(&state, &tenant, &author, "party_parrot", url, now - 10) + .await + .expect("first publish"); + assert!(first.accepted, "{}", first.message); + assert_eq!(live_count("party_parrot").await, 1); + + let url2 = "https://example.com/p2.gif"; + let second = publish_built_emoji_entry(&state, &tenant, &author, "Party_Parrot", url2, now) + .await + .expect("second publish"); + assert!(second.accepted, "{}", second.message); + assert_eq!( + live_count("party_parrot").await, + 1, + "same d keeps one live event" + ); + let surviving: Vec = sqlx::query_scalar( + "SELECT id FROM events WHERE community_id = $1 AND kind = $2 \ + AND d_tag = 'party_parrot' AND deleted_at IS NULL", + ) + .bind(tenant.community().as_uuid()) + .bind(KIND_EMOJI_ENTRY as i32) + .fetch_one(&pool) + .await + .expect("surviving id"); + assert_eq!(hex::encode(surviving), second.event_id); + } + + /// Prefix search over kind:30180 content finds "party parrot" for "parr", and + /// matches words at any position. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn emoji_entry_prefix_search_finds_by_word_prefix() { + let state = ingest_state().await; + let author = nostr::Keys::generate(); + let tenant = emoji_tenant(&state, &[&author]).await; + let now = chrono::Utc::now().timestamp() as u64; + let url = "https://example.com/p.gif"; + for shortcode in ["party_parrot", "sad-parrot", "bufo_joy", "cloud_nine"] { + publish_built_emoji_entry(&state, &tenant, &author, shortcode, url, now) + .await + .unwrap_or_else(|e| panic!("publish {shortcode}: {e:?}")); + } + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect test Postgres"); + let indexed: i64 = sqlx::query_scalar( + "SELECT count(*) FROM events WHERE community_id = $1 AND kind = $2 \ + AND search_tsv IS NOT NULL", + ) + .bind(tenant.community().as_uuid()) + .bind(KIND_EMOJI_ENTRY as i32) + .fetch_one(&pool) + .await + .expect("count indexed entries"); + assert_eq!( + indexed, 4, + "events.search_tsv does not index kind 30180: this database uses the \ + positive FTS allowlist (migration 0008); run against the desired-state lane" + ); + let search = |q: &str| { + let service = buzz_search::SearchService::new(pool.clone()); + let query = buzz_search::SearchQuery { + community: tenant.community(), + q: q.to_owned(), + channel_scope: buzz_search::ChannelScope::Any, + kinds: Some(vec![KIND_EMOJI_ENTRY as i32]), + authors: None, + since: None, + until: None, + page: 1, + per_page: 50, + mode: buzz_search::SearchMode::Prefix, + sort: buzz_search::SearchSort::Relevance, + }; + async move { service.search(&query).await.expect("search").hits.len() } + }; + assert_eq!(search("parr").await, 2, "word-prefix finds both parrots"); + assert_eq!(search("party par").await, 1, "earlier words are exact"); + assert_eq!(search("joy").await, 1, "any word position matches"); + assert_eq!(search("zzz").await, 0); + } + /// A banned relay admin must be refused with the same wire prefix and /// transport status as every other durable-restriction refusal: /// `blocked:` and (via `bridge.rs`'s `AuthFailed` arm) HTTP 403 — never @@ -3966,11 +4396,13 @@ mod postgres_tests { /// client retry-loop against an authorization decision. #[test] fn relay_admin_ban_maps_to_blocked_auth_failure() { - let mapped = map_relay_admin_error(super::super::relay_admin::RelayAdminError::Banned); + let mapped = map_relay_admin_error(super::super::relay_admin::RelayAdminError::Banned( + crate::handlers::auth::BanSource::Own, + )); assert!(matches!( mapped, IngestError::Ban { - refusal: BanRefusal::Banned, + refusal: BanRefusal::Banned(crate::handlers::auth::BanSource::Own), .. } )); @@ -4100,9 +4532,10 @@ mod postgres_tests { let submitted = store .submit( - &host, + Some(&host), "test-operator", Some("lane3 ingest fence regression"), + None, ) .await .expect("submit"); @@ -4245,7 +4678,8 @@ mod postgres_tests { #[test] fn create_group_does_not_require_h_tag() { - // kind:9007 creates the channel — h-tag is optional (client-chosen UUID) + // kind:9007 names its new channel in h, but the create path checks that + // itself (it refuses a create without one), not requires_h_channel_scope assert!(!requires_h_channel_scope(KIND_NIP29_CREATE_GROUP)); } @@ -4448,6 +4882,7 @@ mod postgres_tests { KIND_BOOKMARK_SET, KIND_EMOJI_SET, KIND_EMOJI_LIST, + KIND_EMOJI_ENTRY, KIND_AGENT_ENGRAM, KIND_AGENT_PROFILE, KIND_PERSONA, @@ -6203,9 +6638,8 @@ mod postgres_tests { // ── AppState ───────────────────────────────────────────────────────── // Redis is lazy and never actually contacted on this rejection path. - let redis_pool = deadpool_redis::Config::from_url(FAKE_REDIS_URL) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("deadpool redis pool"); + let redis_pool = + buzz_pubsub::redis_connection(FAKE_REDIS_URL).expect("lazy redis connection"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(FAKE_REDIS_URL, redis_pool.clone()) .await @@ -6486,9 +6920,8 @@ mod postgres_tests { const FAKE_REDIS_URL: &str = "redis://127.0.0.1:1"; // never contacted let db = buzz_db::Db::from_pool(pool.clone()); - let redis_pool = deadpool_redis::Config::from_url(FAKE_REDIS_URL) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("deadpool redis pool"); + let redis_pool = + buzz_pubsub::redis_connection(FAKE_REDIS_URL).expect("lazy redis connection"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(FAKE_REDIS_URL, redis_pool.clone()) .await @@ -6672,12 +7105,14 @@ mod postgres_tests { ); // Control: a working lookup reaches the archive gate. - healthy.membership_cache.insert(member_key.clone(), true); + healthy + .membership_cache + .seed_member(member_key.clone(), true); let control = ingest_event_inner(&healthy, &tracer, &tenant, post("control"), auth()).await; // Only the channel lookup fails: the post must be denied and not stored. - failing.membership_cache.insert(member_key, true); + failing.membership_cache.seed_member(member_key, true); let event = post("lookup fails"); let event_id = event.id.to_bytes().to_vec(); let denied = ingest_event_inner(&failing, &tracer, &tenant, event, auth()).await; @@ -6794,7 +7229,7 @@ mod postgres_tests { scopes: vec![Scope::MessagesWrite], auth_method: HttpAuthMethod::Nip98, }; - failing.membership_cache.insert( + failing.membership_cache.seed_member( (community, source, author.public_key().to_bytes().to_vec()), true, ); @@ -7124,6 +7559,102 @@ mod postgres_tests { assert_eq!(stored.channel_id, Some(channels[0])); } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn subject_cannot_delete_relay_verified_profile() { + use buzz_core::kind::KIND_VERIFIED_PROFILE; + use buzz_db::verified_profiles::ProfileAdmission; + use nostr::Tag; + let f = ScopedTargetFixture::new("verified-profile-deletion").await; + let subject = f.author.public_key().to_hex(); + let now = Utc::now(); + let profile = f + .state + .db + .publish_verified_profile( + ProfileAdmission { + community: f.tenant.community(), + issuer: "https://issuer.test", + pubkey: &subject, + issued_at: now, + admitted_at: now, + display_name: "Alice", + username: "alice", + full_name: Some("Alice Example"), + label: "Example", + refresh_seconds: 3600, + membership_required: false, + }, + &f.state.relay_keypair, + ) + .await + .unwrap() + .expect("publish relay-owned profile"); + let auth = || IngestAuth::Http { + pubkey: f.author.public_key(), + scopes: vec![Scope::MessagesWrite], + auth_method: HttpAuthMethod::Nip98, + }; + let deletion = |tag: Tag| { + EventBuilder::new(Kind::Custom(KIND_DELETION as u16), "") + .tags([tag]) + .sign_with_keys(&f.author) + .unwrap() + }; + let coordinate = |author: String| { + Tag::parse([ + "a".to_owned(), + format!("{KIND_VERIFIED_PROFILE}:{author}:{subject}"), + ]) + .unwrap() + }; + for tag in [ + Tag::parse(["e", &profile.id.to_hex()]).unwrap(), + coordinate(profile.pubkey.to_hex()), + // Even a subject-authored coordinate cannot request deletion of this kind. + coordinate(subject.clone()), + ] { + let event = deletion(tag); + let id = event.id; + let result = f.submit(event, auth()).await; + assert!( + matches!(&result, Err(IngestError::Rejected(message)) + if message == "invalid: deletion target not found or not deletable by you"), + "profile deletion must be denied, got {:?}", + result.err() + ); + assert!(f + .state + .db + .get_event_by_id(f.tenant.community(), id.as_bytes()) + .await + .unwrap() + .is_none()); + let stored = f + .state + .db + .get_event_by_id(f.tenant.community(), profile.id.as_bytes()) + .await + .unwrap() + .expect("profile remains readable"); + assert_eq!(stored.event, profile); + } + + f.submit( + deletion(Tag::parse(["e", &f.global.id.to_hex()]).unwrap()), + auth(), + ) + .await + .expect("ordinary author-owned note remains deletable"); + assert!(f + .state + .db + .get_event_by_id(f.tenant.community(), f.global.id.as_bytes()) + .await + .unwrap() + .is_none()); + } + /// A community with `author`'s live message in an open channel, an /// author global note, and a second open channel for out-of-scope tokens. struct ScopedTargetFixture { @@ -7407,7 +7938,7 @@ mod postgres_tests { match enforce_write_restriction(&state, &tenant, KIND_REPORT, &agent.public_key()).await { Err( err @ IngestError::Ban { - refusal: BanRefusal::Banned, + refusal: BanRefusal::Banned(crate::handlers::auth::BanSource::Owner), .. }, ) => match err.into_legacy() { @@ -7424,6 +7955,9 @@ mod postgres_tests { .unban_community_member(tenant.community(), &owner_bytes, &owner_bytes) .await .expect("unban owner"); + // As the unban command does: drops the community's rows, the + // agent's (which carries the owner's ban) included. + state.invalidate_restrictions_local(tenant.community()); enforce_write_restriction(&state, &tenant, KIND_REACTION, &agent.public_key()) .await .expect("unbanning the owner restores the agent"); @@ -7445,7 +7979,7 @@ mod postgres_tests { .expect("ban owner"); for keys in [&owner, &agent] { - let crate::api::relay_members::MembershipRefusal::Api((status, body)) = + let crate::api::relay_members::MembershipRefusal::Api(reason, (status, body)) = crate::api::relay_members::enforce_relay_membership( &state, &tenant, @@ -7459,6 +7993,7 @@ mod postgres_tests { else { panic!("without a token the relay's own refusal is returned"); }; + assert_eq!(reason, crate::access::AuthReason::Banned); assert_eq!(status, axum::http::StatusCode::FORBIDDEN); assert_eq!( body.0["error"], @@ -7471,6 +8006,8 @@ mod postgres_tests { .unban_community_member(tenant.community(), &owner_bytes, &owner_bytes) .await .expect("unban owner"); + // As the unban command does on its own pod. + state.invalidate_restrictions_local(tenant.community()); crate::api::relay_members::enforce_relay_membership( &state, &tenant, @@ -7538,10 +8075,10 @@ mod postgres_tests { .map_err(|refusal| { let status = refusal.status(); let body = match refusal { - crate::api::relay_members::MembershipRefusal::Api((_, body)) => { + crate::api::relay_members::MembershipRefusal::Api(_, (_, body)) => { body.0["error"].as_str().unwrap_or("").to_owned() } - crate::api::relay_members::MembershipRefusal::NipFi(class) => { + crate::api::relay_members::MembershipRefusal::NipFi(_, class) => { class.http_body().to_owned() } }; @@ -7598,6 +8135,41 @@ mod postgres_tests { ); } + /// Recording an agent's owner drops the agent's cached restriction row. + /// HTTP admission caches the agent's row before it links the token + /// owner, and only checks bans, so the owner's timeout must still reach + /// the agent's first write. + /// Mutation: drop `invalidate_restrictions` from + /// `disconnect_unowned_agent_clusterwide` → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn owner_link_drops_the_agents_cached_restriction_row() { + let state = ingest_state().await; + let (tenant, owner, agent) = token_owner_fixture(&state, "owner-link-timeout").await; + state + .db + .timeout_community_member( + tenant.community(), + owner.public_key().as_bytes(), + owner.public_key().as_bytes(), + Utc::now() + chrono::Duration::hours(1), + None, + ) + .await + .expect("timeout owner"); + + http_membership(&state, &tenant, &agent, Some(owner.public_key())) + .await + .expect("a timeout does not refuse HTTP admission"); + match enforce_write_restriction(&state, &tenant, KIND_REACTION, &agent.public_key()).await { + Err(IngestError::AuthFailed(msg)) => assert!( + msg.starts_with("restricted: you are timed out until "), + "got {msg:?}" + ), + other => panic!("a timed-out owner's newly linked agent must not write: {other:?}"), + } + } + /// The token owner's ban reaches an agent that is itself a member, on a /// closed and an open relay, with no stored owner link. /// Mutation: ignore `token_owner` in `community_ban_outcome` → RED. @@ -7730,9 +8302,8 @@ mod postgres_tests { use sqlx::postgres::PgConnectOptions; use tokio_util::sync::CancellationToken; - // A schema with bans but no `users` table: the ban commits, and only - // the owned-agent lookup fails. It carries `communities` and the - // deletion lock key so the ban passes community write admission. + // A supported ban writer commits before the users table is taken away: + // only the subsequent owned-agent lookup fails. let db_url = crate::test_support::database_url(); let admin = sqlx::PgPool::connect(&db_url) .await @@ -7740,6 +8311,8 @@ mod postgres_tests { let schema = format!("revoke_owner_{}", Uuid::new_v4().simple()); sqlx::raw_sql(sqlx::AssertSqlSafe(format!( "CREATE SCHEMA {schema}; \ + CREATE TABLE {schema}.users (LIKE public.users INCLUDING ALL); \ + CREATE TABLE {schema}.relay_invites (LIKE public.relay_invites INCLUDING ALL); \ CREATE TABLE {schema}.community_bans (LIKE public.community_bans INCLUDING ALL); \ CREATE TABLE {schema}.communities (LIKE public.communities INCLUDING ALL); \ CREATE FUNCTION {schema}.community_deletion_lock_key(target UUID) RETURNS BIGINT \ @@ -7821,6 +8394,10 @@ mod postgres_tests { ) .await .expect("ban commits"); + sqlx::raw_sql(sqlx::AssertSqlSafe(format!("DROP TABLE {schema}.users"))) + .execute(&admin) + .await + .expect("break only the post-commit owner lookup"); let revoked = state .revoke_live_access( &tenant, diff --git a/crates/buzz-relay/src/handlers/media_access.rs b/crates/buzz-relay/src/handlers/media_access.rs new file mode 100644 index 00000000000..626c45c7ac1 --- /dev/null +++ b/crates/buzz-relay/src/handlers/media_access.rs @@ -0,0 +1,165 @@ +//! Prevent a copied inaccessible URL from granting access through a new event. +use super::ingest::IngestError; +use crate::{api::media_access::MediaReadMode, state::AppState}; +use buzz_core::TenantContext; +use nostr::Event; + +pub(crate) async fn validate_media_references( + tenant: &TenantContext, + state: &AppState, + event: &Event, +) -> Result<(), IngestError> { + let mode = state.config.media_read_mode; + if mode == MediaReadMode::Off { + return Ok(()); + } + let base = crate::api::media::media_base_url_for_tenant(&state.config.relay_url, tenant.host()); + let hashes = buzz_core::media::publication_hashes(event, &base); + // The bounded profile read probe searches the original signed JSON for the + // literal hash. Do not accept an encoded-only reference that probe cannot find. + if !profile_hashes_are_literal(event, &hashes) { + metrics::counter!("buzz_media_publication_access_total", "mode" => mode.label(), "reason" => "noncanonical_profile_hash").increment(1); + if mode == MediaReadMode::Enforce { + return Err(IngestError::Rejected( + "restricted: profile media hashes must appear literally in profile content".into(), + )); + } + } + if hashes.len() > 512 { + metrics::counter!("buzz_media_publication_access_total", "mode" => mode.label(), "reason" => "limit").increment(1); + return if mode == MediaReadMode::Enforce { + Err(IngestError::Rejected( + "restricted: too many attachment references".into(), + )) + } else { + // Skip per-reference fan-out, but retain a single best-effort + // publication boundary batch for accepted shadow events. + if state + .db + .record_media_publications(tenant.community(), hashes.into_iter().collect()) + .await + .is_err() + { + metrics::counter!("buzz_media_publication_access_total", "mode" => mode.label(), "reason" => "record_error").increment(1); + } + Ok(()) + }; + } + let author = super::ingest::effective_message_author(event, &state.relay_keypair.public_key()); + for hash in &hashes { + let checked = async { + let meta = state + .media_storage + .get_sidecar(tenant, hash) + .await + .map_err(|error| { + if matches!(error, buzz_media::MediaError::NotFound) { + ( + "missing_sidecar", + IngestError::Rejected( + "restricted: attachment is not accessible".into(), + ), + ) + } else { + ( + "lookup_error", + IngestError::Internal("error: media reference lookup failed".into()), + ) + } + })?; + let access = state + .db + .media_access( + tenant.community(), + hash, + &meta.ext, + &base, + &author, + true, + super::req::event_visible_to_reader, + ) + .await + .map_err(|error| { + ( + if matches!(error, buzz_db::DbError::MediaAuthorizationCapacity) { + "capacity" + } else { + "lookup_error" + }, + IngestError::Internal("error: media authorization unavailable".into()), + ) + })?; + if matches!( + access, + buzz_db::media::MediaAccess::Allowed | buzz_db::media::MediaAccess::UploaderPreview + ) { + Ok(()) + } else { + Err(( + "denied", + IngestError::Rejected("restricted: attachment is not accessible".into()), + )) + } + } + .await; + let reason = checked + .as_ref() + .err() + .map_or("allow", |(reason, _)| *reason); + metrics::counter!("buzz_media_publication_access_total", "mode" => mode.label(), "reason" => reason).increment(1); + if let Err((_, error)) = checked { + if mode == MediaReadMode::Enforce { + return Err(error); + } + } + } + // A marker consumes previews but never grants download access. Shadow + // recording is best effort and cannot change event acceptance on failure. + if !hashes.is_empty() + && state + .db + .record_media_publications(tenant.community(), hashes.into_iter().collect()) + .await + .is_err() + { + metrics::counter!("buzz_media_publication_access_total", "mode" => mode.label(), "reason" => "record_error").increment(1); + if mode == MediaReadMode::Enforce { + return Err(IngestError::Internal( + "error: media publication recording failed".into(), + )); + } + } + Ok(()) +} + +fn profile_hashes_are_literal(event: &Event, hashes: &std::collections::BTreeSet) -> bool { + !matches!(event.kind.as_u16(), 0 | 30175) + || hashes.iter().all(|hash| event.content.contains(hash)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn profile_publication_matches_the_bounded_literal_read_probe() { + let keys = nostr::Keys::generate(); + let hash = "f".repeat(64); + let poster = "a".repeat(64); + let base = "https://example.org/media"; + let plain = format!(r#"{{"picture":"{base}/{hash}.png"}}"#); + let escaped = plain.replace(&hash, &format!("\\u0066{}", &hash[1..])); + let animated = format!( + r#"{{"picture":"{base}/{poster}.png#buzz-anim=https%3A%2F%2Fexample.org%2Fmedia%2F%66{}.gif"}}"#, + &hash[1..] + ); + for (content, accepted) in [(plain, true), (escaped, false), (animated, false)] { + let event = nostr::EventBuilder::new(nostr::Kind::Metadata, content) + .sign_with_keys(&keys) + .unwrap(); + let hashes = buzz_core::media::publication_hashes(&event, base); + assert!(hashes.contains(&hash)); + assert_eq!(profile_hashes_are_literal(&event, &hashes), accepted); + } + } +} diff --git a/crates/buzz-relay/src/handlers/membership_notice_postgres_tests.rs b/crates/buzz-relay/src/handlers/membership_notice_postgres_tests.rs new file mode 100644 index 00000000000..ded5b5e1a50 --- /dev/null +++ b/crates/buzz-relay/src/handlers/membership_notice_postgres_tests.rs @@ -0,0 +1,436 @@ +//! Postgres-backed tests for the membership notices sent by a channel delete, +//! a moderation kick and a moderation DM: each notice reaches the member's +//! live subscription, and a channel-list read made on receipt already shows +//! the change. "On receipt" is enforced by `notice_barrier`, which parks the +//! producer at the notice while the test reads. + +use std::sync::Arc; + +use buzz_core::kind::{ + KIND_DM_HIDE, KIND_DM_VISIBILITY, KIND_MEMBER_ADDED_NOTIFICATION, + KIND_MEMBER_REMOVED_NOTIFICATION, +}; +use buzz_core::TenantContext; +use nostr::{EventBuilder, Keys, Kind, Tag}; +use serde_json::{json, Value}; +use tokio::sync::mpsc::Receiver; +use uuid::Uuid; + +use super::group_state_postgres_tests::{create_channel, http_auth, test_conn}; +use super::side_effects::notice_barrier; +use crate::handlers::ingest::ingest_event; +use crate::state::AppState; + +async fn fixture() -> (Arc, TenantContext) { + let state = crate::api::bridge::postgres_tests::bridge_handler_test_state() + .await + .expect("local Postgres and Redis"); + let host = format!("membership-notices-{}.local", Uuid::new_v4().simple()); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("ensure community") + .id; + (state, TenantContext::resolved(community, &host)) +} + +async fn publish( + state: &Arc, + tenant: &TenantContext, + keys: &Keys, + kind: u16, + tags: &[&[&str]], +) { + let tags: Vec = tags + .iter() + .map(|tag| Tag::parse(tag.iter().copied()).unwrap()) + .collect(); + let event = EventBuilder::new(Kind::Custom(kind), "") + .tags(tags) + .sign_with_keys(keys) + .expect("sign"); + let result = ingest_event(state, tenant, event, http_auth(keys)) + .await + .unwrap_or_else(|error| panic!("ingest kind:{kind}: {error:?}")); + assert!(result.accepted, "kind:{kind} refused: {}", result.message); +} + +/// Register `reader` as a connected client holding the global notice +/// subscription clients send, and return its outbound frames. +fn subscribe_notices( + state: &Arc, + tenant: &TenantContext, + reader: &Keys, +) -> Receiver { + let conn_id = Uuid::new_v4(); + let (tx, rx) = tokio::sync::mpsc::channel(32); + state.conn_manager.register( + conn_id, + tx, + tokio::sync::mpsc::channel(4).0, + tokio::sync::mpsc::channel(1).0, + None, + tokio_util::sync::CancellationToken::new(), + tenant.community(), + Arc::new(std::sync::atomic::AtomicU8::new(0)), + Arc::new(tokio::sync::Mutex::new(Default::default())), + 3, + crate::state::CommunityConnectionControl::new(tokio_util::sync::CancellationToken::new()), + ); + state + .conn_manager + .set_authenticated_pubkey(conn_id, reader.public_key().to_bytes().to_vec()); + let filter = json!({ + "kinds": [KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION], + "#p": [reader.public_key().to_hex()], + }); + state.sub_registry.register_scoped( + tenant.community(), + conn_id, + "notices".into(), + vec![serde_json::from_value(filter).expect("filter")], + None, + ); + rx +} + +/// The `(kind, h, id)` of every live notice delivered so far. +fn live_notices(rx: &mut Receiver) -> Vec<(u64, String, String)> { + let mut notices = Vec::new(); + while let Ok(frame) = rx.try_recv() { + let axum::extract::ws::Message::Text(text) = frame else { + continue; + }; + let message: Value = serde_json::from_str(&text).expect("relay frame"); + if message[0] == "EVENT" { + let event = &message[2]; + notices.push(( + event["kind"].as_u64().unwrap(), + tag_values(event, "h").concat(), + event["id"].as_str().unwrap().to_owned(), + )); + } + } + notices +} + +fn notices(rx: &mut Receiver) -> Vec<(u64, String)> { + live_notices(rx) + .into_iter() + .map(|(kind, h, _)| (kind, h)) + .collect() +} + +/// The notices delivered once at least one arrives, for notices sent off +/// the request path. +async fn next_notices(rx: &mut Receiver) -> Vec<(u64, String)> { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + let delivered = notices(rx); + if !delivered.is_empty() { + return delivered; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }) + .await + .expect("no notice delivered") +} + +fn tag_values(event: &Value, name: &str) -> Vec { + event["tags"] + .as_array() + .unwrap() + .iter() + .filter(|tag| tag[0] == name) + .map(|tag| tag[1].as_str().unwrap().to_owned()) + .collect() +} + +/// The `name` tag values of the events a one-shot read as `reader` returns. +async fn read_tags( + state: &Arc, + tenant: &TenantContext, + reader: &Keys, + filter: Value, + name: &str, +) -> Vec { + let (conn, mut rx) = test_conn(tenant, reader); + let filters: Vec = serde_json::from_value(json!([filter])).unwrap(); + crate::handlers::req::handle_req("read".into(), filters, vec![None], conn, state.clone()).await; + let mut values = Vec::new(); + while let Ok(frame) = rx.try_recv() { + let axum::extract::ws::Message::Text(text) = frame else { + continue; + }; + let message: Value = serde_json::from_str(&text).expect("relay frame"); + match message[0].as_str() { + Some("EVENT") => values.extend(tag_values(&message[2], name)), + Some("EOSE") | Some("CLOSED") => return values, + _ => {} + } + } + panic!("no EOSE"); +} + +/// A channel-list read as `reader`: the channels its 39002 discovery names, +/// as a client builds its sidebar. +async fn listed_channels( + state: &Arc, + tenant: &TenantContext, + reader: &Keys, +) -> Vec { + let filter = json!({"kinds": [39002], "#p": [reader.public_key().to_hex()]}); + read_tags(state, tenant, reader, filter, "d").await +} + +/// The DMs `reader`'s current NIP-DV snapshot hides from its sidebar, read +/// as a client does after its channel list refreshes. +async fn hidden_dms(state: &Arc, tenant: &TenantContext, reader: &Keys) -> Vec { + let filter = json!({"kinds": [KIND_DM_VISIBILITY], "#p": [reader.public_key().to_hex()]}); + read_tags(state, tenant, reader, filter, "h").await +} + +/// Wait for the producer to reach its next notice to the parked reader, run +/// `on_receipt` while it is held there, then let it continue. Returns the +/// notice's channel and what `on_receipt` saw. +pub(crate) async fn at_receipt( + barrier: &mut notice_barrier::Barrier, + on_receipt: impl AsyncFnOnce(String) -> T, +) -> (String, T) { + let (channel, release) = + tokio::time::timeout(std::time::Duration::from_secs(10), barrier.next()) + .await + .expect("producer reached no notice") + .expect("barrier open"); + let seen = on_receipt(channel.to_string()).await; + release.send(()).expect("producer waiting"); + (channel.to_string(), seen) +} + +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn channel_delete_notifies_every_member_after_cleanup() { + let (state, tenant) = fixture().await; + let owner = Keys::generate(); + let member = Keys::generate(); + let channel = create_channel(&state, &tenant, &owner, &[]).await; + let h = channel.to_string(); + publish( + &state, + &tenant, + &owner, + 9000, + &[&["h", &h], &["p", &member.public_key().to_hex()]], + ) + .await; + assert!(listed_channels(&state, &tenant, &member).await.contains(&h)); + let mut owner_rx = subscribe_notices(&state, &tenant, &owner); + let mut member_rx = subscribe_notices(&state, &tenant, &member); + let mut barrier = notice_barrier::install(&member.public_key().to_bytes()); + + // The 9008 is accepted while the member's notice is still held, so the + // notices are off the request path. + tokio::time::timeout( + std::time::Duration::from_secs(5), + publish(&state, &tenant, &owner, 9008, &[&["h", &h]]), + ) + .await + .expect("9008 OK waited on the held notice"); + assert!( + notices(&mut member_rx).is_empty(), + "notice delivered before the OK" + ); + let (noticed, listed) = at_receipt(&mut barrier, async |_| { + listed_channels(&state, &tenant, &member).await + }) + .await; + + assert_eq!(noticed, h); + assert!(!listed.contains(&h), "notice sent before discovery cleanup"); + for rx in [&mut owner_rx, &mut member_rx] { + assert_eq!( + next_notices(rx).await, + vec![(KIND_MEMBER_REMOVED_NOTIFICATION as u64, h.clone())] + ); + } +} + +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn moderation_kick_notifies_the_kicked_member_after_cleanup() { + let (state, tenant) = fixture().await; + let owner = Keys::generate(); + let member = Keys::generate(); + let channel = create_channel(&state, &tenant, &owner, &[]).await; + let h = channel.to_string(); + let member_bytes = member.public_key().to_bytes(); + publish( + &state, + &tenant, + &owner, + 9000, + &[&["h", &h], &["p", &member.public_key().to_hex()]], + ) + .await; + assert!(listed_channels(&state, &tenant, &member).await.contains(&h)); + let mut rx = subscribe_notices(&state, &tenant, &member); + let mut barrier = notice_barrier::install(&member_bytes); + + // The kick mutation commits the removal; live effects follow. + state + .db + .remove_member( + tenant.community(), + channel, + &member_bytes, + &owner.public_key().to_bytes(), + ) + .await + .expect("remove member"); + let effects = tokio::spawn({ + let (state, tenant) = (state.clone(), tenant.clone()); + async move { + crate::handlers::side_effects::apply_kick_live_side_effects( + &tenant, + &state, + channel, + &member_bytes, + ) + .await + } + }); + let (noticed, listed) = at_receipt(&mut barrier, async |_| { + listed_channels(&state, &tenant, &member).await + }) + .await; + effects.await.expect("task").expect("kick live effects"); + + assert_eq!(noticed, h); + assert!( + !listed.contains(&h), + "notice sent before the roster refresh" + ); + assert_eq!( + notices(&mut rx), + vec![(KIND_MEMBER_REMOVED_NOTIFICATION as u64, h.clone())] + ); +} + +/// A recipient whose channel set is cached when its moderation DM is +/// created still finds the DM in the read its notice prompts. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn moderation_dm_notice_follows_a_cached_channel_list() { + let (state, tenant) = fixture().await; + let recipient = Keys::generate(); + let recipient_bytes = recipient.public_key().to_bytes(); + // Warm the recipient's cached channel set, as a recent REQ does. + assert_eq!( + listed_channels(&state, &tenant, &recipient).await, + Vec::::new() + ); + let mut barrier = notice_barrier::install(&recipient_bytes); + + let deliver = tokio::spawn({ + let (state, tenant) = (state.clone(), tenant.clone()); + async move { + crate::handlers::moderation_notices::send_moderation_notice( + &tenant, + &state, + &recipient_bytes, + crate::handlers::moderation_notices::ModerationNotice::ContentActioned { + action_id: Uuid::new_v4(), + public_reason: "spam".into(), + }, + chrono::Utc::now(), + ) + .await + } + }); + let (dm, listed) = at_receipt(&mut barrier, async |_| { + listed_channels(&state, &tenant, &recipient).await + }) + .await; + deliver.await.expect("task").expect("notice"); + + assert!(listed.contains(&dm), "notice sent before the cache drop"); +} + +/// A moderation DM resurfaces the DM, and on receipt of its notice the +/// channel list shows it and the NIP-DV snapshot no longer hides it. The +/// second delivery follows a real hide in the same (pinned) second and still +/// sends its own notice, so a client that only hears notices sees it return. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn moderation_dm_notifies_the_recipient_once_visible() { + let (state, tenant) = fixture().await; + let recipient = Keys::generate(); + let recipient_bytes = recipient.public_key().to_bytes(); + let mut rx = subscribe_notices(&state, &tenant, &recipient); + let mut barrier = notice_barrier::install(&recipient_bytes); + barrier.pin_created_at(nostr::Timestamp::now().as_secs()); + let deliver = || { + let (state, tenant) = (state.clone(), tenant.clone()); + tokio::spawn(async move { + crate::handlers::moderation_notices::send_moderation_notice( + &tenant, + &state, + &recipient_bytes, + crate::handlers::moderation_notices::ModerationNotice::ContentActioned { + action_id: Uuid::new_v4(), + public_reason: "spam".into(), + }, + chrono::Utc::now(), + ) + .await + }) + }; + let on_receipt = async |dm: String| { + ( + listed_channels(&state, &tenant, &recipient) + .await + .contains(&dm), + hidden_dms(&state, &tenant, &recipient).await.contains(&dm), + ) + }; + + let first = deliver(); + let (dm, seen) = at_receipt(&mut barrier, on_receipt).await; + first.await.expect("task").expect("first notice"); + assert_eq!(seen, (true, false), "listed and visible on receipt"); + let first_notice = live_notices(&mut rx); + assert_eq!(first_notice.len(), 1, "{first_notice:?}"); + assert_eq!( + (first_notice[0].0, &first_notice[0].1), + (KIND_MEMBER_ADDED_NOTIFICATION as u64, &dm) + ); + + publish( + &state, + &tenant, + &recipient, + KIND_DM_HIDE as u16, + &[&["h", &dm]], + ) + .await; + assert!(hidden_dms(&state, &tenant, &recipient).await.contains(&dm)); + + let second = deliver(); + let (again, seen) = at_receipt(&mut barrier, on_receipt).await; + second.await.expect("task").expect("second notice"); + assert_eq!(again, dm); + assert_eq!(seen, (true, false), "listed and visible on receipt"); + let second_notice = live_notices(&mut rx); + assert_eq!( + second_notice.len(), + 1, + "the second delivery's notice coalesced" + ); + assert_eq!( + (second_notice[0].0, &second_notice[0].1), + (KIND_MEMBER_ADDED_NOTIFICATION as u64, &dm) + ); + assert_ne!(second_notice[0].2, first_notice[0].2); +} diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index 3315ea8eb6b..d1384b9ff3c 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -1,11 +1,17 @@ /// NIP-42 authentication handler. pub mod admin_action_worker; pub mod admin_outbox_worker; +/// NIP-AR Sync subscriptions. +pub mod artifact_sync; +#[cfg(test)] +mod artifact_sync_postgres_tests; pub mod auth; /// Pure NIP-29 channel membership-authority decisions (kinds 9000/9001/9022). pub mod channel_authz; /// Subscription close (CLOSE) handler. pub mod close; +/// Per-key single-flight refresh with a minimum interval. +pub mod coalesced_refresh; /// Command executor — transactional processing for command kinds. pub mod command_executor; /// Relay-operator community provisioning HTTP support. @@ -15,6 +21,8 @@ pub mod count; #[cfg(test)] mod create_with_members_postgres_tests; #[cfg(test)] +mod deletion_postgres_tests; +#[cfg(test)] mod edit_metadata_postgres_tests; /// EVENT handler — WS dispatcher → ingest pipeline → fan-out. pub mod event; @@ -26,12 +34,18 @@ pub mod identity_archive; pub mod imeta; /// Transport-neutral event ingestion pipeline. pub mod ingest; +/// Local media publication authorization. +pub mod media_access; +#[cfg(test)] +mod membership_notice_postgres_tests; /// Community moderation authorization seam (capability helper). pub mod moderation_authz; /// Community moderation command handler (kinds 9040–9044). pub mod moderation_commands; /// Relay-signed moderation notice DMs. pub mod moderation_notices; +/// Multi-node fan-out: Redis events to local subscribers, with lossless lag handling. +pub mod multinode_fanout; /// Product-feedback validation + deployment sidecar persistence. pub mod product_feedback; #[allow(dead_code, missing_docs)] @@ -52,6 +66,8 @@ pub mod side_effects; mod system_channel_postgres_tests; /// Per-filter query scope for system channels. pub(crate) mod system_channels; +#[cfg(test)] +mod tag_pushdown_postgres_tests; /// Extract an optional TTL (in seconds) from a Nostr event's `ttl` tag, /// applying the server-side override when configured. diff --git a/crates/buzz-relay/src/handlers/moderation_commands.rs b/crates/buzz-relay/src/handlers/moderation_commands.rs index a5a3587b1a5..65897bdd6f2 100644 --- a/crates/buzz-relay/src/handlers/moderation_commands.rs +++ b/crates/buzz-relay/src/handlers/moderation_commands.rs @@ -115,8 +115,9 @@ pub async fn handle_moderation_command( ))), ) })?; - ensure_actor_not_banned(&restriction) - .map_err(|e| IngestError::ban(BanRefusal::Banned, IngestError::Rejected(e)))?; + ensure_actor_not_banned(&restriction).map_err(|e| { + IngestError::ban(BanRefusal::banned(&restriction), IngestError::Rejected(e)) + })?; execute_moderation_command(tenant, state, event, &actor) .await .map_err(IngestError::Rejected) @@ -199,7 +200,7 @@ async fn handle_ban( ) .await .map_err(|e| error(format!("database error: {e}")))?; - state.invalidate_restriction_cache(tenant.community(), &target); + state.invalidate_restrictions(tenant); // Live enforcement: close open sessions for the banned principal now — // this pod's sockets synchronously (fenced to this community) and every @@ -285,7 +286,7 @@ async fn handle_unban( if !lifted { return Err(invalid("member is not banned")); } - state.invalidate_restriction_cache(tenant.community(), &target); + state.invalidate_restrictions(tenant); insert_audit(state, tenant, actor, "unban", Some(&target), None, None).await?; @@ -328,7 +329,7 @@ async fn handle_timeout( ) .await .map_err(|e| error(format!("database error: {e}")))?; - state.invalidate_restriction_cache(tenant.community(), &target); + state.invalidate_restrictions(tenant); let action_id = insert_audit( state, @@ -392,7 +393,7 @@ async fn handle_untimeout( if !cleared { return Err(invalid("member is not timed out")); } - state.invalidate_restriction_cache(tenant.community(), &target); + state.invalidate_restrictions(tenant); insert_audit(state, tenant, actor, "untimeout", Some(&target), None, None).await?; @@ -634,6 +635,7 @@ mod tests { fn banned_admin_cannot_reach_an_unban_command() { let banned = buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }; assert_eq!( @@ -645,6 +647,7 @@ mod tests { // ban, so an authorized moderator can still lift it. let timed_out = buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: Some(Utc::now() + Duration::minutes(5)), }; assert!(ensure_actor_not_banned(&timed_out).is_ok()); diff --git a/crates/buzz-relay/src/handlers/moderation_notices.rs b/crates/buzz-relay/src/handlers/moderation_notices.rs index e5e4b9c3e3e..d5d6bc2c5c5 100644 --- a/crates/buzz-relay/src/handlers/moderation_notices.rs +++ b/crates/buzz-relay/src/handlers/moderation_notices.rs @@ -25,11 +25,14 @@ use nostr::{EventBuilder, Kind, Tag}; use tracing::warn; use uuid::Uuid; -use buzz_core::kind::{event_kind_u32, KIND_STREAM_MESSAGE}; +use buzz_core::kind::{event_kind_u32, KIND_MEMBER_ADDED_NOTIFICATION, KIND_STREAM_MESSAGE}; use buzz_core::tenant::TenantContext; use super::event::dispatch_persistent_event; -use super::side_effects::emit_group_discovery_events; +use super::side_effects::{ + emit_group_discovery_events, emit_membership_notification_tagged, + publish_dm_visibility_snapshot, +}; use crate::state::AppState; /// Tag naming the moderation source row (report/action) a notice was derived @@ -115,6 +118,13 @@ pub async fn send_moderation_notice( ) .await?; let dm_channel_id = dm_channel.id; + // Drop both participants' cached channel sets on every pod, as opening a + // DM does (`command_executor::handle_dm_open`), so the read the notice + // below prompts includes this DM. Done on every delivery, not just on + // creation, so a retry after a failed first delivery still drops them. + for participant in [recipient_pubkey, relay_pubkey_bytes.as_slice()] { + state.invalidate_membership(tenant, dm_channel_id, participant); + } // Count new DM creation; side-effect gates below intentionally do not // gate on was_created (see comment at step 2). @@ -135,6 +145,9 @@ pub async fn send_moderation_notice( .db .unhide_dm(tenant.community(), dm_channel_id, recipient_pubkey) .await?; + // Clients filter the sidebar on the NIP-DV snapshot, not `hidden_at`, so + // republish it before the notice that makes them re-read. + publish_dm_visibility_snapshot(tenant, state, recipient_pubkey).await?; // 2. Ensure the relay's "{host} Moderation" kind:0 profile exists, and 3. // the DM's kind:39000 discovery (with `hidden` / `t=dm` / `p`). Both are @@ -149,6 +162,25 @@ pub async fn send_moderation_notice( } emit_group_discovery_events(tenant, state, dm_channel_id).await?; + // The DM is now readable in the recipient's channel list: tell them, as + // opening a DM does. Sent on every delivery so a new, existing or hidden + // DM resurfaces live; a repeated notice is a harmless hint. The source tag + // keeps two deliveries in the same second from sharing one notice. + let source_id = notice.source_id(); + if let Err(e) = emit_membership_notification_tagged( + tenant, + state, + dm_channel_id, + recipient_pubkey, + relay_pubkey_bytes.as_slice(), + KIND_MEMBER_ADDED_NOTIFICATION, + &[Tag::parse([MODERATION_SOURCE_TAG, &source_id.to_string()])?], + ) + .await + { + warn!(channel = %dm_channel_id, error = %e, "membership notification emission failed"); + } + // 4. Insert the relay-signed kind:9 notice with `h=` and a // `moderation_source` tag naming the source row id (idempotency + // client linking). @@ -159,7 +191,6 @@ pub async fn send_moderation_notice( // (same pubkey + created_at + kind + tags + content = same SHA256 event ID). // `insert_event`'s ON CONFLICT DO NOTHING ensures exactly one row is // durably persisted regardless of how many workers reach this point. - let source_id = notice.source_id(); let tags = vec![ Tag::parse(["h", &dm_channel_id.to_string()])?, Tag::parse([MODERATION_SOURCE_TAG, &source_id.to_string()])?, @@ -209,7 +240,8 @@ async fn publish_moderation_profile( let (stored, was_inserted) = state .db .replace_addressable_event(tenant.community(), &event, None) - .await?; + .await + .map_err(|e| anyhow::anyhow!("moderation notice write failed: {}", e.kind()))?; if was_inserted { let kind_u32 = event_kind_u32(&stored.event); dispatch_persistent_event(tenant, state, &stored, kind_u32, relay_pubkey_hex, None).await; diff --git a/crates/buzz-relay/src/handlers/multinode_fanout.rs b/crates/buzz-relay/src/handlers/multinode_fanout.rs new file mode 100644 index 00000000000..4b8d83d13f3 --- /dev/null +++ b/crates/buzz-relay/src/handlers/multinode_fanout.rs @@ -0,0 +1,459 @@ +//! Multi-node fan-out: deliver events other relay nodes published to Redis to +//! this node's local subscribers. +//! +//! One dispatcher reads the pub/sub broadcast and only routes. Delivery runs on +//! [`WORKERS`] workers, each with a bounded queue. Every event of one +//! `(community, topic)` goes to the same worker, so each channel's events keep +//! their order while different channels are delivered concurrently. +//! +//! A slow delivery holds only its own worker and is delivered late. Falling +//! behind never closes a connection: a database stall slows every node's +//! deliveries at once, and closing their recipients then would send the whole +//! fleet back to that database at the same moment (Review-Proven Rule 9). +//! +//! An event is dropped on this node when its worker's queue is full, when one +//! delivery attempt runs past [`MAX_DELIVERY_ATTEMPT`] (a database connection +//! that stops answering would otherwise hold its worker forever), or when the +//! dispatcher lags the broadcast and skips it. Both are counted, and the +//! syncs the dropped events would have reached get `CLOSED "resync: ..."` +//! (NIP-AR Sync rule 5). A plain subscription is not told. Its client may +//! replay the event when it next reconnects, but only if later deliveries did +//! not move its resume cursor past the event by more than the client's replay +//! slack. +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; +use std::time::Duration; + +use buzz_core::event::StoredEvent; +use buzz_core::CommunityId; +use buzz_pubsub::ChannelEvent; +use tokio::sync::mpsc::error::TrySendError; +use tokio::sync::{broadcast, mpsc}; +use tracing::warn; + +use super::event::{deliver_pubsub_event, pubsub_stored_event, take_local_echo}; +use crate::state::AppState; + +/// Delivery workers per node. +pub const WORKERS: usize = 16; +/// Events each worker may hold before the dispatcher drops new ones. +pub const WORKER_QUEUE: usize = 1024; +/// How long a worker spends on one delivery before dropping it. Measured +/// from when the worker starts the delivery, so time spent waiting in the +/// queue never counts: a stall delays a backlog instead of dropping it. The +/// bound only cuts off a delivery that hangs, such as an access-gate read on +/// a database connection that stopped answering. +pub const MAX_DELIVERY_ATTEMPT: Duration = Duration::from_secs(30); +/// The resync reason for a sync whose live entry was dropped here. +const LAG_RESYNC: &str = "resync: live delivery lagged"; + +/// An event waiting for its worker. +type Queued = (CommunityId, StoredEvent); + +/// Start multi-node fan-out for `rx`: the dispatcher and its workers. The +/// returned handle ends when the broadcast closes. +pub fn spawn( + state: Arc, + rx: broadcast::Receiver, +) -> tokio::task::JoinHandle<()> { + let (dispatcher, queues) = Dispatcher::new(WORKERS, WORKER_QUEUE); + for queue in queues { + tokio::spawn(run_worker(Arc::clone(&state), queue)); + } + tokio::spawn(dispatcher.run(state, rx)) +} + +/// Delivers one worker's queue in order. +async fn run_worker(state: Arc, mut queue: mpsc::Receiver) { + while let Some((community_id, stored)) = queue.recv().await { + let delivery = deliver_pubsub_event(&state, community_id, &stored); + if tokio::time::timeout(MAX_DELIVERY_ATTEMPT, delivery) + .await + .is_err() + { + drop_event(&state, community_id, &stored, "stale"); + } + } +} + +/// Count a dropped event and resync the syncs it would have reached. A +/// delivery cut off partway may have reached some of them; a resync costs +/// them a re-read, never a gap. No connection is closed. +fn drop_event( + state: &AppState, + community_id: CommunityId, + stored: &StoredEvent, + reason: &'static str, +) { + metrics::counter!("buzz_multinode_fanout_dropped_total", "reason" => reason).increment(1); + let matches = state.sub_registry.fan_out_scoped(community_id, stored); + state.artifact_syncs.resync_matches(&matches, LAG_RESYNC); +} + +/// Routes broadcast events to worker queues. +struct Dispatcher { + queues: Vec>, +} + +impl Dispatcher { + /// A dispatcher over `workers` queues of `capacity` events, and the + /// receiving ends for the workers. + fn new(workers: usize, capacity: usize) -> (Self, Vec>) { + let (queues, receivers) = (0..workers.max(1)) + .map(|_| mpsc::channel(capacity.max(1))) + .unzip(); + (Self { queues }, receivers) + } + + async fn run(self, state: Arc, mut rx: broadcast::Receiver) { + loop { + match rx.recv().await { + Ok(channel_event) => self.dispatch(&state, channel_event), + Err(broadcast::error::RecvError::Lagged(skipped)) => self.lagged(&state, skipped), + Err(broadcast::error::RecvError::Closed) => { + tracing::error!("Multi-node fan-out broadcast channel closed"); + return; + } + } + } + } + + /// Queue one event on its worker, or drop it when that worker is full. A + /// local echo was already delivered, so it is dropped before queueing. + fn dispatch(&self, state: &AppState, channel_event: ChannelEvent) { + if take_local_echo(state, &channel_event) { + return; + } + let queue = &self.queues[self.worker_for(&channel_event)]; + let queued = ( + channel_event.community_id, + pubsub_stored_event(channel_event), + ); + if let Err( + TrySendError::Full((community_id, stored)) + | TrySendError::Closed((community_id, stored)), + ) = queue.try_send(queued) + { + drop_event(state, community_id, &stored, "queue_full"); + } + } + + fn worker_for(&self, channel_event: &ChannelEvent) -> usize { + let mut hasher = DefaultHasher::new(); + (channel_event.community_id, channel_event.topic).hash(&mut hasher); + (hasher.finish() % self.queues.len() as u64) as usize + } + + /// The dispatcher skipped `skipped` events it never saw. Any sync may have + /// missed one, so every sync resyncs. + fn lagged(&self, state: &AppState, skipped: u64) { + metrics::counter!("buzz_multinode_fanout_lag_total").increment(skipped); + warn!("Multi-node fan-out lagged by {skipped} messages"); + state.artifact_syncs.resync_all(LAG_RESYNC); + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::atomic::AtomicU8; + + use axum::extract::ws::Message; + use buzz_core::tenant::CommunityId; + use buzz_pubsub::EventTopic; + use nostr::{EventBuilder, Filter, Keys, Kind}; + use tokio_util::sync::CancellationToken; + use uuid::Uuid; + + use std::time::Duration; + + use super::*; + use crate::subscription::ConnId; + + fn community() -> CommunityId { + CommunityId::from_uuid(Uuid::nil()) + } + + const STORED: u16 = 1; + + /// A connection with one subscription to `kind`, its frame receiver, and + /// its cancellation token. + fn subscriber( + state: &AppState, + kind: u16, + ) -> (ConnId, mpsc::Receiver, CancellationToken) { + let conn_id = Uuid::new_v4(); + let (tx, rx) = mpsc::channel(64); + let cancel = CancellationToken::new(); + state.conn_manager.register( + conn_id, + tx, + mpsc::channel(10).0, + mpsc::channel(1).0, + None, + cancel.clone(), + community(), + Arc::new(AtomicU8::new(0)), + Arc::new(tokio::sync::Mutex::new(HashMap::new())), + 3, + crate::state::CommunityConnectionControl::new(CancellationToken::new()), + ); + state.sub_registry.register( + conn_id, + "sub".to_string(), + vec![Filter::new().kind(Kind::Custom(kind))], + None, + ); + (conn_id, rx, cancel) + } + + fn event(kind: u16, n: usize) -> ChannelEvent { + ChannelEvent { + community_id: community(), + topic: EventTopic::Global, + event: EventBuilder::new(Kind::Custom(kind), n.to_string()) + .sign_with_keys(&Keys::generate()) + .expect("sign event"), + } + } + + /// Events reach their subscriber through the workers, in publish order. + #[tokio::test] + async fn delivers_one_topic_in_order_through_workers() { + let state = crate::state::tests::test_state().await; + let (_conn, mut frames, cancel) = subscriber(&state, STORED); + let (tx, rx) = broadcast::channel(64); + let handle = spawn(Arc::clone(&state), rx); + + let sent: Vec<_> = (0..20).map(|n| event(STORED, n)).collect(); + for event in &sent { + tx.send(event.clone()).expect("broadcast"); + } + for event in &sent { + let frame = tokio::time::timeout(Duration::from_secs(5), frames.recv()) + .await + .expect("delivered in time") + .expect("frame"); + let Message::Text(text) = frame else { + panic!("expected an EVENT frame"); + }; + let v: serde_json::Value = serde_json::from_str(&text).expect("frame JSON"); + assert_eq!(v[2]["id"], event.event.id.to_hex()); + } + assert!(!cancel.is_cancelled()); + drop(tx); + handle + .await + .expect("dispatcher ends when the broadcast closes"); + } + + /// A connection with an idle sync on `kind`: the sync is what a dropped + /// event must resync. + fn sync(state: &AppState, kind: u16) -> (ConnId, CancellationToken) { + let (conn_id, _frames, cancel) = subscriber(state, kind); + state.artifact_syncs.insert_idle(conn_id, "sub"); + (conn_id, cancel) + } + + /// How many events were counted as dropped for `reason`. + fn dropped(snapshotter: &metrics_util::debugging::Snapshotter, reason: &str) -> u64 { + snapshotter + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, ..)| { + key.key().name() == "buzz_multinode_fanout_dropped_total" + && key.key().labels().any(|label| label.value() == reason) + }) + .map(|(.., value)| match value { + metrics_util::debugging::DebugValue::Counter(n) => n, + other => panic!("expected a counter, got {other:?}"), + }) + .sum() + } + + /// A full worker queue drops the event: it is counted, the syncs it would + /// have reached resync, and no connection closes. A local echo arriving on + /// the full queue was already delivered, so it is no drop. + #[tokio::test] + async fn full_worker_queue_resyncs_the_dropped_events_syncs_and_closes_nothing() { + let state = crate::state::tests::test_state().await; + let (_plain, _frames, plain_cancel) = subscriber(&state, STORED); + let (synced, sync_cancel) = sync(&state, STORED); + let (unmatched, _) = sync(&state, 7); + // Hold the only queue's receiver without draining it. + let (dispatcher, _queues) = Dispatcher::new(1, 1); + dispatcher.dispatch(&state, event(STORED, 0)); + + let recorder = metrics_util::debugging::DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + metrics::with_local_recorder(&recorder, || { + let echo = event(STORED, 1); + state.mark_local_event(echo.community_id, &echo.event.id); + dispatcher.dispatch(&state, echo); + }); + assert_eq!(dropped(&snapshotter, "queue_full"), 0, "an echo is no drop"); + assert_eq!(state.artifact_syncs.pending_resync(synced, "sub"), None); + + metrics::with_local_recorder(&recorder, || dispatcher.dispatch(&state, event(STORED, 2))); + assert_eq!(dropped(&snapshotter, "queue_full"), 1); + assert_eq!( + state.artifact_syncs.pending_resync(synced, "sub"), + Some(LAG_RESYNC) + ); + assert_eq!( + state.artifact_syncs.pending_resync(unmatched, "sub"), + None, + "only the syncs the event would have reached" + ); + assert!(!plain_cancel.is_cancelled() && !sync_cancel.is_cancelled()); + } + + /// Dispatcher lag resyncs every sync and closes no connection. + #[tokio::test] + async fn dispatcher_lag_resyncs_every_sync_and_closes_nothing() { + let state = crate::state::tests::test_state().await; + let (_plain, _frames, plain_cancel) = subscriber(&state, STORED); + let (first, first_cancel) = sync(&state, STORED); + let (second, second_cancel) = sync(&state, 7); + let (dispatcher, _queues) = Dispatcher::new(1, 1); + + dispatcher.lagged(&state, 7); + for conn in [first, second] { + assert_eq!( + state.artifact_syncs.pending_resync(conn, "sub"), + Some(LAG_RESYNC) + ); + } + assert!( + !plain_cancel.is_cancelled() + && !first_cancel.is_cancelled() + && !second_cancel.is_cancelled() + ); + } + + /// A recipient the access gate cannot check (every database read fails) + /// misses the event without a retry and stays connected. + #[tokio::test(start_paused = true)] + async fn recipient_the_gate_cannot_check_misses_the_event_and_stays_connected() { + let state = crate::state::tests::test_state().await; + state.db.pool().close().await; + let channel_id = Uuid::new_v4(); + state + .channel_visibility_cache + .insert((community(), channel_id), "private".to_string()); + let (conn, mut frames, cancel) = subscriber(&state, STORED); + state + .conn_manager + .set_authenticated_pubkey(conn, vec![7; 32]); + state.sub_registry.register( + conn, + "channel".to_string(), + vec![Filter::new().kind(Kind::Custom(STORED))], + Some(channel_id), + ); + let in_channel = ChannelEvent { + topic: EventTopic::Channel(channel_id), + ..event(STORED, 0) + }; + + let started = tokio::time::Instant::now(); + deliver_pubsub_event(&state, community(), &pubsub_stored_event(in_channel)).await; + assert_eq!(started.elapsed(), Duration::ZERO, "no retry"); + assert!(frames.try_recv().is_err(), "the gate let nothing through"); + assert!(!cancel.is_cancelled()); + + let open = event(STORED, 1); + let id = open.event.id.to_hex(); + deliver_pubsub_event(&state, community(), &pubsub_stored_event(open)).await; + let Ok(Message::Text(text)) = frames.try_recv() else { + panic!("expected the open event"); + }; + let v: serde_json::Value = serde_json::from_str(&text).expect("frame JSON"); + assert_eq!(v[2]["id"], id); + } + + /// A delivery that hangs (here on a database that accepts the connection + /// but never answers) is cut off at the bound: it is counted, the sync it + /// matched resyncs, no connection closes, and the next event queued on + /// the same worker is delivered. + #[tokio::test(start_paused = true)] + async fn hung_delivery_is_dropped_at_the_bound_and_the_worker_moves_on() { + let silent_db = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let url = format!( + "postgres://buzz@{}/buzz", + silent_db.local_addr().expect("addr") + ); + let state = crate::state::tests::test_state_with_database_url_and_pool_options( + &url, + sqlx::postgres::PgPoolOptions::new().acquire_timeout(Duration::from_secs(3600)), + ) + .await; + let channel_id = Uuid::new_v4(); + let (conn, mut frames, cancel) = subscriber(&state, STORED); + state.sub_registry.register( + conn, + "channel".to_string(), + vec![Filter::new().kind(Kind::Custom(STORED))], + Some(channel_id), + ); + state.artifact_syncs.insert_idle(conn, "channel"); + let hangs = ChannelEvent { + topic: EventTopic::Channel(channel_id), + ..event(STORED, 0) + }; + let next = event(STORED, 1); + let next_id = next.event.id.to_hex(); + + let (dispatcher, mut queues) = Dispatcher::new(1, 8); + dispatcher.dispatch(&state, hangs); + dispatcher.dispatch(&state, next); + drop(dispatcher); + + // The worker drains both events, then ends because the queue closed. + let recorder = metrics_util::debugging::DebuggingRecorder::new(); + let snapshotter = recorder.snapshotter(); + let started = tokio::time::Instant::now(); + WithRecorder { + recorder: &recorder, + future: Box::pin(run_worker(Arc::clone(&state), queues.pop().expect("queue"))), + } + .await; + assert_eq!( + started.elapsed(), + MAX_DELIVERY_ATTEMPT, + "cut off at the bound" + ); + let Ok(Message::Text(text)) = frames.try_recv() else { + panic!("expected the next event"); + }; + let v: serde_json::Value = serde_json::from_str(&text).expect("frame JSON"); + assert_eq!(v[2]["id"], next_id, "the hung event was not delivered"); + assert!(frames.try_recv().is_err()); + assert_eq!(dropped(&snapshotter, "stale"), 1); + assert_eq!( + state.artifact_syncs.pending_resync(conn, "channel"), + Some(LAG_RESYNC) + ); + assert!(!cancel.is_cancelled()); + } + + /// Polls `future` with `recorder` as the local metrics recorder, so a + /// task's metrics are visible to the test that awaits it. + struct WithRecorder<'a, F> { + recorder: &'a metrics_util::debugging::DebuggingRecorder, + future: std::pin::Pin>, + } + + impl std::future::Future for WithRecorder<'_, F> { + type Output = F::Output; + + fn poll( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll { + let this = &mut *self; + metrics::with_local_recorder(this.recorder, || this.future.as_mut().poll(cx)) + } + } +} diff --git a/crates/buzz-relay/src/handlers/put_user_postgres_tests.rs b/crates/buzz-relay/src/handlers/put_user_postgres_tests.rs index 07d4f298288..637f7b42e64 100644 --- a/crates/buzz-relay/src/handlers/put_user_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/put_user_postgres_tests.rs @@ -546,3 +546,204 @@ async fn put_user_decides_each_person_after_the_ones_before() { Some("owner") ); } + +async fn put_user_events(state: &AppState, tenant: &TenantContext, channel_id: Uuid) -> usize { + state + .db + .query_events(&EventQuery { + kinds: Some(vec![buzz_core::kind::KIND_NIP29_PUT_USER as i32]), + channel_id: Some(channel_id), + ..EventQuery::for_community(tenant.community()) + }) + .await + .expect("put-user events") + .len() +} + +/// A membership write that fails stores neither the event nor anyone it +/// names, and the same event applies in full once the failure is gone. A test +/// trigger fails the second person's row after the event row and the first +/// person were written in the same transaction. Before, the relay stored the +/// event, logged the failure and accepted it; a resend then returned +/// `duplicate:` and nobody was ever added. Mutations: store the event in its +/// own transaction → RED (event stored after the failure); accept the event +/// when the write fails → RED; apply a duplicate → RED (second notice). +#[tokio::test] +#[ignore = "requires Postgres"] +async fn failed_put_user_stores_nothing() { + let state = state().await; + let tenant = community(&state, "put-user-atomic-fail").await; + let (owner, person, failing) = (Keys::generate(), Keys::generate(), Keys::generate()); + let channel_id = create_channel(&state, &tenant, &owner, &[]).await; + let (person_hex, failing_hex) = (person.public_key().to_hex(), failing.public_key().to_hex()); + + // Each test runs in its own database, so this trigger affects only it. It + // fails the admin row, which only `failing` asks for. + for statement in [ + "CREATE FUNCTION put_user_atomic_fail() RETURNS trigger LANGUAGE plpgsql AS \ + $$ BEGIN RAISE EXCEPTION 'injected membership failure'; END $$", + "CREATE TRIGGER put_user_atomic_fail BEFORE INSERT ON channel_members \ + FOR EACH ROW WHEN (NEW.role = 'admin') EXECUTE FUNCTION put_user_atomic_fail()", + ] { + sqlx::query(statement) + .execute(state.db.pool()) + .await + .expect("install failure trigger"); + } + + let event = put_user( + &owner, + channel_id, + &[&[&person_hex], &[&failing_hex, "admin"]], + &[], + ); + for attempt in ["first send", "resend"] { + match ingest(&state, &tenant, event.clone(), &owner).await { + Ok(result) => panic!( + "{attempt}: a failed put-user was reported as {}: {:?}", + if result.accepted { + "accepted" + } else { + "refused" + }, + result.message + ), + Err(error) => assert!( + format!("{error:?}").contains("membership write failed"), + "{attempt}: {error:?}" + ), + } + assert_eq!( + put_user_events(&state, &tenant, channel_id).await, + 0, + "{attempt}" + ); + for keys in [&person, &failing] { + assert_eq!( + role_of(&state, &tenant, channel_id, keys).await, + None, + "{attempt}: nobody is added" + ); + } + assert_eq!( + joined_notices(&state, &tenant, channel_id, &person).await, + 0, + "{attempt}: no notice announces an add that did not happen" + ); + } + + // With the failure gone, the same signed event applies in full. + sqlx::query("DROP TRIGGER put_user_atomic_fail ON channel_members") + .execute(state.db.pool()) + .await + .expect("drop failure trigger"); + let retry = ingest(&state, &tenant, event.clone(), &owner) + .await + .expect("retry"); + assert!(retry.accepted, "{}", retry.message); + assert_eq!( + report(&retry.message), + serde_json::json!({ "added": [person_hex, failing_hex] }) + ); + assert_eq!( + role_of(&state, &tenant, channel_id, &person) + .await + .as_deref(), + Some("member") + ); + assert_eq!( + role_of(&state, &tenant, channel_id, &failing) + .await + .as_deref(), + Some("admin") + ); + assert_eq!(put_user_events(&state, &tenant, channel_id).await, 1); + + // A resend of the stored event is a duplicate and changes nothing. + let resend = ingest(&state, &tenant, event, &owner) + .await + .expect("resend"); + assert!(resend.accepted); + assert_eq!(resend.message, "duplicate:"); + assert_eq!( + joined_notices(&state, &tenant, channel_id, &person).await, + 1 + ); +} + +/// A refusal decided under the membership lock, after validation passed, +/// rejects the event with `invalid:` and stores nothing, for a single add and +/// for a batch. A trigger removes the actor inside the write transaction, so +/// validation sees an owner and the locked decision sees a non-member of a +/// private channel. +/// Mutations: map the under-lock `AccessDenied` to `error:` → RED; commit the +/// refused event → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn put_user_refused_under_the_lock_stores_nothing() { + let state = state().await; + let tenant = community(&state, "put-user-locked-refusal").await; + let (owner, first, second) = (Keys::generate(), Keys::generate(), Keys::generate()); + let channel_id = create_channel(&state, &tenant, &owner, &[&["visibility", "private"]]).await; + let (first_hex, second_hex) = (first.public_key().to_hex(), second.public_key().to_hex()); + + // Each test runs in its own database, so this trigger affects only it. The + // removal rolls back with the refused transaction. + for statement in [ + "CREATE FUNCTION put_user_revoke_actor() RETURNS trigger LANGUAGE plpgsql AS \ + $$ BEGIN UPDATE channel_members SET removed_at = NOW() \ + WHERE community_id = NEW.community_id AND channel_id = NEW.channel_id \ + AND pubkey = NEW.pubkey AND removed_at IS NULL; RETURN NULL; END $$", + "CREATE TRIGGER put_user_revoke_actor AFTER INSERT ON events \ + FOR EACH ROW WHEN (NEW.kind = 9000) EXECUTE FUNCTION put_user_revoke_actor()", + ] { + sqlx::query(statement) + .execute(state.db.pool()) + .await + .expect("install revoke trigger"); + } + + let reason = "private channel requires an invite from an active member"; + let single = put_user(&owner, channel_id, &[&[&first_hex]], &[]); + let batch = put_user(&owner, channel_id, &[&[&first_hex], &[&second_hex]], &[]); + for event in [single, batch.clone()] { + let message = match ingest(&state, &tenant, event, &owner).await { + Err(IngestError::Rejected(message)) => message, + Err(error) => panic!("expected an invalid: rejection, got {error:?}"), + Ok(result) => panic!("expected a rejection, got OK {}", result.message), + }; + let body = message.strip_prefix("invalid: ").expect("invalid prefix"); + if body.starts_with("members: ") { + assert_eq!( + report(body), + serde_json::json!({ + "rejected": [{ "reason": reason, "pubkeys": [first_hex, second_hex] }], + }) + ); + } else { + assert_eq!(body, reason); + } + assert_eq!(put_user_events(&state, &tenant, channel_id).await, 0); + for keys in [&first, &second] { + assert_eq!(role_of(&state, &tenant, channel_id, keys).await, None); + assert_eq!(joined_notices(&state, &tenant, channel_id, keys).await, 0); + } + assert_eq!( + role_of(&state, &tenant, channel_id, &owner) + .await + .as_deref(), + Some("owner"), + "the actor's removal rolls back with the refusal" + ); + } + + // Nothing was stored, so the same signed event applies once the actor + // keeps their role. + sqlx::query("DROP TRIGGER put_user_revoke_actor ON events") + .execute(state.db.pool()) + .await + .expect("drop revoke trigger"); + let retry = ingest(&state, &tenant, batch, &owner).await.expect("retry"); + assert!(retry.accepted, "{}", retry.message); + assert_eq!(put_user_events(&state, &tenant, channel_id).await, 1); +} diff --git a/crates/buzz-relay/src/handlers/relay_admin.rs b/crates/buzz-relay/src/handlers/relay_admin.rs index 16648595f8b..976a6c8f375 100644 --- a/crates/buzz-relay/src/handlers/relay_admin.rs +++ b/crates/buzz-relay/src/handlers/relay_admin.rs @@ -25,7 +25,8 @@ use buzz_core::tenant::TenantContext; use buzz_db::relay_members::RemoveResult; use crate::handlers::side_effects::{ - fan_out_nip43_membership_list, publish_nip43_member_added, publish_nip43_member_removed, + auto_join_default_channels, fan_out_nip43_membership_list, publish_nip43_member_added, + publish_nip43_member_removed, }; use crate::state::AppState; @@ -133,8 +134,9 @@ fn may_set_workspace_profile( /// [`super::push_lease::AcceptError`] and its `map_push_accept_error` seam. #[derive(Debug, PartialEq, Eq)] pub(super) enum RelayAdminError { - /// Sender is under a durable community ban — `blocked:` / HTTP 403. - Banned, + /// Sender is under a durable community ban — `blocked:` / HTTP 403. The + /// source says whether its own row or its owner's decided it. + Banned(crate::handlers::auth::BanSource), /// Legacy command rejection — `invalid:` / HTTP 400. This is whatever /// [`execute_relay_admin_command`] returned as a `String`, which is mostly /// validation and authorization but also still includes that function's own @@ -161,7 +163,9 @@ fn admits_relay_admin_command( restriction: &buzz_db::moderation::RestrictionState, ) -> Result<(), RelayAdminError> { if restriction.banned { - return Err(RelayAdminError::Banned); + return Err(RelayAdminError::Banned( + crate::handlers::auth::BanSource::of(restriction), + )); } Ok(()) } @@ -337,11 +341,11 @@ async fn execute_relay_admin_command( // to change an existing member's role. let write = state .db - .add_relay_member( + .add_relay_member_with_default_channels( tenant.community(), &target_hex, &role, - Some(&sender_hex), + &sender_hex, &state.relay_keypair, ) .await @@ -363,6 +367,8 @@ async fn execute_relay_admin_command( warn!(error = %e, "failed to publish NIP-43 member added event"); } } + // A no-op re-add also resumes unfinished work from the original actor. + auto_join_default_channels(tenant, state, &target_hex, None).await; fan_out_nip43_membership_list(tenant, state, write.snapshot).await; } @@ -527,11 +533,14 @@ mod postgres_tests { fn banned_actor_is_not_admitted_to_a_relay_admin_command() { let banned = buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }; assert_eq!( admits_relay_admin_command(&banned), - Err(RelayAdminError::Banned), + Err(RelayAdminError::Banned( + crate::handlers::auth::BanSource::Own + )), "a durably banned admin must never reach a relay-admin command" ); } @@ -543,6 +552,7 @@ mod postgres_tests { fn timed_out_actor_is_still_admitted() { let timed_out = buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: Some(chrono::Utc::now() + chrono::Duration::minutes(5)), }; assert!( @@ -754,9 +764,8 @@ mod postgres_tests { .expect("ensure community"); let tenant = TenantContext::resolved(record.id, host); - let redis_pool = deadpool_redis::Config::from_url(&config.redis_url) - .create_pool(Some(deadpool_redis::Runtime::Tokio1)) - .expect("redis pool config"); + let redis_pool = + buzz_pubsub::redis_connection(&config.redis_url).expect("redis pool config"); let pubsub = Arc::new( buzz_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone()) .await @@ -988,6 +997,163 @@ mod postgres_tests { assert!(!bystander_socket.cancellation_token().is_cancelled()); } + /// A kind:9030 add joins the new relay member to the community's + /// effective default channels, once: the flagged open channel gains them + /// as a member with one kind:44100; the unflagged channel does not. A + /// kind:9022 leave followed by a repeat kind:9030 (an idempotent no-op on + /// the roster) does not re-add them. An added agent's `channel_add_policy` + /// holds against the adder. Mutations: delete the + /// `auto_join_default_channels` call → RED; pass no actor, or drop the + /// policy check → the `nobody` agent is joined (RED); check the policy + /// against anyone but the adder → the owned `owner_only` agent is not + /// (RED). + #[tokio::test] + #[ignore = "requires Postgres"] + async fn adding_a_member_auto_joins_default_channels() { + use crate::handlers::group_state_postgres_tests::{ + create_channel, edit_channel, http_auth, + }; + use crate::handlers::ingest::ingest_event; + + let host = format!("add-auto-join-{}.example", uuid::Uuid::new_v4().simple()); + let (state, tenant) = workspace_profile_test_state(&host, true).await; + let (owner, target) = (Keys::generate(), Keys::generate()); + state + .db + .add_relay_member( + tenant.community(), + &owner.public_key().to_hex(), + "owner", + None, + &nostr::Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("seed owner"); + let flagged = create_channel(&state, &tenant, &owner, &[]).await; + let control = create_channel(&state, &tenant, &owner, &[]).await; + edit_channel(&state, &tenant, &owner, flagged, &[&["auto_join", "true"]]) + .await + .expect("relay owner flags channel"); + + let roles = |keys: &Keys| { + let state = state.clone(); + let community = tenant.community(); + let pubkey = keys.public_key().to_bytes(); + async move { + let mut roles = Vec::new(); + for channel_id in [flagged, control] { + roles.push( + state + .db + .get_member_role(community, channel_id, &pubkey) + .await + .expect("member role"), + ); + } + roles + } + }; + let added_notifications = || { + let state = state.clone(); + let community = tenant.community(); + let target_hex = target.public_key().to_hex(); + async move { + state + .db + .count_events(&buzz_db::EventQuery { + kinds: Some(vec![buzz_core::kind::KIND_MEMBER_ADDED_NOTIFICATION as i32]), + p_tag_hex: Some(target_hex), + global_only: true, + ..buzz_db::EventQuery::for_community(community) + }) + .await + .expect("count 44100") + } + }; + let add = || { + EventBuilder::new(Kind::Custom(RELAY_ADMIN_ADD_MEMBER as u16), "") + .tags(vec![Tag::public_key(target.public_key())]) + .sign_with_keys(&owner) + .expect("sign 9030") + }; + + handle_relay_admin_event(&tenant, &state, &add()) + .await + .expect("owner adds member"); + assert_eq!(roles(&target).await, [Some("member".to_string()), None]); + assert_eq!(added_notifications().await, 1); + + let leave = EventBuilder::new(Kind::Custom(9022), "") + .tags([Tag::parse(["h", &flagged.to_string()]).expect("h tag")]) + .sign_with_keys(&target) + .expect("sign 9022"); + let left = ingest_event(&state, &tenant, leave, http_auth(&target)) + .await + .expect("ingest 9022"); + assert!(left.accepted, "{:?}", left.message); + handle_relay_admin_event(&tenant, &state, &add()) + .await + .expect("repeat add is a roster no-op"); + assert_eq!( + roles(&target).await, + [None, None], + "a repeat kind:9030 must not resurrect a kind:9022 leave" + ); + assert_eq!(added_notifications().await, 1); + + // The adder acts for someone else, so the added agent's + // `channel_add_policy` decides, as for the same actor's kind:9000: + // `nobody` refuses every default channel; `owner_only` admits only + // the agent's owner. + let (refusing, owned) = (Keys::generate(), Keys::generate()); + for keys in [&owner, &refusing, &owned] { + state + .db + .ensure_user(tenant.community(), &keys.public_key().to_bytes()) + .await + .expect("user row"); + } + for (agent, policy) in [(&refusing, "nobody"), (&owned, "owner_only")] { + state + .db + .set_channel_add_policy(tenant.community(), &agent.public_key().to_bytes(), policy) + .await + .expect("agent policy"); + } + state + .db + .set_agent_owner( + tenant.community(), + &owned.public_key().to_bytes(), + &owner.public_key().to_bytes(), + ) + .await + .expect("agent owner"); + for (agent, expected) in [ + (&refusing, [None, None]), + (&owned, [Some("member".to_string()), None]), + ] { + let add = EventBuilder::new(Kind::Custom(RELAY_ADMIN_ADD_MEMBER as u16), "") + .tags(vec![Tag::public_key(agent.public_key())]) + .sign_with_keys(&owner) + .expect("sign 9030"); + handle_relay_admin_event(&tenant, &state, &add) + .await + .expect("owner adds agent"); + assert!( + state + .db + .get_relay_member(tenant.community(), &agent.public_key().to_hex()) + .await + .expect("relay member") + .is_some(), + "the roster add stands either way" + ); + assert_eq!(roles(agent).await, expected); + } + } + /// A pod-local root socket registered and bound to `keys`, as root AUTH /// leaves it. fn bound_root_socket( @@ -1264,13 +1430,13 @@ mod postgres_tests { assert!(!bystander_socket.is_cancelled(), "the bystander stays"); } - /// A timeout and an untimeout each drop the target's cached restriction - /// row on the pod that handles them, so typing and observer frames see - /// the change at once instead of after the cache TTL. - /// Mutation: remove `invalidate_restriction_cache` from either → RED. + /// Each of the ban, unban, timeout and untimeout commands drops the + /// target's cached restriction row, so HTTP gates, typing and observer + /// frames see the change at once instead of after the cache's max age. + /// Mutation: remove `invalidate_restrictions` from any of them → RED. #[tokio::test] #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] - async fn timeout_commands_drop_the_cached_restriction_row() { + async fn restriction_commands_drop_the_cached_restriction_row() { let host = format!("timeout-cache-{}.example", uuid::Uuid::new_v4().simple()); let (state, tenant) = workspace_profile_test_state(&host, true).await; let (owner, target) = (Keys::generate(), Keys::generate()); @@ -1309,8 +1475,16 @@ mod postgres_tests { buzz_core::kind::KIND_MODERATION_UNTIMEOUT, vec![Tag::public_key(target.public_key())], ), + command( + buzz_core::kind::KIND_MODERATION_BAN, + vec![Tag::public_key(target.public_key())], + ), + command( + buzz_core::kind::KIND_MODERATION_UNBAN, + vec![Tag::public_key(target.public_key())], + ), ] { - state.restriction_cache.insert( + state.seed_restriction( key.clone(), buzz_db::moderation::RestrictionState::default(), ); @@ -1320,7 +1494,7 @@ mod postgres_tests { .await .unwrap_or_else(|e| panic!("kind {} must apply: {e:?}", event.kind.as_u16())); assert_eq!( - state.restriction_cache.get(&key), + state.restriction_cache.entry(&key).map(|(state, _)| state), None, "kind {} must drop the cached row", event.kind.as_u16() diff --git a/crates/buzz-relay/src/handlers/report.rs b/crates/buzz-relay/src/handlers/report.rs index 32395a23582..50217f21fc1 100644 --- a/crates/buzz-relay/src/handlers/report.rs +++ b/crates/buzz-relay/src/handlers/report.rs @@ -80,11 +80,36 @@ pub async fn handle_report_event( // Known Phase-1 limitation: the media sidecar API does not expose a // cheap typed not-found vs transient-storage distinction here, so // all lookup failures surface as a missing blob to the reporter. - state + let meta = state .media_storage .get_sidecar(tenant, &sha_hex) .await .map_err(|_| "invalid: report target blob not found".to_string())?; + if state.config.media_read_mode == crate::api::media_access::MediaReadMode::Enforce { + let base = crate::api::media::media_base_url_for_tenant( + &state.config.relay_url, + tenant.host(), + ); + let access = state + .db + .media_access( + tenant.community(), + &sha_hex, + &meta.ext, + &base, + &reporter_pubkey, + false, + super::req::event_visible_to_reader, + ) + .await; + if !matches!( + access, + Ok(buzz_db::media::MediaAccess::Allowed + | buzz_db::media::MediaAccess::UploaderPreview) + ) { + return Err("invalid: report target blob not found".to_owned()); + } + } (ReportTarget::Blob(sha256), None) } ParsedReportTarget::Pubkey { pubkey } => (ReportTarget::Pubkey(pubkey), None), diff --git a/crates/buzz-relay/src/handlers/report_resolution.rs b/crates/buzz-relay/src/handlers/report_resolution.rs index ef7c953e9d3..c04ec08c8f7 100644 --- a/crates/buzz-relay/src/handlers/report_resolution.rs +++ b/crates/buzz-relay/src/handlers/report_resolution.rs @@ -667,6 +667,11 @@ async fn drive_enforcement( } } } + // The restriction row changed: drop the community's cached rows on + // every pod. On every convergence path, so recovery repeats it. + if matches!(action, "ban" | "timeout") { + state.invalidate_restrictions(tenant); + } // A ban closes the target's open sessions clusterwide, matching the // in-community kind-9040 ban. It runs before finalize so a crash in // between leaves the action non-terminal and recovery re-runs it here; diff --git a/crates/buzz-relay/src/handlers/req.rs b/crates/buzz-relay/src/handlers/req.rs index 646cfe375b0..cd19e86dcb1 100644 --- a/crates/buzz-relay/src/handlers/req.rs +++ b/crates/buzz-relay/src/handlers/req.rs @@ -21,8 +21,9 @@ use buzz_auth::Scope; use crate::connection::{AuthState, ConnectionState}; use crate::protocol::RelayMessage; use crate::state::AppState; +use crate::subscription::SubscriptionScope; -const MAX_SUBSCRIPTIONS: usize = 1024; +pub(crate) const MAX_SUBSCRIPTIONS: usize = 1024; /// Maximum aggregate number of explicit `#h` values accepted in one REQ, /// COUNT, HTTP `/query`, or HTTP `/count` request. @@ -52,7 +53,10 @@ pub(crate) const FILTER_QUERY_CONCURRENCY: usize = 4; // the range fails the build. const _: () = assert!(FILTER_QUERY_CONCURRENCY >= 2 && FILTER_QUERY_CONCURRENCY <= 8); -/// Handle a REQ message: register the subscription, deliver historical events, then send EOSE. +/// Admit a `REQ` and handle it inline. The read loop admits before it spawns +/// the handler, so arrival order decides ownership; this is the same path for +/// callers that run the handler in place. +#[cfg(test)] pub async fn handle_req( sub_id: String, filters: Vec, @@ -60,39 +64,59 @@ pub async fn handle_req( conn: Arc, state: Arc, ) { + let Ok(owner) = super::close::admit(&sub_id, &conn).await else { + return; + }; + handle_admitted_req(sub_id, owner, filters, before_ids, conn, state).await; +} + +/// Handle a REQ message: register the subscription, deliver historical events, then send EOSE. +/// +/// The REQ was admitted by `close::admit` with `owner`. Every exit before +/// the claim refuses through `close_if_owner`, so a request that a newer +/// same-ID `REQ` or a `CLOSE` superseded during its access checks sends +/// nothing and registers nothing. +pub async fn handle_admitted_req( + sub_id: String, + owner: u64, + filters: Vec, + before_ids: Vec>>, + conn: Arc, + state: Arc, +) { + let mut access = crate::access::ReadLog::req(&conn, &sub_id, &filters); let (conn_id, pubkey_bytes, token_channel_ids) = { match conn.auth_state_snapshot() { AuthState::Authenticated(ctx) => { if !ctx.scopes.is_empty() && !ctx.scopes.contains(&Scope::MessagesRead) { - conn.send(RelayMessage::notice("restricted: insufficient scope")); - conn.send(RelayMessage::closed( + super::close::refuse_if_owner_with_notice( &sub_id, + owner, "restricted: insufficient scope", - )); + "restricted: insufficient scope", + &conn, + &state, + ) + .await; + access.deny("insufficient_scope"); return; } let pk_bytes = ctx.pubkey.to_bytes().to_vec(); - let subs = conn.subscriptions.lock().await; - if !subs.contains_key(&sub_id) && subs.len() >= MAX_SUBSCRIPTIONS { - conn.send(RelayMessage::closed( - &sub_id, - "error: too many subscriptions", - )); - return; - } - (conn.conn_id, pk_bytes, ctx.channel_ids.clone()) } _ => { - conn.send(RelayMessage::notice( - "auth-required: authenticate before subscribing", - )); - conn.send(RelayMessage::closed( + super::close::refuse_if_owner_with_notice( &sub_id, + owner, + "auth-required: authenticate before subscribing", "auth-required: not authenticated", - )); + &conn, + &state, + ) + .await; + access.deny("auth_required"); return; } } @@ -102,14 +126,26 @@ pub async fn handle_req( let requested_channel_ids = match extract_channel_ids_from_filters_limited(&filters) { Ok(ids) => ids, Err(()) => { - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "restricted: too many explicit channels", - )); + owner, + Some("restricted: too many explicit channels"), + &conn, + &state, + ) + .await; + access.deny("too_many_channels"); return; } }; + // Every distinct channel a filter names, including group-state `#d`, is + // confirmed below. `#h` is bounded above; past the same limit, `#d` + // names are left out of confirmation and live routing rather than + // refused, as before `#d` routed live. + let (named_channels, live_names) = + super::system_channels::channels_named_by_filters(&filters, MAX_EXPLICIT_CHANNEL_VALUES); + let mut accessible_channels = if filters_are_nip43_membership_only(&filters) { metrics::counter!("buzz_req_global_access_resolution_skips_total", "kind" => "13534") .increment(1); @@ -121,8 +157,16 @@ pub async fn handle_req( { Ok(ids) => ids, Err(e) => { - warn!(conn_id = %conn_id, "Failed to get accessible channels: {e}"); - conn.send(RelayMessage::closed(&sub_id, "error: database error")); + warn!(conn_id = %conn_id, error_kind = %e.kind(), "Failed to get accessible channels"); + super::close::close_if_owner( + &sub_id, + owner, + Some(DATABASE_ERROR_CLOSED), + &conn, + &state, + ) + .await; + access.error("database_error"); return; } } @@ -145,8 +189,16 @@ pub async fn handle_req( { Ok(ids) => ids, Err(e) => { - warn!(conn_id = %conn_id, "Failed to get readable named-only channels: {e}"); - conn.send(RelayMessage::closed(&sub_id, "error: database error")); + warn!(conn_id = %conn_id, error_kind = %e.kind(), "Failed to get readable named-only channels"); + super::close::close_if_owner( + &sub_id, + owner, + Some(DATABASE_ERROR_CLOSED), + &conn, + &state, + ) + .await; + access.error("database_error"); return; } }; @@ -169,13 +221,18 @@ pub async fn handle_req( // `confirm_requested_channel_access`). Running this ahead of the search branch // is what fixes the search false-miss: a `#h=` search would // otherwise be scoped against the stale vector and return empty. - if let Some(requested) = requested_channel_ids.as_ref() { + // + // Confirm every channel any filter names (`#h`, or `#d` on group-state + // kinds), not only the all-`#h` set: each filter's history and live + // scope come from its own names, and a live scope is fixed at + // registration, so a stale miss would last until the client resubscribes. + if !named_channels.is_empty() { let repaired_from = accessible_channels.len(); let confirmed = match confirm_requested_channel_access( &state, conn.tenant.community(), &pubkey_bytes, - requested, + &named_channels, token_channel_ids.as_deref(), &mut accessible_channels, named_only.ids(), @@ -184,8 +241,20 @@ pub async fn handle_req( { Ok(confirmed) => confirmed, Err(e) => { - warn!(conn_id = %conn_id, "Channel membership confirmation failed: {e}"); - conn.send(RelayMessage::closed(&sub_id, "error: database error")); + warn!( + conn_id = %conn_id, + error_kind = %e.kind(), + "Channel membership confirmation failed" + ); + super::close::close_if_owner( + &sub_id, + owner, + Some(DATABASE_ERROR_CLOSED), + &conn, + &state, + ) + .await; + access.error("database_error"); return; } }; @@ -203,8 +272,16 @@ pub async fn handle_req( ) .await { - warn!(conn_id = %conn_id, "Failed to classify repaired channels: {e}"); - conn.send(RelayMessage::closed(&sub_id, "error: database error")); + warn!(conn_id = %conn_id, error_kind = %e.kind(), "Failed to classify repaired channels"); + super::close::close_if_owner( + &sub_id, + owner, + Some(DATABASE_ERROR_CLOSED), + &conn, + &state, + ) + .await; + access.error("database_error"); return; } } @@ -229,10 +306,15 @@ pub async fn handle_req( .as_ref() .is_some_and(|authorized| authorized.is_empty()) { - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "restricted: not a channel member", - )); + owner, + Some("restricted: not a channel member"), + &conn, + &state, + ) + .await; + access.deny("not_channel_member"); return; } @@ -251,24 +333,36 @@ pub async fn handle_req( Err(crate::nip_fi_gate::SessionExpired) => { // Fix 4: [FI-TRACE-DENIAL-ORACLE] gate is off_mode when no assertion // exists, so SessionExpired here always implies an active FI session. - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "restricted: authorization denied", - )); + owner, + Some("restricted: authorization denied"), + &conn, + &state, + ) + .await; + access.deny("session_expired"); return; } }; + // One-shot like search: accepting it replaces the ID's old holder. + let Some(owner) = claim_admitted_search(&sub_id, owner, &conn, &state).await else { + return; + }; unless_cancelled( &conn, handle_huddle_liveness_req( &sub_id, + owner, &filters, authorized_requested_channels.as_deref().unwrap_or_default(), &conn, &state, + &mut access, ), ) .await; + super::close::close_if_owner(&sub_id, owner, None, &conn, &state).await; return; } @@ -283,24 +377,39 @@ pub async fn handle_req( if channel_id.is_none() { let authed_pubkey_hex = hex::encode(&pubkey_bytes); if !p_gated_filters_authorized(&filters, &authed_pubkey_hex) { - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "restricted: p-gated events require #p matching your pubkey", - )); + owner, + Some("restricted: p-gated events require #p matching your pubkey"), + &conn, + &state, + ) + .await; + access.deny("p_gated"); return; } if !engram_filters_authorized(&filters, &authed_pubkey_hex) { - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "restricted: agent-engram reads require authors=[self] or #p=[self]", - )); + owner, + Some("restricted: agent-engram reads require authors=[self] or #p=[self]"), + &conn, + &state, + ) + .await; + access.deny("engram_gated"); return; } if !author_only_filters_authorized(&filters, &authed_pubkey_hex) { - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "restricted: author-only kinds require authors=[self]", - )); + owner, + Some("restricted: author-only kinds require authors=[self]"), + &conn, + &state, + ) + .await; + access.deny("author_only"); return; } } @@ -312,10 +421,15 @@ pub async fn handle_req( let has_search = filters.iter().any(|f| f.search.is_some()); if has_search { if filters.iter().any(|f| f.search.is_none()) { - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "error: mixed search and non-search filters not supported", - )); + owner, + Some("error: mixed search and non-search filters not supported"), + &conn, + &state, + ) + .await; + access.deny("mixed_search"); return; } // IMPORTANT 6: acquire a REQ effect permit before the search query and @@ -327,14 +441,19 @@ pub async fn handle_req( Ok(permit) => permit, Err(crate::nip_fi_gate::SessionExpired) => { // Fix 4: [FI-TRACE-DENIAL-ORACLE] - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "restricted: authorization denied", - )); + owner, + Some("restricted: authorization denied"), + &conn, + &state, + ) + .await; + access.deny("session_expired"); return; } }; - let Some(owner) = claim_search_subscription(&sub_id, &conn, &state).await else { + let Some(owner) = claim_admitted_search(&sub_id, owner, &conn, &state).await else { return; }; let search = async { @@ -352,6 +471,7 @@ pub async fn handle_req( &conn, &state, trace_state.as_ref(), + &mut access, ) .await; }; @@ -376,23 +496,36 @@ pub async fn handle_req( Ok(permit) => permit, Err(crate::nip_fi_gate::SessionExpired) => { // Fix 4: [FI-TRACE-DENIAL-ORACLE] - conn.send(RelayMessage::closed( + super::close::close_if_owner( &sub_id, - "restricted: authorization denied", - )); + owner, + Some("restricted: authorization denied"), + &conn, + &state, + ) + .await; + access.deny("session_expired"); return; } }; - let Some(owner) = claim_live_subscription( - &sub_id, - &filters, - authorized_requested_channels.as_deref(), - &conn, - &state, - ) - .await - else { + // Each filter routes live events under its own scope, so a channel one + // filter names never reaches a sibling filter (see `filter_live_scope`). + let live_filters = filters + .iter() + .map(|filter| { + ( + filter.clone(), + super::system_channels::filter_live_scope( + filter, + &accessible_channels, + &named_only, + live_names, + ), + ) + }) + .collect(); + let Some(owner) = claim_admitted_live(&sub_id, owner, live_filters, &conn, &state).await else { return; }; @@ -401,8 +534,10 @@ pub async fn handle_req( // Registration above is one uncancellable unit; the history read below is // read-only delivery and races gate cancellation, so expiry drops it and // releases the permit without sending another EVENT or EOSE. It returns - // whether a statement timeout ended it: retirement then runs after the - // race, because a dropped retirement would leak its unreleased topics. + // the CLOSED reason when a failed read ended it: retirement then runs + // after the race, because a dropped retirement would leak its unreleased + // topics. + let access = &mut access; let history = async { #[cfg(test)] crate::nip_fi_test_hooks::before_req_history(conn.tenant.community()).await; @@ -488,12 +623,20 @@ pub async fn handle_req( let events = match filter_events { Ok(evs) => evs, Err(e) => { - warn!(conn_id = %conn_id, sub_id = %sub_id, "Historical query failed: {e}"); - if e.is_statement_cancelled() { - return true; - } - conn.send(RelayMessage::eose(&sub_id)); - return false; + warn!( + conn_id = %conn_id, + sub_id = %sub_id, + error_kind = %e.kind(), + "Historical query failed" + ); + access.error(if e.is_statement_cancelled() { + "query_timed_out" + } else { + "database_error" + }); + // CLOSED, never EOSE: EOSE tells the client it has every + // stored event, so a resuming client would skip this history. + return Some(history_read_closed_reason(&e)); } }; @@ -524,7 +667,8 @@ pub async fn handle_req( Err(e) => { warn!( conn_id = %conn_id, sub_id = %sub_id, - "conformance row-community lookup failed: {e}" + error_kind = %e.kind(), + "conformance row-community lookup failed" ); std::collections::HashMap::new() } @@ -569,9 +713,10 @@ pub async fn handle_req( } let msg = RelayMessage::event(&sub_id, &stored.event); - if !conn.send(msg) { - return false; + if !super::close::send_if_owner(&sub_id, owner, msg, &conn).await { + return None; } + access.queued_one(); total_sent += 1; if total_sent.is_multiple_of(100) { tokio::task::yield_now().await; @@ -579,7 +724,9 @@ pub async fn handle_req( } } - conn.send(RelayMessage::eose(&sub_id)); + if super::close::send_if_owner(&sub_id, owner, RelayMessage::eose(&sub_id), &conn).await { + access.served(); + } debug!( conn_id = %conn_id, @@ -587,13 +734,15 @@ pub async fn handle_req( count = total_sent, "EOSE sent after historical delivery" ); - false + None }; let outcome = unless_cancelled(&conn, history).await; drop(_req_permit); match outcome { - Some(false) => {} - Some(true) => close_timed_out_subscription(&sub_id, owner, &conn, &state).await, + Some(None) => {} + Some(Some(reason)) => { + super::close::close_if_owner(&sub_id, owner, Some(reason), &conn, &state).await; + } None => { super::close::close_if_owner(&sub_id, owner, None, &conn, &state).await; } @@ -770,6 +919,7 @@ async fn handle_search_req( conn: &ConnectionState, state: &AppState, trace_state: Option<&crate::conformance::AbstractState>, + access: &mut crate::access::ReadLog, ) { // `None` means "no accessible channels and no global access" → EOSE, // exactly as the legacy string-filter helper short-circuited. A filter @@ -777,7 +927,9 @@ async fn handle_search_req( if build_search_channel_scope_filter(implicit_channels, include_global).is_none() && named_only.is_empty() { - conn.send(RelayMessage::eose(sub_id)); + if super::close::send_if_owner(sub_id, owner, RelayMessage::eose(sub_id), conn).await { + access.served(); + } return; } @@ -793,10 +945,7 @@ async fn handle_search_req( let accessible_channels = &*super::system_channels::filter_channel_scope(filter, implicit_channels, named_only); - let limit = filter - .limit - .map(|l| (l as u32).min(buzz_db::DEFAULT_MAX_PAGE_LIMIT as u32)) - .unwrap_or(buzz_db::DEFAULT_MAX_PAGE_LIMIT as u32); + let limit = buzz_core::filter::clamp_limit(filter.limit, PAGE_LIMIT_MAX, PAGE_LIMIT_MAX); if limit == 0 { continue; // NIP-01: limit 0 means "no results from this filter" @@ -875,8 +1024,25 @@ async fn handle_search_req( let search_result = match state.search.search(&search_query).await { Ok(r) => r, Err(e) => { - warn!(sub_id = %sub_id, "NIP-50 search failed: {e}"); - break; + // CLOSED, not EOSE: an empty EOSE would read as "no + // matches". Stop the whole REQ so later filters do not + // each wait out the search pool's acquire timeout too. + // Fixed kind only: the error must never carry query text. + warn!( + sub_id = %sub_id, + error_kind = %e.kind(), + "NIP-50 search failed" + ); + access.error("search_failed"); + super::close::close_if_owner( + sub_id, + owner, + Some(search_closed_reason(&e)), + conn, + state, + ) + .await; + return; } }; @@ -885,26 +1051,50 @@ async fn handle_search_req( let exhausted = search_result.hits.len() < SEARCH_PAGE_SIZE as usize; let page_empty = search_result.hits.is_empty(); - let hit_ids: Vec<[u8; 32]> = - search_result.hits.into_iter().map(|h| h.event_id).collect(); + let hit_keys: Vec<_> = search_result + .hits + .iter() + .map(|h| (h.event_id, h.created_at)) + .collect(); - if !hit_ids.is_empty() { - let id_refs: Vec<&[u8]> = hit_ids.iter().map(|b| b.as_slice()).collect(); + if !hit_keys.is_empty() { let events = match state .db - .get_events_by_ids_routed("req_search_hydrate", tenant.community(), &id_refs) + .get_events_by_ids_at_routed( + "req_search_hydrate", + tenant.community(), + &hit_keys, + ) .await { Ok(evs) => evs, Err(e) if e.is_statement_cancelled() => { // CLOSED (not EOSE) keeps partial results from reading as complete. - warn!(sub_id = %sub_id, "NIP-50 batch fetch timed out: {e}"); + warn!(sub_id = %sub_id, "NIP-50 batch fetch timed out"); + access.error("query_timed_out"); close_timed_out_subscription(sub_id, owner, conn, state).await; return; } Err(e) => { - warn!(sub_id = %sub_id, "NIP-50 batch fetch failed: {e}"); - break; + // CLOSED, not EOSE: an EOSE after a failed hydration + // would mark the hits never fetched as "no matches". + // That includes a history read shed while the reader + // is saturated, which the client should retry. + warn!( + sub_id = %sub_id, + error_kind = %e.kind(), + "NIP-50 batch fetch failed" + ); + access.error("database_error"); + super::close::close_if_owner( + sub_id, + owner, + Some(DATABASE_ERROR_CLOSED), + conn, + state, + ) + .await; + return; } }; @@ -934,7 +1124,8 @@ async fn handle_search_req( Err(e) => { warn!( sub_id = %sub_id, - "conformance row-community lookup failed: {e}" + error_kind = %e.kind(), + "conformance row-community lookup failed" ); std::collections::HashMap::new() } @@ -954,7 +1145,7 @@ async fn handle_search_req( .map(|ev| (ev.event.id.to_bytes(), ev)) .collect(); - for id_array in &hit_ids { + for (id_array, _) in &hit_keys { if emitted >= limit { break; } @@ -981,9 +1172,11 @@ async fn handle_search_req( if !seen_ids.insert(stored.event.id) { continue; } - if !conn.send(RelayMessage::event(sub_id, &stored.event)) { + let frame = RelayMessage::event(sub_id, &stored.event); + if !super::close::send_if_owner(sub_id, owner, frame, conn).await { return; } + access.queued_one(); emitted += 1; } } @@ -994,7 +1187,9 @@ async fn handle_search_req( } } - conn.send(RelayMessage::eose(sub_id)); + if super::close::send_if_owner(sub_id, owner, RelayMessage::eose(sub_id), conn).await { + access.served(); + } } /// Convert a single NIP-01 filter into an [`EventQuery`] for the database. @@ -1019,11 +1214,13 @@ pub async fn build_event_query_from_filter( /// returning a truncated count. pub(crate) const COUNT_FALLBACK_CANDIDATE_LIMIT: i64 = 5_000; -/// Apply the bounded candidate budget used by COUNT post-filter fallbacks. -pub(crate) fn apply_count_fallback_limit(query: &mut EventQuery) { +/// Prepare a COUNT post-filter fallback query: the bounded candidate budget, +/// and exact NIP-01 matching so it counts what the SQL COUNT path would. +pub(crate) fn prepare_count_fallback(query: &mut EventQuery) { let fetch_limit = COUNT_FALLBACK_CANDIDATE_LIMIT + 1; query.limit = Some(fetch_limit); query.max_limit = Some(fetch_limit); + query.exact_match = true; } /// Return whether a COUNT fallback query exceeded its exact-count budget. @@ -1037,9 +1234,9 @@ pub(crate) fn count_fallback_exceeded(candidate_count: usize) -> bool { /// /// Pushed constraints: kinds, authors (single or multi), ids, since, until, /// authorized channel scope (#h single or multi, injected by caller), #p (single), -/// #d (single, NIP-33-only kinds), #e (any). +/// #d (single, NIP-33-only kinds), #e (any), #a (any). /// -/// Anything else (multi-#p, #t, #a, search, #d on non-NIP-33) requires +/// Anything else (multi-#p, #t, #k, search, #d on non-NIP-33) requires /// post-filtering and cannot use the fast COUNT path. pub fn filter_fully_pushable(filter: &Filter) -> bool { // Check if filter exclusively targets NIP-33 kinds (needed for #d pushability). @@ -1070,11 +1267,11 @@ pub fn filter_fully_pushable(filter: &Filter) -> bool { return false; } } - "e" => { - // #e is fully pushed (any count) via JSONB containment. + "e" | "a" => { + // #e and #a are fully pushed (any count) as exact tag matches. } _ => { - // Any other generic tag (#t, #a, etc.) is not pushed exactly. + // Any other generic tag (#t, #k, etc.) is not pushed exactly. // #t/#P on group-state kinds are matched in SQL // (`group_state_tag_values`), but this fast path does not // model them, so COUNT still post-filters them. @@ -1122,6 +1319,9 @@ fn extract_channel_id_from_filter(filter: &Filter) -> Option { values.iter().next()?.parse::().ok() } +/// [`buzz_db::DEFAULT_MAX_PAGE_LIMIT`] as the `u32` that [`buzz_core::filter::clamp_limit`] takes. +const PAGE_LIMIT_MAX: u32 = buzz_db::DEFAULT_MAX_PAGE_LIMIT as u32; + /// Convert a single NIP-01 filter into an [`EventQuery`] for the database. /// /// Each filter is queried independently so that per-filter `limit` and time @@ -1142,6 +1342,13 @@ fn filter_to_query_params( ks.iter().map(|k| k.as_u16() as i32).collect() } }); + // An empty `authors`, `ids` or tag set also matches nothing (NIP-01), but + // the conversions below drop or ignore it, so COUNT would count without + // it. Use the same sentinel, so every read answers it without a query. + let matches_nothing = filter.authors.as_ref().is_some_and(|a| a.is_empty()) + || filter.ids.as_ref().is_some_and(|i| i.is_empty()) + || filter.generic_tags.values().any(|values| values.is_empty()); + let kinds = if matches_nothing { Some(vec![]) } else { kinds }; let since = filter .since @@ -1149,10 +1356,11 @@ fn filter_to_query_params( let until = filter .until .and_then(|u| chrono::DateTime::from_timestamp(u.as_secs() as i64, 0)); - let limit = filter - .limit - .map(|l| (l as i64).min(buzz_db::DEFAULT_MAX_PAGE_LIMIT)) - .unwrap_or(buzz_db::DEFAULT_MAX_PAGE_LIMIT); + let limit = i64::from(buzz_core::filter::clamp_limit( + filter.limit, + PAGE_LIMIT_MAX, + PAGE_LIMIT_MAX, + )); // Push author filter into SQL. Single-author uses the indexed `pubkey` column; // multi-author uses the `authors` IN-list pushdown added in the pure-nostr PR. @@ -1193,6 +1401,15 @@ fn filter_to_query_params( } }); + // Push #a (NIP-01 address) into SQL the same way, so references to an + // addressable event, such as reactions to it, are matched before LIMIT. + // An empty `#a` matches nothing, as in the NIP-01 post-filter. + let a_tag_key = nostr::SingleLetterTag::lowercase(nostr::Alphabet::A); + let a_tags = filter + .generic_tags + .get(&a_tag_key) + .map(|values| values.iter().map(|v| v.to_string()).collect::>()); + // Push single-value #p tag into SQL via event_mentions join. // This is critical for gift-wrap (kind:1059) and membership notification // queries where >500 events for other recipients would otherwise push @@ -1254,9 +1471,13 @@ fn filter_to_query_params( // NIP-CL: a membership notice's `#t` is its channel type. SQL keeps only // the types this filter may see; a filter without `#t` sees legacy types. let notice_channel_types = buzz_core::filter::notice_channel_types(filter); + // NIP-CW: a filter with `#p` is never a plain thread-reply read. Only a + // single value reaches SQL as `p_tag_hex`, so mark every `#p` filter here. + let exact_match = filter.generic_tags.contains_key(&p_tag); EventQuery { notice_channel_types, + exact_match, channel_id, kinds, pubkey, @@ -1269,6 +1490,7 @@ fn filter_to_query_params( authors, ids, e_tags, + a_tags, d_tag_values, tag_values, ..EventQuery::for_community(community) @@ -1413,16 +1635,23 @@ fn huddle_liveness_session_ids(filters: &[Filter]) -> Vec { async fn handle_huddle_liveness_req( sub_id: &str, + owner: u64, filters: &[Filter], parent_channel_ids: &[uuid::Uuid], conn: &ConnectionState, state: &AppState, + access: &mut crate::access::ReadLog, ) { if parent_channel_ids.is_empty() { - conn.send(RelayMessage::closed( + super::close::close_if_owner( sub_id, - "restricted: huddle liveness requires an authorized #h channel", - )); + owner, + Some("restricted: huddle liveness requires an authorized #h channel"), + conn, + state, + ) + .await; + access.deny("not_channel_member"); return; } @@ -1438,8 +1667,13 @@ async fn handle_huddle_liveness_req( { Ok(links) => links, Err(error) => { - warn!("Huddle liveness linkage batch failed: {error}"); - conn.send(RelayMessage::closed(sub_id, "error: database error")); + warn!( + error_kind = %error.kind(), + "Huddle liveness linkage batch failed" + ); + super::close::close_if_owner(sub_id, owner, Some(DATABASE_ERROR_CLOSED), conn, state) + .await; + access.error("database_error"); return; } }; @@ -1457,7 +1691,15 @@ async fn handle_huddle_liveness_req( Ok(_) => continue, Err(error) => { warn!(session_id = %session_id, "Huddle liveness lease lookup failed: {error}"); - conn.send(RelayMessage::closed(sub_id, "error: liveness unavailable")); + super::close::close_if_owner( + sub_id, + owner, + Some("error: liveness unavailable"), + conn, + state, + ) + .await; + access.error("liveness_unavailable"); return; } } @@ -1495,67 +1737,83 @@ async fn handle_huddle_liveness_req( Ok(event) => event, Err(error) => { warn!(session_id = %session_id, "Huddle liveness signing failed: {error}"); - conn.send(RelayMessage::closed(sub_id, "error: signing failed")); + super::close::close_if_owner( + sub_id, + owner, + Some("error: signing failed"), + conn, + state, + ) + .await; + access.error("signing_failed"); return; } }; - if !conn.send(RelayMessage::event(sub_id, &event)) { + let frame = RelayMessage::event(sub_id, &event); + if !super::close::send_if_owner(sub_id, owner, frame, conn).await { return; } + access.queued_one(); } - conn.send(RelayMessage::eose(sub_id)); + if super::close::send_if_owner(sub_id, owner, RelayMessage::eose(sub_id), conn).await { + access.served(); + } } -/// Claim `sub_id` for a live REQ under the lifecycle lock: record a fresh -/// owner token, register for fan-out (replacing any same-ID entry), retain its -/// topics, and release the replaced scope's. Returns the owner token, or -/// `None` once the connection is closing — the caller then exits silently. -async fn claim_live_subscription( +/// Admit and claim `sub_id` for a live REQ in one step, as a handler run in +/// place would. `None` if the connection is closing or a newer request took +/// the ID between the two steps. +#[cfg(test)] +pub(crate) async fn claim_live_subscription( sub_id: &str, - filters: &[Filter], - channel_ids: Option<&[uuid::Uuid]>, + filters: Vec<(Filter, SubscriptionScope)>, + conn: &ConnectionState, + state: &AppState, +) -> Option { + let owner = super::close::admit(sub_id, conn).await.ok()?; + claim_admitted_live(sub_id, owner, filters, conn, state).await +} + +/// Claim `sub_id` for the live REQ admitted with `owner`, under the lifecycle +/// lock: register for fan-out (replacing any same-ID entry), retain its +/// topics, and release the replaced scope's. Each filter carries its own +/// server-resolved live scope; the subscription retains each topic in their +/// union once. Returns `owner`, or `None` once the connection is closing or a +/// newer same-ID REQ or a `CLOSE` superseded this request — the caller then +/// exits silently. +pub(crate) async fn claim_admitted_live( + sub_id: &str, + owner: u64, + filters: Vec<(Filter, SubscriptionScope)>, conn: &ConnectionState, state: &AppState, ) -> Option { let mut subs = conn.subscriptions.lock().await; - if conn.cancel.is_cancelled() { + if !super::close::claim_locked(&mut subs, sub_id, owner, conn) { return None; } - let owner = super::close::next_owner(); - subs.insert(sub_id.to_string(), owner); - let community = conn.tenant.community(); - let replaced = match channel_ids { - Some(ids) => state.sub_registry.register_channels_scoped( - community, - conn.conn_id, - sub_id.to_string(), - filters.to_vec(), - ids.to_vec(), - ), - None => state.sub_registry.register_scoped( - community, - conn.conn_id, - sub_id.to_string(), - filters.to_vec(), - None, - ), - }; - match channel_ids { - Some(ids) => { - for &channel_id in ids { - state - .pubsub - .retain_topic(&conn.tenant, EventTopic::Channel(channel_id)) - .await; - } - } - None => { - state - .pubsub - .retain_topic(&conn.tenant, EventTopic::Global) - .await; - } + // A sync that held the ID stops; the registry entry and topics below are + // replaced in place. + state.artifact_syncs.remove(conn.conn_id, sub_id); + let topics = SubscriptionScope::union(filters.iter().map(|(_, scope)| scope)); + let replaced = state.sub_registry.register_filters_scoped( + conn.tenant.community(), + conn.conn_id, + sub_id.to_string(), + filters, + ); + if topics.is_global() { + state + .pubsub + .retain_topic(&conn.tenant, EventTopic::Global) + .await; + } + for &channel_id in topics.channel_ids() { + state + .pubsub + .retain_topic(&conn.tenant, EventTopic::Channel(channel_id)) + .await; } if let Some(replaced) = replaced { super::close::release_scope_topics(state, &conn.tenant, &replaced.scope).await; @@ -1563,22 +1821,33 @@ async fn claim_live_subscription( Some(owner) } -/// Claim `sub_id` for a one-shot search REQ under the lifecycle lock. -/// Accepting it retires whatever holds the ID (NIP-01 replacement), even -/// though search never registers for fan-out. `None` once the connection is -/// closing. +/// Admit and claim `sub_id` for a one-shot REQ in one step, as a handler run +/// in place would. +#[cfg(test)] async fn claim_search_subscription( sub_id: &str, conn: &ConnectionState, state: &AppState, +) -> Option { + let owner = super::close::admit(sub_id, conn).await.ok()?; + claim_admitted_search(sub_id, owner, conn, state).await +} + +/// Claim `sub_id` for the one-shot search or huddle-liveness REQ admitted with +/// `owner`, under the lifecycle lock. Accepting it retires whatever holds the +/// ID (NIP-01 replacement), even though neither registers for fan-out. `None` +/// once the connection is closing or this request was superseded. +async fn claim_admitted_search( + sub_id: &str, + owner: u64, + conn: &ConnectionState, + state: &AppState, ) -> Option { let mut subs = conn.subscriptions.lock().await; - if conn.cancel.is_cancelled() { + if !super::close::claim_locked(&mut subs, sub_id, owner, conn) { return None; } - super::close::retire_locked(&mut subs, sub_id, conn, state).await; - let owner = super::close::next_owner(); - subs.insert(sub_id.to_string(), owner); + super::close::retire_holder_locked(sub_id, conn, state).await; Some(owner) } @@ -1600,6 +1869,34 @@ async fn close_timed_out_subscription( /// Clients match it to skip retrying the same expensive query. pub(crate) const QUERY_TIMED_OUT_CLOSED: &str = "error: query timed out"; +/// CLOSED reason for any other failed DB read. Generic on purpose: the raw +/// error stays in the relay log, and clients treat it as retryable. +pub(crate) const DATABASE_ERROR_CLOSED: &str = "error: database error"; + +/// CLOSED reason for a failed REQ history read. +fn history_read_closed_reason(e: &buzz_db::DbError) -> &'static str { + if e.is_statement_cancelled() { + QUERY_TIMED_OUT_CLOSED + } else { + DATABASE_ERROR_CLOSED + } +} + +/// CLOSED reason for a NIP-50 search the search service could not answer +/// (e.g. the read replica it queries is down). +pub(crate) const SEARCH_FAILED_CLOSED: &str = "error: search failed"; + +/// CLOSED reason for a failed NIP-50 search: a search cancelled by the search +/// pool's statement timeout gets the stable timeout reason, like any other +/// cancelled read; anything else is the retryable [`SEARCH_FAILED_CLOSED`]. +fn search_closed_reason(e: &buzz_search::SearchError) -> &'static str { + if e.is_statement_cancelled() { + QUERY_TIMED_OUT_CLOSED + } else { + SEARCH_FAILED_CLOSED + } +} + /// CLOSED reason for a failed one-shot DB read (COUNT): a statement cancel gets /// the stable timeout reason; anything else keeps the raw error. pub(crate) fn db_read_closed_reason(e: &buzz_db::DbError) -> String { @@ -1892,6 +2189,7 @@ mod tests { let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::new_v4()); let cancel = tokio_util::sync::CancellationToken::new(); let conn = ConnectionState { + refusal_budget: Default::default(), conn_id: uuid::Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved(community, "t.local".to_string()), remote_addr: "127.0.0.1:1234".parse().expect("addr"), @@ -1915,6 +2213,29 @@ mod tests { vec![Filter::new().kind(nostr::Kind::TextNote)] } + /// Give every filter the same live scope: `channels`, or global. + fn scoped( + filters: &[Filter], + channels: Option<&[uuid::Uuid]>, + ) -> Vec<(Filter, SubscriptionScope)> { + let scope = channels.map_or_else(SubscriptionScope::global, |channels| { + SubscriptionScope::channels(channels.iter().copied()) + }); + filters + .iter() + .map(|filter| (filter.clone(), scope.clone())) + .collect() + } + + /// The owner token the lifecycle map holds for `sub_id`. + async fn token(conn: &ConnectionState, sub_id: &str) -> Option { + conn.subscriptions + .lock() + .await + .get(sub_id) + .map(|held| held.owner) + } + fn registered(state: &AppState, conn: &ConnectionState, sub_id: &str) -> bool { state .sub_registry @@ -1933,16 +2254,98 @@ mod tests { .collect() } + /// A live REQ that reuses a sync's ID retires the sync, so fan-out + /// delivers to the new subscription instead of the stale sync inbox. + /// Mutation: drop the `artifact_syncs.remove` in + /// `claim_live_subscription` → the event is diverted → RED. #[tokio::test] - async fn timed_out_historical_read_deregisters_before_closed() { + async fn live_req_replacing_a_sync_retires_it() { + let state = crate::state::tests::test_state().await; + let (conn, _send_rx) = lifecycle_conn(); + state.artifact_syncs.insert_idle(conn.conn_id, "s"); + claim_live_subscription( + "s", + scoped(&text_filters(), Some(&[uuid::Uuid::new_v4()])), + &conn, + &state, + ) + .await + .expect("claim"); + assert!(!state.artifact_syncs.contains(conn.conn_id, "s")); + let event = nostr::EventBuilder::text_note("x") + .sign_with_keys(&nostr::Keys::generate()) + .expect("sign"); + let matches = vec![(conn.conn_id, "s".to_string())]; + let delivered = state + .artifact_syncs + .divert(&buzz_core::StoredEvent::new(event, None), matches.clone()); + assert_eq!(delivered, matches); + } + + /// A refused sync REQ answers `CLOSED`, so whatever held its ID must stop + /// first (NIP-01 replacement): no later frame may arrive under a closed + /// ID. Covers a filter refusal and an auth refusal. Mutation: send the + /// refusal without `retire_locked` → the old subscription stays → RED. + #[tokio::test] + async fn refused_sync_req_retires_the_old_holder() { let state = crate::state::tests::test_state().await; let (conn, mut send_rx) = lifecycle_conn(); + let conn = Arc::new(conn); let channel = uuid::Uuid::new_v4(); let topic = EventTopic::Channel(channel); - let owner = - claim_live_subscription("thread", &text_filters(), Some(&[channel]), &conn, &state) + let valid = buzz_core::artifact_sync::parse_sync( + &serde_json::json!({"artifact":"current","#h":[channel.to_string()]}), + ); + for (filter, reason) in [ + (Err("sync requires #h"), "invalid: sync requires #h"), + (valid, "auth-required: not authenticated"), + ] { + claim_live_subscription( + "s", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await + .expect("claim"); + let permit = Arc::new(tokio::sync::Semaphore::new(1)) + .acquire_owned() .await - .expect("claim"); + .expect("permit"); + let owner = super::super::close::admit("s", &conn).await.expect("admit"); + super::super::artifact_sync::handle_sync( + "s".into(), + owner, + filter, + Arc::clone(&conn), + Arc::clone(&state), + permit, + ) + .await; + assert!(conn.subscriptions.lock().await.is_empty(), "{reason}"); + assert!(!registered(&state, &conn, "s"), "{reason}"); + assert_eq!(state.pubsub.topic_refcount(&conn.tenant, topic).await, 0); + assert_eq!( + closed_frames(&mut send_rx), + vec![serde_json::json!(["CLOSED", "s", reason]).to_string()] + ); + } + } + + #[tokio::test] + async fn timed_out_historical_read_deregisters_before_closed() { + let state = crate::state::tests::test_state().await; + let (conn, mut send_rx) = lifecycle_conn(); + let channel = uuid::Uuid::new_v4(); + let topic = EventTopic::Channel(channel); + let owner = claim_live_subscription( + "thread", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await + .expect("claim"); assert_eq!(state.pubsub.topic_refcount(&conn.tenant, topic).await, 1); close_timed_out_subscription("thread", owner, &conn, &state).await; @@ -1974,14 +2377,22 @@ mod tests { EventTopic::Channel(old_channel), EventTopic::Channel(new_channel), ); - let old = - claim_live_subscription("x", &text_filters(), Some(&[old_channel]), &conn, &state) - .await - .expect("claim"); - let new = - claim_live_subscription("x", &text_filters(), Some(&[new_channel]), &conn, &state) - .await - .expect("claim"); + let old = claim_live_subscription( + "x", + scoped(&text_filters(), Some(&[old_channel])), + &conn, + &state, + ) + .await + .expect("claim"); + let new = claim_live_subscription( + "x", + scoped(&text_filters(), Some(&[new_channel])), + &conn, + &state, + ) + .await + .expect("claim"); assert_eq!( state.pubsub.topic_refcount(&conn.tenant, old_topic).await, 0 @@ -1989,7 +2400,7 @@ mod tests { close_timed_out_subscription("x", old, &conn, &state).await; - assert_eq!(conn.subscriptions.lock().await.get("x"), Some(&new)); + assert_eq!(token(&conn, "x").await, Some(new)); assert!( registered(&state, &conn, "x"), "replacement must stay registered" @@ -2013,9 +2424,14 @@ mod tests { let (conn, mut send_rx) = lifecycle_conn(); let channel = uuid::Uuid::new_v4(); let topic = EventTopic::Channel(channel); - claim_live_subscription("x", &text_filters(), Some(&[channel]), &conn, &state) - .await - .expect("claim"); + claim_live_subscription( + "x", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await + .expect("claim"); let search = claim_search_subscription("x", &conn, &state) .await @@ -2026,17 +2442,158 @@ mod tests { ); assert_eq!(state.pubsub.topic_refcount(&conn.tenant, topic).await, 0); - let live = claim_live_subscription("x", &text_filters(), Some(&[channel]), &conn, &state) - .await - .expect("claim"); + let live = claim_live_subscription( + "x", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await + .expect("claim"); close_timed_out_subscription("x", search, &conn, &state).await; - assert_eq!(conn.subscriptions.lock().await.get("x"), Some(&live)); + assert_eq!(token(&conn, "x").await, Some(live)); assert!(registered(&state, &conn, "x")); assert_eq!(state.pubsub.topic_refcount(&conn.tenant, topic).await, 1); assert!(closed_frames(&mut send_rx).is_empty()); } + /// A NIP-50 search the search pool cannot serve (its reader is down) ends + /// the REQ with a CLOSED error, never an EOSE that reads as "no matches", + /// and the REQ's later search filters never wait on the pool. + #[tokio::test] + async fn failed_search_closes_without_eose_or_trying_later_filters() { + const ACQUIRE: std::time::Duration = std::time::Duration::from_millis(500); + let state = crate::state::tests::test_state_with_database_url_and_pool_options( + "postgres://127.0.0.1:1/none", + sqlx::postgres::PgPoolOptions::new().acquire_timeout(ACQUIRE), + ) + .await; + let (conn, mut send_rx) = lifecycle_conn(); + let owner = claim_search_subscription("s", &conn, &state) + .await + .expect("claim"); + let filters: Vec = (0..4) + .map(|i| { + Filter::new() + .kind(nostr::Kind::TextNote) + .search(format!("needle{i}")) + }) + .collect(); + + let (_guard, out) = crate::access::tests::capture_scoped(); + let mut access = crate::access::ReadLog::req(&conn, "s", &filters); + let started = std::time::Instant::now(); + handle_search_req( + "s", + owner, + &filters, + &[], + &super::super::system_channels::NamedOnlyChannels::default(), + true, + &conn.tenant, + &[0; 32], + &conn, + &state, + None, + &mut access, + ) + .await; + let elapsed = started.elapsed(); + drop(access); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert_eq!(lines[0]["level"], "WARN", "{}", lines[0]); + assert_eq!(lines[0]["outcome"], "error", "{}", lines[0]); + assert_eq!(lines[0]["reason"], "search_failed", "{}", lines[0]); + assert_eq!(lines[0]["search"], true, "{}", lines[0]); + + assert_eq!( + closed_frames(&mut send_rx), + vec![format!(r#"["CLOSED","s","{SEARCH_FAILED_CLOSED}"]"#)], + "exactly one CLOSED error and no EOSE" + ); + assert!( + conn.subscriptions.lock().await.is_empty(), + "the failed search must release its ID" + ); + // Each filter that reaches the pool waits out ACQUIRE on the dead port. + assert!( + elapsed < ACQUIRE * 3, + "later filters must not try the pool: took {elapsed:?} for {} filters", + filters.len() + ); + } + + /// A REQ whose `EOSE` is not queued did not complete, so it must log + /// `aborted`, not `served`: once when a same-ID replacement takes the ID + /// while the empty search waits to send its `EOSE`, and once when the + /// outbound queue rejects the frame. Mutation: ignore `send_if_owner`'s + /// result before `access.served()` → `served` → RED. + #[tokio::test] + async fn unqueued_eose_logs_aborted_not_served() { + use super::super::close::test_seam::{Pause, SEND_PAUSE}; + let state = crate::state::tests::test_state().await; + let filters = vec![Filter::new().search("needle")]; + for case in ["replaced", "queue_rejected"] { + let (conn, send_rx) = lifecycle_conn(); + let owner = claim_search_subscription("s", &conn, &state) + .await + .expect("claim"); + let (_guard, out) = crate::access::tests::capture_scoped(); + let mut access = crate::access::ReadLog::req(&conn, "s", &filters); + let mut send_rx = Some(send_rx); + if case == "queue_rejected" { + drop(send_rx.take()); + } + let pause = Arc::new(Pause::default()); + let named_only = super::super::system_channels::NamedOnlyChannels::default(); + { + let search = SEND_PAUSE.scope( + Arc::clone(&pause), + handle_search_req( + "s", + owner, + &filters, + &[], + &named_only, + false, + &conn.tenant, + &[0; 32], + &conn, + &state, + None, + &mut access, + ), + ); + tokio::pin!(search); + tokio::select! { + _ = &mut search => panic!("{case}: the search must pause before EOSE"), + _ = pause.reached.notified() => {} + } + if case == "replaced" { + conn.subscriptions.lock().await.insert( + "s".to_string(), + crate::handlers::close::SubOwner { + owner: owner + 1_000_000, + claimed: false, + }, + ); + } + pause.resume.notify_one(); + search.await; + } + drop(access); + let lines = out.lines(); + assert_eq!(lines.len(), 1, "{case}: {lines:?}"); + assert_eq!(lines[0]["outcome"], "aborted", "{case}: {}", lines[0]); + assert_eq!(lines[0]["level"], "INFO", "{case}: {}", lines[0]); + if let Some(rx) = send_rx.as_mut() { + assert!(closed_frames(rx).is_empty(), "{case}: no stale EOSE"); + } + } + } + /// Concurrent same-ID claims and stale teardowns: whichever claim lands /// last owns the ID, and every stale teardown is a silent no-op. #[tokio::test] @@ -2046,17 +2603,27 @@ mod tests { let conn = Arc::new(conn); let channel = uuid::Uuid::new_v4(); let topic = EventTopic::Channel(channel); - let stale = claim_live_subscription("x", &text_filters(), Some(&[channel]), &conn, &state) - .await - .expect("claim"); + let stale = claim_live_subscription( + "x", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await + .expect("claim"); let tasks = (0..16).map(|i| { let (conn, state) = (Arc::clone(&conn), Arc::clone(&state)); tokio::spawn(async move { if i % 2 == 0 { - claim_live_subscription("x", &text_filters(), Some(&[channel]), &conn, &state) - .await - .expect("claim"); + claim_live_subscription( + "x", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await + .expect("claim"); } else { close_timed_out_subscription("x", stale, &conn, &state).await; } @@ -2066,7 +2633,13 @@ mod tests { task.await.expect("task"); } - let owner = *conn.subscriptions.lock().await.get("x").expect("x owned"); + let owner = conn + .subscriptions + .lock() + .await + .get("x") + .expect("x owned") + .owner; assert_ne!(owner, stale); assert!(registered(&state, &conn, "x")); assert_eq!(state.pubsub.topic_refcount(&conn.tenant, topic).await, 1); @@ -2107,7 +2680,7 @@ mod tests { let (conn, mut send_rx) = lifecycle_conn(); let conn = Arc::new(conn); let (a, b) = (uuid::Uuid::new_v4(), uuid::Uuid::new_v4()); - let old = claim_live_subscription("x", &text_filters(), Some(&[a]), &conn, &state) + let old = claim_live_subscription("x", scoped(&text_filters(), Some(&[a])), &conn, &state) .await .expect("claim"); @@ -2120,8 +2693,7 @@ mod tests { let (filters, b_scope) = (text_filters(), [b]); let mut replacement = Box::pin(claim_live_subscription( "x", - &filters, - Some(&b_scope), + scoped(&filters, Some(&b_scope)), &conn, &state, )); @@ -2140,7 +2712,7 @@ mod tests { closed_frames(&mut send_rx), vec![format!(r#"["CLOSED","x","{QUERY_TIMED_OUT_CLOSED}"]"#)] ); - assert_eq!(conn.subscriptions.lock().await.get("x"), Some(&new)); + assert_eq!(token(&conn, "x").await, Some(new)); assert!(subscribed(&state, &conn, b) && !subscribed(&state, &conn, a)); let refcount = |c| { state @@ -2171,7 +2743,7 @@ mod tests { crate::state::CommunityConnectionControl::new(conn.cancel.clone()), ); let (a, b) = (uuid::Uuid::new_v4(), uuid::Uuid::new_v4()); - claim_live_subscription("x", &text_filters(), Some(&[a]), &conn, &state) + claim_live_subscription("x", scoped(&text_filters(), Some(&[a])), &conn, &state) .await .expect("claim"); @@ -2188,8 +2760,7 @@ mod tests { let (filters, b_scope) = (text_filters(), [b]); let mut replacement = Box::pin(claim_live_subscription( "x", - &filters, - Some(&b_scope), + scoped(&filters, Some(&b_scope)), &conn, &state, )); @@ -2203,7 +2774,7 @@ mod tests { revoke.await; let new = replacement.await.expect("claim"); - assert_eq!(conn.subscriptions.lock().await.get("x"), Some(&new)); + assert_eq!(token(&conn, "x").await, Some(new)); assert!(subscribed(&state, &conn, b) && !subscribed(&state, &conn, a)); let refcount = |c| { state @@ -2218,6 +2789,137 @@ mod tests { state.conn_manager.deregister(conn.conn_id); } + /// A revoke that evicts a holder a newer same-ID REQ is already replacing + /// retires the holder only: the client replaced it, so no `CLOSED` names + /// the ID, and the pending replacement keeps its token and still claims. + /// Mutation: drop the `replaced` check from the eviction → the + /// replacement's token is removed, its claim fails, and a `CLOSED` is + /// sent → RED. + #[tokio::test] + async fn revoke_of_a_replaced_holder_spares_the_pending_replacement() { + let state = crate::state::tests::test_state().await; + let (conn, mut send_rx) = lifecycle_conn(); + let conn = Arc::new(conn); + state.conn_manager.register( + conn.conn_id, + conn.send_tx.clone(), + conn.ctrl_tx.clone(), + tokio::sync::mpsc::channel(1).0, + None, + conn.cancel.clone(), + conn.tenant.community(), + Arc::clone(&conn.backpressure_count), + Arc::clone(&conn.subscriptions), + 3, + crate::state::CommunityConnectionControl::new(conn.cancel.clone()), + ); + let (a, b) = (uuid::Uuid::new_v4(), uuid::Uuid::new_v4()); + claim_live_subscription("x", scoped(&text_filters(), Some(&[a])), &conn, &state) + .await + .expect("claim"); + // The replacement is admitted and still in its access checks. + let pending = super::super::close::admit("x", &conn).await.expect("admit"); + + crate::handlers::side_effects::evict_conn_channel_subscriptions( + &conn.tenant, + &state, + a, + conn.conn_id, + ) + .await; + + let refcount = |c| { + state + .pubsub + .topic_refcount(&conn.tenant, EventTopic::Channel(c)) + }; + assert!( + !registered(&state, &conn, "x"), + "the revoked holder retires" + ); + assert_eq!(refcount(a).await, 0); + assert_eq!(token(&conn, "x").await, Some(pending)); + assert!(closed_frames(&mut send_rx).is_empty()); + + let claimed = claim_admitted_live( + "x", + pending, + scoped(&text_filters(), Some(&[b])), + &conn, + &state, + ) + .await; + assert_eq!(claimed, Some(pending)); + assert!(subscribed(&state, &conn, b)); + assert_eq!(refcount(b).await, 1); + state.conn_manager.deregister(conn.conn_id); + } + + /// A request admitted before a newer same-ID request, or before a + /// `CLOSE`, can no longer claim: an older REQ finishing its access checks + /// late must not replace the newer one, and a closed ID must stay closed. + /// Mutation: drop the owner check from `claim_admitted_live` → the stale + /// claim registers → RED. + #[tokio::test] + async fn superseded_or_closed_requests_cannot_claim() { + let state = crate::state::tests::test_state().await; + let (conn, mut send_rx) = lifecycle_conn(); + let conn = Arc::new(conn); + let (a, b) = (uuid::Uuid::new_v4(), uuid::Uuid::new_v4()); + let refcount = |c| { + state + .pubsub + .topic_refcount(&conn.tenant, EventTopic::Channel(c)) + }; + + let older = super::super::close::admit("x", &conn).await.expect("admit"); + let newer = super::super::close::admit("x", &conn).await.expect("admit"); + claim_admitted_live( + "x", + newer, + scoped(&text_filters(), Some(&[b])), + &conn, + &state, + ) + .await + .expect("the newest request claims"); + let stale = claim_admitted_live( + "x", + older, + scoped(&text_filters(), Some(&[a])), + &conn, + &state, + ) + .await; + assert_eq!(stale, None); + assert_eq!(token(&conn, "x").await, Some(newer)); + assert!(subscribed(&state, &conn, b) && !subscribed(&state, &conn, a)); + assert_eq!((refcount(a).await, refcount(b).await), (0, 1)); + + let pending = super::super::close::admit("y", &conn).await.expect("admit"); + super::super::close::handle_close("y".into(), Arc::clone(&conn), Arc::clone(&state)).await; + let late = claim_admitted_live( + "y", + pending, + scoped(&text_filters(), Some(&[a])), + &conn, + &state, + ) + .await; + let late_search = claim_admitted_search("y", pending, &conn, &state).await; + assert_eq!((late, late_search), (None, None)); + assert!(!registered(&state, &conn, "y")); + assert_eq!(refcount(a).await, 0); + assert!( + !super::super::close::close_if_owner("y", pending, Some("late"), &conn, &state).await + ); + assert_eq!( + closed_frames(&mut send_rx), + vec![r#"["CLOSED","y",""]"#.to_string()], + "only the CLOSE acknowledgement" + ); + } + /// Connection cleanup fences later claims: a detached REQ task resuming /// after it gets `None` and leaves nothing behind. #[tokio::test] @@ -2226,14 +2928,24 @@ mod tests { let (conn, mut send_rx) = lifecycle_conn(); let channel = uuid::Uuid::new_v4(); let topic = EventTopic::Channel(channel); - claim_live_subscription("live", &text_filters(), Some(&[channel]), &conn, &state) - .await - .expect("claim"); + claim_live_subscription( + "live", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await + .expect("claim"); conn.cancel.cancel(); super::super::close::release_connection_subscriptions(&conn, &state).await; - let late_live = - claim_live_subscription("late", &text_filters(), Some(&[channel]), &conn, &state).await; + let late_live = claim_live_subscription( + "late", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await; let late_search = claim_search_subscription("search", &conn, &state).await; assert_eq!((late_live, late_search), (None, None)); @@ -2267,6 +2979,7 @@ mod tests { let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::new_v4()); let cancel = tokio_util::sync::CancellationToken::new(); let conn = Arc::new(ConnectionState { + refusal_budget: Default::default(), conn_id: uuid::Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved(community, "t.local".to_string()), remote_addr: "127.0.0.1:1234".parse().expect("addr"), @@ -2285,7 +2998,7 @@ mod tests { }); // Claim, then fill the send buffer so the next `send` returns false. - let owner = claim_live_subscription("x", &text_filters(), None, &conn, &state) + let owner = claim_live_subscription("x", scoped(&text_filters(), None), &conn, &state) .await .expect("claim"); // Occupy the one slot so try_send returns Full on the CLOSED. @@ -2327,6 +3040,7 @@ mod tests { let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::new_v4()); let cancel = tokio_util::sync::CancellationToken::new(); let conn = Arc::new(ConnectionState { + refusal_budget: Default::default(), conn_id: uuid::Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved(community, "t.local".to_string()), remote_addr: "127.0.0.1:1234".parse().expect("addr"), @@ -2360,9 +3074,14 @@ mod tests { ); let channel = uuid::Uuid::new_v4(); - claim_live_subscription("x", &text_filters(), Some(&[channel]), &conn, &state) - .await - .expect("claim"); + claim_live_subscription( + "x", + scoped(&text_filters(), Some(&[channel])), + &conn, + &state, + ) + .await + .expect("claim"); // Fill the one send slot so the CLOSED restricted try_send returns Full. send_rx.try_recv().ok(); // drain any earlier messages @@ -2552,6 +3271,15 @@ mod tests { .expect("max_limit") as i64 } + #[test] + fn huge_filter_limit_is_clamped_to_page_max() { + let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::new_v4()); + let q = filter_to_query_params(&Filter::new().limit(usize::MAX), None, community); + assert_eq!(q.limit, Some(buzz_db::DEFAULT_MAX_PAGE_LIMIT)); + let q = filter_to_query_params(&Filter::new().limit(0), None, community); + assert_eq!(q.limit, Some(0)); + } + #[test] fn artifact_d_filter_is_pushed_before_limit() { let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::new_v4()); @@ -2647,7 +3375,11 @@ mod tests { fn count_fallback_fetches_one_extra_candidate() { let mut query = EventQuery::for_community(buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil())); - apply_count_fallback_limit(&mut query); + prepare_count_fallback(&mut query); + assert!( + query.exact_match, + "COUNT fallbacks never take the thread route" + ); assert_eq!(query.limit, Some(COUNT_FALLBACK_CANDIDATE_LIMIT + 1)); assert_eq!(query.max_limit, Some(COUNT_FALLBACK_CANDIDATE_LIMIT + 1)); assert!(!count_fallback_exceeded( @@ -2714,6 +3446,77 @@ mod tests { ); } + /// `#a` reaches SQL as an exact match for every filter shape, so reads + /// of references to an address are not starved by `LIMIT` and COUNT takes + /// the fast path. An empty `#a` matches nothing, as the post-filter does. + #[test] + fn a_tag_filters_reach_sql_and_are_fully_pushable() { + let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()); + let owner = "ab".repeat(32); + let addr = format!("30175:{owner}:persona"); + let other = format!("30175:{owner}:other"); + let parse = |v: serde_json::Value| -> Filter { serde_json::from_value(v).unwrap() }; + + let reactions = parse(serde_json::json!({"kinds": [7], "#a": [addr]})); + let q = filter_to_query_params(&reactions, None, community); + assert_eq!(q.a_tags, Some(vec![addr.clone()])); + assert!(q.tag_values.is_empty()); + assert!(filter_fully_pushable(&reactions)); + + let kindless = parse(serde_json::json!({"#a": [addr, other]})); + assert_eq!( + filter_to_query_params(&kindless, None, community).a_tags, + // Filter tag values are a set, so they arrive sorted. + Some(vec![other.clone(), addr.clone()]) + ); + assert!(filter_fully_pushable(&kindless)); + + let empty = parse(serde_json::json!({"kinds": [7], "#a": []})); + assert_eq!( + filter_to_query_params(&empty, None, community).a_tags, + Some(vec![]) + ); + let absent = parse(serde_json::json!({"kinds": [7]})); + assert_eq!( + filter_to_query_params(&absent, None, community).a_tags, + None + ); + + let with_k = parse(serde_json::json!({"kinds": [7], "#a": [addr], "#k": ["30175"]})); + assert!( + !filter_fully_pushable(&with_k), + "#k is still a post-filter, so COUNT must not take the fast path" + ); + } + + #[test] + fn empty_filter_sets_match_nothing_in_sql() { + let community = buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()); + let addr = format!("30175:{}:persona", "ab".repeat(32)); + for key in ["authors", "ids", "#e", "#p", "#d", "#h", "#k", "#t"] { + for with_a in [false, true] { + let mut json = serde_json::json!({"kinds": [7], key: []}); + if with_a { + json["#a"] = serde_json::json!([addr]); + } + let filter: Filter = serde_json::from_value(json).unwrap(); + assert_eq!( + filter_to_query_params(&filter, None, community).kinds, + Some(vec![]), + "empty {key} (with #a: {with_a}) must match nothing" + ); + } + } + + let empty_d_value: Filter = + serde_json::from_value(serde_json::json!({"kinds": [30175], "#d": [""]})).unwrap(); + assert_eq!( + filter_to_query_params(&empty_d_value, None, community).kinds, + Some(vec![30175]), + "an empty string is a real #d value, not an empty set" + ); + } + #[test] fn test_extract_channel_id_single_channel() { let channel_id = uuid::Uuid::new_v4(); @@ -3488,6 +4291,7 @@ mod tests { let subscriptions = Arc::new(tokio::sync::Mutex::new(HashMap::new())); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved(community, "test.local".to_string()), remote_addr: "127.0.0.1:1234".parse().unwrap(), @@ -3572,7 +4376,7 @@ mod tests { // Arms `before_liveness_req` — the hook immediately before `acquire_effect()` // in the `filters_are_huddle_liveness_only` branch of `handle_req`. Dispatches // `handle_req` with a KIND_HUDDLE_LIVENESS filter with an authorized `#h` channel - // (pre-populated in accessible_channels_cache so no DB call is needed) and a live + // (seeded into the accessible-channel caches so no DB call is needed) and a live // gate. Waits for the hook, fires expiry, then releases. The handler must return // CLOSED "authorization denied" and the `liveness_query_counter` must remain 0 — // proving the permit gate stopped execution before the `huddle_started_links` DB @@ -3617,6 +4421,7 @@ mod tests { let subscriptions = Arc::new(tokio::sync::Mutex::new(HashMap::new())); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved(community, "test.local".to_string()), remote_addr: "127.0.0.1:1234".parse().unwrap(), @@ -3644,13 +4449,11 @@ mod tests { let state = crate::state::tests::test_state().await; - // Pre-populate the accessible_channels_cache so the handle_req + // Seed the accessible-channel caches so the handle_req // membership check succeeds without a real DB connection. let channel_uuid = Uuid::from_u128(0xDEAD_BEEF_CAFE_1500); let pubkey_bytes = keys.public_key().to_bytes().to_vec(); - state - .accessible_channels_cache - .insert((community, pubkey_bytes), vec![channel_uuid]); + state.seed_accessible_channels(community, pubkey_bytes, vec![channel_uuid]); // Register the liveness query counter — proves the DB call boundary. let query_count = crate::nip_fi_test_hooks::liveness_query_counter::register(community); @@ -3660,7 +4463,7 @@ mod tests { // KIND_HUDDLE_LIVENESS with #h = channel_uuid: // - `filters_are_huddle_liveness_only` → true (kind-only check) // - `extract_channel_ids_from_filters_limited` → Some([channel_uuid]) - // - accessible_channels_cache hit → channel is authorized + // - accessible-channel cache hit → channel is authorized // - `authorized_requested_channels` = Some([channel_uuid]) → non-empty // - handler enters the liveness branch, reaches before_liveness_req hook let h_tag = nostr::SingleLetterTag::lowercase(nostr::Alphabet::H); @@ -3754,6 +4557,7 @@ mod tests { let (terminal_ctrl_tx, _terminal_ctrl_rx) = mpsc::channel::(1); let subscriptions = Arc::new(tokio::sync::Mutex::new(HashMap::new())); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved(community, "test.local".to_string()), remote_addr: "127.0.0.1:1234".parse().unwrap(), @@ -3779,9 +4583,7 @@ mod tests { community_control: crate::state::CommunityConnectionControl::new(cancel.clone()), }); let state = crate::state::tests::test_state().await; - state - .accessible_channels_cache - .insert((community, keys.public_key().to_bytes().to_vec()), vec![]); + state.seed_accessible_channels(community, keys.public_key().to_bytes().to_vec(), vec![]); let mut filter = Filter::new().kind(nostr::Kind::TextNote).limit(1); let (arrived_rx, _release) = if search { @@ -3897,6 +4699,7 @@ mod tests { let (terminal_ctrl_tx, _terminal_ctrl_rx) = mpsc::channel::(1); let subscriptions = Arc::new(tokio::sync::Mutex::new(HashMap::new())); let conn = Arc::new(crate::connection::ConnectionState { + refusal_budget: Default::default(), conn_id: Uuid::new_v4(), tenant: buzz_core::tenant::TenantContext::resolved(community, "test.local".to_string()), remote_addr: "127.0.0.1:1234".parse().unwrap(), @@ -3922,8 +4725,9 @@ mod tests { community_control: crate::state::CommunityConnectionControl::new(cancel.clone()), }); let channels = [Uuid::new_v4(), Uuid::new_v4()]; - state.accessible_channels_cache.insert( - (community, keys.public_key().to_bytes().to_vec()), + state.seed_accessible_channels( + community, + keys.public_key().to_bytes().to_vec(), channels.to_vec(), ); let filters: Vec = channels @@ -3986,6 +4790,8 @@ mod tests { } mod postgres_tests { + use super::*; + #[tokio::test] #[ignore = "requires Postgres"] async fn w3_b2_req_barrier_expiry_mid_flight_blocks_subscription_registration() { @@ -3998,5 +4804,74 @@ mod tests { async fn history_timeout_retirement_survives_expiry() { super::history_timeout_retirement_survives_expiry_body().await; } + + /// NIP-CW keeps any `#p` filter off the narrowed thread route. Two + /// `#p` values never reach SQL as `p_tag_hex`, so without the adapter's + /// mark this read took the route and lost a bare reference to the root. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn multi_p_thread_filter_keeps_nip01_results() { + use nostr::{EventBuilder, Keys, Kind, Tag}; + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .expect("connect"); + let db = buzz_db::Db::from_pool(pool.clone()); + let community_uuid = uuid::Uuid::new_v4(); + sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)") + .bind(community_uuid) + .bind(format!("multi-p-{}.example", community_uuid.simple())) + .execute(&pool) + .await + .expect("insert community"); + let channel = uuid::Uuid::new_v4(); + sqlx::query( + "INSERT INTO channels (id, community_id, name, created_by) VALUES ($1, $2, $3, $4)", + ) + .bind(channel) + .bind(community_uuid) + .bind(format!("multi-p-{}", channel.simple())) + .bind(vec![7_u8; 32]) + .execute(&pool) + .await + .expect("insert channel"); + let community = buzz_core::tenant::CommunityId::from_uuid(community_uuid); + let h = Tag::parse(["h", &channel.to_string()]).expect("h tag"); + let (author, alice, bob) = (Keys::generate(), Keys::generate(), Keys::generate()); + let root = EventBuilder::new(Kind::Custom(9), "root") + .tags([h.clone()]) + .sign_with_keys(&author) + .expect("sign root"); + let root_hex = root.id.to_hex(); + // Names the root only in a bare `e` tag, so it has no thread row. + let bare = EventBuilder::new(Kind::Custom(9), "bare reference") + .tags([ + h, + Tag::parse(["e", &root_hex]).expect("e tag"), + Tag::public_key(alice.public_key()), + ]) + .sign_with_keys(&author) + .expect("sign bare"); + for event in [&root, &bare] { + db.insert_event(community, event, Some(channel)) + .await + .expect("insert event"); + } + + let filter = Filter::new() + .kinds([Kind::Custom(9), Kind::Custom(40002)]) + .custom_tag(SingleLetterTag::lowercase(Alphabet::H), channel.to_string()) + .custom_tag(SingleLetterTag::lowercase(Alphabet::E), root_hex) + .pubkeys([alice.public_key(), bob.public_key()]); + let params = filter_to_query_params(&filter, Some(channel), community); + let ids: Vec<_> = db + .query_events_routed("req_historical", ¶ms) + .await + .expect("query") + .into_iter() + .filter(|stored| filters_match(std::slice::from_ref(&filter), stored)) + .map(|stored| stored.event.id) + .collect(); + assert_eq!(ids, vec![bare.id], "two-value #p reads match NIP-01"); + } } } diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index 3fa7036b401..cc0c10ca3c7 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -11,7 +11,7 @@ use buzz_core::kind::{ KIND_DM_VISIBILITY, KIND_GIT_REPO_ANNOUNCEMENT, KIND_IA_ARCHIVED, KIND_IA_ARCHIVED_LIST, KIND_IA_UNARCHIVED, KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, KIND_NIP29_GROUP_ADMINS, KIND_NIP29_GROUP_MEMBERS, KIND_NIP29_GROUP_METADATA, - KIND_NIP43_MEMBERSHIP_LIST, KIND_REACTION, KIND_THREAD_SUMMARY, + KIND_NIP43_MEMBERSHIP_LIST, KIND_REACTION, KIND_THREAD_SUMMARY, KIND_VERIFIED_PROFILE, }; use buzz_core::StoredEvent; use buzz_db::channel::{MemberRecord, MemberRole}; @@ -159,6 +159,43 @@ pub(crate) async fn apply_kick_live_side_effects( return Err(e.into()); } } + + // The removal is committed: refresh the channel's discovery roster, then + // tell the kicked member, as a kind:9001 removal does. The notice tells a + // client to re-read that roster, so a failed refresh returns before it and + // the moderation driver retries the action. A channel deleted since the + // kick has no roster to refresh: that is convergence, once its discovery + // is gone. A recovery re-drive repeats both; the refresh is replaceable + // and a repeated notice is a harmless hint. A failed notice is logged and + // does not undo the kick. + if let Err(e) = emit_group_discovery_events(tenant, state, channel_id).await { + if !matches!( + e.downcast_ref::(), + Some(buzz_db::DbError::ChannelNotFound(_)) + ) { + return Err(e); + } + state + .db + .soft_delete_discovery_events( + tenant.community(), + channel_id, + state.relay_keypair.public_key().as_bytes(), + ) + .await?; + } + if let Err(e) = emit_membership_notification( + tenant, + state, + channel_id, + target_pubkey, + state.relay_keypair.public_key().as_bytes(), + KIND_MEMBER_REMOVED_NOTIFICATION, + ) + .await + { + warn!(channel = %channel_id, error = %e, "membership notification emission failed"); + } Ok(()) } @@ -231,7 +268,8 @@ async fn disable_departed_member_workflows( } /// Close every live channel-scoped subscription on `conn_id`, removing them from -/// the connection's local map and sending `CLOSED restricted` for each. Runs +/// the connection's local map and sending `CLOSED restricted` for each; a +/// holder that a pending same-ID REQ is replacing is only retired. Runs /// under the connection's lifecycle lock so a concurrent same-ID claim is /// either fully before (and revoked) or fully after (and untouched). pub(crate) async fn evict_conn_channel_subscriptions( @@ -252,17 +290,40 @@ pub(crate) async fn evict_conn_channel_subscriptions( channel_id, ); for update in removed { + // A newer same-ID REQ that has not claimed yet owns the ID and is + // replacing this holder, so the client already treats the holder as + // gone (NIP-01): retire it without touching the newer request's token + // or sending a frame for the ID. + let replaced = conn_subscriptions + .get(&update.sub_id) + .is_some_and(|held| !held.claimed); // A multi-channel sub keeps its other channels (and its map token). state .pubsub .release_topic(tenant, buzz_pubsub::EventTopic::Channel(channel_id)) .await; - if update.removed { + // A sync cannot keep its other channels: its set is no longer exact, + // so the whole sync ends with a resync (NIP-AR Sync rule 9). + let sync = state.artifact_syncs.remove(conn_id, &update.sub_id); + if sync && !update.removed { + if let Some(rest) = state + .sub_registry + .remove_subscription(conn_id, &update.sub_id) + { + super::close::release_scope_topics(state, tenant, &rest.scope).await; + } + } + if (update.removed || sync) && !replaced { conn_subscriptions.remove(&update.sub_id); - if !state.conn_manager.send_to( - conn_id, - RelayMessage::closed(&update.sub_id, "restricted: channel access revoked"), - ) { + let reason = if sync { + "resync: channel access changed" + } else { + "restricted: channel access revoked" + }; + if !state + .conn_manager + .send_to(conn_id, RelayMessage::closed(&update.sub_id, reason)) + { // Terminal frame lost — cancel so the subscription is not // silently orphaned on a congested connection. state.conn_manager.cancel_conn(conn_id); @@ -335,13 +396,14 @@ pub async fn handle_side_effects( match kind { 0 => handle_kind0_profile(tenant, event, state).await, 5 => handle_standard_deletion_event(tenant, event, state).await, - // kind:9000 belongs to the put-user path in ingest, which reports - // each person's result. - 9000 => Err(anyhow::anyhow!("kind:9000 requires apply_put_user")), + // kind:9000 belongs to the atomic put-user path in ingest, which + // reports each person's result. + 9000 => Err(anyhow::anyhow!("kind:9000 requires persist_put_user")), 9001 => handle_remove_user(tenant, event, state).await, // kind:9002 belongs to the atomic persistence path in ingest. 9002 => Err(anyhow::anyhow!("kind:9002 requires atomic persistence")), - 9005 => handle_delete_event_side_effect(tenant, event, state).await, + // kind:9005 belongs to the atomic deletion path in ingest. + 9005 => Err(anyhow::anyhow!("kind:9005 requires persist_deletion")), 9007 => handle_create_group(tenant, event, state).await, 9008 => handle_delete_group(tenant, event, state).await, 9009 => { @@ -382,6 +444,10 @@ pub(crate) async fn authorized_standard_deletion_target( else { return Ok(None); }; + // The profile's p tag names its subject, not an author with deletion rights. + if event_kind_u32(&target.event) == KIND_VERIFIED_PROFILE { + return Ok(None); + } let author = effective_message_author(&target.event, &state.relay_keypair.public_key()); let authorized = author == actor || state @@ -455,6 +521,9 @@ pub async fn validate_standard_deletion_event( return Err(anyhow::anyhow!("invalid a-tag format")); } if let Ok(target_kind) = parts[0].parse() { + if target_kind == KIND_VERIFIED_PROFILE { + anyhow::bail!(DELETION_TARGET_DENIED); + } check_deletion_privacy_k_tag(event, target_kind)?; } let target_pubkey_bytes = @@ -516,6 +585,26 @@ fn check_deletion_privacy_k_tag(event: &Event, target_kind: u32) -> anyhow::Resu Ok(()) } +/// True when `actor` may change a channel's privileged metadata: a channel +/// owner or admin, or the owning human of an active owner-role agent in the +/// channel, even when that human is not a member (this diverges from +/// kind:9001 intentionally). +async fn actor_has_channel_authority( + state: &Arc, + community_id: buzz_core::CommunityId, + channel_id: Uuid, + actor_bytes: &[u8], +) -> anyhow::Result { + let members = state.db.get_members(community_id, channel_id).await?; + if members + .iter() + .any(|m| m.pubkey == actor_bytes && (m.role == "owner" || m.role == "admin")) + { + return Ok(true); + } + actor_owns_any_owner_agent(state, community_id, &members, actor_bytes).await +} + /// Returns `true` if `actor_bytes` is the NIP-OA owner of **any** active owner-role /// member in `members`. Used by kind:9002 and kind:9008 to authorize the owning /// human of a channel's agent-owner(s) even when the human is not a channel member. @@ -597,7 +686,7 @@ pub async fn validate_admin_event( match kind { // Ingest validates kind:9000 with `validate_put_user`, which keeps - // each person's result for `apply_put_user`. + // each person's result for `persist_put_user`. 9000 => Err(anyhow::anyhow!("kind:9000 requires validate_put_user")), 9001 => { // REMOVE_USER: self-remove allowed unless actor is the last owner; removing others requires owner/admin @@ -631,25 +720,13 @@ pub async fn validate_admin_event( } 9002 => { // EDIT_METADATA: require at least one recognized metadata tag. - const RECOGNIZED_TAGS: &[&str] = &[ - "name", - "about", - "archived", - "topic", - "purpose", - "visibility", - "ttl", - "t", - "join_role", - "unlisted", - ]; let has_recognized = event .tags .iter() - .any(|t| RECOGNIZED_TAGS.contains(&t.kind().to_string().as_str())); + .any(|t| is_metadata_tag(&t.kind().to_string())); if !has_recognized { return Err(anyhow::anyhow!( - "kind:9002 must include at least one metadata tag (name, about, archived, topic, purpose, visibility, ttl, t, join_role, unlisted)" + "kind:9002 must include at least one metadata tag (name, about, archived, topic, purpose, visibility, ttl, t, join_role, unlisted, auto_join)" )); } @@ -724,6 +801,48 @@ pub async fn validate_admin_event( } } + // `auto_join` is a community setting, not a channel one: the + // relay joins every new community member into the channel. So it + // takes the actor's *relay* role (owner or admin), not a channel + // role, and the actor need not be a channel member. Only a + // stream channel can be a default channel; the open-and- + // unarchived requirement (just open, for `false`) is decided in + // the write, under the channel row lock, on the state the event + // leaves behind. + let mut sets_auto_join = false; + for t in event.tags.iter() { + if t.kind().to_string() == "auto_join" { + match t.content() { + Some("true") | Some("false") => sets_auto_join = true, + Some(v) => { + return Err(anyhow::anyhow!( + "invalid auto_join value: {v} (must be \"true\" or \"false\")" + )); + } + None => { + return Err(anyhow::anyhow!("auto_join tag must have a value")); + } + } + } + } + if sets_auto_join { + let relay_role = state + .db + .get_relay_member(tenant.community(), &event.pubkey.to_hex()) + .await? + .map(|m| m.role); + if !matches!(relay_role.as_deref(), Some("owner" | "admin")) { + return Err(anyhow::anyhow!( + "actor not authorized: auto_join requires a relay owner or admin" + )); + } + if channel.channel_type != buzz_db::channel::ChannelType::Stream.as_str() { + return Err(anyhow::anyhow!( + "auto_join is only available on stream channels" + )); + } + } + // Validate ttl values before storage. Empty string clears the TTL // (channel becomes permanent); any other value must parse as a // positive integer number of seconds. A bare tag with no value is @@ -755,44 +874,36 @@ pub async fn validate_admin_event( } // name/about/archived/visibility/ttl/labels/join_role/unlisted - // require owner/admin; - // topic/purpose allow any member who may post. - let has_privileged_tag = event.tags.iter().any(|t| { - let k = t.kind().to_string(); - k == "name" - || k == "about" - || k == "archived" - || k == "visibility" - || k == "ttl" - || k == "t" - || k == "join_role" - || k == "unlisted" - }); + // require owner/admin; topic/purpose allow any member who may + // post; auto_join was decided above by relay role, so an event + // carrying only that tag needs neither. + let has_member_tag = event + .tags + .iter() + .any(|t| MEMBER_METADATA_TAGS.contains(&t.kind().to_string().as_str())); + let has_privileged_tag = event + .tags + .iter() + .any(|t| PRIVILEGED_METADATA_TAGS.contains(&t.kind().to_string().as_str())); if has_privileged_tag { - let members = state.db.get_members(tenant.community(), channel_id).await?; - let actor_member = members.iter().find(|m| m.pubkey == actor_bytes); - match actor_member { - Some(m) if m.role == "owner" || m.role == "admin" => Ok(()), - _ => { - // Allow the owning human of any active owner-role agent in the - // channel, even when the human is not a channel member — - // diverges from kind:9001 intentionally. - if actor_owns_any_owner_agent( - state, - tenant.community(), - &members, - &actor_bytes, - ) - .await? - { - return Ok(()); - } - Err(anyhow::anyhow!( - "actor not authorized for name/about/archived/visibility/ttl/label/join_role/unlisted changes" - )) - } + if actor_has_channel_authority(state, tenant.community(), channel_id, &actor_bytes) + .await? + { + return Ok(()); } - } else { + // A relay operator may rename a listed channel, so that + // duplicate names can be repaired through this path + // (scripts/maintenance/rename_duplicate_listed_channel_names.sh). + // Every other privileged change still needs a channel owner + // or admin. The store checks "listed" again under the row + // lock (`ChannelMetadataEdit::operator_rename`). + if operator_may_rename(state, event, &channel).await? { + return Ok(()); + } + Err(anyhow::anyhow!( + "actor not authorized for name/about/archived/visibility/ttl/label/join_role/unlisted changes" + )) + } else if has_member_tag { // topic/purpose: any member whose role may post (never a // guest). let is_member = state @@ -819,6 +930,15 @@ pub async fn validate_admin_event( } else { Err(anyhow::anyhow!("only members can change topic or purpose")) } + } else if sets_auto_join { + Ok(()) + } else { + // Every recognized tag must be authorized by one of the arms + // above; a tag added to `is_metadata_tag` but to no rule + // is refused rather than accepted with no authorization. + Err(anyhow::anyhow!( + "kind:9002 metadata tag has no authorization rule" + )) } } 9005 => { @@ -931,7 +1051,7 @@ pub async fn emit_system_message( .db .insert_event(tenant.community(), &event, Some(channel_id)) .await - .map_err(|e| anyhow::anyhow!("system message insert failed: {e}"))?; + .map_err(|e| anyhow::anyhow!("system message insert failed: {}", e.kind()))?; fan_out_system_message(tenant, state, channel_id, &event).await; Ok(()) @@ -981,6 +1101,11 @@ async fn fan_out_system_message( /// incremented, so the emitted summary is exact even under concurrent /// replies/deletes (newest `created_at` wins client-side). /// +/// Coalesced per root through [`AppState::thread_summary_refresh`]: a quiet +/// thread emits at once, while a busy one emits at most once per +/// [`crate::state::THREAD_SUMMARY_REFRESH_INTERVAL`] per pod, with a trailing +/// emit that reads state committed after the last mutation in the burst. +/// /// Spawned: runs after the triggering write committed and must not add /// latency to the ingest acknowledgement, mirroring /// `dispatch_persistent_event`. @@ -990,86 +1115,178 @@ pub fn emit_live_thread_summary( channel_id: Uuid, root_id: Vec, ) { + let key = (tenant.community(), root_id.clone()); let tenant = tenant.clone(); - let state = Arc::clone(state); - tokio::spawn(async move { - let summary = match state - .db - .get_thread_summary(tenant.community(), &root_id) - .await - { - Ok(Some(summary)) => summary, - // Root has no thread row — nothing to summarize (e.g., the root - // itself was just deleted). - Ok(None) => return, - Err(e) => { - warn!( - root = %hex::encode(&root_id), - "live thread summary lookup failed: {e}" - ); - return; - } - }; + let task_state = Arc::clone(state); + state.thread_summary_refresh.request(key, move || { + publish_live_thread_summary( + tenant.clone(), + Arc::clone(&task_state), + channel_id, + root_id.clone(), + ) + }); +} - let root_hex = hex::encode(&root_id); - // Same tags/content shape as the channel-window page overlay in - // `api/bridge.rs` — one contract, two delivery doors. - let content = serde_json::json!({ - "reply_count": summary.reply_count, - "descendant_count": summary.descendant_count, - "last_reply_at": summary.last_reply_at.map(|t| t.timestamp()), - "participants": summary.participants.iter().map(hex::encode).collect::>(), - }); - let tags = [ - Tag::parse(["e", &root_hex]), - Tag::parse(["d", &root_hex]), - Tag::parse(["h", &channel_id.to_string()]), - ]; - let mut parsed = Vec::with_capacity(tags.len()); - for tag in tags { - match tag { - Ok(tag) => parsed.push(tag), - Err(e) => { - warn!(root = %root_hex, "live thread summary tag failed: {e}"); - return; - } - } +async fn publish_live_thread_summary( + tenant: TenantContext, + state: Arc, + channel_id: Uuid, + root_id: Vec, +) { + let summary = match state + .db + .get_thread_summary(tenant.community(), &root_id) + .await + { + Ok(Some(summary)) => summary, + // Root has no thread row — nothing to summarize (e.g., the root + // itself was just deleted). + Ok(None) => return, + Err(e) => { + warn!( + root = %hex::encode(&root_id), + "live thread summary lookup failed: {e}" + ); + return; } - let event = match EventBuilder::new( - Kind::Custom(KIND_THREAD_SUMMARY as u16), - content.to_string(), - ) - .tags(parsed) - .sign_with_keys(&state.relay_keypair) - { - Ok(event) => event, + }; + + let root_hex = hex::encode(&root_id); + // Same tags/content shape as the channel-window page overlay in + // `api/bridge.rs` — one contract, two delivery doors. + let content = serde_json::json!({ + "reply_count": summary.reply_count, + "descendant_count": summary.descendant_count, + "last_reply_at": summary.last_reply_at.map(|t| t.timestamp()), + "participants": summary.participants.iter().map(hex::encode).collect::>(), + }); + let tags = [ + Tag::parse(["e", &root_hex]), + Tag::parse(["d", &root_hex]), + Tag::parse(["h", &channel_id.to_string()]), + ]; + let mut parsed = Vec::with_capacity(tags.len()); + for tag in tags { + match tag { + Ok(tag) => parsed.push(tag), Err(e) => { - warn!(root = %root_hex, "live thread summary sign failed: {e}"); + warn!(root = %root_hex, "live thread summary tag failed: {e}"); return; } - }; - - // Redis before local fan-out so subscribers on other relay pods - // receive it too, matching `dispatch_persistent_event`. - state.mark_local_event(tenant.community(), &event.id); - if let Err(e) = state - .pubsub - .publish_event(&tenant, EventTopic::Channel(channel_id), &event) - .await - { - state - .local_event_ids - .invalidate(&(tenant.community(), event.id.to_bytes())); - warn!(root = %root_hex, "live thread summary Redis publish failed: {e}"); } - let stored = StoredEvent::new(event, Some(channel_id)); - crate::handlers::event::fan_out_event_to_local_subscribers( - &state, - tenant.community(), - &stored, - ) + } + let event = match EventBuilder::new( + Kind::Custom(KIND_THREAD_SUMMARY as u16), + content.to_string(), + ) + .tags(parsed) + .sign_with_keys(&state.relay_keypair) + { + Ok(event) => event, + Err(e) => { + warn!(root = %root_hex, "live thread summary sign failed: {e}"); + return; + } + }; + + // Redis before local fan-out so subscribers on other relay pods + // receive it too, matching `dispatch_persistent_event`. + state.mark_local_event(tenant.community(), &event.id); + if let Err(e) = state + .pubsub + .publish_event(&tenant, EventTopic::Channel(channel_id), &event) + .await + { + state + .local_event_ids + .invalidate(&(tenant.community(), event.id.to_bytes())); + warn!(root = %root_hex, "live thread summary Redis publish failed: {e}"); + } + let stored = StoredEvent::new(event, Some(channel_id)); + crate::handlers::event::fan_out_event_to_local_subscribers(&state, tenant.community(), &stored) .await; - }); +} + +/// Test-only barrier at the point a membership notice is sent: a test parks +/// the producer there, reads what a client would read on receipt, then lets +/// it continue. It can also pin the notices' clock. Keyed by recipient so +/// parallel tests do not interfere. +#[cfg(test)] +pub(crate) mod notice_barrier { + use std::collections::HashMap; + use std::sync::{Mutex, OnceLock}; + use tokio::sync::{mpsc, oneshot}; + + use uuid::Uuid; + + /// A parked notice: its channel, and the handle that lets it continue. + pub(crate) type Parked = (Uuid, oneshot::Sender<()>); + type Waiters = Mutex, mpsc::UnboundedSender>>; + + fn waiters() -> &'static Waiters { + static WAITERS: OnceLock = OnceLock::new(); + WAITERS.get_or_init(Default::default) + } + + /// Parks every notice to one recipient while held; dropping it removes + /// the recipient's waiter and clock pin. + pub(crate) struct Barrier { + recipient: Vec, + parked: mpsc::UnboundedReceiver, + } + + impl Barrier { + /// The next notice to reach the barrier, with its release handle. + pub(crate) async fn next(&mut self) -> Option { + self.parked.recv().await + } + + /// Sign every later notice to the recipient at `created_at`, as if all + /// were sent in the same second. + pub(crate) fn pin_created_at(&self, created_at: u64) { + pins() + .lock() + .unwrap() + .insert(self.recipient.clone(), created_at); + } + } + + impl Drop for Barrier { + fn drop(&mut self) { + waiters().lock().unwrap().remove(&self.recipient); + pins().lock().unwrap().remove(&self.recipient); + } + } + + /// Park every notice to `recipient` until the returned barrier drops. + pub(crate) fn install(recipient: &[u8]) -> Barrier { + let (tx, parked) = mpsc::unbounded_channel(); + waiters().lock().unwrap().insert(recipient.to_vec(), tx); + Barrier { + recipient: recipient.to_vec(), + parked, + } + } + + fn pins() -> &'static Mutex, u64>> { + static PINS: OnceLock, u64>>> = OnceLock::new(); + PINS.get_or_init(Default::default) + } + + pub(super) fn pinned_created_at(recipient: &[u8]) -> Option { + pins().lock().unwrap().get(recipient).copied() + } + + pub(super) async fn reached(channel_id: Uuid, recipient: &[u8]) { + let waiter = waiters().lock().unwrap().get(recipient).cloned(); + if let Some(waiter) = waiter { + let (release, released) = oneshot::channel(); + if waiter.send((channel_id, release)).is_ok() { + let _ = released.await; + } + } + } } /// Emit a relay-signed membership notification event stored globally (channel_id = None). @@ -1089,6 +1306,30 @@ pub async fn emit_membership_notification( target_pubkey: &[u8], actor_pubkey: &[u8], notification_kind: u32, +) -> anyhow::Result<()> { + emit_membership_notification_tagged( + tenant, + state, + channel_id, + target_pubkey, + actor_pubkey, + notification_kind, + &[], + ) + .await +} + +/// [`emit_membership_notification`] with `extra_tags` after the standard +/// ones. A tag that differs per cause, such as a moderation source, keeps two +/// notices in the same second from sharing one event id. +pub(crate) async fn emit_membership_notification_tagged( + tenant: &TenantContext, + state: &Arc, + channel_id: Uuid, + target_pubkey: &[u8], + actor_pubkey: &[u8], + notification_kind: u32, + extra_tags: &[Tag], ) -> anyhow::Result<()> { // No channel row means no type to tag. Send nothing rather than an // untagged notice, which every client would treat as a legacy type. @@ -1108,12 +1349,14 @@ pub async fn emit_membership_notification( target_pubkey, actor_pubkey, notification_kind, + extra_tags, ) .await } /// [`emit_membership_notification`] for a caller that already read the /// channel's type, such as a kind:9000 notifying several people. +#[allow(clippy::too_many_arguments)] async fn emit_typed_membership_notification( tenant: &TenantContext, state: &Arc, @@ -1122,6 +1365,7 @@ async fn emit_typed_membership_notification( target_pubkey: &[u8], actor_pubkey: &[u8], notification_kind: u32, + extra_tags: &[Tag], ) -> anyhow::Result<()> { let target_hex = hex::encode(target_pubkey); let actor_hex = hex::encode(actor_pubkey); @@ -1151,8 +1395,18 @@ async fn emit_typed_membership_notification( let type_tag = Tag::parse([buzz_core::filter::NOTICE_CHANNEL_TYPE_TAG, channel_type]) .map_err(|e| anyhow::anyhow!("failed to build channel type tag: {e}"))?; - let event = EventBuilder::new(Kind::Custom(notification_kind as u16), content) + #[cfg(test)] + notice_barrier::reached(channel_id, target_pubkey).await; + + let builder = EventBuilder::new(Kind::Custom(notification_kind as u16), content) .tags([p_tag, h_tag, type_tag]) + .tags(extra_tags.iter().cloned()); + #[cfg(test)] + let builder = match notice_barrier::pinned_created_at(target_pubkey) { + Some(at) => builder.custom_created_at(nostr::Timestamp::from(at)), + None => builder, + }; + let event = builder .sign_with_keys(&state.relay_keypair) .map_err(|e| anyhow::anyhow!("failed to sign membership notification: {e}"))?; @@ -1160,7 +1414,8 @@ async fn emit_typed_membership_notification( let (stored, was_inserted) = state .db .insert_event(tenant.community(), &event, None) - .await?; + .await + .map_err(|e| anyhow::anyhow!("membership notification insert failed: {}", e.kind()))?; if !was_inserted { return Ok(()); } @@ -1201,41 +1456,116 @@ async fn emit_typed_membership_notification( Ok(()) } -/// Sign, store (replacing previous), and fan-out a single addressable discovery event. +/// kind:9002 tags that only a channel owner or admin may change. +const PRIVILEGED_METADATA_TAGS: &[&str] = &[ + "name", + "about", + "archived", + "visibility", + "ttl", + "t", + "join_role", + "unlisted", +]; + +/// kind:9002 tags that any member who may post may change. +const MEMBER_METADATA_TAGS: &[&str] = &["topic", "purpose"]; + +/// kind:9002 tags that a relay owner or admin may change, whatever their +/// channel role. +const RELAY_ROLE_METADATA_TAGS: &[&str] = &["auto_join"]; + +/// True when `kind` is a kind:9002 tag that changes channel metadata. +fn is_metadata_tag(kind: &str) -> bool { + PRIVILEGED_METADATA_TAGS.contains(&kind) + || MEMBER_METADATA_TAGS.contains(&kind) + || RELAY_ROLE_METADATA_TAGS.contains(&kind) +} + +/// True when a relay operator sends `event` and it only renames `channel`, a +/// listed channel: open, not unlisted, a stream or forum, and not deleted. +/// Those are the channels whose names must be unique, so this is the repair +/// path for a duplicate name and grants nothing else. +async fn operator_may_rename( + state: &crate::state::AppState, + event: &Event, + channel: &buzz_db::channel::ChannelRecord, +) -> anyhow::Result { + let listed = channel.visibility == "open" + && !channel.unlisted + && matches!(channel.channel_type.as_str(), "stream" | "forum") + && channel.deleted_at.is_none(); + Ok(listed + && is_rename_only(event) + && actor_is_relay_operator(state, event.pubkey.to_bytes()).await?) +} + +/// True when the only metadata a kind:9002 changes is the channel name. +fn is_rename_only(event: &Event) -> bool { + let mut changes = event + .tags + .iter() + .map(|t| t.kind().to_string()) + .filter(|kind| is_metadata_tag(kind)); + changes.all(|kind| kind == "name") && event.tags.iter().any(|t| t.kind().to_string() == "name") +} + +/// True when `pubkey` holds the relay operator role. A roster lookup failure +/// is an error, never "not an operator". +async fn actor_is_relay_operator( + state: &crate::state::AppState, + pubkey: [u8; 32], +) -> anyhow::Result { + crate::api::admin::is_relay_operator(state, pubkey) + .await + .map_err(|e| anyhow::anyhow!("relay staff lookup failed: {}", e.message)) +} + +/// Sign, store (replacing previous), and fan-out one of a channel's +/// relay-signed kind:39000/39001 events, with the tags `build_tags` makes +/// from the channel and its members. +/// +/// The inputs, the timestamp and the replacement all sit behind the event's +/// replacement lock (see `LockedGroupStateSnapshot`). Read outside it, an +/// auto-join that read `auto_join` before a racing kind:9002 cleared it +/// stored its snapshot after the edit's, at the same or a later second, and +/// the stale tag stayed live. async fn emit_addressable_discovery_event( tenant: &TenantContext, state: &Arc, channel_id: Uuid, kind: u32, - tags: Vec, relay_pubkey_hex: &str, + build_tags: impl FnOnce( + &buzz_db::channel::ChannelRecord, + &[MemberRecord], + ) -> anyhow::Result>, ) -> anyhow::Result<()> { - // Ensure the new event's created_at is strictly greater than any existing event - // of the same (kind, pubkey, channel_id). Without this, rapid successive updates - // (e.g. set topic then set purpose in the same second) can produce events with - // identical created_at, causing the second to be rejected by stale-write protection - // (NIP-16 tiebreaker: lower event ID wins, which is random). + #[cfg(test)] + crate::nip_fi_test_hooks::before_group_state_lock(tenant.community()).await; + let snapshot = state + .db + .lock_group_state_snapshot( + tenant.community(), + channel_id, + kind as i32, + &state.relay_keypair.public_key().to_bytes(), + ) + .await?; + #[cfg(test)] + crate::nip_fi_test_hooks::after_group_state_read(tenant.community()).await; + let tags = build_tags(&snapshot.channel, &snapshot.members)?; + // One second past the live event, so the replacement never loses a + // same-second tiebreak (NIP-16: lower event ID wins, which is random). let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs(); - let min_ts = { - let existing = state - .db - .query_events_for_event_write(&buzz_db::event::EventQuery { - kinds: Some(vec![kind as i32]), - channel_id: Some(channel_id), - limit: Some(1), - ..buzz_db::event::EventQuery::for_community(tenant.community()) - }) - .await - .unwrap_or_default(); - existing - .first() - .map(|e| e.event.created_at.as_secs() + 1) - .unwrap_or(now) - }; - let ts = now.max(min_ts); + let ts = snapshot + .latest_created_at + .map(|timestamp| timestamp + 1) + .unwrap_or(now) + .max(now); let event = EventBuilder::new(Kind::Custom(kind as u16), "") .tags(tags) @@ -1243,10 +1573,10 @@ async fn emit_addressable_discovery_event( .sign_with_keys(&state.relay_keypair) .map_err(|e| anyhow::anyhow!("failed to sign kind:{kind}: {e}"))?; - let (stored, was_inserted) = state - .db - .replace_addressable_event(tenant.community(), &event, Some(channel_id)) - .await?; + let (stored, was_inserted) = snapshot + .replace(&event) + .await + .map_err(|e| anyhow::anyhow!("channel state write failed: {}", e.kind()))?; if was_inserted { let kind_u32 = event_kind_u32(&stored.event); dispatch_persistent_event(tenant, state, &stored, kind_u32, relay_pubkey_hex, None).await; @@ -1354,58 +1684,45 @@ pub async fn emit_group_discovery_events( state: &Arc, channel_id: Uuid, ) -> anyhow::Result<()> { - let channel = state - .db - .get_channel_for_event_write(tenant.community(), channel_id) - .await?; - let members = state - .db - .get_members_for_event_write(tenant.community(), channel_id) - .await?; - let relay_pubkey_hex = hex::encode(state.relay_keypair.public_key().to_bytes()); let group_id = channel_id.to_string(); - { - let tags = buzz_db::channel::group_metadata_tags(&channel, &members) - .into_iter() - .map(Tag::parse) - .collect::, _>>()?; - emit_addressable_discovery_event( - tenant, - state, - channel_id, - KIND_NIP29_GROUP_METADATA, - tags, - &relay_pubkey_hex, - ) - .await?; - } + emit_addressable_discovery_event( + tenant, + state, + channel_id, + KIND_NIP29_GROUP_METADATA, + &relay_pubkey_hex, + |channel, members| { + Ok(buzz_db::channel::group_metadata_tags(channel, members) + .into_iter() + .map(Tag::parse) + .collect::, _>>()?) + }, + ) + .await?; - { - let mut tags: Vec = vec![Tag::parse(["d", &group_id])?]; - tags.extend(group_state_identity_tags(&channel.identity())?); - for m in members - .iter() - .filter(|m| m.role == "owner" || m.role == "admin") - { - let pubkey_hex = hex::encode(&m.pubkey); - tags.push(Tag::parse(["p", &pubkey_hex, &m.role])?); - } - emit_addressable_discovery_event( - tenant, - state, - channel_id, - KIND_NIP29_GROUP_ADMINS, - tags, - &relay_pubkey_hex, - ) - .await?; - } + emit_addressable_discovery_event( + tenant, + state, + channel_id, + KIND_NIP29_GROUP_ADMINS, + &relay_pubkey_hex, + |channel, members| { + let mut tags: Vec = vec![Tag::parse(["d", &group_id])?]; + tags.extend(group_state_identity_tags(&channel.identity())?); + // The snapshot already scoped `members` to `GROUP_ADMIN_ROLES`. + for m in members { + let pubkey_hex = hex::encode(&m.pubkey); + tags.push(Tag::parse(["p", &pubkey_hex, &m.role])?); + } + Ok(tags) + }, + ) + .await?; - // Re-capture membership behind the writer lock immediately before the - // authoritative 39002 replacement. Metadata/admin snapshots retain their - // existing behavior; only membership publication needs this freshness fence. + // The roster takes the same fence behind the channel's membership lock, + // which its replacement also validates against. let relay_pubkey = state.relay_keypair.public_key().to_bytes(); let mut member_snapshot = state .db @@ -1760,17 +2077,27 @@ impl PutUserReport { } } -/// Apply a stored kind:9000 and return its OK message. An event naming -/// several people reports each person's result; one naming a single person -/// keeps the empty message a single add has always had. `put_member` decides -/// every admission rule again under the channel's membership lock, so a person -/// validation allowed can still be refused here. -pub(crate) async fn apply_put_user( +/// Store a validated kind:9000 and apply it, returning the stored event, +/// whether it was new, and its OK message. +/// +/// One transaction stores the event and writes every allowed person. If it +/// fails, nothing is stored and the client is told, so it can resend the same +/// event. `put_members_with_event` decides every admission rule again under +/// the channel's membership lock, so a person validation allowed can still be +/// refused there; when everyone is refused, nothing is stored and the error is +/// a [`buzz_db::DbError::AccessDenied`] with the same text validation gives. +/// +/// An event naming several people reports each person's result; one naming a +/// single person keeps the empty message a single add has always had. Live +/// effects (cache invalidation, notices, discovery events) run only after the +/// commit. +pub(crate) async fn persist_put_user( tenant: &TenantContext, event: &Event, state: &Arc, plan: PutUserPlan, -) -> String { + thread_meta: Option>, +) -> anyhow::Result<(buzz_core::StoredEvent, bool, String)> { let channel_id = plan.channel_id; let batch = plan.targets.len() > 1; let actor_bytes = event.pubkey.to_bytes().to_vec(); @@ -1790,21 +2117,30 @@ pub(crate) async fn apply_put_user( requested: target.role, }) .collect(); - let results = match state + let (stored, results) = match state .db - .put_members(tenant.community(), channel_id, &puts, Some(&actor_bytes)) - .await + .put_members_with_event(tenant.community(), channel_id, event, &puts, thread_meta) + .await? { - Ok(results) => results, - // Nothing was written. - Err(e) => { - error!(channel = %channel_id, error = %e, "NIP-29 PUT_USER write failed"); - for target in &allowed { - report.reject(&target.pubkey, "error: membership write failed".into()); + buzz_db::channel_members::MemberPutEventWrite::Applied { stored, results } => { + (stored, results) + } + buzz_db::channel_members::MemberPutEventWrite::Duplicate(stored) => { + return Ok((stored, false, String::new())); + } + buzz_db::channel_members::MemberPutEventWrite::Refused(errors) => { + for (target, error) in allowed.iter().zip(errors) { + report.reject(&target.pubkey, put_refusal_reason(error)); } - Vec::new() + let message = match report.rejected.as_slice() { + // One person keeps the single-add error text. + [(reason, _)] if !batch => reason.clone(), + _ => report.message(), + }; + return Err(buzz_db::DbError::AccessDenied(message).into()); } }; + // Every person's notification is tagged with the channel's type: read it // once. No channel row means no type to tag, so no notifications. let channel_type = if results.iter().any(Result::is_ok) { @@ -1830,13 +2166,8 @@ pub(crate) async fn apply_put_user( for (target, result) in allowed.iter().zip(results) { let put = match result { Ok(put) => put, - Err(buzz_db::DbError::AccessDenied(reason)) => { - report.reject(&target.pubkey, reason); - continue; - } - Err(e) => { - error!(channel = %channel_id, error = %e, "NIP-29 PUT_USER write failed"); - report.reject(&target.pubkey, "error: membership write failed".into()); + Err(error) => { + report.reject(&target.pubkey, put_refusal_reason(error)); continue; } }; @@ -1879,6 +2210,7 @@ pub(crate) async fn apply_put_user( &target.pubkey, &actor_bytes, KIND_MEMBER_ADDED_NOTIFICATION, + &[], ) .await { @@ -1901,10 +2233,19 @@ pub(crate) async fn apply_put_user( rejected = report.rejected.iter().map(|(_, pubkeys)| pubkeys.len()).sum::(), "NIP-29 PUT_USER processed" ); - if batch { + let message = if batch { report.message() } else { String::new() + }; + Ok((stored, true, message)) +} + +/// The reported reason a person was refused under the membership lock. +fn put_refusal_reason(error: buzz_db::DbError) -> String { + match error { + buzz_db::DbError::AccessDenied(reason) => reason, + other => other.to_string(), } } @@ -2012,6 +2353,15 @@ pub(crate) async fn persist_edit_metadata( val.parse().map_err(|e: String| anyhow::anyhow!(e))?; edit.columns.join_role = Some(join_role.as_str().to_string()); } + "auto_join" => { + // Validated during authorization; fail closed on a resend + // that somehow carries another value. + edit.columns.auto_join = Some(match val { + "true" => true, + "false" => false, + _ => return Err(anyhow::anyhow!("invalid auto_join value: {val}")), + }); + } "ttl" => { // Empty string clears the TTL (permanent); otherwise it is a // positive integer of seconds, validated during authorization. @@ -2046,6 +2396,16 @@ pub(crate) async fn persist_edit_metadata( if let Some(labels) = channel_labels_from_tags(event) { edit.columns.labels = Some(labels.map_err(|e| anyhow::anyhow!("{e}"))?); } + // A relay operator may rename a listed channel, archived ones included, + // whatever the operator's channel role, so that duplicate names can be + // repaired. Without channel authority the rename applies only to a + // listed channel. The store decides both under the channel row lock, so + // an owner who makes the channel private or unlisted meanwhile is seen. + // Channel authority is looked up only for an operator's rename. + edit.operator_rename = + is_rename_only(event) && actor_is_relay_operator(state, event.pubkey.to_bytes()).await?; + edit.channel_authority = edit.operator_rename + && actor_has_channel_authority(state, tenant.community(), channel_id, &actor_bytes).await?; let now = chrono::Utc::now(); let mut notices = Vec::new(); @@ -2074,6 +2434,11 @@ pub(crate) async fn persist_edit_metadata( "type": "unlisted_changed", "actor": actor_hex, "unlisted": unlisted })); } + if let Some(auto_join) = edit.columns.auto_join { + notices.push(serde_json::json!({ + "type": "auto_join_changed", "actor": actor_hex, "auto_join": auto_join + })); + } if let Some(ttl_seconds) = edit.columns.ttl_seconds { notices.push(serde_json::json!({ "type": "ttl_changed", "actor": actor_hex, "ttl_seconds": ttl_seconds @@ -2246,11 +2611,14 @@ pub(crate) fn create_unlisted_from_tags(event: &Event) -> anyhow::Result { Ok(unlisted) } -async fn handle_delete_event_side_effect( +/// The kind 9005 target, when it exists. Ingest has already checked authority +/// and that the target lives in the `h` channel; the channel check is repeated +/// here because the soft-delete must never cross channels. +async fn plan_group_deletion_target( tenant: &TenantContext, event: &Event, state: &Arc, -) -> anyhow::Result<()> { +) -> anyhow::Result> { let channel_id = extract_h_tag_channel(event).ok_or_else(|| anyhow::anyhow!("missing h tag"))?; @@ -2277,72 +2645,52 @@ async fn handle_delete_event_side_effect( // Verify the target event belongs to the same channel as the h-tag. // Without this check, an admin of channel A could delete events in channel B // by sending h=A, e=. - if let Some(target_event) = state + let Some(target) = state .db .get_event_by_id_including_deleted_for_event_write(tenant.community(), &target_id) .await .map_err(|e| anyhow::anyhow!("get_event_by_id failed: {e}"))? - { - match target_event.channel_id { - Some(target_ch) if target_ch != channel_id => { - return Err(anyhow::anyhow!( - "target event belongs to a different channel" - )); - } - None => { - return Err(anyhow::anyhow!("target event has no channel")); - } - _ => {} // Same channel — OK + else { + return Ok(Vec::new()); + }; + match target.channel_id { + Some(target_ch) if target_ch != channel_id => { + return Err(anyhow::anyhow!( + "target event belongs to a different channel" + )); } + None => { + return Err(anyhow::anyhow!("target event has no channel")); + } + _ => {} // Same channel — OK } + Ok(vec![ + PlannedDeletionTarget::load(tenant, state, target_id, target).await?, + ]) +} - // Look up thread metadata so we can pass parent/root IDs to the - // transactional delete function. - let meta = state - .db - .get_thread_metadata_by_event(tenant.community(), &target_id) - .await - .map_err(|e| anyhow::anyhow!("get_thread_metadata failed: {e}"))?; - - let parent_id = meta.as_ref().and_then(|m| m.parent_event_id.clone()); - let root_id = meta.as_ref().and_then(|m| m.root_event_id.clone()); - - // Atomically soft-delete the event and decrement thread counters in one transaction. - let deleted = state - .db - .soft_delete_event_and_update_thread( - tenant.community(), - &target_id, - parent_id.as_deref(), - root_id.as_deref(), - ) - .await - .map_err(|e| anyhow::anyhow!("soft_delete_event failed: {e}"))?; - - if !deleted { - warn!(target_event = %hex::encode(&target_id), "event already deleted or not found"); - return Ok(()); // No-op: skip system message to avoid false audit records. - } - - // Thread counters were decremented in the same transaction — push a fresh - // relay-signed 39005 so live badge counts also count *down*. - if let Some(root_id) = root_id { - emit_live_thread_summary(tenant, state, channel_id, root_id); - } - +/// Post the kind 9005 `message_deleted` system message for a deleted target. +async fn emit_group_deletion_tombstone( + tenant: &TenantContext, + event: &Event, + state: &Arc, + planned: &PlannedDeletionTarget, +) -> anyhow::Result<()> { + let channel_id = planned + .target + .channel_id + .ok_or_else(|| anyhow::anyhow!("target event has no channel"))?; let actor_hex = hex::encode(event.pubkey.to_bytes()); let mut tombstone = serde_json::json!({ "type": "message_deleted", "actor": actor_hex, - "target_event_id": hex::encode(&target_id), + "target_event_id": hex::encode(&planned.id), }); copy_optional_string_field(event, &mut tombstone, "action_id"); copy_optional_string_field(event, &mut tombstone, "reason_code"); copy_optional_string_field(event, &mut tombstone, "public_reason"); emit_system_message(tenant, state, channel_id, tombstone, chrono::Utc::now()).await?; - - info!(target_event = %hex::encode(&target_id), "NIP-29 DELETE_EVENT processed"); Ok(()) } @@ -2375,17 +2723,14 @@ async fn handle_create_group( .unwrap_or_default(); let unlisted = create_unlisted_from_tags(event)?; - // If the event has an h-tag UUID, ingest_event() already created the channel - // via create_channel_with_id(). Fetch it rather than creating a duplicate. - // If no h-tag, fall back to the original auto-UUID creation path. + // Ingest already created the channel named by the h tag, in the same + // commit as this event. Fetch it rather than creating a duplicate. // - // Double-count analysis (C5): the counter increments below do NOT - // double-count vs. ingest.rs. For the h-tag path, ingest increments on - // was_created=true and this handler only reaches create_channel() on a DB - // lookup Err — an error recovery path where ingest's channel is - // inaccessible, so the counter correctly records a new creation. For the - // no-h-tag path, ingest never creates the channel, so this is the sole - // increment. + // Double-count analysis (C5): the counter increment below does NOT + // double-count vs. ingest.rs. Ingest increments on was_created=true and + // this handler only reaches create_channel() on a DB lookup Err — an + // error recovery path where ingest's channel is inaccessible, so the + // counter correctly records a new creation. // `members_added`: ingest's create also added the event's `p` tags. let (channel, members_added) = if let Some(client_uuid) = extract_h_tag_channel(event) { match state @@ -2421,27 +2766,8 @@ async fn handle_create_group( } } } else { - let ch = state - .db - .create_labeled_channel( - tenant.community(), - &name, - channel_type, - visibility, - description.as_deref(), - &actor_bytes, - ttl_seconds, - &labels, - unlisted, - ) - .await?; - metrics::counter!( - "buzz_channels_created_total", - "community" => tenant.host().to_owned(), - "type" => channel_type.to_string() - ) - .increment(1); - (ch, false) + // Ingest refuses a kind:9007 without an `h` tag before storing it. + anyhow::bail!("missing or invalid h tag"); }; // Creator becomes owner — evict any stale negative membership lookup. @@ -2524,6 +2850,9 @@ async fn handle_create_group( Ok(()) } +/// Concurrent 44101 notices a channel delete sends to its members. +const DELETE_NOTICE_CONCURRENCY: usize = 8; + async fn handle_delete_group( tenant: &TenantContext, event: &Event, @@ -2533,14 +2862,15 @@ async fn handle_delete_group( extract_h_tag_channel(event).ok_or_else(|| anyhow::anyhow!("missing h tag"))?; let actor_bytes = event.pubkey.to_bytes().to_vec(); - // Soft-delete the channel. + // Soft-delete the channel, capturing its members under the same lock so a + // concurrent join is either included or refused. let deleted = state .db - .soft_delete_channel(tenant.community(), channel_id) + .soft_delete_channel_capturing_members(tenant.community(), channel_id) .await .map_err(|e| anyhow::anyhow!("soft_delete_channel failed: {e}"))?; - if !deleted { + if deleted.is_none() { warn!(channel = %channel_id, "channel already deleted or not found"); } @@ -2561,6 +2891,36 @@ async fn handle_delete_group( // Stale is_member=true entries would bypass the DB's deleted_at guard. state.invalidate_channel_deleted(tenant); + // Notify every member only after the delete and discovery cleanup, so a + // client that re-reads on the notice no longer sees the channel. The + // notices run off the request path, bounded like `handle_req`'s filter + // reads, so a large channel neither holds the OK nor depends on the + // system message below. + if let Some(deleted) = deleted { + let (tenant, state, actor_bytes) = (tenant.clone(), state.clone(), actor_bytes.clone()); + tokio::spawn(async move { + use futures_util::stream::{self, StreamExt}; + stream::iter(&deleted.members) + .for_each_concurrent(DELETE_NOTICE_CONCURRENCY, |member| async { + if let Err(e) = emit_typed_membership_notification( + &tenant, + &state, + channel_id, + &deleted.channel_type, + member, + &actor_bytes, + KIND_MEMBER_REMOVED_NOTIFICATION, + &[], + ) + .await + { + warn!(channel = %channel_id, error = %e, "membership notification emission failed"); + } + }) + .await; + }); + } + let actor_hex = hex::encode(&actor_bytes); emit_system_message( tenant, @@ -2577,15 +2937,25 @@ async fn handle_delete_group( Ok(()) } -async fn handle_join_request( +/// What [`join_channel_as_self`] did for the member. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SelfJoinOutcome { + /// The member was added and every join side effect was emitted. + Joined, + /// The member was already active in the channel; nothing changed. + AlreadyMember, +} + +/// Join `pubkey` to an open, unarchived channel as a self-join: no inviter, +/// the channel's `join_role`, and the kind:40099, 39000/39002 and 44100 +/// side effects of a kind:9021. Shared by the kind:9021 handler and the +/// default-channel auto-join on new community memberships. +pub(crate) async fn join_channel_as_self( tenant: &TenantContext, - event: &Event, state: &Arc, -) -> anyhow::Result<()> { - let channel_id = - extract_h_tag_channel(event).ok_or_else(|| anyhow::anyhow!("missing h tag"))?; - let actor_bytes = event.pubkey.to_bytes().to_vec(); - + channel_id: Uuid, + pubkey: &[u8], +) -> anyhow::Result { // Only open channels allow self-join via kind:9021. let channel = state .db @@ -2597,27 +2967,45 @@ async fn handle_join_request( "channel is private — request an invitation" )); } + if channel.archived_at.is_some() { + return Err(anyhow::anyhow!("channel is archived")); + } // Skip if already an active member — prevents duplicate join notifications. // Fail closed on DB errors rather than falling through to add_member. if state - .is_member_cached(tenant.community(), channel_id, &actor_bytes) + .is_member_cached(tenant.community(), channel_id, pubkey) .await? { - info!(channel = %channel_id, "kind:9021 join — already a member, skipping"); - return Ok(()); + return Ok(SelfJoinOutcome::AlreadyMember); } // A self-join gets the channel's `join_role`, read by `put_member` under // the membership lock: member in a normal channel, guest in an announce - // channel, where a member must then make them a member. + // channel, where a member must then make them a member. `put_member` + // also decides visibility and archive state again under its locks, so a + // channel made private or archived since the checks above is refused + // here, with no side effects. state .db - .put_member(tenant.community(), channel_id, &actor_bytes, None, None) + .put_member(tenant.community(), channel_id, pubkey, None, None) .await?; - state.invalidate_membership(tenant, channel_id, &actor_bytes); + announce_self_join(tenant, state, channel_id, pubkey).await?; + Ok(SelfJoinOutcome::Joined) +} - let actor_hex = hex::encode(&actor_bytes); +/// The side effects of a committed self-join: the membership cache, the +/// `member_joined` kind:40099, kind:39000/39002 and kind:44100. Only the +/// system message is fatal, as for kind:9021. +async fn announce_self_join( + tenant: &TenantContext, + state: &Arc, + channel_id: Uuid, + pubkey: &[u8], +) -> anyhow::Result<()> { + state.invalidate_membership(tenant, channel_id, pubkey); + + let actor_hex = hex::encode(pubkey); emit_system_message( tenant, state, @@ -2639,8 +3027,8 @@ async fn handle_join_request( tenant, state, channel_id, - &actor_bytes, - &actor_bytes, + pubkey, + pubkey, buzz_core::kind::KIND_MEMBER_ADDED_NOTIFICATION, ) .await @@ -2648,7 +3036,227 @@ async fn handle_join_request( warn!("membership notification for join failed: {e}"); } - info!(channel = %channel_id, "kind:9021 join processed"); + Ok(()) +} + +/// Process the durable default-channel work of this roster admission. +/// Failed reads or writes retain the token for a later claim or admission. +/// Leaves made during this admission are preserved. +pub(crate) async fn auto_join_default_channels( + tenant: &TenantContext, + state: &Arc, + pubkey_hex: &str, + gate: Option<&Arc>, +) { + if let Err(e) = finish_default_channel_joins(tenant, state, pubkey_hex, gate).await { + warn!(member = %pubkey_hex, error = %e, "default-channel joins remain pending"); + metrics::counter!("buzz_auto_join_failures_total").increment(1); + } +} + +async fn finish_default_channel_joins( + tenant: &TenantContext, + state: &Arc, + pubkey_hex: &str, + gate: Option<&Arc>, +) -> anyhow::Result<()> { + // A socket's AUTH retry runs on every admission, so it reads the replica + // and keeps the writer pool free. A roster write (no gate) reads the + // writer, where it has just committed the token. + let pending = match gate { + Some(_) => { + state + .db + .pending_default_channel_join_routed(tenant.community(), pubkey_hex) + .await? + } + None => { + state + .db + .pending_default_channel_join(tenant.community(), pubkey_hex) + .await? + } + }; + let Some(admission) = pending else { + return Ok(()); + }; + let pubkey = hex::decode(pubkey_hex)?; + // Use the persisted original actor even when a retry comes from the member. + let actor = admission + .added_by + .as_deref() + .filter(|actor| *actor != "invite") + .map(hex::decode) + .transpose()?; + if let Some(actor) = actor.as_deref().filter(|actor| *actor != pubkey.as_slice()) { + if let Some((policy, owner)) = state + .db + .get_agent_channel_policy(tenant.community(), &pubkey) + .await? + { + if let Err(denied) = + channel_authz::decide_channel_add_policy(&policy, owner.as_deref(), actor) + { + info!(member = %pubkey_hex, error = %denied, "default-channel add refused by member policy"); + state + .db + .finish_default_channel_join(tenant.community(), pubkey_hex, admission.token) + .await?; + return Ok(()); + } + } + } + let channels = state.db.list_auto_join_channels(tenant.community()).await?; + let mut failure = None; + for channel in channels { + #[cfg(test)] + if gate.is_some() { + crate::nip_fi_test_hooks::before_auto_join_channel(tenant.community()).await; + } + let _permit = match gate { + Some(gate) => match gate.acquire_effect().await { + Ok(permit) => Some(permit), + Err(_) => return Ok(()), // Pending work belongs to the next admission. + }, + None => None, + }; + if let Err(error) = + finish_default_channel_join(tenant, state, channel.id, &pubkey, &admission).await + { + warn!(channel = %channel.id, member = %pubkey_hex, error = %error, + "default-channel join remains pending; continuing other channels"); + failure = Some(error); + } + } + if let Some(error) = failure { + return Err(error); + } + state + .db + .finish_default_channel_join(tenant.community(), pubkey_hex, admission.token) + .await?; + Ok(()) +} + +async fn finish_default_channel_join( + tenant: &TenantContext, + state: &Arc, + channel: Uuid, + pubkey: &[u8], + admission: &buzz_db::relay_members::PendingDefaultChannelJoin, +) -> anyhow::Result<()> { + match state + .db + .put_pending_default_member(tenant.community(), channel, pubkey, admission.token) + .await + { + Ok(Some(_)) => { + // Membership is durable now. Announcements keep their existing + // failure handling; retries must not replay them for active members. + if let Err(error) = announce_self_join(tenant, state, channel, pubkey).await { + warn!(channel = %channel, error = %error, "default-channel announcement failed"); + metrics::counter!("buzz_auto_join_failures_total").increment(1); + } + metrics::counter!("buzz_auto_join_channels_total").increment(1); + } + Ok(None) => {} + Err(buzz_db::DbError::ChannelNotFound(_)) => {} + Err(error) => return Err(error.into()), + } + Ok(()) +} + +/// Join a person admitted to a community that keeps no membership roster +/// (`require_relay_membership = false`) to every effective `auto_join` +/// channel they have never been a member of, as kind:9021 self-joins. +/// +/// Runs after every human WebSocket admission there, because such a +/// community has no roster insert to run [`auto_join_default_channels`] at. +/// "Never a member" is the channel's own membership history: a kind:9022 +/// leave or a kind:9001 removal keeps a removed row, so the person is not +/// joined back, and a channel flagged later is joined on their next +/// admission. +/// +/// Each channel's write and announcement hold an effect permit from the +/// admitting socket's `gate`, as every other session effect does, so nothing +/// is written once the session has expired or the socket is cancelled; the +/// task stops at the first refusal. A channel it stops before, or whose +/// membership write fails, has no row, so the next admission tries it again. +/// Failures are logged and counted (`buzz_auto_join_failures_total`). +pub(crate) async fn auto_join_never_joined_channels( + tenant: &TenantContext, + state: &Arc, + pubkey: &[u8], + gate: &Arc, +) { + join_never_joined_channels(tenant, state, pubkey, gate).await; + #[cfg(test)] + crate::nip_fi_test_hooks::after_auto_join(tenant.community()).await; +} + +async fn join_never_joined_channels( + tenant: &TenantContext, + state: &Arc, + pubkey: &[u8], + gate: &Arc, +) { + let member = hex::encode(pubkey); + let channels = match state + .db + .list_never_joined_auto_join_channels(tenant.community(), pubkey) + .await + { + Ok(channels) => channels, + Err(e) => { + warn!(%member, error = %e, "auto-join skipped: listing default channels failed"); + metrics::counter!("buzz_auto_join_failures_total").increment(1); + return; + } + }; + for channel_id in channels { + #[cfg(test)] + crate::nip_fi_test_hooks::before_auto_join_channel(tenant.community()).await; + let Ok(_permit) = gate.acquire_effect().await else { + info!(channel = %channel_id, %member, "auto-join stopped: the session ended"); + return; + }; + let joined = match state + .db + .put_first_member(tenant.community(), channel_id, pubkey) + .await + { + Ok(None) => continue, + Ok(Some(_)) => announce_self_join(tenant, state, channel_id, pubkey).await, + Err(e) => Err(e.into()), + }; + match joined { + Ok(()) => { + metrics::counter!("buzz_auto_join_channels_total").increment(1); + info!(channel = %channel_id, %member, "auto-joined default channel on admission"); + } + Err(e) => { + metrics::counter!("buzz_auto_join_failures_total").increment(1); + warn!(channel = %channel_id, %member, error = %e, "auto-join of default channel on admission failed"); + } + } + } +} + +async fn handle_join_request( + tenant: &TenantContext, + event: &Event, + state: &Arc, +) -> anyhow::Result<()> { + let channel_id = + extract_h_tag_channel(event).ok_or_else(|| anyhow::anyhow!("missing h tag"))?; + match join_channel_as_self(tenant, state, channel_id, &event.pubkey.to_bytes()).await? { + SelfJoinOutcome::AlreadyMember => { + info!(channel = %channel_id, "kind:9021 join — already a member, skipping"); + } + SelfJoinOutcome::Joined => { + info!(channel = %channel_id, "kind:9021 join processed"); + } + } Ok(()) } @@ -2749,14 +3357,19 @@ pub(crate) async fn persist_workflow_deletion( .ok_or_else(|| anyhow::anyhow!("missing workflow coordinate"))?; let mut parts = coordinate.splitn(3, ':'); let _kind = parts.next(); - let owner = hex::decode(parts.next().unwrap_or_default())?; + let owner = hex::decode(parts.next().unwrap_or_default()) + .map_err(|_| anyhow::anyhow!("invalid workflow coordinate"))?; let d_tag = parts .next() .ok_or_else(|| anyhow::anyhow!("invalid workflow coordinate"))?; let (stored, dispatch, channel_id) = state .db .insert_workflow_deletion(tenant.community(), event, &owner, d_tag) - .await?; + .await + .map_err(|e| { + // The write carries the whole event: log only a fixed kind. + anyhow::anyhow!("workflow deletion write failed: {}", e.kind()) + })?; if let Some(channel_id) = channel_id { state .workflow_engine @@ -2856,132 +3469,227 @@ async fn handle_a_tag_deletion( Ok(()) } +/// Kind 5 with no `e` tag: the NIP-09 `a`-coordinate path. A kind 5 that names +/// `e` targets is persisted atomically by [`persist_deletion`] instead. async fn handle_standard_deletion_event( tenant: &TenantContext, event: &Event, state: &Arc, ) -> anyhow::Result<()> { - let target_ids = extract_target_event_ids(event); - if !has_e_tag(event) { - // NIP-09 a-tag deletion path for addressable events. Keyed on the - // absence of *any* e tag (not just valid e-ids): a malformed e + a must - // not route here and silently soft-delete the coordinate. - return handle_a_tag_deletion(tenant, event, state).await; + if has_e_tag(event) { + // Keyed on the presence of *any* e tag (not just valid e-ids): a + // malformed e + a must not route to the a path and silently + // soft-delete the coordinate. + anyhow::bail!("kind:5 with e tags requires persist_deletion"); } + handle_a_tag_deletion(tenant, event, state).await +} - for target_id in target_ids { - let target_event = match state - .db - .get_event_by_id_including_deleted_for_event_write(tenant.community(), &target_id) - .await? - { - Some(target) => target, - None => continue, - }; - if u32::from(target_event.event.kind.as_u16()) == super::push_lease::KIND_PUSH_LEASE { - tracing::debug!( - target_id = %hex::encode(&target_id), - "NIP-09 deletion ignored for push lease" - ); - continue; - } +/// A target a deletion soft-deletes inside its own insert transaction. +struct PlannedDeletionTarget { + id: Vec, + target: StoredEvent, + parent_id: Option>, + root_id: Option>, +} +impl PlannedDeletionTarget { + async fn load( + tenant: &TenantContext, + state: &Arc, + id: Vec, + target: StoredEvent, + ) -> anyhow::Result { let meta = state .db - .get_thread_metadata_by_event(tenant.community(), &target_id) + .get_thread_metadata_by_event(tenant.community(), &id) .await?; - let parent_id = meta.as_ref().and_then(|m| m.parent_event_id.clone()); - let root_id = meta.as_ref().and_then(|m| m.root_event_id.clone()); + Ok(Self { + parent_id: meta.as_ref().and_then(|m| m.parent_event_id.clone()), + root_id: meta.and_then(|m| m.root_event_id), + id, + target, + }) + } +} - let deleted = state - .db - .soft_delete_event_and_update_thread( - tenant.community(), - &target_id, - parent_id.as_deref(), - root_id.as_deref(), - ) - .await?; +/// Whether `event` is a deletion whose targets are soft-deleted in the same +/// transaction that stores it ([`persist_deletion`]): every kind 9005, and a +/// kind 5 that names `e` targets. A kind 5 naming only an `a` coordinate stays +/// a side effect. +pub(crate) fn is_atomic_deletion(kind: u32, event: &Event) -> bool { + kind == 9005 || (kind == 5 && has_e_tag(event)) +} + +/// Store a kind 5 / 9005 deletion and soft-delete its targets in one commit. +/// +/// A failure stores nothing, so the client is told and can resend. A resend of +/// a stored deletion soft-deletes any target still live and then reports +/// itself as inserted, like a workflow deletion that repairs its target. That +/// repair reaches only a deletion still inside the ingest timestamp window: +/// rows torn by the earlier, non-atomic write stay torn, and the bridge aux +/// closure's deletion-of-aux hop is what still cancels their targets. +/// +/// Projections of a deleted target (live thread counts, the reaction table and +/// the 9005 system message) run after the commit and stay best-effort. +pub(crate) async fn persist_deletion( + tenant: &TenantContext, + event: &Event, + state: &Arc, + channel_id: Option, + thread_meta: Option>, +) -> anyhow::Result<(StoredEvent, bool)> { + let is_group_deletion = event_kind_u32(event) == 9005; + let planned = if is_group_deletion { + plan_group_deletion_target(tenant, event, state).await? + } else { + plan_standard_deletion_targets(tenant, event, state).await? + }; + let targets: Vec> = planned + .iter() + .map(|p| { + Ok(buzz_db::DeletionTarget { + event_id: &p.id, + created_at: chrono::DateTime::from_timestamp( + p.target.event.created_at.as_secs() as i64, + 0, + ) + .ok_or_else(|| anyhow::anyhow!("invalid deletion target timestamp"))?, + parent_event_id: p.parent_id.as_deref(), + root_event_id: p.root_id.as_deref(), + }) + }) + .collect::>()?; + let (stored, inserted, deleted) = state + .db + .insert_deletion_event(tenant.community(), event, channel_id, thread_meta, &targets) + .await?; + let mut repaired = false; + for (planned, deleted) in planned.iter().zip(deleted) { if !deleted { continue; } - + repaired = true; // Thread counters were decremented in the same transaction — push a // fresh relay-signed 39005 so live badge counts also count *down*. - if let (Some(root_id), Some(channel_id)) = (root_id, target_event.channel_id) { - emit_live_thread_summary(tenant, state, channel_id, root_id); + if let (Some(root_id), Some(channel_id)) = (&planned.root_id, planned.target.channel_id) { + emit_live_thread_summary(tenant, state, channel_id, root_id.clone()); } + if is_group_deletion { + if let Err(e) = emit_group_deletion_tombstone(tenant, event, state, planned).await { + error!(target_event = %hex::encode(&planned.id), "NIP-29 DELETE_EVENT tombstone failed: {e}"); + } + info!(target_event = %hex::encode(&planned.id), "NIP-29 DELETE_EVENT processed"); + } else if u32::from(planned.target.event.kind.as_u16()) == KIND_REACTION { + remove_deleted_reaction(tenant, state, &planned.id, &planned.target).await; + } + } + Ok((stored, inserted || repaired)) +} - if u32::from(target_event.event.kind.as_u16()) == KIND_REACTION { - // Try by reaction_event_id first; fall back to tuple-based removal - // if the backfill was missed (set_reaction_event_id is best-effort). - let removed = state - .db - .remove_reaction_by_source_event_id(tenant.community(), &target_id) - .await - .unwrap_or(false); - if !removed { - // Derive (target, actor, emoji) from the reaction event itself. - // Use effective_message_author to handle legacy relay-signed - // reactions where event.pubkey is the relay key, not the user. - let actor = super::ingest::effective_message_author( - &target_event.event, - &state.relay_keypair.public_key(), - ); - let emoji = if target_event.event.content.is_empty() { - "+" +/// The kind 5 `e` targets that exist. Ingest has already checked authority over +/// every one of them. +async fn plan_standard_deletion_targets( + tenant: &TenantContext, + event: &Event, + state: &Arc, +) -> anyhow::Result> { + let mut planned = Vec::new(); + for target_id in extract_target_event_ids(event) { + let Some(target) = state + .db + .get_event_by_id_including_deleted_for_event_write(tenant.community(), &target_id) + .await? + else { + continue; + }; + if u32::from(target.event.kind.as_u16()) == super::push_lease::KIND_PUSH_LEASE { + tracing::debug!( + target_id = %hex::encode(&target_id), + "NIP-09 deletion ignored for push lease" + ); + continue; + } + planned.push(PlannedDeletionTarget::load(tenant, state, target_id, target).await?); + } + Ok(planned) +} + +/// Drop a deleted reaction from the reaction table. +async fn remove_deleted_reaction( + tenant: &TenantContext, + state: &Arc, + target_id: &[u8], + target_event: &StoredEvent, +) { + // Try by reaction_event_id first; fall back to tuple-based removal + // if the backfill was missed (set_reaction_event_id is best-effort). + let removed = state + .db + .remove_reaction_by_source_event_id(tenant.community(), target_id) + .await + .unwrap_or(false); + if removed { + return; + } + // Derive (target, actor, emoji) from the reaction event itself. + // Use effective_message_author to handle legacy relay-signed + // reactions where event.pubkey is the relay key, not the user. + let actor = super::ingest::effective_message_author( + &target_event.event, + &state.relay_keypair.public_key(), + ); + let emoji = if target_event.event.content.is_empty() { + "+" + } else { + &target_event.event.content + }; + let Some(react_target_hex) = target_event.event.tags.iter().rev().find_map(|t| { + if t.kind().to_string() == "e" { + t.content().and_then(|v| { + if v.len() == 64 && v.chars().all(|c| c.is_ascii_hexdigit()) { + Some(v.to_string()) } else { - &target_event.event.content - }; - if let Some(react_target_hex) = target_event.event.tags.iter().rev().find_map(|t| { - if t.kind().to_string() == "e" { - t.content().and_then(|v| { - if v.len() == 64 && v.chars().all(|c| c.is_ascii_hexdigit()) { - Some(v.to_string()) - } else { - None - } - }) - } else { - None - } - }) { - if let Ok(react_target_id) = hex::decode(&react_target_hex) { - if let Ok(Some(react_target_event)) = state - .db - .get_event_by_id_for_event_write(tenant.community(), &react_target_id) - .await - { - let react_target_ts = chrono::DateTime::from_timestamp( - react_target_event.event.created_at.as_secs() as i64, - 0, - ) - .unwrap_or_else(chrono::Utc::now); - if let Err(e) = state - .db - .remove_reaction( - tenant.community(), - &react_target_id, - react_target_ts, - &actor, - emoji, - ) - .await - { - tracing::warn!( - error = %e, - "failed to remove reaction from DB during NIP-09 deletion" - ); - } - } - } + None } - } + }) + } else { + None + } + }) else { + return; + }; + let Ok(react_target_id) = hex::decode(&react_target_hex) else { + return; + }; + if let Ok(Some(react_target_event)) = state + .db + .get_event_by_id_for_event_write(tenant.community(), &react_target_id) + .await + { + let react_target_ts = chrono::DateTime::from_timestamp( + react_target_event.event.created_at.as_secs() as i64, + 0, + ) + .unwrap_or_else(chrono::Utc::now); + if let Err(e) = state + .db + .remove_reaction( + tenant.community(), + &react_target_id, + react_target_ts, + &actor, + emoji, + ) + .await + { + tracing::warn!( + error = %e, + "failed to remove reaction from DB during NIP-09 deletion" + ); } } - - Ok(()) } /// Most members a kind:9007 may add besides its creator. @@ -3487,6 +4195,7 @@ async fn seed_manifest_pointer( refs: BTreeMap::new(), packs: Vec::new(), parent: None, + published_at: None, }; empty .validate() @@ -3602,6 +4311,7 @@ async fn emit_initial_ref_state( head: DEFAULT_HEAD, refs: &empty_refs, actor_pubkey_hex: owner_hex, + published_at: None, }; let event = build_ref_state_event(&inputs, &state.relay_keypair) .map_err(|e| anyhow::anyhow!("build_ref_state_event: {e}"))?; @@ -3941,35 +4651,34 @@ pub async fn publish_nipia_archival_list( ); } - // NIP-16 resolves same-second replacements by event id. Force this - // canonical snapshot strictly past the current head instead of letting a - // rapid archive→unarchive randomly preserve the stale archive state. - let now = nostr::Timestamp::now().as_secs(); - let previous = state - .db - .query_events_for_event_write(&buzz_db::event::EventQuery { - kinds: Some(vec![KIND_IA_ARCHIVED_LIST as i32]), - pubkey: Some(relay_pubkey.to_bytes().to_vec()), - limit: Some(1), - global_only: true, - ..buzz_db::event::EventQuery::for_community(tenant.community()) - }) - .await?; - let created_at = previous - .first() - .map(|event| (event.event.created_at.as_secs() + 1).max(now)) - .unwrap_or(now); - - let event = EventBuilder::new(Kind::Custom(KIND_IA_ARCHIVED_LIST as u16), "") - .tags(tags) - .custom_created_at(nostr::Timestamp::from(created_at)) - .sign_with_keys(&state.relay_keypair) - .map_err(|e| anyhow::anyhow!("failed to sign kind:{KIND_IA_ARCHIVED_LIST}: {e}"))?; - + // NIP-IA: each snapshot's created_at is strictly past the previous + // one's, so clients can ask only for a newer list. The head is read + // behind the replacement lock: two publishers racing on one head would + // otherwise both stamp head + 1 and let a same-second replacement win + // by event id. let (stored, was_inserted) = state .db - .replace_addressable_event(tenant.community(), &event, None) - .await?; + .replace_addressable_event_after_head( + tenant.community(), + KIND_IA_ARCHIVED_LIST as i32, + &relay_pubkey.to_bytes(), + None, + |previous| { + let now = nostr::Timestamp::now().as_secs(); + let created_at = previous.map_or(now, |previous| (previous + 1).max(now)); + EventBuilder::new(Kind::Custom(KIND_IA_ARCHIVED_LIST as u16), "") + .tags(tags) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(&state.relay_keypair) + .map_err(|e| { + buzz_db::DbError::InvalidData(format!( + "failed to sign kind:{KIND_IA_ARCHIVED_LIST}: {e}" + )) + }) + }, + ) + .await + .map_err(|e| anyhow::anyhow!("archive snapshot write failed: {}", e.kind()))?; if !was_inserted { continue; } @@ -4074,7 +4783,8 @@ pub async fn publish_dm_visibility_snapshot( let (stored, was_inserted) = state .db .replace_parameterized_event(tenant.community(), &event, &viewer_hex, None) - .await?; + .await + .map_err(|e| anyhow::anyhow!("DM visibility write failed: {}", e.kind()))?; if was_inserted { dispatch_persistent_event( tenant, diff --git a/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs b/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs index 710fbdbe90b..530f6db3bb0 100644 --- a/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs @@ -1424,3 +1424,394 @@ async fn workflows_in_system_channels_follow_channel_access() { ); } } + +/// A live REQ through the production handler, on a connection that fan-out +/// can reach. `history` holds the event IDs sent before EOSE. +struct LiveReq { + conn: Arc, + rx: tokio::sync::mpsc::Receiver, + history: Vec, +} + +impl LiveReq { + async fn open(f: &Fixture, reader: &Keys, filters: Value) -> Self { + let (conn, rx) = test_conn(&f.tenant, reader); + f.state.conn_manager.register( + conn.conn_id, + conn.send_tx.clone(), + conn.ctrl_tx.clone(), + conn.terminal_ctrl_tx.clone(), + None, + conn.cancel.clone(), + f.tenant.community(), + conn.backpressure_count.clone(), + conn.subscriptions.clone(), + conn.grace_limit, + crate::state::CommunityConnectionControl::new(conn.cancel.clone()), + ); + f.state + .conn_manager + .set_authenticated_pubkey(conn.conn_id, reader.public_key().to_bytes().to_vec()); + let mut live = Self { + conn, + rx, + history: Vec::new(), + }; + live.req(f, filters).await; + live + } + + /// Send a REQ for sub `s` (replacing any earlier one) and drain to EOSE. + async fn req(&mut self, f: &Fixture, filters: Value) { + let filters: Vec = serde_json::from_value(filters).expect("filters"); + let before = vec![None; filters.len()]; + crate::handlers::req::handle_req( + "s".into(), + filters, + before, + self.conn.clone(), + f.state.clone(), + ) + .await; + self.history.clear(); + loop { + let (kind, frame) = self + .frame(std::time::Duration::from_secs(5)) + .await + .expect("EOSE"); + match kind.as_str() { + "EVENT" => self + .history + .push(frame[2]["id"].as_str().expect("id").to_owned()), + "EOSE" => return, + other => panic!("unexpected frame {other}: {frame}"), + } + } + } + + async fn frame(&mut self, wait: std::time::Duration) -> Option<(String, Value)> { + loop { + let frame = tokio::time::timeout(wait, self.rx.recv()).await.ok()??; + let axum::extract::ws::Message::Text(text) = frame else { + continue; + }; + let message: Value = serde_json::from_str(&text).expect("relay frame"); + return Some((message[0].as_str().expect("frame type").to_owned(), message)); + } + } + + /// The next live event, as `(kind, d or h tag, id)`. + async fn next_event(&mut self) -> (u16, String, String) { + let (kind, frame) = self + .frame(std::time::Duration::from_secs(5)) + .await + .expect("live event"); + assert_eq!(kind, "EVENT", "{frame}"); + let event: nostr::Event = serde_json::from_value(frame[2].clone()).expect("event"); + let scope = event + .tags + .iter() + .find(|tag| matches!(tag.as_slice().first().map(String::as_str), Some("d" | "h"))) + .and_then(|tag| tag.as_slice().get(1).cloned()) + .unwrap_or_default(); + (event.kind.as_u16(), scope, event.id.to_hex()) + } + + async fn assert_quiet(&mut self, who: &str) { + if let Some(frame) = self.frame(std::time::Duration::from_millis(200)).await { + panic!("{who}: unexpected frame {frame:?}"); + } + } + + async fn close(&self, f: &Fixture) { + crate::handlers::close::handle_close("s".into(), self.conn.clone(), f.state.clone()).await; + } +} + +async fn refcount(f: &Fixture, topic: buzz_pubsub::EventTopic) -> usize { + f.state.pubsub.topic_refcount(&f.tenant, topic).await +} + +/// Hand a relay-signed kind:39000 for `channel` to the handler that receives +/// another pod's events from Redis. This covers the receive side only, not +/// publishing or Redis transport. +async fn fan_out_from_another_pod(f: &Fixture, channel: Uuid, name: &str) -> String { + let event = EventBuilder::new(Kind::Custom(39000), "") + .tags([ + Tag::parse(["d", &channel.to_string()]).unwrap(), + Tag::parse(["name", name]).unwrap(), + ]) + .sign_with_keys(&f.state.relay_keypair) + .expect("sign 39000"); + let id = event.id.to_hex(); + crate::handlers::event::fan_out_pubsub_event( + &f.state, + buzz_pubsub::ChannelEvent { + community_id: f.tenant.community(), + topic: buzz_pubsub::EventTopic::Channel(channel), + event, + }, + ) + .await; + id +} + +/// A `#d` group-state REQ keeps receiving its channel's replacements after +/// EOSE, from this pod and through the handler for other pods' events, for +/// every reader who may read the +/// channel: a private channel's member and an open channel's outsider. A +/// private channel's outsider gets neither history nor live updates, and +/// never retains the channel's topic. CLOSE and same-ID replacement release +/// each retained topic once. +/// Mutation: give a filter without `#h` only the global scope in +/// `filter_live_scope` → RED (no live replacement after EOSE). +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn group_state_replacements_reach_live_d_subscribers() { + use buzz_pubsub::EventTopic; + let f = fixture().await; + let owner = Keys::generate(); + let outsider = Keys::generate(); + let private = create_channel(&f.state, &f.tenant, &owner, &[&["visibility", "private"]]).await; + let open = create_channel(&f.state, &f.tenant, &owner, &[&["visibility", "open"]]).await; + let by_d = |channel: Uuid| json!([{"kinds": [39000], "#d": [channel.to_string()]}]); + + let mut member = LiveReq::open(&f, &owner, by_d(private)).await; + let mut open_outsider = LiveReq::open(&f, &outsider, by_d(open)).await; + let mut private_outsider = LiveReq::open(&f, &outsider, by_d(private)).await; + assert_eq!(member.history, [group_state_id(&f, private, 39000).await]); + assert_eq!( + open_outsider.history, + [group_state_id(&f, open, 39000).await] + ); + assert!(private_outsider.history.is_empty()); + assert_eq!(refcount(&f, EventTopic::Channel(private)).await, 1); + assert_eq!(refcount(&f, EventTopic::Channel(open)).await, 1); + assert_eq!(refcount(&f, EventTopic::Global).await, 3); + + // This pod: the relay publishes a replacement after each edit. + for channel in [private, open] { + edit_channel( + &f.state, + &f.tenant, + &owner, + channel, + &[&["name", "renamed"]], + ) + .await + .expect("edit"); + } + assert_eq!( + member.next_event().await, + ( + 39000, + private.to_string(), + group_state_id(&f, private, 39000).await + ) + ); + assert_eq!( + open_outsider.next_event().await, + ( + 39000, + open.to_string(), + group_state_id(&f, open, 39000).await + ) + ); + + // Another pod's event, at the Redis receive handler. + let private_id = fan_out_from_another_pod(&f, private, "from-redis").await; + let open_id = fan_out_from_another_pod(&f, open, "from-redis").await; + assert_eq!( + member.next_event().await, + (39000, private.to_string(), private_id) + ); + assert_eq!( + open_outsider.next_event().await, + (39000, open.to_string(), open_id) + ); + private_outsider.assert_quiet("private outsider").await; + member.assert_quiet("member").await; + open_outsider.assert_quiet("open outsider").await; + + // Same-ID replacement moves the member's channel topic, once. + member.req(&f, by_d(open)).await; + assert_eq!(refcount(&f, EventTopic::Channel(private)).await, 0); + assert_eq!(refcount(&f, EventTopic::Channel(open)).await, 2); + assert_eq!(refcount(&f, EventTopic::Global).await, 3); + + for live in [&member, &open_outsider, &private_outsider] { + live.close(&f).await; + } + assert_eq!(refcount(&f, EventTopic::Channel(open)).await, 0); + assert_eq!(refcount(&f, EventTopic::Global).await, 0); +} + +/// In a REQ that mixes named and unnamed filters, the named filters keep +/// live delivery for their own channel and the unnamed filter keeps global +/// events. A `#P` or `#t:["system",