Skip to content

Commit 8519db1

Browse files
wpfleger96Hayt
andauthored
feat(buzz-relay): NIP-FI stateless enforcement (S3) — upgrade gate, NIP-42 pairing, session lifetime, JWKS warm (#7224)
## What this PR does Implements NIP-FI stateless enforcement at the relay WebSocket upgrade point. Every connection attempt on a NIP-FI–enabled relay must carry a valid federated identity assertion signed for the connecting Nostr pubkey; the relay validates it before the first frame is read, pairs it with NIP-42 AUTH, and enforces a bounded session lifetime without persistent state. ### Core enforcement seam - **Assertion at upgrade** (`nip_fi_upgrade.rs`): identity header is parsed with the same `extract_bearer_token` and denied with the same `http_denial` as HTTP ingress (`nip_fi_http.rs`), JWT verified (RS256/ES256/EdDSA), expiry checked, and the Nostr pubkey embedded in the sub claim must match the NIP-42 AUTH pubkey that arrives in the socket within the AUTH timeout. Denial returns exact byte contracts — `401 + WWW-Authenticate: Nostr + "authentication required\n"` for missing evidence, `403 + "evidence rejected\n"` for malformed or invalid evidence. The active HTTP/1.1 gate runs before `bind_community`, so denied upgrades pay zero DB cost. - **NIP-42 pairing** (`nip_fi_gate.rs`, `audio/handler.rs`): after the assertion is validated at upgrade, a `SessionAdmissionGate` is created with the assertion's expiry deadline and a `CancellationToken`. The gate is passed to every effect-acquiring path so no new effect permit is granted after the session expires. AUTH is verified against the assertion pubkey; a mismatched AUTH key receives `NOTICE restricted: authorization denied` and a socket close. Every other post-upgrade AUTH denial on an FI connection uses the same terminal shape — the canonical spec NOTICE on the terminal queue, then close — so frame type and close behaviour reveal nothing about private policy: ban, allowlist, or relay-membership denial → `restricted: authorization denied`; ban/allowlist/membership lookup failure or an internal verifier failure → `restricted: authorization unavailable`; an invalid NIP-42 proof → `restricted: evidence rejected`. Connections without an assertion keep today's `OK false` replies. - **Session lifetime** (`nip_fi_session.rs`): three independent deadlines bound each session — token `exp`, max assertion age from config, and relay max connection lifetime. The first to fire cancels the gate and sends the terminal denied frame. - **Effect admission at expiry** (`audio/join.rs`, `handlers/req.rs`): no new effect permit is granted after expiry. Two paths carry calculated budgets. The audio **lease resolver** holds its permit for at most `worst_case::PERMIT_HOLD` (14.5 s), and cancellation **during that resolver** reaches socket close within `worst_case::EXIT` (25 s: resolver, release of the won lease, terminal flush). Redis checkout has one total deadline and directory scripts are single-round-trip `EVAL`, which is what makes those budgets hold. When post-write fence verification fails after a landed CAS, the acquire keeps the reply and attempts an exact owner+generation cleanup on the same connection without a serving-write lease; if that cleanup fails or its reply is uncertain, the lease expires by its 30 s TTL. Neither number bounds audio close in general: other admission and teardown waits (for example the channel lookup after the resolver) and the known limitations below have no client-side deadline. REQ liveness, search and history reads race gate cancellation: a lost race drops the read, releases the permit, retires the claim through `close_if_owner`, and sends no further EVENT or EOSE. A history statement timeout ends the read with a timed-out outcome, and its owner-checked retirement (`CLOSED`, map, index and topic release) runs after the race with the permit dropped, so cancellation cannot drop it halfway. Subscription registration stays one uncancellable unit, and the permit is still taken before the claim. - **JWKS recovery** (`main.rs`): builds on main's `warm_nip_fi_jwks_snapshots` / `nip_fi_jwks_refresh_loop`. Issuers warm concurrently and the first refresh is seeded from the warm result (one interval for a warm issuer, 5 s for a cold one). A refresh that finds no live snapshot retries at the fast cadence (5 s after a warm issuer dies, doubling to a 300 s cap) instead of waiting a full interval, and `run_jwks_refresh_supervisor` restarts the loop after a panic (1 s → 60 s backoff); On shutdown it is cancelled and awaited before the drain backstop is disarmed; cancel drops an in-flight fetch and starts no further issuer, so the join stays inside the drain bound. Logs carry `issuer_index` only. ### Known limitations - **Known limitations: bounded only by the dependency.** No new effect is admitted after expiry. Two awaits that are already admitted have no client-side bound, so if a dependency stalls at expiry, teardown waits for it: - **Audio join commit:** its effect permit spans `tx.commit()`, room publication and the `event_mentions` insert. During a DB or Redis stall, audio cleanup and socket close wait for the dependency. - **REQ subscription setup:** the first subscriber to a topic sends `Subscribe` to the pubsub task through a bounded channel (capacity 4096). The send blocks only if that queue is full, which happens when the pubsub task isn't keeping up (for example during reconnect backoff or a burst). Registration holds the connection's `conn.subscriptions` lifecycle lock across the send, so a blocked send also blocks other claims on that connection, including search, and any cleanup waiting on that lock. The send itself predates this PR; holding the REQ permit across it is new here. ### Archive/join serialization `commit_participant_join` now takes a row-level write lock (`SELECT ... FOR NO KEY UPDATE`) on the channel row at step 3. This serializes all join commits against concurrent `archive_channel` calls — the archive UPDATE (`archived_at` non-key column) blocks on the row lock, closing the READ COMMITTED race on both the `Existing` and `AutoAddRequired` paths. ### HTTP/2 extended-CONNECT gate (latent path) The root WebSocket handler uses a belt-and-suspenders approach. The HTTP/1.1 path (currently the only live WebSocket shape — workspace Axum does not enable `http2`) is gated pre-extractor via the `Upgrade: websocket` + `Connection: Upgrade` header predicate. A second gate point inside the `Ok(ws)` arm is structural future-proofing: if `http2` is ever enabled, any h2 extended-CONNECT shape the extractor accepts but the h1 predicate misses is caught there. The active HTTP/1.1 fire-point sits before `bind_community` (zero DB cost on denial); the latent h2 fire-point runs after it. ### Mixed-version huddle control (rolling deploy) Owners advertise the `huddle-commit-phase` mesh capability. The ingress selects the mode after the owner stream opens: it sends the appended `RegisterPeerCommitPhase` variant, and later `CommitConfirmed`, only when the owner's exact runtime gossip record carries that flag at that point, and latches the result for the session. A successful open implies the owner's record is present, so a record that lands during acquisition is not missed. Otherwise it sends plain `RegisterPeer`, which every owner decodes. A new owner publishes a plain `RegisterPeer` once at registration (pre-commit-phase behavior) and holds a `RegisterPeerCommitPhase` peer until its confirm; duplicate or legacy confirms publish nothing. Existing wire variant indices are unchanged. ### Off-mode compatibility When `BUZZ_NIP_FI_MODE=off` (or unset), the relay reads no identity header and installs no upgrade gate, NIP-42 pairing check, or session deadline. Existing NIP-42 AUTH flows are unchanged. Huddle commit-before-publish is not FI-gated and applies in every mode, so huddle join publication timing differs from main even in Off mode. External connection cancellation (socket close, archival, revoke) now stops an in-flight liveness, search or history read at its next await; an uncancelled connection's frames and payload bytes are unchanged. ## Test coverage Every test this PR adds, or whose assertions it changes, runs in exactly one CI lane: infra-free tests in `just test-unit`, Postgres-backed tests in `postgres_tests` modules under the PostgreSQL lane. The `buzz-relay` bin tests run whole in `just test-unit`. `scripts/run-tests.sh` mirrors the effective relay unit selection for machines without nextest, except main's pre-existing `api::admin::` module. Every `buzz-relay` test fixture reads `Config` through `Config::for_test()`, which holds `NIP_FI_ENV_LOCK`, so a single-process `cargo test` run cannot observe a half-written FI environment (`fixture_config_read_waits_for_fi_env_lock`). The stub pools in the router and AUTH fixtures use a 100ms acquire timeout, which shortens a database fallthrough rather than removing it. - **Upgrade/router gate** (`router::tests`): Enforce-mode `nip_fi_*` gate tests for h1 WS upgrade, NIP-11 content negotiation, and audio ingress. Off-mode witnesses `nip_fi_off_root_passes_without_header`, `nip_fi_off_root_ignores_malformed_header`, `nip_fi_off_audio_passes_without_header`, `nip_fi_off_audio_ignores_malformed_header` prove the gate is bypassed (status outside 401/403/503, and no-header status equals malformed-header status); they do not prove a successful upgrade. - **NIP-FI units**: `nip_fi_config`, `nip_fi_upgrade`, `nip_fi_gate`, `nip_fi_session`, covering assertion contracts, NIP-42 pairing, session lifetime, and gate behavior. - **Effect barrier at cancellation** (`postgres_tests`, PostgreSQL lane): `w3_b2_req_barrier_expiry_mid_flight_blocks_subscription_registration`, `w4_b2_count_barrier_expiry_mid_flight_blocks_count_query`. - **AUTH denial uniformity** (`handlers::auth::tests`): each production-handler witness asserts the exact terminal frame, no denial on the data or ctrl channel, and cancellation, plus the unchanged Off-mode `OK false`. Unit: `fi_invalid_nip42_proof_emits_terminal_evidence_rejected`, `fi_ban_check_error_emits_terminal_authorization_unavailable`, `handle_auth_pairing_mismatch_runs_full_root_denial_path`, and `nip42_denial_class_separates_internal_failure_from_bad_evidence` (internal verifier failure → `authorization unavailable`; each client-evidence NIP-42 failure → `evidence rejected`). PostgreSQL lane: `fi_ban_denial_emits_terminal_authorization_denied` (real `community_bans` row; Off mode keeps `OK false` on ctrl, then close), `fi_relay_membership_denial_emits_terminal_authorization_denied`, `fi_allowlist_check_error_emits_terminal_authorization_unavailable`, `fi_relay_membership_check_error_emits_terminal_authorization_unavailable`, `fix_4a_allowlist_denial_with_fi_assertion_emits_canonical_restricted_frame`. - **Bounded audio exits** (`audio::handler::tests`, `just test-unit`): `check_cancel_exit_with_never_ready_sink_returns_within_flush_budget` drives the production `check_cancel!` fence with a queued FI denial into a never-ready sink and requires it to return within `WS_TERMINAL_FLUSH_TIMEOUT`; `challenge_send_to_never_ready_sink_exits_within_flush_budget_on_cancel` requires the NIP-42 challenge send to yield to cancellation and exit within the same budget; every pre-`send_loop` audio exit write goes through the same `connection::send_exit_frames_bounded` helper. - **Audio NIP-42 classification** (`audio::handler::tests`, `just test-unit`): `audio_bad_nip42_proof_with_fi_emits_one_evidence_rejected_then_cancels` requires exactly one canonical `restricted: evidence rejected` frame and cancellation; `audio_bad_nip42_proof_off_mode_keeps_auth_failed_frame` pins the Off-mode frame. - **Effect permit before pre-auth writes** (PostgreSQL lane): `handlers::auth::tests::postgres_tests::expiry_before_nip_oa_materialize_writes_no_rows_and_commits_no_auth` expires the session just before NIP-OA materialize and asserts no `users` or agent-owner row and no committed auth. - **Community admission** (`just test-unit`): `state::tests::on_not_run_runs_once_on_each_deny_arm_and_never_on_admit`. - **Auth metrics contract**: `connection::tests::auth_lifecycle_reconciles_every_terminal_and_never_leaks_gauge` records every terminal including `PairingMismatch`; `metrics::contract_tests::*` derive the series count from `AuthOutcome::ALL`. - **JWKS** (`main.rs`): `hard_dead_warm_issuer_resets_to_fast_cadence` and `jwks_refresh_success_waits_interval_failure_uses_fast_backoff` drive the real loop with paused Tokio time; `cold_issuer_*` cover the backoff helper; `f1_supervisor_loop_drives_recovery_and_restores_admission` runs `run_jwks_refresh_supervisor` over a real `ProductionJwksSource` through injected panic → restart → hard-dead → 5 s retry → recovery, then checks `key_set` admission and that the first post-restart fetch follows the cold cadence (every issuer restarts cold); `jwks_refresh_cancel_drops_in_flight_fetch_and_skips_remaining_issuers` cancels during a pending fetch with a second issuer due. - **Bounded lease acquire** (`audio::handler::tests::postgres_tests`, PostgreSQL lane): `failed_post_cas_verification_is_fenced_and_discards_the_won_lease` requires a won-then-unverified lease to return fenced and be deleted by exact owner+generation; `stalled_lease_sql_and_stalled_exit_release_close_within_exit_bound` stalls lease SQL and the exit release and requires socket close within `worst_case::EXIT`. `audio::join::tests` pins `PERMIT_HOLD` at 14.5 s and `EXIT` at 25 s. - **REQ/search cancellation** (`handlers::req::tests`, `just test-unit`): `expiry_during_stalled_history_read_releases_permit_and_claim` and `expiry_during_stalled_search_read_releases_permit_and_claim` stall the read inside production `handle_req`, expire the gate, and require `expire()` to return within 2 s, an empty subscription map, and no EVENT or EOSE. - **History timeout retirement** (`handlers::req::tests::postgres_tests`, PostgreSQL lane): `history_timeout_retirement_survives_expiry` drives a two-channel history REQ into a real statement timeout, pauses retirement after the index removal and before the topic release, expires the gate, then resumes. It requires the map and index entries gone and both channel topic refcounts at zero. - **Archive/join serialization** (PostgreSQL lane): `f2a_archived_channel_rejects_existing_join`, `f2b_join_for_update_blocks_concurrent_archive_existing_path`, `f2c_join_for_update_blocks_concurrent_archive_auto_add_path`. - **Huddle room and handler**: `audio::room::tests` pending-peer tests, including `roster_revisions_are_ordered_and_snapshot_is_authoritative`; `fix_b_w1_w3_handler_pre_commit_cancel_emits_no_delta`, `fix_b_w2_success_emits_exactly_one_delta_with_monotone_revision`. PostgreSQL lane: `b1_cross_pod_bootstrap_precedes_buffered_owner_delta`, `commit_confirm_timeout_at_seam_triggers_teardown_on_stalled_owner_stream`, `confirm_failure_combined_outcome_no_orphan_join_exactly_one_48102`, `confirm_send_pending_expiry_terminates_client_with_denial_within_1s`, `c1_handler_ingress_sends_only_base_frames_to_legacy_owner`, `f7a_cross_pod_joined_payload_includes_owner_pod_peers`. - **Mixed-version control** (`audio::join::tests`): `shared_control_variants_are_byte_identical_to_base_wire` (against frozen `audio::join::base_wire`), `c1_new_ingress_speaks_base_wire_to_legacy_owner`, `c2_base_ingress_register_publishes_once_on_new_owner`, `c3_capable_owner_record_selects_commit_phase_hold_back`, `capability_record_installed_during_open_selects_commit_phase`, `duplicate_or_legacy_commit_confirmed_is_a_no_op`, `fix_b_commit_confirmed_arm_commits_peer_and_broadcasts_joined`, `pending_remote_stream_close_emits_no_joined_no_left`. --------- Signed-off-by: Will Pfleger <[email protected]> Signed-off-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
1 parent b9d22a2 commit 8519db1

50 files changed

Lines changed: 20761 additions & 931 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Justfile‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,51 @@ test-unit:
473473
# because they live in the binary target; the nested
474474
# `tests::postgres_tests::` stays in the PostgreSQL lane.
475475
cargo nextest run -p buzz-relay --lib --bin buzz-relay \
476-
-E 'test(/^api::admin::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_config::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + test(/^api::git::transport::off_mode_precedence_tests::/) + test(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + 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) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/)) - test(/^tests::postgres_tests::/))'
476+
-E 'test(/^api::admin::/) + test(/^handlers::channel_authz::/) + test(/^handlers::moderation_authz::/) + test(/^handlers::side_effects::tests::/) + test(/^storage_sweep::tests::/) + test(/^nip_fi_http::tests::/) + test(/^nip_fi_config::tests::/) + test(/^readiness::tests::/) + test(/^router::tests::/) + test(/^api::parse_query_tests::/) + 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(=state::tests::neither_a_confirmed_inactive_community_nor_a_failed_lookup_admits_the_socket) + 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) + (kind(bin) & (test(/^tests::/) + test(/^composition_tests::/) + test(/^env_filter_tests::/)) - test(/^tests::postgres_tests::/))'
477+
# Note on audio::join::tests scope: the full suite is infra-free (no DB,
478+
# no Redis). The infra-free audio/FI regression witnesses — bootstrap
479+
# ordering barrier, CommitConfirmed arm, pending-close invisibility,
480+
# abnormal-stream-close fanout, and never-ready-sink writer witnesses —
481+
# are all selected by audio::join::tests and audio::handler::tests.
482+
# DB-backed audio join tests use #[ignore] and run in the postgres lane.
483+
# NIP-FI (S3) relay witnesses: the wholly-new nip_fi_upgrade module,
484+
# the auth metrics contract module, plus the exact NIP-FI tests added,
485+
# or whose assertions changed, in mixed modules (audio::room,
486+
# connection, handlers::*, state). nip_fi_config and router are
487+
# selected whole by the command above. Mixed modules are listed by exact
488+
# name so main's unselected tests (several wait out the ~30s sqlx
489+
# acquire timeout) stay out. NIP-FI tests that need Postgres live in
490+
# postgres_tests and
491+
# run in the PostgreSQL lane. Keep scripts/run-tests.sh in step.
492+
cargo nextest run -p buzz-relay --lib -E '
493+
test(/^nip_fi_upgrade::/)
494+
+ test(/^metrics::contract_tests::/)
495+
+ test(=audio::room::tests::roster_revisions_are_ordered_and_snapshot_is_authoritative)
496+
+ test(=connection::tests::auth_lifecycle_reconciles_every_terminal_and_never_leaks_gauge)
497+
+ test(=audio::room::tests::b1_pending_peer_removed_before_commit_emits_no_delta)
498+
+ test(=audio::room::tests::b2_commit_peer_emits_exactly_one_joined_delta_and_marks_visible)
499+
+ test(=audio::room::tests::b3_commit_peer_revision_is_monotone_between_concurrent_events)
500+
+ test(=audio::room::tests::f7a_pending_peer_excluded_from_snapshot_until_committed)
501+
+ test(=connection::tests::b2_cancelled_connection_event_frame_not_dispatched)
502+
+ test(=connection::tests::b3_expiry_denial_precedes_close_through_send_loop)
503+
+ test(=connection::tests::b3_root_pairing_denial_precedes_close_through_send_loop)
504+
+ test(=connection::tests::cancellation_during_select_with_fi_denial_routes_through_bounded_path)
505+
+ test(=connection::tests::cancelled_never_ready_sink_with_queued_fi_denial_exits_within_timeout)
506+
+ test(=connection::tests::deadline_exp_is_earliest_selects_exp)
507+
+ test(=connection::tests::deadline_max_connection_lifetime_is_earliest_selects_partition)
508+
+ test(=connection::tests::deadline_no_lifetime_returns_upstream_only)
509+
+ test(=connection::tests::expiry_notice_queued_on_ctrl_before_cancel)
510+
+ test(=connection::tests::f3_root_outer_wrapper_delivers_denial_on_bootstrap_cancellation)
511+
+ test(=connection::tests::f3_root_pre_built_expired_gate_terminates_connection)
512+
+ test(=handlers::auth::tests::b2_pre_cancelled_connection_never_becomes_authenticated)
513+
+ test(=handlers::auth::tests::fi_ban_check_error_emits_terminal_authorization_unavailable)
514+
+ test(=handlers::auth::tests::fi_invalid_nip42_proof_emits_terminal_evidence_rejected)
515+
+ test(=handlers::auth::tests::handle_auth_pairing_mismatch_runs_full_root_denial_path)
516+
+ test(=handlers::auth::tests::nip42_denial_class_separates_internal_failure_from_bad_evidence)
517+
+ test(=handlers::event::tests::p1b_agent_observer_event_barrier_expiry_blocks_fanout_and_ack)
518+
+ test(=handlers::req::tests::p1a_huddle_liveness_req_barrier_expiry_blocks_query_and_emission)
519+
+ test(=state::tests::f3_cancellation_during_check_terminates_socket_without_waiting_for_check)
520+
+ test(=state::tests::on_not_run_runs_once_on_each_deny_arm_and_never_on_admit)'
477521
# ACP author-gate and queue tests protect the trust boundary between
478522
# relay events and agent prompts. They are infra-free; ignored lifecycle
479523
# tests remain excluded and run in their dedicated integration lanes.

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ pub use nip_fi::jwks::ScriptedJwksFetcher;
6565
#[cfg(any(test, feature = "test-utils"))]
6666
pub use nip_fi::StaticIssuerKeySource;
6767
#[cfg(any(test, feature = "test-utils"))]
68+
pub use nip_fi::ToggleJwksFetcher;
69+
#[cfg(any(test, feature = "test-utils"))]
6870
pub use rate_limit::AlwaysAllowRateLimiter;
6971

7072
/// How the connection was authenticated.

‎crates/buzz-auth/src/nip_fi/assertion.rs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,48 @@ impl fmt::Debug for VerifiedAssertion {
232232
}
233233
}
234234

235+
#[cfg(any(test, feature = "test-utils"))]
236+
impl VerifiedAssertion {
237+
/// Test-only factory for building `VerifiedAssertion` fixtures without
238+
/// going through the full JWT/JWKS verification path. NOT available in
239+
/// production builds.
240+
///
241+
/// # Panics
242+
///
243+
/// Panics when `authority_deadlines` is empty — an empty set violates the
244+
/// non-empty invariant that `upstream_authority_deadline()` relies on.
245+
pub fn for_test(
246+
asserted_key: Option<PublicKey>,
247+
authority_deadlines: Vec<DateTime<Utc>>,
248+
) -> Self {
249+
assert!(
250+
!authority_deadlines.is_empty(),
251+
"VerifiedAssertion::for_test: authority_deadlines must be non-empty \
252+
(upstream_authority_deadline() panics on empty)"
253+
);
254+
use super::config::{AssertionPolicyId, TransportContractId};
255+
Self {
256+
identity: FederatedIdentity {
257+
issuer: "test-issuer".to_string(),
258+
subject: "test-subject".to_string(),
259+
},
260+
asserted_key,
261+
capabilities: CanonicalCapabilities::from_pairs(vec![]),
262+
authority_deadlines,
263+
assertion_policy_id: AssertionPolicyId::zero(),
264+
transport_contract_id: TransportContractId::zero(),
265+
revalidation_dependencies: RevalidationDependencies {
266+
verification_key_id: "test-kid".to_string(),
267+
key_snapshot_generation: 0,
268+
key_snapshot_hard_deadline: DateTime::<Utc>::MAX_UTC,
269+
confidential_assertion: ConfidentialAssertion {
270+
compact_jws: "test.test.test".to_string(),
271+
},
272+
},
273+
}
274+
}
275+
}
276+
235277
impl RevalidationDependencies {
236278
pub(super) fn new(
237279
verification_key_id: String,

‎crates/buzz-auth/src/nip_fi/jwks/mod.rs‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -747,6 +747,75 @@ impl<F> std::fmt::Debug for ProductionJwksSource<F> {
747747
}
748748
}
749749

750+
/// A toggle-controlled [`JwksFetcher`] for use in downstream-crate integration
751+
/// tests. Returns a minimal but valid JWKS document when the toggle is `true`,
752+
/// and `NetworkError` when `false`.
753+
///
754+
/// This is the only path by which a crate outside `buzz-auth` can build a
755+
/// `ProductionJwksSource` with a controllable fetch outcome — `sealed::Sealed`
756+
/// is crate-private, so downstream crates cannot implement `JwksFetcher`
757+
/// directly. Because the returned JWKS is real (not a synthetic shortcut), the
758+
/// full `ProductionJwksSource` code path — parse, bound, cache, hard-deadline —
759+
/// exercises itself normally, and the resulting `AssertionKeySet` is valid for
760+
/// verifier lookups.
761+
///
762+
/// Only available with the `test-utils` feature enabled.
763+
#[cfg(any(test, feature = "test-utils"))]
764+
#[derive(Clone, Debug)]
765+
pub struct ToggleJwksFetcher {
766+
/// When `true` the fetcher returns a minimal valid JWKS body; when `false`
767+
/// it returns `JwksFetchError::NetworkError`.
768+
pub available: std::sync::Arc<std::sync::atomic::AtomicBool>,
769+
/// Fired (via `notify_one`) after every fetch attempt completes, whether
770+
/// successful or not. Tests can await this to deterministically observe
771+
/// that the fetch loop executed a given attempt before proceeding.
772+
pub fetch_done: std::sync::Arc<tokio::sync::Notify>,
773+
}
774+
775+
#[cfg(any(test, feature = "test-utils"))]
776+
impl ToggleJwksFetcher {
777+
/// Construct a new `ToggleJwksFetcher`. Pass `initial` as the starting
778+
/// availability state; `available` and `fetch_done` are externally
779+
/// observable and can be driven from the test after construction.
780+
pub fn new(initial: bool) -> Self {
781+
Self {
782+
available: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(initial)),
783+
fetch_done: std::sync::Arc::new(tokio::sync::Notify::new()),
784+
}
785+
}
786+
}
787+
788+
#[cfg(any(test, feature = "test-utils"))]
789+
impl super::verifier::sealed::Sealed for ToggleJwksFetcher {}
790+
791+
#[cfg(any(test, feature = "test-utils"))]
792+
impl JwksFetcher for ToggleJwksFetcher {
793+
fn fetch_jwks<'a>(
794+
&'a self,
795+
_uri: &'a str,
796+
) -> impl std::future::Future<Output = Result<String, JwksFetchError>> + Send + 'a {
797+
// A minimal P-256 JWK. The coordinates are the same values used in
798+
// buzz-auth's own test suite (tests.rs `minimal_jwks_json`).
799+
const TOGGLE_JWKS: &str = concat!(
800+
r#"{"keys":[{"kty":"EC","crv":"P-256","#,
801+
r#""x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU","#,
802+
r#""y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0","#,
803+
r#""use":"sig","alg":"ES256","kid":"toggle-kid"}]}"#
804+
);
805+
let available = self.available.load(std::sync::atomic::Ordering::SeqCst);
806+
let fetch_done = std::sync::Arc::clone(&self.fetch_done);
807+
async move {
808+
let result = if available {
809+
Ok(TOGGLE_JWKS.to_string())
810+
} else {
811+
Err(JwksFetchError::NetworkError)
812+
};
813+
fetch_done.notify_one();
814+
result
815+
}
816+
}
817+
}
818+
750819
#[cfg(test)]
751820
mod tests;
752821

‎crates/buzz-auth/src/nip_fi/mod.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ pub use jwks::{
3333
HttpJwksFetcher, IssuerJwksConfig, JwksFetchError, JwksFetcher, JwksSourceContract,
3434
ProductionJwksSource,
3535
};
36+
37+
#[cfg(any(test, feature = "test-utils"))]
38+
pub use jwks::ToggleJwksFetcher;
3639
pub use startup::{validate_nip_fi_config, NipFiMode, NipFiStartupError};
3740
pub use verifier::{
3841
AssertionKeySet, FederatedAssertionVerifier, IssuerKeySource, VerifierError, VerifyAssertion,

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1174,6 +1174,16 @@ impl Db {
11741174
}
11751175
}
11761176

1177+
/// Return a reference to the writer pool.
1178+
///
1179+
/// Callers that need a pool handle for standalone free functions (e.g.,
1180+
/// `buzz_db::insert_mentions`) can use this. Prefer the `Db` method
1181+
/// equivalents when they exist; use `pool()` only for functions that have
1182+
/// no `Db` wrapper yet.
1183+
pub fn pool(&self) -> &PgPool {
1184+
&self.pool
1185+
}
1186+
11771187
/// Refresh all expected operation-specific waiter gauges, including zero.
11781188
///
11791189
/// The relay pool sampler calls this periodically so an exporter idle

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

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,82 @@ async fn acquire_channel_membership_lock(
197197
Ok(())
198198
}
199199

200+
// ── Transaction-level membership helpers (for commit_participant_join) ────────
201+
202+
/// Acquire the per-channel membership advisory lock on a caller-owned transaction.
203+
///
204+
/// Equivalent to the internal `acquire_channel_membership_lock`, but exposed
205+
/// for callers that need to compose multiple operations in one transaction
206+
/// (e.g., `commit_participant_join` in `audio/handler.rs`).
207+
pub async fn acquire_channel_membership_lock_in_transaction(
208+
tx: &mut Transaction<'_, Postgres>,
209+
community_id: CommunityId,
210+
channel_id: Uuid,
211+
) -> Result<()> {
212+
acquire_channel_membership_lock(tx, community_id, channel_id).await
213+
}
214+
215+
/// Check whether a pubkey is an active channel member on a caller-owned transaction.
216+
///
217+
/// Runs the same query as `is_member` but within the caller's transaction so
218+
/// the read is serialized with any concurrent membership writes on the same lock.
219+
pub async fn is_member_in_transaction(
220+
tx: &mut Transaction<'_, Postgres>,
221+
community_id: CommunityId,
222+
channel_id: Uuid,
223+
pubkey: &[u8],
224+
) -> Result<bool> {
225+
let row = sqlx::query(
226+
"SELECT COUNT(*) as cnt FROM channel_members cm \
227+
JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL \
228+
WHERE cm.community_id = $1 AND cm.channel_id = $2 AND cm.pubkey = $3 AND cm.removed_at IS NULL",
229+
)
230+
.bind(community_id.as_uuid())
231+
.bind(channel_id)
232+
.bind(pubkey)
233+
.fetch_one(&mut **tx)
234+
.await?;
235+
let cnt: i64 = row.try_get("cnt")?;
236+
Ok(cnt > 0)
237+
}
238+
239+
/// Auto-add a member on a caller-owned transaction (for ephemeral-channel admission).
240+
///
241+
/// Inserts or reactivates the membership row at `Member` role with the given
242+
/// `invited_by` (channel creator for huddle auto-add). Does NOT acquire the
243+
/// advisory lock — callers must have already called
244+
/// `acquire_channel_membership_lock_in_transaction` before calling this.
245+
///
246+
/// Used by `commit_participant_join` to atomically add membership and the
247+
/// `48101` event in a single transaction under a session effect permit.
248+
pub async fn insert_auto_membership_in_transaction(
249+
tx: &mut Transaction<'_, Postgres>,
250+
community_id: CommunityId,
251+
channel_id: Uuid,
252+
pubkey: &[u8],
253+
invited_by: &[u8],
254+
) -> Result<()> {
255+
sqlx::query(
256+
r#"
257+
INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by)
258+
VALUES ($1, $2, $3, 'member'::member_role, $4)
259+
ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET
260+
removed_at = NULL,
261+
removed_by = NULL,
262+
role = EXCLUDED.role
263+
"#,
264+
)
265+
.bind(community_id.as_uuid())
266+
.bind(channel_id)
267+
.bind(pubkey)
268+
.bind(invited_by)
269+
.execute(&mut **tx)
270+
.await?;
271+
Ok(())
272+
}
273+
274+
// ── End transaction-level helpers ─────────────────────────────────────────────
275+
200276
/// An active member roster captured while holding the channel's membership
201277
/// serialization lock on one writer connection.
202278
pub struct LockedMemberSnapshot {

0 commit comments

Comments
 (0)