#[test] fn database_metrics_and_slow_logs_exclude_sensitive_or_unbounded_fields() { let implementation = include_str!("../src/runtime/observability.rs"); let datastore_macro = include_str!("../../buzz-datastore-tracing/src/lib.rs"); let instrumentation = format!("{implementation}\n{datastore_macro}"); for forbidden in [ "\"community\" =>", "\"event_id\" =>", "\"event_kind\" =>", "\"sql\" =>", "\"query\" =>", "\"query_id\" =>", "\"d_tag\" =>", "\"coordinate\" =>", "community =", "event_id =", "event_kind =", "sql =", "query_id =", "d_tag =", "coordinate =", ] { assert!( !instrumentation.contains(forbidden), "database instrumentation must not expose {forbidden}" ); } // 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 =")); assert!( datastore_macro.contains("parent: None"), "slow warnings must not inherit dynamic datastore span fields" ); // The runtime tracing-layer assertion covers field names because a source // search would also match ordinary local variables such as `record_error`. } #[test] fn relay_admin_db_wrappers_have_exactly_one_datastore_span() { for (domain, source) in [ ( "relay_admin_actions", include_str!("../src/store/relay_admin_actions.rs"), ), ( "relay_operators", include_str!("../src/store/relay_operators.rs"), ), ] { let db_impl = source .split_once("impl crate::Db {") .unwrap_or_else(|| panic!("{domain} must own its Db wrappers")) .1 .split_once("\n#[cfg(test)]") .unwrap_or_else(|| panic!("{domain} Db wrappers must precede focused tests")) .0; let mut pending_spans = 0; let mut methods = 0; for line in db_impl.lines() { if line.contains("#[datastore_span(") { pending_spans += 1; } if line.trim_start().starts_with("pub async fn ") { assert_eq!(pending_spans, 1, "{domain} wrapper `{line}` span count"); pending_spans = 0; methods += 1; } } assert!(methods > 0, "{domain} must own public Db wrappers"); assert_eq!( pending_spans, 0, "{domain} has an unattached datastore span" ); } } #[test] fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() { let observability = include_str!("../src/runtime/observability.rs"); assert!(observability.contains("enum PoolOperation")); assert!(observability.contains("pub(crate) enum WriterOperation")); assert!(observability.contains("pub(crate) enum ReaderOperation")); assert!(observability.contains("Self::WriterAuthentication")); assert!(observability.contains("Self::ReaderSubscriptionHistory")); assert!(observability.contains("pub(crate) async fn acquire_writer(")); assert!(observability.contains("pub(super) async fn acquire_reader_with_legacy_metrics(")); assert!(observability.contains("static POOL_WAITERS: [Mutex")); assert!(!observability.contains("AtomicU64")); assert!(!observability.contains("DbOperation::Other")); assert!(!observability.contains("\"other\"")); assert!(!observability.contains("buzz_db_pool_acquire_timeouts_total")); assert!(!observability.contains("\"result\" =>")); let legacy_transaction = observability .split_once("pub(crate) async fn begin_transaction(") .expect("observability must expose attributed transaction acquisition") .1 .split_once("pub(crate) async fn observe_advisory_lock") .expect("transaction acquisition must precede advisory-lock observation") .0; assert!(legacy_transaction.contains("acquire_writer_with_legacy_metrics(")); let runtime = include_str!("../src/runtime/mod.rs"); assert!(runtime.contains("observability::acquire_writer_until(")); assert!(runtime.contains("WriterOperation::Readiness")); assert!(runtime.contains("WriterOperation::EventWrite")); assert!(runtime.contains("ReaderOperation::Bootstrap")); assert!(runtime.contains("pub async fn begin_event_write_transaction")); let reader_boot = runtime .split_once("async fn read_pool_boot_ping_once(") .expect("runtime must expose the reader boot probe") .1 .split_once("#[cfg(test)]") .expect("reader boot probe must precede its test seam") .0; assert!(reader_boot.contains("acquire_reader_with_legacy_metrics(")); let routed_reader = runtime .split_once("async fn proved_reader(") .expect("runtime must expose the routed-reader checkout") .1 .split_once("async fn reader_aurora_capability_on(") .expect("routed-reader checkout must precede capability probing") .0; assert!(routed_reader.contains("acquire_reader_with_legacy_metrics(read_pool, operation)")); let event_write_transaction = runtime .split_once("pub async fn begin_event_write_transaction(") .expect("runtime must expose the public event-write transaction seam") .1 .split_once("pub async fn insert_event_with_serving_write_guard(") .expect("public event-write transaction must precede guarded writes") .0; assert!(event_write_transaction.contains(COMMUNITY_CHOKEPOINT_LEGACY_MARKER)); let migration = include_str!("../src/runtime/migration.rs"); let migration_lock = migration .split_once("pub(crate) async fn with_exclusive_schema_destruction_lock") .expect("migration must expose the schema-safety acquisition seam") .1 .split_once("async fn reject_legacy_nip_rs_cardinality_ambiguity") .expect("schema-safety acquisition must precede migration validation") .0; assert!(migration_lock.contains("acquire_writer_with_legacy_metrics(")); let allowlist = include_str!("../src/store/allowlist.rs"); assert!(allowlist.contains("WriterOperation::Authentication")); assert!(allowlist.contains("WriterOperation::Authorization")); assert!(!allowlist.contains("fetch_one(&self.pool)")); let event = include_str!("../src/store/event.rs"); assert!(event.contains("query_events_with_operation")); assert!(event.contains("WriterOperation::Authorization")); assert!(event.contains("WriterOperation::SubscriptionHistory")); assert!(event.contains("ReaderOperation::SubscriptionHistory")); let soft_delete_discovery = event .split_once("pub async fn soft_delete_discovery_events") .expect("event store must expose discovery-event deletion") .1 .split_once("\n}\n\n#[cfg(test)]") .expect("discovery deletion must end the production Db implementation") .0; assert!(soft_delete_discovery.contains("WriterOperation::EventWrite")); assert!(soft_delete_discovery.contains("begin_community_event_write_transaction(")); assert!(soft_delete_discovery.contains("execute(tx.conn())")); let side_effects = include_str!("../../buzz-relay/src/handlers/side_effects.rs"); assert!(side_effects.contains("query_events_for_event_write")); assert!(side_effects.contains("query_events_for_bootstrap")); assert!(side_effects.contains(".list_channels_for_bootstrap(")); let deletion = include_str!("../src/store/deletion.rs"); let public_serving_catalog = deletion .split_once("pub async fn validate_serving_catalog(&self)") .expect("deletion store must preserve its public serving-catalog API") .1 .split_once("async fn validate_serving_catalog_on") .expect("public serving-catalog validation must delegate to its connection helper") .0; assert!(public_serving_catalog.contains("WriterOperation::Bootstrap")); assert!(public_serving_catalog.contains("observability::acquire_writer(")); assert!(public_serving_catalog.contains("validate_serving_catalog_on")); assert!(!public_serving_catalog.contains("self.pool.acquire()")); let thread = include_str!("../src/store/thread.rs"); let thread_metadata = thread .split_once("pub async fn get_thread_metadata_by_event(") .expect("thread store must expose metadata lookup") .1 .split_once("// -- Db API") .expect("metadata lookup must precede the Db wrapper section") .0; assert!(thread_metadata.contains("WriterOperation::EventWrite")); assert!(thread_metadata.contains("fetch_optional(&mut *connection)")); assert!(!thread_metadata.contains("fetch_optional(pool)")); let channel = include_str!("../src/store/channel.rs"); assert!(channel.contains("begin_community_write_transaction(")); for (start, end, expected) in [ ( "pub async fn create_channel(\n", "/// Creates a channel with a client-supplied UUID", "begin_community_write_transaction(", ), ( "pub async fn create_channel_with_id(\n", "/// Fetches a channel record by `(community_id, id)`", "begin_community_write_transaction(", ), ( "pub async fn update_channel(\n", "/// Sets the topic for a channel", "begin_community_write_transaction(", ), ( "pub async fn set_topic(\n", "/// Sets the purpose for a channel", "begin_community_write_transaction(", ), ( "pub async fn set_purpose(\n", "/// Archives a channel", "begin_community_write_transaction(", ), ( "pub async fn archive_channel(\n", "/// Unarchives a channel", "begin_community_write_transaction(", ), ( "pub async fn unarchive_channel(\n", "/// Soft-delete a channel", "begin_community_write_transaction(", ), ( "pub async fn soft_delete_channel(\n", "/// Archive ephemeral channels", "begin_community_write_transaction(", ), ] { let function = channel .split_once(start) .unwrap_or_else(|| panic!("missing channel seam {start}")) .1 .split_once(end) .unwrap_or_else(|| panic!("channel seam {start} must precede {end}")) .0; assert!( function.contains(expected), "channel seam {start} must use {expected}" ); assert!(!function.contains("pool.begin().await")); assert!(!function.contains(".execute(pool)")); assert!(!function.contains(".fetch_optional(pool)")); } let get_channel = channel .split_once("async fn get_channel_with_operation(") .expect("channel store must route shared lookups through caller-owned intent") .1 .split_once("/// Returns the canvas content") .expect("channel lookup helper must precede canvas reads") .0; assert!(get_channel.contains("acquire_writer(pool, operation)")); 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 .split_once("async fn list_channels_with_operation(") .expect("channel listing must accept caller-owned intent") .1 .split_once("/// A channel archived by the ephemeral-channel reaper") .expect("channel listing must precede ephemeral-channel types") .0; assert!(list_channels.contains("acquire_writer(pool, operation)")); assert!(list_channels.contains("fetch_all(&mut *connection)")); assert!(!list_channels.contains("fetch_all(pool)")); assert!(channel.contains("pub async fn list_channels_for_bootstrap(")); let channel_members = include_str!("../src/store/channel_members.rs"); assert!(channel_members.contains("async fn get_members_with_operation(")); assert!(channel_members.contains("pub async fn get_members_for_event_write(")); assert!(channel_members.contains("async fn get_users_bulk_with_operation(")); assert!(channel_members.contains("pub async fn get_users_bulk_for_event_write(")); let huddle_link = event .split_once("async fn huddle_started_link_exists_with_operation(") .expect("huddle link lookup must accept caller-owned intent") .1 .split_once("/// Insert a Nostr event") .expect("huddle link lookup must precede event insertion") .0; assert!(huddle_link.contains("acquire_writer(pool, operation)")); assert!(event.contains("pub async fn huddle_started_link_exists_for_event_write(")); let ingest = include_str!("../../buzz-relay/src/handlers/ingest.rs"); assert!(ingest.contains(".huddle_started_link_exists_for_event_write(")); let audio = include_str!("../../buzz-relay/src/audio/handler.rs"); assert!(audio.contains(".huddle_started_link_exists(")); let workflow_sink = include_str!("../../buzz-relay/src/workflow_sink.rs"); assert!(workflow_sink.contains(".get_members_for_event_write(")); assert!(workflow_sink.contains(".get_users_bulk_for_event_write(")); for write_caller in [ include_str!("../../buzz-relay/src/handlers/side_effects.rs"), include_str!("../../buzz-relay/src/handlers/ingest.rs"), include_str!("../../buzz-relay/src/handlers/command_executor.rs"), workflow_sink, ] { assert!(!write_caller.contains(".get_channel(")); assert!(write_caller.contains(".get_channel_for_event_write(")); } let user = include_str!("../src/store/user.rs"); let agent_channel_policy = user .split_once("pub async fn get_agent_channel_policy(") .expect("user store must expose get_agent_channel_policy") .1 .split_once("/// Check whether `actor_pubkey`") .expect("agent policy lookup must precede owner lookup") .0; assert!(agent_channel_policy.contains("WriterOperation::Authorization")); assert!(agent_channel_policy.contains("fetch_optional(&mut *connection)")); assert!(!agent_channel_policy.contains("fetch_optional(pool)")); let is_agent_owner = user .split_once("pub async fn is_agent_owner(") .expect("user store must expose is_agent_owner") .1 .split_once("/// Set the channel_add_policy") .expect("is_agent_owner must precede set_agent_channel_policy") .0; assert!(is_agent_owner.contains("WriterOperation::Authorization")); assert!(is_agent_owner.contains("acquire_writer(")); assert!(is_agent_owner.contains("fetch_optional(&mut *connection)")); assert!(!is_agent_owner.contains("fetch_optional(pool)")); let moderation = include_str!("../src/store/moderation.rs"); let restriction_state = moderation .split_once("pub async fn restriction_state(") .expect("moderation store must expose restriction_state") .1 .split_once("/// Fetch the full ban/timeout row") .expect("restriction state must precede full ban reads") .0; assert!(restriction_state.contains("WriterOperation::Authorization")); // The single aggregate row is read on the attributed writer connection, // never directly on the pool. assert!(restriction_state.contains("fetch_one(&mut *connection)")); assert!(!restriction_state.contains("(pool)")); let community_store = include_str!("../src/store/community.rs"); let ensure_community = community_store .split_once("pub async fn ensure_configured_community(") .expect("community store must expose ensure_configured_community") .1 .split_once("/// Atomically creates a community") .expect("configured-community helpers must precede community creation") .0; assert!(ensure_community.contains("WriterOperation::Authorization")); assert!(ensure_community.contains("WriterOperation::Bootstrap")); assert!(ensure_community.contains("ensure_configured_community_with_operation")); assert!(ensure_community.contains("acquire_writer(&self.pool, operation)")); assert!(ensure_community.contains("fetch_optional(&mut *connection)")); let management_lookup = community_store .split_once("pub async fn lookup_community_by_host_for_management(") .expect("community store must expose management host lookup") .1 .split_once("/// Lists communities where") .expect("management lookup must precede owner listing") .0; assert!(management_lookup.contains("WriterOperation::Authorization")); assert!(management_lookup.contains("fetch_optional(&mut *connection)")); assert!(!management_lookup.contains("fetch_optional(&self.pool)")); let community_production = community_store .split("\n#[cfg(test)]") .next() .expect("community production source"); for required in [ "WriterOperation::TenantResolution", "WriterOperation::Authorization", "WriterOperation::SubscriptionHistory", "WriterOperation::EventWrite", ] { assert!( community_production.contains(required), "community P0 paths must include {required} attribution" ); } assert!(!community_production.contains("self.pool.begin().await")); assert!(!community_production.contains(".fetch_one(&self.pool)")); assert!(!community_production.contains(".fetch_all(&self.pool)")); assert!(!community_production.contains(".execute(&self.pool)")); assert_eq!( community_production .matches(".fetch_optional(&self.pool)") .count(), 1, "only the out-of-scope NIP-11 metadata read may retain a raw pool checkout" ); let thread_summary = thread .split_once("pub async fn get_thread_summary(") .expect("thread store must expose get_thread_summary") .1 .split_once("/// Fetch one channel window") .expect("thread summary must precede channel-window reads") .0; assert!(thread_summary.contains("WriterOperation::EventWrite")); assert!(thread_summary.contains("fetch_optional(&mut *connection)")); assert!(!thread_summary.contains("fetch_optional(pool)")); assert!(!thread_summary.contains("fetch_all(pool)")); let archived_identities = include_str!("../src/store/archived_identities.rs"); let archived_identity_production = archived_identities .split("\n#[cfg(test)]") .next() .expect("archived identity production source"); assert_eq!( archived_identity_production .matches("WriterOperation::EventWrite") .count(), 4, "all four archived identity operations must be attributed to event writes" ); assert!(!archived_identity_production.contains("fetch_optional(pool)")); assert!(!archived_identity_production.contains("fetch_all(pool)")); assert!(!archived_identity_production.contains("execute(pool)")); let relay_main = include_str!("../../buzz-relay/src/main.rs"); assert!(relay_main.contains("pool_state.db.refresh_pool_waiter_metrics();")); assert!(relay_main.contains("ensure_deployment_community(&db,")); let provisioning = include_str!("../../buzz-relay/src/handlers/community_provisioning.rs"); assert!(provisioning.contains(".ensure_configured_community_for_bootstrap(")); let runtime = include_str!("../src/runtime/mod.rs"); assert!(runtime.contains("observability::refresh_pool_waiters(self.read_pool.is_some())")); let replica_fence = include_str!("../src/runtime/replica_fence.rs"); let replica_fence_production = replica_fence .split("\n#[cfg(test)]") .next() .expect("replica-fence production source"); // 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 leader_lock = include_str!("../src/store/leader_lock.rs"); let leader_lock_production = leader_lock .split("\n#[cfg(test)]") .next() .expect("leader-lock production source"); let leader_lock_acquisition = leader_lock_production .split_once("pub async fn try_lock_session_leader(") .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:") .expect("channel store must expose ephemeral reaper") .1 .split_once("\nimpl Db {") .expect("ephemeral reaper must precede Db wrappers") .0; assert!(channel_reaper.contains("WriterOperation::Maintenance")); assert!(channel_reaper.contains("fetch_all(&mut *connection)")); let deletion = include_str!("../src/store/deletion.rs"); let lease_reaper = deletion .split_once("pub async fn reap_expired_serving_write_leases") .expect("deletion store must expose serving-lease reaper") .1 .split_once("/// Return serving-lease counts") .expect("serving-lease reaper must precede stats") .0; assert!(lease_reaper.contains("WriterOperation::Maintenance")); assert!(lease_reaper.contains("execute(&mut *connection)")); let lease_stats = deletion .split_once("pub async fn serving_lease_stats") .expect("deletion store must expose serving-lease stats") .1 .split_once("/// Whether a community remains active") .expect("serving-lease stats must precede serving-state reads") .0; assert!(lease_stats.contains("WriterOperation::Maintenance")); assert!(lease_stats.contains("fetch_one(&mut *connection)")); // Lease seams that delegate to the bounded helper inherit its attribution. let bounded_lease_sql = deletion .split_once("async fn bounded_serving_lease_sql(") .expect("deletion store must expose the bounded serving-lease helper") .1 .split_once("/// Acquire a durable, expiring lease") .expect("bounded serving-lease helper must precede lease acquisition") .0; assert!(bounded_lease_sql.contains("WriterOperation::EventWrite")); assert!(!bounded_lease_sql.contains("self.pool.begin().await")); for (start, end) in [ ( "pub async fn acquire_serving_write_lease", "/// Renew an already-admitted external side-effect lease", ), ( "pub async fn renew_serving_write_lease", "/// Release a serving side-effect lease", ), ( "pub async fn release_serving_write_lease", "/// Check that an external side-effect lease remains current", ), ( "pub async fn verify_serving_write_lease", "/// Delete expired serving leases", ), ( "pub async fn is_serving_active", "async fn advance_with_checkpoint", ), ] { let function = deletion .split_once(start) .unwrap_or_else(|| panic!("missing serving-write seam {start}")) .1 .split_once(end) .unwrap_or_else(|| panic!("serving-write seam {start} must precede {end}")) .0; assert!( function.contains("WriterOperation::EventWrite") || function.contains("self.bounded_serving_lease_sql("), "serving-write seam {start} must be event-write attributed" ); assert!(!function.contains("self.pool.begin().await")); assert!(!function.contains(".execute(&self.pool)")); assert!(!function.contains(".fetch_one(&self.pool)")); } let ensure_authorization = user .split_once("pub async fn ensure_user_for_authorization(") .expect("user store must expose NIP-OA authorization ensure") .1 .split_once("/// Get a single user record") .expect("authorization ensure must precede generic user reads") .0; assert!(ensure_authorization.contains("WriterOperation::Authorization")); let set_owner_authorization = user .split_once("pub async fn set_agent_owner_for_authorization(") .expect("user store must expose NIP-OA authorization owner write") .1 .split_once("/// Get the channel_add_policy") .expect("authorization owner write must precede policy reads") .0; assert!(set_owner_authorization.contains("WriterOperation::Authorization")); let relay_api = include_str!("../../buzz-relay/src/api/mod.rs"); assert!(relay_api.contains(".ensure_user_for_authorization(")); assert!(relay_api.contains(".set_agent_owner_for_authorization(")); for (domain, source) in [ ( "channel_members", include_str!("../src/store/channel_members.rs"), ), ("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), ("reaction", include_str!("../src/store/reaction.rs")), ("relay_invite", include_str!("../src/store/relay_invite.rs")), ( "relay_members", include_str!("../src/store/relay_members.rs"), ), ("thread", thread), ( "relay_operators", include_str!("../src/store/relay_operators.rs"), ), ("leader_lock", leader_lock), ] { let production = source.split("\n#[cfg(test)]").next().unwrap_or(source); for bypass in [ "pool.begin().await", "self.pool.begin().await", ".fetch_one(pool)", ".fetch_one(&self.pool)", ".fetch_all(pool)", ".fetch_all(&self.pool)", ".fetch_optional(pool)", ".fetch_optional(&self.pool)", ".execute(pool)", ".execute(&self.pool)", ] { assert!( !production.contains(bypass), "{domain} production path bypasses operation attribution with {bypass}" ); } } } #[test] fn pool_level_insert_mentions_opens_the_tenant_local_chokepoint() { let runtime = include_str!("../src/runtime/mod.rs"); let insert_mentions = runtime .split_once("pub async fn insert_mentions(\n") .expect("runtime must expose pool-level insert_mentions") .1 .split_once("pub(crate) async fn insert_mentions_in_transaction(") .expect("pool-level insert_mentions must precede its transaction seam") .0; assert!( insert_mentions.contains(COMMUNITY_CHOKEPOINT_MARKER), "post-commit mention indexing must be admitted like any other event-table write" ); } #[test] fn event_write_paths_include_tenant_local_chokepoint_calls() { let event = include_str!("../src/store/event.rs"); let insert_event = event .split_once("pub async fn insert_event(\n") .expect("event store must expose pool-level insert_event") .1 .split_once("/// Insert a Nostr event in a caller-owned admitted transaction") .expect("pool insert must precede transaction-seam insert") .0; assert!( has_any_tenant_local_chokepoint(insert_event), "pool-level event inserts must include a tenant-local event-write chokepoint call" ); let insert_with_thread_meta = event .split_once("pub async fn insert_event_with_thread_metadata(\n") .expect("event store must expose pool-level thread-metadata insert") .1 .split_once("impl Db {") .expect("pool thread-metadata insert must precede Db wrappers") .0; assert!( has_any_tenant_local_chokepoint(insert_with_thread_meta), "thread-metadata event inserts must include a tenant-local chokepoint call" ); let replaceable = include_str!("../src/store/replaceable.rs"); let replace_addressable = replaceable .split_once("pub async fn replace_addressable_event(\n") .expect("replaceable store must expose replace_addressable_event") .1 .split_once("/// Replace a NIP-33 event inside a caller-owned transaction.") .expect("addressable replacement must precede parameterized transaction seam") .0; assert!( has_any_tenant_local_chokepoint(replace_addressable), "addressable replacements must include a tenant-local chokepoint call" ); let replace_parameterized = replaceable .split_once("pub async fn replace_parameterized_event(\n") .expect("replaceable store must expose replace_parameterized_event") .1 .split_once("}\n\n#[cfg(test)]") .expect("parameterized replacement must precede tests") .0; assert!( has_any_tenant_local_chokepoint(replace_parameterized), "parameterized replacements must include a tenant-local chokepoint call" ); let channel_members = include_str!("../src/store/channel_members.rs"); let snapshot_lock = channel_members .split_once("pub async fn lock_member_snapshot(\n") .expect("channel_members must expose lock_member_snapshot") .1 .split_once("/// Add a member to a channel.") .expect("snapshot lock path must precede member add path") .0; assert!( has_any_tenant_local_chokepoint(snapshot_lock), "snapshot publication locks must include a tenant-local chokepoint call" ); let push = include_str!("../src/store/push.rs"); let accept_lease = push .split_once("pub async fn accept_lease_event(\n") .expect("push store must expose accept_lease_event") .1 .split_once("fn constraint_acceptance_outcome") .expect("accept_lease_event must precede constraint outcome mapping") .0; assert!( has_any_tenant_local_chokepoint(accept_lease), "push lease source-event writes must include a tenant-local chokepoint call" ); let reaction = include_str!("../src/store/reaction.rs"); let insert_reaction = reaction .split_once("pub async fn insert_reaction_event_with_thread_metadata(\n") .expect("reaction store must expose insert_reaction_event_with_thread_metadata") .1 .split_once("/// Soft-delete a reaction by setting") .expect("reaction insert must precede reaction soft-delete") .0; assert!( has_any_tenant_local_chokepoint(insert_reaction), "live kind:7 reaction inserts must include a tenant-local chokepoint call" ); } #[test] fn legacy_compatibility_metrics_remain_pinned_to_the_preexisting_event_write_entrypoints() { let runtime = include_str!("../src/runtime/mod.rs"); let typed_helper = runtime .split_once("pub(crate) async fn begin_community_event_write_transaction(\n") .expect("runtime must expose the typed tenant-local chokepoint") .1 .split_once( "pub(crate) async fn begin_community_event_write_transaction_with_legacy_metrics(\n", ) .expect("typed chokepoint must precede the legacy compatibility wrapper") .0; assert!( typed_helper.contains("CommunityEventWriteMetricPopulation::TypedOnly"), "the default tenant-local chokepoint must stay typed-only" ); assert!( !typed_helper.contains("CommunityEventWriteMetricPopulation::LegacyCompatibility"), "the default tenant-local chokepoint must not emit legacy compatibility metrics" ); let legacy_db_wrapper = runtime .split_once("pub async fn begin_event_write_transaction(\n") .expect("Db must expose the public event-write entrypoint") .1 .split_once("/// Insert an event while holding and validating an admitted serving-write") .expect("public Db entrypoint must precede the serving-lease writer") .0; assert!( legacy_db_wrapper.contains(COMMUNITY_CHOKEPOINT_LEGACY_MARKER), "Db::begin_event_write_transaction must preserve the legacy compatibility population" ); let replaceable = include_str!("../src/store/replaceable.rs"); for (label, start, end) in [ ( "replace_addressable_event", "pub async fn replace_addressable_event(\n", "/// Atomically replace a NIP-33 parameterized replaceable event.", ), ( "replace_parameterized_event", "pub async fn replace_parameterized_event(\n", "}\n\n#[cfg(test)]", ), ] { let seam = replaceable .split_once(start) .unwrap_or_else(|| panic!("replaceable store must expose {label}")) .1 .split_once(end) .unwrap_or_else(|| panic!("{label} must precede its next production seam")) .0; assert!( seam.contains(COMMUNITY_CHOKEPOINT_LEGACY_MARKER), "{label} must preserve the legacy compatibility population" ); } let push = include_str!("../src/store/push.rs"); let accept_lease = push .split_once("pub async fn accept_lease_event(\n") .expect("push store must expose accept_lease_event") .1 .split_once("fn constraint_acceptance_outcome") .expect("accept_lease_event must precede constraint outcome mapping") .0; assert!( accept_lease.contains(COMMUNITY_CHOKEPOINT_LEGACY_MARKER), "push lease acceptance must preserve the legacy compatibility population" ); let event = include_str!("../src/store/event.rs"); let insert_event = event .split_once("pub async fn insert_event(\n") .expect("event store must expose pool-level insert_event") .1 .split_once("/// Insert a Nostr event in a caller-owned admitted transaction") .expect("pool insert must precede transaction-seam insert") .0; assert!( insert_event.contains(COMMUNITY_CHOKEPOINT_MARKER), "typed-only event inserts must stay on the typed tenant-local chokepoint" ); assert!( !insert_event.contains(COMMUNITY_CHOKEPOINT_LEGACY_MARKER), "typed-only event inserts must not emit legacy compatibility metrics" ); let reaction = include_str!("../src/store/reaction.rs"); let insert_reaction = reaction .split_once("pub async fn insert_reaction_event_with_thread_metadata(\n") .expect("reaction store must expose insert_reaction_event_with_thread_metadata") .1 .split_once("/// Soft-delete a reaction by setting") .expect("reaction insert must precede reaction soft-delete") .0; assert!( insert_reaction.contains(COMMUNITY_CHOKEPOINT_MARKER), "typed-only reaction inserts must stay on the typed tenant-local chokepoint" ); assert!( !insert_reaction.contains(COMMUNITY_CHOKEPOINT_LEGACY_MARKER), "typed-only reaction inserts must not emit legacy compatibility metrics" ); } /// Function-level routing check for guarded-table writers. /// /// A file can contain both a legitimate chokepoint writer and a bypass writer. /// Every writing function must either open the tenant-local community /// chokepoint itself, take a caller-owned `&mut AdmittedTx` (which only the /// chokepoint can construct, so the compiler proves provenance), use reviewed /// adapter-owned transaction state whose constructor is pinned to the /// chokepoint, or appear in a reviewed exception list below. /// /// A raw `&mut Transaction` or `&mut PgConnection` parameter is not a route: /// nothing about its type says the transaction was admitted. const GUARDED_TABLE_WRITE_MARKERS: [&str; 9] = [ "INSERT INTO events", "UPDATE events", "DELETE FROM events", "INSERT INTO reactions", "UPDATE reactions", "DELETE FROM reactions", "INSERT INTO event_mentions", "UPDATE event_mentions", "DELETE FROM event_mentions", ]; const COMMUNITY_CHOKEPOINT_MARKER: &str = "begin_community_event_write_transaction("; const GENERAL_COMMUNITY_CHOKEPOINT_MARKER: &str = "begin_community_write_transaction("; const SWEEP_COMMUNITY_CHOKEPOINT_MARKER: &str = "begin_community_sweep_transaction("; const COMMUNITY_CHOKEPOINT_LEGACY_MARKER: &str = "begin_community_event_write_transaction_with_legacy_metrics("; fn has_any_tenant_local_chokepoint(source: &str) -> bool { source.contains(COMMUNITY_CHOKEPOINT_MARKER) || source.contains(SWEEP_COMMUNITY_CHOKEPOINT_MARKER) || source.contains(GENERAL_COMMUNITY_CHOKEPOINT_MARKER) || source.contains(COMMUNITY_CHOKEPOINT_LEGACY_MARKER) } const ADMITTED_TX_SIGNATURE_MARKERS: [&str; 2] = ["&mut AdmittedTx", "&mut crate::AdmittedTx"]; const GUARDED_TX_ADAPTER_METHOD_PINS: [(&str, &str); 1] = [( "pub async fn replace_member_event(", "pub async fn lock_member_snapshot(", )]; fn production_contains_guarded_write(production_source: &str) -> bool { GUARDED_TABLE_WRITE_MARKERS .iter() .any(|marker| production_source.contains(marker)) } fn fn_signature_starts_here(trimmed_line: &str) -> bool { [ "fn ", "async fn ", "pub fn ", "pub async fn ", "pub(crate) fn ", "pub(crate) async fn ", "pub(super) fn ", "pub(super) async fn ", ] .iter() .any(|prefix| trimmed_line.starts_with(prefix)) } /// Split production source into one slice per function. A slice runs from its /// signature to the doc comment or attributes of the next function, so a /// following function's docs (which may quote SQL) are never attributed to the /// function before it. /// /// Signatures and attributes are found in the masked view (see /// [`mask_comments_and_literals`]), so an `fn` line inside a comment or a /// multiline string never splits a function. Doc comments are blank in that /// view, so `///` lead-ins are read from the original line. fn function_slices(production_source: &str) -> Vec<&str> { let masked = mask_comments_and_literals(production_source); // (signature offset, offset where the next function's lead-in begins) let mut starts = Vec::new(); let mut lead_ins = Vec::new(); let mut lead_in: Option = None; let mut offset = 0usize; for (line, code) in production_source .split_inclusive('\n') .zip(masked.split_inclusive('\n')) { let trimmed = code.trim_start(); let indent = code.len() - trimmed.len(); if fn_signature_starts_here(trimmed) { starts.push(offset + indent); lead_ins.push(lead_in.take().unwrap_or(offset + indent)); } else if line.trim_start().starts_with("///") || trimmed.starts_with("#[") { lead_in.get_or_insert(offset); } else { lead_in = None; } offset += line.len(); } let mut functions = Vec::new(); for (index, start) in starts.iter().enumerate() { let end = lead_ins .get(index + 1) .copied() .unwrap_or(production_source.len()); functions.push(&production_source[*start..end]); } functions } fn function_header(function_source: &str) -> &str { function_source .lines() .next() .unwrap_or("") .trim() } fn function_accepts_admitted_transaction(function_source: &str) -> bool { let signature = function_source.split('{').next().unwrap_or(function_source); ADMITTED_TX_SIGNATURE_MARKERS .iter() .any(|marker| signature.contains(marker)) } fn function_uses_guarded_tx_adapter_state(function_source: &str) -> bool { function_source.contains("&mut *self.tx") || function_source.contains("&mut self.tx") } fn adapter_constructor_is_chokepoint_pinned(production_source: &str, method_header: &str) -> bool { for (adapter_method, adapter_constructor) in GUARDED_TX_ADAPTER_METHOD_PINS { if method_header.starts_with(adapter_method) { return function_slices(production_source) .into_iter() .find(|function_source| { function_header(function_source).starts_with(adapter_constructor) }) .is_some_and(has_any_tenant_local_chokepoint); } } false } fn function_has_syntactic_guarded_write_route( function_source: &str, production_source: &str, ) -> bool { let header = function_header(function_source); has_any_tenant_local_chokepoint(function_source) || function_accepts_admitted_transaction(function_source) || (function_uses_guarded_tx_adapter_state(function_source) && adapter_constructor_is_chokepoint_pinned(production_source, header)) } fn syntactic_guarded_write_route_violations(production_source: &str) -> Vec { function_slices(production_source) .into_iter() .filter(|function_source| { production_contains_guarded_write(function_source) && !function_has_syntactic_guarded_write_route(function_source, production_source) }) .map(|function_source| function_header(function_source).to_owned()) .collect() } #[test] fn serving_table_policy_rejects_same_file_mixed_guarded_writers() { let mixed_source = r#" pub async fn guarded_writer(pool: &sqlx::PgPool) { let mut tx = begin_community_event_write_transaction(pool, community, WriterOperation::EventWrite) .await .expect("tx"); sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(&mut *tx) .await .expect("write"); } pub async fn unguarded_writer(pool: &sqlx::PgPool) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(pool) .await .expect("unguarded"); } "#; let violations = syntactic_guarded_write_route_violations(mixed_source); assert!( violations .iter() .any(|name| name.starts_with("pub async fn unguarded_writer(")), "whole-file co-occurrence policy is too weak: one guarded writer in a file must not bless \ a sibling unguarded writer; violations: {violations:?}" ); assert!( !violations .iter() .any(|name| name.starts_with("pub async fn guarded_writer(")), "guarded writer must remain allowed; violations: {violations:?}" ); } #[test] fn serving_table_policy_rejects_writer_connection_only_bypasses() { let acquire_writer_bypass = r#" pub async fn bypass_with_writer_connection(pool: &sqlx::PgPool) { let mut connection = crate::observability::acquire_writer(pool, WriterOperation::EventWrite) .await .expect("connection"); sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(&mut *connection) .await .expect("write"); } "#; let pool_begin_bypass = r#" pub async fn bypass_with_pool_begin(pool: &sqlx::PgPool) { let mut tx = pool.begin().await.expect("tx"); sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(&mut *tx) .await .expect("write"); } "#; let acquire_writer_violations = syntactic_guarded_write_route_violations(acquire_writer_bypass); assert!( acquire_writer_violations .iter() .any(|name| name.starts_with("pub async fn bypass_with_writer_connection(")), "acquire_writer + raw guarded-table write must be rejected; violations: \ {acquire_writer_violations:?}" ); let pool_begin_violations = syntactic_guarded_write_route_violations(pool_begin_bypass); assert!( pool_begin_violations .iter() .any(|name| name.starts_with("pub async fn bypass_with_pool_begin(")), "pool.begin + raw guarded-table write must be rejected; violations: \ {pool_begin_violations:?}" ); } #[test] fn serving_table_policy_requires_admitted_tx_not_raw_transactions() { let source = r#" pub(crate) async fn raw_transaction_writer(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } pub(crate) async fn raw_connection_writer(conn: &mut sqlx::PgConnection) { sqlx::query("INSERT INTO event_mentions (community_id, event_id) VALUES ($1, $2)") .execute(conn) .await .expect("write"); } pub(crate) async fn admitted_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .bind(tx.community().as_uuid()) .execute(tx.conn()) .await .expect("write"); } "#; let violations = syntactic_guarded_write_route_violations(source); assert_eq!( violations, [ "pub(crate) async fn raw_transaction_writer(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>) {", "pub(crate) async fn raw_connection_writer(conn: &mut sqlx::PgConnection) {", ], "a raw transaction or connection parameter carries no admission proof; only \ `&mut AdmittedTx` does" ); } /// Every function in `source` that builds an `AdmittedTx`, paired with whether /// it admits the transaction it wraps. The scan deliberately does not strip /// `#[cfg(test)]` items: a test-only forge would let crate tests run follow-ups /// on an unadmitted transaction, so it must admit like any other constructor. fn admitted_tx_constructors(source: &str) -> Vec<(String, bool)> { let production: String = source .lines() .filter(|line| !line.trim_start().starts_with("//")) // `impl … for AdmittedTx {` headers open a block, not a value. .filter(|line| !line.trim_start().starts_with("impl")) .map(|line| format!("{line}\n")) .collect(); function_slices(&production) .into_iter() .filter(|function| function.contains("Self {") || function.contains("AdmittedTx {")) .map(|function| { let admits = function.contains(".guard_transaction(&mut tx, community)") || function.contains(".guard_transaction_with_serving_lease(&mut tx, lease)"); (function.to_string(), admits) }) .collect() } #[test] fn admitted_tx_is_constructed_only_by_admitting_constructors() { // The fields are private to `runtime/admitted_tx.rs`, so only that file can // build the value. Pin that each function there that builds it also admits // the transaction it wraps, so a new unguarded constructor cannot slip in. let constructors = admitted_tx_constructors(include_str!("../src/runtime/admitted_tx.rs")); assert_eq!( constructors.len(), 2, "AdmittedTx must have exactly the two admitting constructors" ); for (constructor, admits) in constructors { assert!( admits, "AdmittedTx constructor must admit the transaction it wraps: {constructor}" ); } } #[test] fn admitted_tx_constructor_scan_reports_test_only_forges() { let source = r#" impl AdmittedTx { pub(crate) async fn admit(mut tx: Tx, community: CommunityId) -> Result { guard.guard_transaction(&mut tx, community).await?; Ok(Self { tx, community }) } #[cfg(test)] pub(crate) fn forge_for_tests(tx: Tx, community: CommunityId) -> Self { Self { tx, community } } } "#; let unadmitted: Vec = admitted_tx_constructors(source) .into_iter() .filter(|(_, admits)| !admits) .map(|(function, _)| { function .lines() .next() .unwrap_or_default() .trim() .to_string() }) .collect(); assert_eq!( unadmitted, ["pub(crate) fn forge_for_tests(tx: Tx, community: CommunityId) -> Self {"], "an indented `#[cfg(test)]` forge must still be reported as unadmitted" ); } #[test] fn cfg_test_items_are_skipped_without_hiding_later_production_code() { let source = "pub fn before() {}\n\ #[cfg(test)]\n\ struct Marker;\n\ pub fn after_struct() {}\n\ #[cfg(test)]\n\ static LOCK: std::sync::Mutex<()> =\n\ std::sync::Mutex::new(());\n\ pub fn after_static() {}\n\ #[cfg(test)]\n\ static S: [u8; 1] =\n\ [const { 0 }; 1];\n\ pub fn after_const_block() {}\n\ #[cfg(test)]\n\ #[derive(Debug)]\n\ struct Fields {\n\ value: u8,\n\ }\n\ pub fn after_fields() {}\n\ #[cfg(test)]\n\ mod tests {\n\ fn hidden() {\n\ }\n\ }\n\ pub fn after_module() {}\n"; let production = strip_cfg_test_items(source); for name in [ "before", "after_struct", "after_static", "after_const_block", "after_fields", "after_module", ] { assert!( production.contains(&format!("pub fn {name}()")), "{name} is production code and must stay visible: {production}" ); } for hidden in ["Marker", "LOCK", "static S", "value: u8", "fn hidden"] { assert!( !production.contains(hidden), "{hidden} is test-only and must be skipped: {production}" ); } let raw_writer = "pub(crate) async fn raw_writer(conn: &mut sqlx::PgConnection) {\n\ sqlx::query(\"INSERT INTO events (community_id, id) VALUES ($1, $2)\")\n\ .execute(conn)\n\ .await\n\ .expect(\"write\");\n\ }\n"; for (test_item, hidden) in [ ("struct X;", "struct X"), ("fn helper() {} // test helper", "fn helper"), ("const BRACES: &str = \"{}\"; // fixture", "BRACES"), ( "const URL: &str = \"https://relay.test\"; // fixture", "relay.test", ), ("fn u() -> &'static str { \"ws://x\" } // c", "ws://x"), ] { let production = strip_cfg_test_items(&format!("#[cfg(test)]\n{test_item}\n{raw_writer}")); assert!( !production.contains(hidden), "`{test_item}` is test-only and must be skipped: {production}" ); assert!( production_contains_guarded_write(&production), "a guarded write after `{test_item}` must stay visible: {production}" ); assert_eq!( syntactic_guarded_write_route_violations(&production), ["pub(crate) async fn raw_writer(conn: &mut sqlx::PgConnection) {"], "a raw writer after `{test_item}` must still be scanned" ); } } fn should_scan_guarded_write_source_file(path: &std::path::Path) -> bool { let file_name = path .file_name() .and_then(|name| name.to_str()) .unwrap_or(""); path.extension().is_some_and(|ext| ext == "rs") // Whole files loaded only via `#[cfg(test)] #[path = "..."] mod ...;` are // entirely test code but carry no internal `#[cfg(test)]` marker of their // own to slice against. Standalone `*_tests.rs` modules share that shape. && file_name != "test_support.rs" && file_name != "tests.rs" && !file_name.ends_with("_tests.rs") } fn collect_production_rs_files(dir: &std::path::Path, out: &mut Vec) { for entry in std::fs::read_dir(dir).expect("read source directory") { let entry = entry.expect("read directory entry"); let path = entry.path(); if path.is_dir() { collect_production_rs_files(&path, out); } else if should_scan_guarded_write_source_file(&path) { out.push(path); } } } #[test] fn serving_table_policy_skips_standalone_test_modules() { use std::path::Path; assert!( !should_scan_guarded_write_source_file(Path::new("src/runtime/tests.rs")), "`tests.rs` is a standalone test-only module" ); assert!( !should_scan_guarded_write_source_file(Path::new( "src/store/thread_window/postgres_tests.rs", )), "`*_tests.rs` modules are standalone test-only sources, not production seams" ); assert!( !should_scan_guarded_write_source_file(Path::new("src/store/foo_tests.rs")), "the suffix-based rule must cover other standalone test-only modules" ); assert!( !should_scan_guarded_write_source_file(Path::new("src/test_support.rs")), "test_support.rs is loaded only under cfg(test)" ); assert!( should_scan_guarded_write_source_file(Path::new("src/store/event.rs")), "production source must remain in scope" ); } #[test] fn serving_table_writes_expose_syntactic_chokepoint_or_guarded_tx_routes() { use std::path::Path; // `buzz-relay` is scanned too: relay code reaches fenced tables only through // `buzz-db` helpers, and a direct relay write must meet the same rule. let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); let mut checked_guarded_files = 0usize; for (crate_name, src_root) in [ ("buzz-db", manifest.join("src")), ("buzz-relay", manifest.join("../buzz-relay/src")), ] { let mut files = Vec::new(); collect_production_rs_files(&src_root, &mut files); assert!( !files.is_empty(), "guarded-table scan must see {crate_name} production source files" ); for path in files { let relative = path .strip_prefix(&src_root) .expect("file is under src root") .to_string_lossy() .replace('\\', "/"); let source = std::fs::read_to_string(&path).expect("read source file"); let production = strip_cfg_test_items(&source); if production_contains_guarded_write(&production) { checked_guarded_files += 1; let violations = syntactic_guarded_write_route_violations(&production); assert!( violations.is_empty(), "{crate_name}/src/{relative} has guarded-table INSERT/UPDATE/DELETE seams \ that neither open the tenant-local chokepoint nor take `&mut AdmittedTx`: \ {violations:?}" ); } } } assert!( checked_guarded_files > 0, "guarded-table scan must exercise at least one file that writes a fenced table" ); } /// `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 /// its body. Braces inside comments and literals are not counted (see /// [`mask_comments_and_literals`]). Unlike cutting the file at the first /// `#[cfg(test)]`, this keeps production code that follows a test-only item. /// The whole file is masked once and the marker is found in that view, so a /// mention in a comment or string (even a multiline one) strips nothing. The /// marker also counts only when it is the first code on its line. fn strip_cfg_test_items(source: &str) -> String { const MARKER: &str = "#[cfg(test)]"; let masked = mask_comments_and_literals(source); let mut kept = String::with_capacity(source.len()); let mut copied = 0usize; let mut search = 0usize; while let Some(found) = masked[search..].find(MARKER) { let at = search + found; let line_start = masked[..at].rfind('\n').map_or(0, |newline| newline + 1); search = at + MARKER.len(); if !masked[line_start..at].trim().is_empty() { continue; } kept.push_str(&source[copied..at]); copied = search + cfg_test_item_len(&masked[search..]); search = copied; } kept.push_str(&source[copied..]); kept } /// Length of the item that starts `masked_item`, which must already be masked /// so braces in comments and literals are not counted. fn cfg_test_item_len(masked_item: &str) -> usize { let mut depth = 0usize; for (index, byte) in masked_item.bytes().enumerate() { match byte { b';' if depth == 0 => return index + 1, b'{' => depth += 1, b'}' => { depth = depth.saturating_sub(1); if depth == 0 { return index + 1; } } _ => {} } } masked_item.len() } /// Whether the `r` at `index` begins a raw literal token: `r"`, or the `br"` / /// `cr"` raw byte and C strings, rather than ending an identifier such as `for"`. fn raw_literal_prefix_starts_token(bytes: &[u8], index: usize) -> bool { let is_ident = |at: Option| { at.and_then(|at| bytes.get(at)) .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_') }; let before = index.checked_sub(1); !is_ident(before) || (matches!(before.map(|at| bytes[at]), Some(b'b' | b'c')) && !is_ident(index.checked_sub(2))) } /// `source` with every comment (`//`, `///`, nested `/* */`) and every string, /// raw string, and char literal replaced by spaces, byte for byte. Newlines are /// kept, so offsets and line structure match `source`. Scans that look for /// code (braces, calls) read the masked text; scans that look for SQL read /// the original, because the SQL lives inside string literals. fn mask_comments_and_literals(source: &str) -> String { let bytes = source.as_bytes(); let mut masked = bytes.to_vec(); for span in source_spans(source) { for byte in &mut masked[span.start..span.end] { if *byte != b'\n' { *byte = b' '; } } } String::from_utf8(masked).expect("masking replaces whole ASCII-delimited spans") } #[derive(Clone, Copy, PartialEq, Eq)] enum SpanKind { Comment, /// A plain (`"…"`) string literal; `start` is its opening quote. Str, /// A raw string literal; `start` is its `r`, followed by `hashes` `#`s. RawStr { hashes: usize, }, Char, } struct SourceSpan { start: usize, end: usize, kind: SpanKind, } impl SourceSpan { /// The text between a string literal's delimiters, escapes left as written. fn string_body<'a>(&self, source: &'a str) -> Option<&'a str> { match self.kind { SpanKind::Str => source.get(self.start + 1..self.end.saturating_sub(1)), SpanKind::RawStr { hashes } => { source.get(self.start + 2 + hashes..self.end.saturating_sub(1 + hashes)) } SpanKind::Comment | SpanKind::Char => None, } } } /// Every comment, string, raw string, and char literal in `source`, in order. fn source_spans(source: &str) -> Vec { let bytes = source.as_bytes(); let mut spans = Vec::new(); let mut index = 0usize; while index < bytes.len() { let start = index; let kind = match bytes[index] { b'/' if bytes.get(index + 1) == Some(&b'/') => { while index < bytes.len() && bytes[index] != b'\n' { index += 1; } SpanKind::Comment } b'/' if bytes.get(index + 1) == Some(&b'*') => { let mut depth = 0usize; while index < bytes.len() { if bytes[index] == b'/' && bytes.get(index + 1) == Some(&b'*') { depth += 1; index += 2; } else if bytes[index] == b'*' && bytes.get(index + 1) == Some(&b'/') { depth -= 1; index += 2; if depth == 0 { break; } } else { index += 1; } } SpanKind::Comment } b'r' if matches!(bytes.get(index + 1), Some(b'"' | b'#')) && raw_literal_prefix_starts_token(bytes, index) && bytes.get( index + 1 + bytes[index + 1..] .iter() .take_while(|byte| **byte == b'#') .count(), ) == Some(&b'"') => { let hashes = bytes[index + 1..] .iter() .take_while(|byte| **byte == b'#') .count(); let close = format!("\"{}", "#".repeat(hashes)); let body = index + 2 + hashes; index = source[body..] .find(&close) .map_or(bytes.len(), |offset| body + offset + close.len()); SpanKind::RawStr { hashes } } b'"' => { index += 1; while index < bytes.len() && bytes[index] != b'"' { index += if bytes[index] == b'\\' { 2 } else { 1 }; } index += 1; SpanKind::Str } b'\'' if char_literal_end(source, index).is_some() => { index = char_literal_end(source, index).expect("guard matched"); SpanKind::Char } _ => { index += 1; continue; } }; spans.push(SourceSpan { start, end: index.min(bytes.len()), kind, }); } spans } /// The end (exclusive) of the char literal whose opening quote is at `start`, /// such as `'{'`, `'é'`, `'\''`, `'\x7f'`, or `'\u{1F600}'`. `None` for a /// lifetime, which has no closing quote. fn char_literal_end(source: &str, start: usize) -> Option { // `start` holds an ASCII quote, so `start + 1` is a char boundary. let rest = &source[start + 1..]; let body = if let Some(escape) = rest.strip_prefix('\\') { // The longest escape is `\u{10FFFF}`: a backslash and 9 more bytes. // Skip the escaped byte so `'\''` does not close on its own quote. let close = escape.get(1..)?.find('\'')? + 1; (close <= 9).then_some(1 + close)? } else { rest.chars().next()?.len_utf8() }; rest[body..] .starts_with('\'') .then_some(start + 1 + body + 1) } #[test] fn masker_blanks_every_literal_form_and_keeps_code() { for (input, expected) in [ // Raw strings with zero, one, or several `#`, and the `b`/`c` raw // prefixes. Each body ends in `\`, which would escape the closing quote // if the literal were scanned as a plain string. (r#"a(r"\") {}"#, "a( ) {}"), (r###"a(r##"x"#{"##) {}"###, "a( ) {}"), (r##"a(br#"\"#) {}"##, "a(b ) {}"), (r#"a(br"\") {}"#, "a(b ) {}"), (r#"a(cr"\") {}"#, "a(c ) {}"), // Plain byte and C strings. (r#"a(b"{") {}"#, "a(b ) {}"), (r#"a(c"{") {}"#, "a(c ) {}"), // Plain and escaped char literals. ( r"a('\'', '\\', '\n', '{') {}", "a( , , , ) {}", ), // Multi-byte and long-escape char literals. Each holds a brace, or // hides one from a scan that misreads the literal's length. ("a('é', '{') {}", "a( , ) {}"), (r"a('\u{1F600}', '{') {}", "a( , ) {}"), (r"a('\x7f', '{') {}", "a( , ) {}"), // Code that only looks like a literal stays as it is. ("let r#type = 1; {}", "let r#type = 1; {}"), ("fn f<'a>(x: &'a str) {}", "fn f<'a>(x: &'a str) {}"), ] { assert_eq!( mask_comments_and_literals(input), expected, "masking `{input}`" ); } } /// Whether `source` inserts into `events` itself (not `event_mentions` or any /// other `events_*` table), in any letter case, across line breaks and string /// continuations, `\n`/`\t`/`\r` escapes, and with or without a `public.` /// schema prefix. fn inserts_events_row(source: &str) -> bool { !events_insert_tails(source).is_empty() } /// `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(); } if !normalized.ends_with(' ') { normalized.push(' '); } } else { normalized.push(ch.to_ascii_lowercase()); } } normalized } /// Whether an unqualified table name is `events` or one of its partitions /// (`events_p_past`, `events_p2026_01`, …): a direct partition write skips /// nothing the parent's writers must do. fn is_events_table(table: &str) -> bool { table == "events" || table .strip_prefix("events_p") .is_some_and(|rest| rest.starts_with(|ch: char| ch == '_' || ch.is_ascii_digit())) } /// The normalized SQL that follows each `INSERT INTO events` (or one of its /// partitions) in `source`. fn events_insert_tails(source: &str) -> Vec { let normalized = normalized_sql(source); let mut tails = Vec::new(); for marker in ["insert into events", "insert into public.events"] { for (index, marker) in normalized.match_indices(marker) { let table_start = index + marker.len() - "events".len(); let table_len = normalized[table_start..] .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) .unwrap_or(normalized.len() - table_start); if is_events_table(&normalized[table_start..table_start + table_len]) { tails.push(normalized[table_start + table_len..].to_owned()); } } } tails } /// An events insert must run both follow-ups: the push enqueue and the /// pre-commit TTL refresh. `after_admitted_insert` does both; a writer that /// inserts inside a savepoint calls the two halves separately. /// /// Only real calls count: a hook in a comment or a string literal does not. fn runs_event_follow_ups(function_source: &str) -> bool { let code = mask_comments_and_literals(function_source); code.contains("event_follow_up::after_admitted_insert(") || (code.contains("event_follow_up::enqueue_push_match(") && code.contains(".record_channel_event(")) } fn event_insert_follow_up_violations(production_source: &str) -> Vec { function_slices(production_source) .into_iter() .filter(|function_source| { inserts_events_row(function_source) && !runs_event_follow_ups(function_source) }) .map(|function_source| function_header(function_source).to_owned()) .collect() } #[test] fn event_insert_follow_up_policy_rejects_writers_without_the_hook() { let source = r##" pub(crate) async fn unhooked_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .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)") .execute(tx.conn()) .await .expect("write"); crate::store::event_follow_up::enqueue_push_match(tx.conn(), community, id, kind) .await .expect("enqueue"); } pub(crate) async fn hooked_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); crate::store::event_follow_up::after_admitted_insert(tx, id, created_at, kind, channel) .await .expect("follow up"); } pub(crate) async fn savepoint_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); crate::store::event_follow_up::enqueue_push_match(tx.conn(), community, id, kind) .await .expect("enqueue"); tx.record_channel_event(channel, kind); } pub(crate) async fn mention_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO event_mentions (community_id, event_id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } pub(crate) async fn lowercase_writer(tx: &mut AdmittedTx) { sqlx::query("insert into public.events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } pub(crate) async fn continued_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO \ events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } /// Kept at module scope, not `#[cfg(test)]`, because production calls it. pub(crate) async fn writer_under_doc_mention(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } // see `#[cfg(test)] mod x {` pub(crate) async fn writer_under_brace_mention(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } pub(crate) async fn writer_with_escaped_newline(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO\nevents (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } pub(crate) async fn writer_with_commented_out_hook(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); // 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)") .execute(tx.conn()) .await .expect("write"); /* crate::store::event_follow_up::enqueue_push_match(tx.conn(), community, id, kind) /* nested */ tx.record_channel_event(channel, kind); */ } pub(crate) async fn writer_with_hook_in_string(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); tracing::debug!("skipped event_follow_up::after_admitted_insert(tx, ..)"); } pub(crate) async fn writer_with_nested_block_commented_hook(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); /* /* 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)") .execute(tx.conn()) .await .expect("write"); tracing::debug!("\"event_follow_up::after_admitted_insert(\""); } pub(crate) async fn writer_with_hook_in_raw_string(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); tracing::debug!(r#""event_follow_up::after_admitted_insert(""#); } /* #[cfg(test)] */ pub(crate) async fn writer_after_block_commented_cfg_test(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } 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, created_at, kind, channel) } "#; sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } #[cfg(test)] fn test_only_helper() -> (&'static str, char, &'static str, char, &'static [u8]) { // an unbalanced { in a comment ("{", '{', r#"}"} {"#, '"', br#"\"#) } pub(crate) async fn writer_after_test_helper(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(tx.conn()) .await .expect("write"); } #[cfg(test)] mod tests { async fn test_writer(pool: &PgPool) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)") .execute(pool) .await .expect("fixture"); } } "##; assert_eq!( 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) {", "pub(crate) async fn writer_under_doc_mention(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_under_brace_mention(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_escaped_newline(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_commented_out_hook(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_block_commented_hook(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_hook_in_string(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_nested_block_commented_hook(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_hook_after_escaped_quote(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_hook_in_raw_string(tx: &mut AdmittedTx) {", "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) {", "pub(crate) async fn writer_after_test_helper(tx: &mut AdmittedTx) {", ], "an events insert must run the push enqueue and record the TTL refresh" ); } fn production_event_writer_source_files() -> Vec { use std::path::Path; let crates_root = Path::new(env!("CARGO_MANIFEST_DIR")) .parent() .expect("crate lives under crates/"); let mut files = Vec::new(); for entry in std::fs::read_dir(crates_root).expect("read crates directory") { let src = entry.expect("read crates entry").path().join("src"); if src.is_dir() { collect_production_rs_files(&src, &mut files); } } files } #[test] fn every_production_event_insert_runs_the_follow_up_hook() { let files = production_event_writer_source_files(); let mut hooked_writers = 0usize; let mut violations = Vec::new(); for path in files { let source = std::fs::read_to_string(&path).expect("read source file"); let production = strip_cfg_test_items(&source); if !inserts_events_row(&production) { continue; } for function_source in function_slices(&production) { if inserts_events_row(function_source) && runs_event_follow_ups(function_source) { hooked_writers += 1; } } violations.extend( event_insert_follow_up_violations(&production) .into_iter() .map(|header| format!("{}: {header}", path.display())), ); } assert!( violations.is_empty(), "production `INSERT INTO events` writers must call `event_follow_up` because no \ trigger does the push enqueue or channel TTL refresh: {violations:?}" ); // The seven writers at the time of BUZZ-176. A lower count means the scan // stopped seeing a writer, not that one was removed safely. assert!( hooked_writers >= 7, "expected at least seven hooked event writers, found {hooked_writers}" ); } // 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. // 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; 2] = [ // 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(", ]; fn event_insert_roster_guard_violations(production_source: &str) -> Vec { function_slices(production_source) .into_iter() .filter(|function_source| { let header = function_header(function_source); let code = mask_comments_and_literals(function_source); inserts_events_row(function_source) && !EVENT_INSERT_ROSTER_GUARD_EXCEPTIONS .iter() .any(|exception| header.starts_with(exception)) && !code.contains("guard_channel_roster_event(") && !code.contains("validate_channel_roster_snapshot(") }) .map(|function_source| function_header(function_source).to_owned()) .collect() } #[test] fn event_insert_roster_guard_policy_rejects_writers_without_the_guard() { let source = r#" pub(crate) async fn unguarded_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } pub(crate) async fn guarded_writer(tx: &mut AdmittedTx) { guard_channel_roster_event(tx, kind, channel, tags).await?; sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } pub(crate) async fn locked_writer(tx: &mut AdmittedTx) { validate_channel_roster_snapshot(tx, channel, tags).await?; sqlx::query("insert into public.events (community_id, id) VALUES ($1, $2)"); } pub(crate) async fn mention_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO event_mentions (community_id, event_id) VALUES ($1, $2)"); } pub(crate) async fn commented_guard_writer(tx: &mut AdmittedTx) { // guard_channel_roster_event(tx, kind, channel, tags).await?; /* validate_channel_roster_snapshot(tx, channel, tags).await?; */ sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } pub(crate) async fn quoted_guard_writer(tx: &mut AdmittedTx) { tracing::debug!("guard_channel_roster_event("); sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } pub(crate) async fn write_nip43_membership_snapshot(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } pub async fn accept_lease_event(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } #[cfg(test)] mod tests { fn fixture() { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } } "#; assert_eq!( event_insert_roster_guard_violations(&strip_cfg_test_items(source)), [ "pub(crate) async fn unguarded_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn commented_guard_writer(tx: &mut AdmittedTx) {", "pub(crate) async fn quoted_guard_writer(tx: &mut AdmittedTx) {", ], "only real roster-guard calls in production writers count" ); } /// Presence check: every production `INSERT INTO events` function must contain /// a real (uncommented, unquoted) roster-guard call. It does not prove the call /// is awaited, reachable, or given the event's real kind and channel; the PG /// `app_roster_guard_*` tests cover behavior. #[test] fn every_production_event_insert_runs_the_roster_guard() { let mut checked_writers = 0; let mut violations = Vec::new(); for path in production_event_writer_source_files() { let source = std::fs::read_to_string(&path).expect("read source file"); let production = strip_cfg_test_items(&source); checked_writers += function_slices(&production) .into_iter() .filter(|function| inserts_events_row(function)) .count(); violations.extend( event_insert_roster_guard_violations(&production) .into_iter() .map(|header| format!("{}: {header}", path.display())), ); } assert!( violations.is_empty(), "production `INSERT INTO events` writers must run the app-side roster guard: {violations:?}" ); // Five guarded writers plus the two explicitly exempt writers. assert!( checked_writers >= 7, "expected at least seven event writers, found {checked_writers}" ); } /// Whether an `INSERT INTO events` tail names `d_tag` in an explicit column /// list. An insert without a column list does not count. fn events_insert_names_d_tag(tail: &str) -> bool { tail.trim_start() .strip_prefix('(') .and_then(|columns| columns.split_once(')')) .is_some_and(|(columns, _)| columns.split(',').any(|column| column.trim() == "d_tag")) } fn event_insert_d_tag_violations(production_source: &str) -> Vec { function_slices(production_source) .into_iter() .filter(|function_source| { !events_insert_tails(function_source) .iter() .all(|tail| events_insert_names_d_tag(tail)) }) .map(|function_source| function_header(function_source).to_owned()) .collect() } #[test] fn event_insert_d_tag_policy_rejects_writers_without_the_column() { let source = r##" pub(crate) async fn writer_without_d_tag(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id, kind) VALUES ($1, $2, $3)"); } pub(crate) async fn writer_with_d_tag(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events \ (community_id, id, kind, d_tag) VALUES ($1, $2, $3, $4)"); } pub(crate) async fn writer_with_compact_columns(tx: &mut AdmittedTx) { sqlx::query("insert into public.events (community_id,id,kind,d_tag) VALUES ($1,$2,$3,$4)"); } pub(crate) async fn writer_with_d_tag_only_in_values(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id, kind) SELECT community_id, id, d_tag FROM x"); } pub(crate) async fn writer_with_lookalike_column(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id, kind, d_tag_hash) VALUES ($1, $2, $3, $4)"); } pub(crate) async fn writer_without_column_list(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events SELECT * FROM staged_events"); } pub(crate) async fn second_insert_without_d_tag(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events (community_id, id, d_tag) VALUES ($1, $2, $3)"); sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } pub(crate) async fn mention_writer(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO event_mentions (community_id, event_id) VALUES ($1, $2)"); } #[cfg(test)] mod tests { fn fixture() { sqlx::query("INSERT INTO events (community_id, id) VALUES ($1, $2)"); } } "##; assert_eq!( event_insert_d_tag_violations(&strip_cfg_test_items(source)), [ "pub(crate) async fn writer_without_d_tag(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_d_tag_only_in_values(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_with_lookalike_column(tx: &mut AdmittedTx) {", "pub(crate) async fn writer_without_column_list(tx: &mut AdmittedTx) {", "pub(crate) async fn second_insert_without_d_tag(tx: &mut AdmittedTx) {", ], "every production events insert must name `d_tag` in its column list" ); } /// Addressable events (kinds 30000-39999) replace by `d_tag`, and the only /// index that serves that lookup is partial on `d_tag IS NOT NULL`. A writer /// that leaves the column out stores NULL, so its rows never replace. Nothing /// repairs them after the fact, so every production writer must name the column. /// /// This is a text match, not a proof. It checks the column list of literal /// `INSERT INTO [public.]events (...)` SQL inside function bodies under each /// crate's `src/`. It does not see `ONLY`, quoted or `format!`-built table /// names, a comment between the keywords, or SQL held in a constant outside a /// function, and it does not check that the bound value is non-NULL. Exempt /// probes are skipped by function header, so every insert inside them is too. #[test] fn every_production_event_insert_names_d_tag() { let mut checked_writers = 0; let mut violations = Vec::new(); for path in production_event_writer_source_files() { let source = std::fs::read_to_string(&path).expect("read source file"); let production = strip_cfg_test_items(&source); checked_writers += function_slices(&production) .into_iter() .filter(|function| inserts_events_row(function)) .count(); violations.extend( event_insert_d_tag_violations(&production) .into_iter() .map(|header| format!("{}: {header}", path.display())), ); } assert!( violations.is_empty(), "production `INSERT INTO events` writers must name `d_tag` in their column list: \ {violations:?}" ); // 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 >= 7, "expected at least seven 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" ); } } // The two serving channel-NULL writers are exempt only while their INSERT // remains structurally channel-NULL (checked below). 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 } /// The assignments of a `SET` list, and whether this literal ends them: the /// list stops at the first `WHERE` or (for an upsert with no `WHERE`) /// `RETURNING` outside parentheses, so a subquery's `WHERE` does not hide /// the assignments after it. fn set_list(assignments: &str) -> (&str, bool) { let mut depth = 0usize; for (index, ch) in assignments.char_indices() { match ch { '(' => depth += 1, ')' => depth = depth.saturating_sub(1), ' ' if depth == 0 => { let rest = &assignments[index..]; if rest.starts_with(" where ") || rest.starts_with(" returning ") { return (&assignments[..index], true); } } _ => {} } } (assignments, false) } /// Whether a `SET` list assigns `created_at` or `channel_id`, including the /// row form `(a, b) = (...)`, or a column it cannot read (a `{…}` /// placeholder). fn assigns_event_floor_column(assignments: &str) -> bool { let (assignments, _) = set_list(assignments); 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(',') .map(str::trim) .any(|column| { matches!(column, "created_at" | "channel_id") || column.starts_with('{') }) }) }) } /// Whether a `SET` list (see [`set_list`]) is missing from its literal: /// empty, or holding an item with no `=`, such as a `{…}` placeholder or a /// column whose value follows in another literal. fn set_list_is_unreadable(assignments: &str) -> bool { let (assignments, _) = set_list(assignments); let mut depth = 0usize; assignments.trim().is_empty() || assignments .split(|ch| { match ch { '(' => depth += 1, ')' => depth = depth.saturating_sub(1), _ => {} } ch == ',' && depth == 0 }) .any(|assignment| !assignment.contains('=')) } /// The table a write targets, without its schema (a literal or a `{…}` /// placeholder; any schema may hold an `events` table). fn unqualified_table(target: &str) -> &str { target.rsplit_once('.').map_or(target, |(_, table)| table) } /// The table the last `INSERT INTO` in `sql` (normalized) targets, without /// its schema. fn last_insert_target(sql: &str) -> Option<&str> { let index = sql.rfind("insert into ")?; let target = sql[index + "insert into ".len()..] .split(|ch: char| !(ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '{' | '}'))) .next()?; Some(unqualified_table(target)) } /// Whether one SQL literal (normalized) assigns a floor column through a /// direct `UPDATE` of `events`, or of a target it does not spell: a /// placeholder, or a `SET` list whose `UPDATE` lies in another literal. /// A `SET` list it cannot read counts as assigning one, and so does an /// `UPDATE` list that runs to the end of the literal, since a later literal /// (a `QueryBuilder` push) may continue it. An events upsert list that runs /// to the end is read on through `later`, the function's later literals. /// `prior_insert` is the target of the last `INSERT` in an earlier literal /// of the same function, which an upsert continued here belongs to. fn literal_updates_event_floor_columns(sql: &str, prior_insert: Option<&str>, later: &str) -> bool { // `SET(` with no space is still a row assignment. let sql = format!(" {} ", sql.trim()).replace(" set(", " set ("); sql.match_indices(" set ").any(|(index, marker)| { let (assignments, terminated) = set_list(&sql[index + marker.len()..]); // A SET list continued in another literal or argument cannot be read. let unreadable = set_list_is_unreadable(assignments); let assigns = !unreadable && assigns_event_floor_column(assignments); let before = &sql[..index]; if before.ends_with(" do update") { // The upsert check resolves a readable, complete list's INSERT, // which may be in another literal of the same builder. An open // events (or unresolved) upsert list is read on through the // later literals, where a push may append a floor column. if unreadable { return true; } if terminated || !last_insert_target(before) .or(prior_insert) .is_none_or(is_events_table) { return false; } let continued = format!("{assignments} {later}"); return set_list_is_unreadable(&continued) || assigns_event_floor_column(&continued); } if !unreadable && !assigns && terminated { return false; } let Some(update) = before.rfind(" update ") else { // A bare SET (Redis `SET`, prose) is not SQL unless it assigns. return assigns; }; let mut target = before[update + " update ".len()..].split_whitespace(); let mut table = target.next(); if table == Some("only") { table = target.next(); } // The target may have an alias, with or without AS. let alias = target.collect::>(); let (Some(table), [] | [_] | ["as", _]) = (table, alias.as_slice()) else { // An unreadable target is a violation only when it assigns a // floor column; prose ("update … is set") assigns nothing. return assigns; }; let table = unqualified_table(table); is_events_table(table) || table.contains('{') }) } fn updates_event_floor_columns(function: &str) -> bool { let literals = source_spans(function) .iter() .filter_map(|span| span.string_body(function)) .map(normalized_sql) .collect::>(); let direct_update = literals.iter().enumerate().any(|(index, sql)| { let prior_insert = literals[..index] .iter() .rev() .find_map(|earlier| last_insert_target(earlier)); literal_updates_event_floor_columns(sql, prior_insert, &literals[index + 1..].join(" ")) }); // `ON CONFLICT ... DO UPDATE SET` names no table: it updates the target of // the INSERT it belongs to, so an events upsert can re-home an existing row. let normalized = normalized_sql(function).replace(" set(", " set ("); let events_upsert = normalized .match_indices("do update set ") .any(|(index, marker)| { last_insert_target(&normalized[..index]).is_some_and(is_events_table) && assigns_event_floor_column(&normalized[index + marker.len()..]) }); direct_update || events_upsert } /// Writes one SQL literal (normalized) hides from the per-function checks: /// an INSERT whose target or tail is not literal, `events` written by a /// statement other than INSERT, or a PREPARE. fn literal_sql_violations(sql: &str) -> Vec<&'static str> { let sql = format!(" {} ", sql.trim()); let mut violations = Vec::new(); for (index, _) in sql.match_indices(" into ") { let rest = &sql[index + " into ".len()..]; let target = rest.split([' ', '(']).next().expect("first part"); let table = unqualified_table(target); if sql[..index].ends_with(" insert") { if target.is_empty() || table.contains('{') { violations.push("INSERT target is not a literal table"); } else if is_events_table(table) && rest.contains('{') { violations.push("events INSERT with a non-literal part"); } } else if is_events_table(table) { violations.push("events written by a statement other than INSERT"); } } if sql.match_indices(" copy ").any(|(index, marker)| { let target = sql[index + marker.len()..].split([' ', '(']).next(); target.is_some_and(|target| is_events_table(unqualified_table(target))) }) { violations.push("events written by a statement other than INSERT"); } let words = sql.split_whitespace().collect::>(); if words .windows(2) .any(|pair| pair[0] == "prepare" && (pair[1] == "transaction" || pair[1].starts_with('{'))) || words.last() == Some(&"prepare") { violations.push("PREPARE TRANSACTION in a production writer"); } violations } /// The offset of the delimiter that closes the bracket opened at `open` in /// `masked` (comments and literals already blanked). fn matching_close(masked: &str, open: usize) -> Option { let mut depth = 0usize; for (index, byte) in masked.bytes().enumerate().skip(open) { match byte { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => { depth = depth.checked_sub(1)?; if depth == 0 { return Some(index); } } _ => {} } } None } /// `text` as a plain Rust string literal. fn plain_literal(text: &str) -> String { format!("\"{}\"", plain_body(text)) } /// Raw `text` escaped as the body of a plain string literal. fn plain_body(text: &str) -> String { text.replace('\\', "\\\\").replace('"', "\\\"") } /// A string literal's body, as written in a plain (escaped) literal. fn plain_string_body(span: &SourceSpan, source: &str) -> Option { let body = span.string_body(source)?; Some(if matches!(span.kind, SpanKind::Str) { body.to_owned() } else { plain_body(body) }) } /// The string literal that is the whole of `arg`, if it is one. fn sole_string_literal(arg: &str) -> Option { let trimmed = arg.trim(); let offset = arg.len() - arg.trim_start().len(); let mut spans = source_spans(trimmed).into_iter(); let span = spans.next()?; (spans.next().is_none() && span.start == 0 && span.end == trimmed.len() && matches!(span.kind, SpanKind::Str | SpanKind::RawStr { .. })) .then_some(SourceSpan { start: span.start + offset, end: span.end + offset, kind: span.kind, }) } /// The opening delimiter of each `name!` macro call in `masked` (comments /// and literals blanked), last first, with any path prefix (`::core::`) and /// any of `(`, `[` or `{`: `(start of name, delimiter offset)`. fn macro_calls(masked: &str, name: &str) -> Vec<(usize, usize)> { let mut calls = masked .match_indices(name) .filter_map(|(at, _)| { let starts_token = !masked[..at] .chars() .next_back() .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_'); let after = masked[at + name.len()..].strip_prefix('!')?; let open = at + name.len() + 1 + (after.len() - after.trim_start().len()); (starts_token && matches!(masked.as_bytes().get(open), Some(b'(' | b'[' | b'{'))) .then_some((at, open)) }) .collect::>(); calls.reverse(); calls } /// Bring SQL that per-function literal scans cannot see into view, so the /// floor policy fails closed on it now that no trigger backs it up: each /// `include_str!("…")` becomes one literal holding the included file /// (resolved against `path`), and each `concat!` becomes one literal of its /// arguments, with `{opaque}` standing in for any non-literal argument. The /// SQL checks treat a placeholder in a write target or a `SET` column as /// unattributable. An `include_str!` whose path is not one literal or /// cannot be read is a violation, as is any `query_file` macro. fn sql_visible_source(path: &std::path::Path, source: &str) -> (String, Vec) { let mut violations = Vec::new(); let mut text = source.to_owned(); for (macro_name, expand_include) in [("include_str", true), ("concat", false)] { // Last occurrence first: a rewrite never moves an earlier offset, and // an inner `concat!` is joined before the one around it. loop { let masked = mask_comments_and_literals(&text); let Some(&(at, open)) = macro_calls(&masked, macro_name).first() else { break; }; let Some(close) = matching_close(&masked, open) else { violations.push(format!("{macro_name}!…) is unterminated")); break; }; let args = &text[open + 1..close]; let replacement = if expand_include { let included = sole_string_literal(args) .and_then(|span| span.string_body(args).map(str::to_owned)) .and_then(|relative| { let resolved = path.parent()?.join(&relative); std::fs::read_to_string(resolved).ok() }); match included { Some(contents) => plain_literal(&contents), None => { violations.push(format!("include_str!({}) is opaque", args.trim())); plain_literal("") } } } else { let masked_args = &masked[open + 1..close]; let mut joined = String::new(); let mut depth = 0usize; let mut arg_start = 0usize; for (index, byte) in masked_args.bytes().chain(std::iter::once(b',')).enumerate() { match byte { b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => depth = depth.saturating_sub(1), b',' if depth == 0 => { let arg = &args[arg_start..index.min(args.len())]; arg_start = index + 1; if arg.trim().is_empty() { continue; } match sole_string_literal(arg) .and_then(|span| plain_string_body(&span, arg)) { Some(body) => joined.push_str(&body), None => joined.push_str("{opaque}"), } } _ => {} } } format!("\"{joined}\"") }; text.replace_range(at..=close, &replacement); } } // sqlx's `query_file*!` macros load SQL from a file at compile time; // nothing uses them, so ban them rather than resolve them. let masked = mask_comments_and_literals(&text); for (at, _) in masked.match_indices("query_file") { let starts_token = !masked[..at] .chars() .next_back() .is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_'); let name_len = masked[at..] .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) .unwrap_or(masked.len() - at); if starts_token && masked[at + name_len..].trim_start().starts_with('!') { violations.push(format!( "{}! loads SQL from a file", &masked[at..at + name_len] )); } } (text, violations) } /// Length of the function item that starts `masked_function` (comments and /// literals blanked): through the `}` closing its body, or through the `;` of /// a bodiless declaration. Unlike [`cfg_test_item_len`], a `;` inside the /// signature's parentheses or brackets (`[u8; 4]`) does not end it. Without a /// body the whole input counts, so an unrecognized shape never hides SQL. fn function_item_len(masked_function: &str) -> usize { let mut nesting = 0usize; for (index, byte) in masked_function.bytes().enumerate() { match byte { b'(' | b'[' => nesting += 1, b')' | b']' => nesting = nesting.saturating_sub(1), b';' if nesting == 0 => return index + 1, b'{' if nesting == 0 => { return matching_close(masked_function, index) .map_or(masked_function.len(), |close| close + 1); } _ => {} } } masked_function.len() } /// Each function slice cut to the function's own item, so a const or static /// after its body is not attributed to it (see [`item_level_literals`]). fn function_items(production: &str) -> Vec<&str> { function_slices(production) .into_iter() .map(|function| &function[..function_item_len(&mask_comments_and_literals(function))]) .collect() } /// String literals outside every function body (consts, statics and macro /// bodies), as plain literals one per line. A function's floor guard cannot /// be attributed to SQL there. fn item_level_literals(production: &str) -> String { let base = production.as_ptr() as usize; let functions: Vec<(usize, usize)> = function_items(production) .into_iter() .map(|function| { let start = function.as_ptr() as usize - base; (start, start + function.len()) }) .collect(); let mut literals = String::new(); for span in source_spans(production) { if functions .iter() .any(|(start, end)| *start <= span.start && span.end <= *end) { continue; } if let Some(body) = plain_string_body(&span, production) { literals.push_str(&format!("\"{body}\"\n")); } } literals } /// Every floor-policy violation in one production file, after /// [`sql_visible_source`] has exposed included and concatenated SQL. fn file_event_floor_policy_violations(path: &std::path::Path, source: &str) -> Vec { let (production, mut violations) = sql_visible_source(path, &strip_cfg_test_items(source)); // The fence cannot bound a prepared transaction's rows without the // retired trigger (see `replica_fence::sample_writer`), so no supported // writer may prepare one. for span in source_spans(&production) { if let Some(body) = span.string_body(&production) { for violation in literal_sql_violations(&normalized_sql(body)) { if !violations.iter().any(|seen| seen == violation) { violations.push(violation.to_owned()); } } } } let item_level = item_level_literals(&production); if inserts_events_row(&item_level) || updates_event_floor_columns(&item_level) { violations.push("event-write SQL outside any function body".to_owned()); } violations.extend(event_floor_policy_violations(&production)); violations } fn event_floor_policy_violations(production: &str) -> Vec { function_items(production) .into_iter() .filter(|function| { 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"); } async fn row_time_no_space(tx: &mut AdmittedTx) { sqlx::query("UPDATE events SET(created_at,kind)=($1,1) WHERE id=$2"); } async fn guarded_upsert_rehome(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query("INSERT INTO events (id, channel_id) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET channel_id = EXCLUDED.channel_id"); } async fn guarded_upsert_row_time(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET(kind, created_at) = (1, $2)"); } async fn guarded_upsert_rehome_returning(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query("INSERT INTO events (id, channel_id) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET channel_id = EXCLUDED.channel_id RETURNING id, kind"); } async fn guarded_upsert_other_column(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET tags = EXCLUDED.tags"); } async fn guarded_upsert_do_nothing(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO NOTHING"); } async fn guarded_insert_then_other_table_upsert(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT DO NOTHING"); sqlx::query("INSERT INTO parameterized_event_watermarks (d_tag, created_at) VALUES ($1, $2) ON CONFLICT (d_tag) DO UPDATE SET created_at = EXCLUDED.created_at"); } async fn other_table_upsert_returning(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO channel_members (pubkey, role) VALUES ($1, $2) ON CONFLICT (pubkey) DO UPDATE SET removed_at = NULL, role = EXCLUDED.role RETURNING pubkey, role, removed_at"); } async fn subquery_where_then_channel(tx: &mut AdmittedTx) { sqlx::query("UPDATE events SET tags = (SELECT tags FROM events e2 WHERE e2.id = $1), channel_id = $2 WHERE id = $3"); } async fn subquery_where_only(tx: &mut AdmittedTx) { sqlx::query("UPDATE events SET tags = (SELECT tags FROM events e2 WHERE e2.id = $1) WHERE id = $2"); } async fn guarded_upsert_subquery_then_rehome(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET content = (SELECT content FROM events e2 WHERE e2.id = $1), channel_id = EXCLUDED.channel_id"); } async fn builder_continues_set_list(tx: &mut AdmittedTx) { QueryBuilder::new("UPDATE events SET tags = ").push_bind(t).push(", created_at = ").push_bind(c).push(" WHERE id = ").push_bind(id); } async fn builder_other_table_open_set_list(tx: &mut AdmittedTx) { QueryBuilder::new("UPDATE channels SET name = ").push_bind(n).push(" WHERE id = ").push_bind(id); } async fn guarded_builder_upsert_continues_set_list(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; QueryBuilder::new("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET tags = EXCLUDED.tags").push(", channel_id = EXCLUDED.channel_id"); } async fn guarded_builder_upsert_continues_other_column(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; QueryBuilder::new("INSERT INTO events (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET tags = EXCLUDED.tags").push(", kind = EXCLUDED.kind"); } async fn partition_update(tx: &mut AdmittedTx) { sqlx::query("UPDATE events_p_past SET created_at = $1 WHERE id = $2"); } async fn partition_insert(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO events_p_past (id) VALUES ($1)"); } async fn public_partition_insert(tx: &mut AdmittedTx) { sqlx::query("INSERT INTO public.events_p2026_01 (id) VALUES ($1)"); } async fn guarded_partition_upsert_rehome(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query("INSERT INTO events_p_future (id, channel_id) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET channel_id = EXCLUDED.channel_id"); } async fn events_prefixed_table(tx: &mut AdmittedTx) { sqlx::query("UPDATE events_per_domain SET created_at = $1 WHERE id = $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) {", "async fn row_time_no_space(tx: &mut AdmittedTx) {", "async fn guarded_upsert_rehome(tx: &mut AdmittedTx) {", "async fn guarded_upsert_row_time(tx: &mut AdmittedTx) {", "async fn guarded_upsert_rehome_returning(tx: &mut AdmittedTx) {", "async fn subquery_where_then_channel(tx: &mut AdmittedTx) {", "async fn guarded_upsert_subquery_then_rehome(tx: &mut AdmittedTx) {", "async fn builder_continues_set_list(tx: &mut AdmittedTx) {", "async fn guarded_builder_upsert_continues_set_list(tx: &mut AdmittedTx) {", "async fn partition_update(tx: &mut AdmittedTx) {", "async fn partition_insert(tx: &mut AdmittedTx) {", "async fn public_partition_insert(tx: &mut AdmittedTx) {", "async fn guarded_partition_upsert_rehome(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 event_floor_policy_fails_closed_on_sql_it_cannot_attribute() { let dir = std::env::temp_dir().join(format!("buzz-floor-policy-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&dir).expect("fixture dir"); std::fs::write( dir.join("insert_event.sql"), "INSERT INTO \"events\" (id) VALUES ($1)", ) .expect("sql fixture"); std::fs::write(dir.join("notes.md"), "Prose that quotes nothing.").expect("md fixture"); let path = dir.join("writer.rs"); let source = r##" const LEADING_INSERT: &str = "INSERT INTO events (id) VALUES ($1)"; const USER_AGENT: &str = concat!("buzz-agent/", env!("CARGO_PKG_VERSION")); static NOTES: &str = include_str!("notes.md"); async fn joined_insert(tx: &mut AdmittedTx) { sqlx::query(concat!("INSERT INTO ", "events (id) VALUES ($1)")); } async fn guarded_joined_insert(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query(concat!("INSERT INTO ", r#"events"#, " (id) VALUES ($1)")); } const TRAILING_REWRITE: &str = "UPDATE events SET created_at = $1 WHERE id = $2"; async fn joined_rewrite(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query(concat!("UPDATE events ", "SET created_at = $1 WHERE id = $2")); } async fn included_insert(tx: &mut AdmittedTx) { sqlx::query(include_str!("insert_event.sql")); } async fn guarded_included_insert(tx: &mut AdmittedTx) { crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel).await?; sqlx::query(include_str!("insert_event.sql")); } async fn opaque_include(tx: &mut AdmittedTx) { sqlx::query(include_str!(concat!(env!("OUT_DIR"), "/insert.sql"))); } async fn opaque_concat(tx: &mut AdmittedTx) { sqlx::query(concat!("INSERT INTO ", env!("EVENTS_TABLE"))); } async fn two_phase(tx: &mut AdmittedTx) { sqlx::query("PREPARE TRANSACTION 'fence'"); } "##; let violations = file_event_floor_policy_violations(&path, source); // One writer per shape: the SQL is split, assembled, loaded or spelled so // the per-literal checks cannot read it whole. const WRITER: &str = "async fn writer(tx: &mut AdmittedTx) {"; const OPAQUE_INSERT: &str = "INSERT target is not a literal table"; let shapes: [(&str, &[&str]); 23] = [ // Controls: an opaque WHERE predicate (the retention deletes), a // placeholder table with no floor column (tenant severing), and a // builder whose upsert continues in another literal. ( r#"sqlx::query(concat!("UPDATE events SET deleted_at = NOW() WHERE NOT ", pred!(), ""))"#, &[], ), ( r#"format!("UPDATE {table} SET community_id = NULL WHERE community_id = $1")"#, &[], ), ( r#"QueryBuilder::new("INSERT INTO listeners (a) ").push(" ON CONFLICT (a) DO UPDATE SET created_at = EXCLUDED.created_at")"#, &[], ), // A non-literal `concat!` argument as the target or a SET column. ( r#"concat!("UPDATE ", table!(), " SET created_at = $1")"#, &[WRITER], ), ( r#"concat!("UPDATE events SET ", cols!(), " = $1")"#, &[WRITER], ), // Every macro delimiter. ( r#"concat!["INSERT INTO ", "events (id) VALUES ($1)"]"#, &[WRITER], ), ( r#"::core::concat!{"INSERT INTO ", "events (id) VALUES ($1)"}"#, &[WRITER], ), (r#"include_str!["insert_event.sql"]"#, &[WRITER]), (r#"include_str! {"insert_event.sql"}"#, &[WRITER]), // Compile-time file SQL is banned outright. ( r#"sqlx::query_file!("insert_event.sql")"#, &["query_file! loads SQL from a file"], ), ( r#"sqlx::query_file_as!(Row, "insert_event.sql")"#, &["query_file_as! loads SQL from a file"], ), // SQL assembled at runtime. ( r#"format!("{}{}", "INSERT INTO ", "events (id) VALUES ($1)")"#, &[OPAQUE_INSERT], ), ( r#"format!("INSERT INTO {t} (id) VALUES ($1)")"#, &[OPAQUE_INSERT], ), ( r#"["INSERT INTO ", "events (id) VALUES ($1)"].concat()"#, &[OPAQUE_INSERT], ), ( r#"format!("INSERT INTO events (id) VALUES ($1) {suffix}")"#, &["events INSERT with a non-literal part", WRITER], ), ( r#"format!("{}{}", "UPDATE ", "events SET created_at = $1")"#, &[WRITER], ), ( r#"format!("UPDATE public.events SET {column} = $1")"#, &[WRITER], ), // A SET list continued in another literal or argument. ( r#"format!("UPDATE events SET {}", "created_at = $1")"#, &[WRITER], ), ( r#"["UPDATE events SET ", "channel_id = $1"].concat()"#, &[WRITER], ), ( r#"QueryBuilder::new("UPDATE events SET ").push("created_at = ")"#, &[WRITER], ), ( r#"QueryBuilder::new("INSERT INTO events (id) ").push(" ON CONFLICT (id) DO UPDATE SET ").push("channel_id = EXCLUDED.channel_id")"#, &[WRITER], ), ( r#"sqlx::query("MERGE INTO events e USING src ON e.id = src.id WHEN MATCHED THEN DO NOTHING")"#, &["events written by a statement other than INSERT"], ), ( r#"format!("{} TRANSACTION 'x'", "PREPARE")"#, &["PREPARE TRANSACTION in a production writer"], ), ]; let shape_violations = shapes.map(|(shape, _)| { file_event_floor_policy_violations(&path, &format!("{WRITER}\n {shape};\n}}\n")) }); // Each item-level form is caught on its own, wherever it sits. std::fs::write( dir.join("insert_event.sql"), "insert into events (id) values ($1)", ) .expect("sql fixture"); let items = [ "const LEADING: &str = \"INSERT INTO events (id) VALUES ($1)\";\nfn f() {}\n", "fn f() {}\nconst TRAILING: &str = \"UPDATE events SET channel_id = $1\";\nfn g() {}\n", "fn f() {}\nstatic INCLUDED: &str = include_str!(\"insert_event.sql\");\n", ]; let item_violations = items.map(|item| file_event_floor_policy_violations(&path, item)); std::fs::remove_dir_all(&dir).expect("remove fixture dir"); assert_eq!( violations, [ r#"include_str!(concat!(env!("OUT_DIR"), "/insert.sql")) is opaque"#, OPAQUE_INSERT, "PREPARE TRANSACTION in a production writer", "event-write SQL outside any function body", "async fn joined_insert(tx: &mut AdmittedTx) {", "async fn joined_rewrite(tx: &mut AdmittedTx) {", "async fn included_insert(tx: &mut AdmittedTx) {", ] ); for ((shape, expected), found) in shapes.iter().zip(&shape_violations) { assert_eq!(found, expected, "shape `{shape}`"); } for (item, found) in items.iter().zip(&item_violations) { assert_eq!( found, &["event-write SQL outside any function body"], "item-level SQL in `{item}`" ); } } #[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 source = std::fs::read_to_string(&path).expect("source"); let (production, _) = sql_visible_source(&path, &strip_cfg_test_items(&source)); guarded_writers += function_items(&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( file_event_floor_policy_violations(&path, &source) .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 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" ); } } // This policy covers the supported Rust writers while the retiring database // guards remain in place for mixed-version pods. SQL is read from the original // source; calls and struct fields use the existing masked view. const SINGLE_TABLE_GUARD_TABLES: [&str; 5] = [ "channels", "communities", "community_deletion_requests", "community_deletion_approvals", "community_deletion_manifest_keys", ]; const DELETION_STORE_PATH: &str = "buzz-db/src/store/deletion.rs"; /// The text after each occurrence of `marker` that sits on identifier /// boundaries, so `on conflict` matches before a space or `(` alike. fn sql_token_suffixes<'a>(source: &'a str, marker: &str) -> Vec<&'a str> { let is_ident = |ch: char| ch.is_ascii_alphanumeric() || ch == '_'; source .match_indices(marker) .filter_map(|(at, found)| { let rest = &source[at + found.len()..]; (!source[..at].chars().next_back().is_some_and(is_ident) && !rest.chars().next().is_some_and(is_ident)) .then_some(rest) }) .collect() } fn sql_table_suffixes<'a>(source: &'a str, verb: &str, table: &str) -> Vec<&'a str> { [format!("{verb} {table}"), format!("{verb} public.{table}")] .iter() .flat_map(|marker| sql_token_suffixes(source, marker)) .collect() } // Keep SET and WHERE from the same statement, including an INSERT's conflict UPDATE. fn sql_update_sets<'a>(source: &'a str, table: &str) -> Vec<(&'a str, &'a str)> { let updates = sql_table_suffixes(source, "update", table) .into_iter() .filter_map(|rest| { let rest = rest.split(['"', ';']).next()?.trim_start(); // UPDATE table [[AS] alias] SET ..., including SET(a, b) = ... let set = *sql_token_suffixes(rest, "set").first()?; let alias = &rest[..rest.len() - set.len() - "set".len()]; (alias.split_whitespace().count() <= 2).then_some(set.trim_start()) }); let conflict_updates = sql_table_suffixes(source, "insert into", table) .into_iter() .filter_map(|rest| { let statement = rest.split(['"', ';']).next()?; let conflict = *sql_token_suffixes(statement, "on conflict").first()?; sql_token_suffixes(conflict, "do update set") .first() .map(|set| set.trim_start()) }); updates .chain(conflict_updates) .map(|set| set.split_once(" where ").unwrap_or((set, ""))) .collect() } const DESTRUCTIVE_FROZEN_OR_EQUAL: &str = "destructive_storage_frozen_at is null or destructive_storage_manifest ="; /// A guard admits a statement only as a plain conjunct of its own WHERE: it /// follows the WHERE start or an `AND` (never `NOT`), and there is no `OR` /// word outside the known frozen-or-equal groups, and no subquery. fn plain_guard(predicate: &str, guard: &str) -> bool { let conjunct = predicate.match_indices(guard).any(|(at, _)| { let before = &predicate[..at]; // Allow a table qualifier: `communities.deletion_state = ...`. let before = before .strip_suffix('.') .map_or(before, |qualified| { qualified.trim_end_matches(|ch: char| ch.is_ascii_alphanumeric() || ch == '_') }) .trim_end_matches([' ', '(']); before.is_empty() || before.ends_with(" and") }); let rest = predicate.replace(DESTRUCTIVE_FROZEN_OR_EQUAL, "").replace( "destructive_storage_manifest is null or destructive_storage_manifest =", "", ); let words = || rest.split(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')); conjunct && !words().any(|word| word == "or" || word == "select") } fn sql_assigned_columns(set: &str) -> Vec<&str> { set.match_indices('=') .flat_map(|(at, _)| -> Vec<&str> { let left = set[..at].trim_end(); if left.ends_with(')') { // Tuple assignment: SET (a, b) = (...). let mut depth = 0; for (at, ch) in left.char_indices().rev() { match ch { ')' => depth += 1, '(' => { depth -= 1; if depth == 0 { return left[at + 1..left.len() - 1] .split(',') .map(str::trim) .collect(); } } _ => {} } } } left.rsplit(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_')) .next() .filter(|column| !column.is_empty()) .into_iter() .collect() }) .collect() } fn single_table_guard_violations( path: &str, production: &str, // Lifecycle exemption, stamp exemption, chunk guard, active predicate, request freezes. rule_hits: &mut [Vec; 5], ) -> Vec { let mut violations = Vec::new(); let code = mask_comments_and_literals(production); if let Some((_, fields)) = code.split_once("struct ChannelUpdate") { let fields = fields .split_once('{') .expect("struct body") .1 .split('}') .next() .expect("struct fields"); if fields.split(',').any(|field| { field.split_once(':').is_some_and(|(name, _)| { name.split_whitespace() .last() .is_some_and(|name| name.starts_with("community")) }) }) { violations.push("ChannelUpdate must not expose a community field".to_owned()); } } for function in function_slices(production) { let header = function_header(function); let sql = normalized_sql(function); let code = mask_comments_and_literals(function); let mut reject = |reason: &str| violations.push(format!("{header}: {reason}")); let name = header .split_once("fn ") .expect("function name") .1 .split('(') .next() .expect("function arguments"); let lifecycle_writer = path == DELETION_STORE_PATH && header.starts_with("async fn transition_community("); let channel_sets = sql_update_sets(&sql, "channels"); if channel_sets .iter() .any(|(set, _)| sql_assigned_columns(set).contains(&"community_id")) || (!channel_sets.is_empty() && sql.split("set_parts.push(").skip(1).any(|part| { let assignment = part.split(';').next().expect("dynamic SET fragment"); sql_assigned_columns(assignment).contains(&"community_id") })) { reject("channels.community_id UPDATE"); } let community_sets = sql_update_sets(&sql, "communities"); if community_sets.iter().any(|(set, _)| { sql_assigned_columns(set).iter().any(|column| { ["deletion_state", "deletion_fence_generation", "deleted_at"].contains(column) }) }) { if lifecycle_writer { rule_hits[0].push(name.to_owned()); } else { reject("community lifecycle UPDATE outside transition_community"); } } if !community_sets.is_empty() && !lifecycle_writer { rule_hits[3].push(name.to_owned()); if community_sets .iter() .any(|(_, predicate)| !plain_guard(predicate, "deletion_state = 'active'")) { reject("community UPDATE requires an active predicate in its statement"); } } if sql_table_suffixes(&sql, "insert into", "communities") .iter() .any(|rest| { let Some(columns) = rest.trim_start().strip_prefix('(') else { return true; }; columns .split(')') .next() .expect("INSERT columns") .split(',') .any(|column| { ["deletion_state", "deletion_fence_generation", "deleted_at"] .contains(&column.trim()) }) }) { reject( "community creation requires explicit columns without deletion lifecycle fields", ); } if !sql_table_suffixes(&sql, "delete from", "communities").is_empty() { reject("production community DELETE"); } let request_sets = sql_update_sets(&sql, "community_deletion_requests"); if request_sets.iter().any(|(set, _)| { sql_assigned_columns(set).iter().any(|column| { [ "community_id", "community_host", "request_origin", "owner_pubkey", "mediating_operator_pubkey", "acknowledgement_version", ] .contains(column) }) }) { reject("deletion request identity/provenance UPDATE"); } let mut freezes_inventory = false; let mut freezes_destructive_storage = false; for (set, predicate) in &request_sets { let columns = sql_assigned_columns(set); if columns.iter().any(|column| { [ "schema_manifest", "storage_manifest", "inventory_manifest", "inventory_digest", "inventory_frozen_at", ] .contains(column) }) { freezes_inventory = true; if !plain_guard(predicate, "inventory_frozen_at is null") { reject( "request inventory UPDATE requires inventory_frozen_at IS NULL in WHERE", ); } } if columns .iter() .any(|column| column.starts_with("destructive_storage_")) { freezes_destructive_storage = true; if !plain_guard(predicate, DESTRUCTIVE_FROZEN_OR_EQUAL) { reject("request destructive storage UPDATE requires the frozen-or-equal guard in WHERE"); } if columns .iter() .filter(|column| column.starts_with("destructive_storage_")) .any(|column| !set.contains(&format!("{column} = coalesce({column},"))) { reject("request destructive storage UPDATE must preserve a frozen value with COALESCE"); } } } if freezes_inventory || freezes_destructive_storage { rule_hits[4].push(name.to_owned()); } if ["update", "delete from"] .iter() .any(|verb| !sql_table_suffixes(&sql, verb, "community_deletion_approvals").is_empty()) || !sql_update_sets(&sql, "community_deletion_approvals").is_empty() { reject("approval UPDATE, upsert or DELETE"); } let manifest = "community_deletion_manifest_keys"; let manifest_updates = sql_table_suffixes(&sql, "update", manifest).len(); let manifest_writes = manifest_updates + sql_table_suffixes(&sql, "insert into", manifest).len() + sql_table_suffixes(&sql, "delete from", manifest).len(); if manifest_writes > 0 { // Chunk content never changes. The only UPDATE is the one-way // `deleted_at` stamp, held to the same plain-conjunct rule as guards. let sets = sql_update_sets(&sql, manifest); let deletion_stamp = path == DELETION_STORE_PATH && header.starts_with("pub async fn mark_manifest_chunk_deleted(") && manifest_writes == 1 && manifest_updates == 1 && matches!(sets.as_slice(), [(set, predicate)] if set.trim() == "deleted_at = now()" && ["request_id = $1", "chunk_no = $2", "deleted_at is null"] .iter() .all(|guard| plain_guard(predicate, guard))); let guarded = code.contains("guard_manifest_chunk_write("); if deletion_stamp { rule_hits[1].push(name.to_owned()); } else if manifest_updates > 0 || !sets.is_empty() { reject("manifest chunk UPDATE other than the one-way deleted_at stamp"); } else if path == DELETION_STORE_PATH && guarded { rule_hits[2].push(name.to_owned()); } else { reject("manifest chunk INSERT or DELETE must use guard_manifest_chunk_write"); } } } violations } #[test] fn single_table_policy_rejects_channel_retenanting() { for source in [ r#"async fn retenant() { query("UPDATE channels SET community_id = $1 WHERE id = $2"); }"#, r#"async fn retenant() { query("update public.channels as c set name = $1, community_id=$2 where id=$3"); }"#, r#"async fn retenant() { set_parts.push(format!("community_id = $1")); query("UPDATE channels SET {} WHERE id = $2"); }"#, "pub struct ChannelUpdate { pub community_id: Option, }", "pub struct ChannelUpdate { pub community: CommunityId, }", ] { assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, source, &mut Default::default()) .len(), 1, "{source}" ); } } #[test] fn single_table_policy_requires_active_community_updates() { let source = r#"async fn bypass() { query("UPDATE communities SET icon = NULL WHERE id = $1"); }"#; assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, source, &mut Default::default()).len(), 1 ); let guarded = source.replace( "WHERE id = $1", "WHERE id = $1 AND deletion_state = 'active'", ); assert!( single_table_guard_violations(DELETION_STORE_PATH, &guarded, &mut Default::default()) .is_empty() ); // A predicate in a SELECT or another UPDATE does not admit this statement. let separate = source.replace( "query(", "query(\"SELECT id FROM communities WHERE deletion_state = 'active'\"); query(", ); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &separate, &mut Default::default()) .len(), 1 ); let two_updates = r#"async fn bypass() { query("UPDATE communities SET icon = NULL WHERE id = $1 AND deletion_state = 'active'"); query("UPDATE communities SET icon = NULL WHERE id = $2"); }"#; assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, two_updates, &mut Default::default()) .len(), 1 ); } #[test] fn single_table_policy_rejects_weakened_guards() { for sql in [ "UPDATE communities SET icon = NULL WHERE id = $1 AND (deletion_state = 'active' OR true)", "UPDATE communities SET icon = NULL WHERE id = $1 OR deletion_state = 'active'", "UPDATE communities SET icon = NULL WHERE id IN (SELECT id FROM communities WHERE deletion_state = 'active')", "UPDATE communities SET icon = NULL WHERE id = $1 AND NOT deletion_state = 'active'", "UPDATE communities SET icon = NULL WHERE id = $1 AND NOT communities.deletion_state = 'active'", "UPDATE communities SET icon = NULL WHERE id = $1 AND (deletion_state = 'active')OR(true)", "UPDATE community_deletion_requests SET inventory_digest = NULL WHERE id = $1 AND (inventory_frozen_at IS NULL OR true)", "UPDATE community_deletion_requests SET destructive_storage_manifest = COALESCE(destructive_storage_manifest, $2) WHERE id = $1 AND (destructive_storage_frozen_at IS NULL OR destructive_storage_manifest = $2 OR true)", ] { let source = format!("async fn bypass() {{ query(\"{sql}\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{sql}" ); } } #[test] fn single_table_policy_requires_inventory_freeze_predicate() { for column in [ "schema_manifest", "storage_manifest", "inventory_manifest", "inventory_digest", "inventory_frozen_at", ] { let source = format!("async fn bypass() {{ query(\"UPDATE community_deletion_requests SET {column} = NULL WHERE id = $1\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{column}" ); let guarded = source.replace( "WHERE id = $1", "WHERE id = $1 AND inventory_frozen_at IS NULL", ); assert!( single_table_guard_violations(DELETION_STORE_PATH, &guarded, &mut Default::default()) .is_empty(), "{column}" ); } } #[test] fn single_table_policy_requires_destructive_freeze_predicate() { for column in [ "destructive_storage_manifest", "destructive_storage_frozen_at", ] { let source = format!("async fn bypass() {{ query(\"UPDATE community_deletion_requests SET {column} = COALESCE({column}, $2) WHERE id = $1\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{column}" ); let guarded = source.replace("WHERE id = $1", "WHERE id = $1 AND (destructive_storage_frozen_at IS NULL OR destructive_storage_manifest = $2)"); assert!( single_table_guard_violations(DELETION_STORE_PATH, &guarded, &mut Default::default()) .is_empty(), "{column}" ); // The guard keeps an equal manifest admissible, so SET must not overwrite it. let overwrite = guarded.replace(&format!("COALESCE({column}, $2)"), "NULL"); let violations = single_table_guard_violations(DELETION_STORE_PATH, &overwrite, &mut Default::default()); assert!( violations.len() == 1 && violations[0].contains("preserve a frozen value"), "{column}: {violations:?}" ); } } #[test] fn single_table_policy_checks_conflict_updates() { for (sql, reason) in [ ("INSERT INTO communities (host) VALUES ($1) ON CONFLICT (host) DO UPDATE SET icon = NULL", "requires an active predicate"), ("INSERT INTO communities (host) VALUES ($1) ON CONFLICT (host) DO UPDATE SET deleted_at = now() WHERE communities.deletion_state = 'active'", "lifecycle UPDATE"), ("INSERT INTO community_deletion_requests (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET community_id = $2", "identity/provenance UPDATE"), ("INSERT INTO community_deletion_requests (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET inventory_digest = NULL", "inventory_frozen_at IS NULL"), ("INSERT INTO community_deletion_requests (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET destructive_storage_manifest = NULL", "frozen-or-equal guard"), ] { let source = format!("async fn bypass() {{ query(\"{sql}\"); }}"); let violations = single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()); assert!(violations.iter().any(|violation| violation.contains(reason)), "{sql}: {violations:?}"); } let source = r#"async fn guarded() { query("INSERT INTO communities (host) VALUES ($1) ON CONFLICT (host) DO UPDATE SET host = communities.host WHERE communities.deletion_state = 'active'"); query("INSERT INTO community_deletion_requests (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET inventory_digest = $2 WHERE inventory_frozen_at IS NULL"); query("INSERT INTO community_deletion_requests (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET destructive_storage_manifest = COALESCE(destructive_storage_manifest, $2) WHERE destructive_storage_frozen_at IS NULL OR destructive_storage_manifest = $2"); }"#; assert!( single_table_guard_violations(DELETION_STORE_PATH, source, &mut Default::default()) .is_empty() ); } #[test] fn single_table_policy_rejects_implicit_community_insert_columns() { for sql in [ "INSERT INTO communities VALUES ($1, $2)", "INSERT INTO communities SELECT * FROM staging", ] { let source = format!("async fn bypass() {{ query(\"{sql}\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{sql}" ); } let explicit = r#"async fn create() { query("INSERT INTO communities (host) SELECT host FROM staging"); }"#; assert!( single_table_guard_violations(DELETION_STORE_PATH, explicit, &mut Default::default()) .is_empty() ); } #[test] fn single_table_policy_checks_tuple_assignments() { for (sql, reason) in [ ("UPDATE channels SET (name, community_id) = ($1, $2) WHERE id = $3", "channels.community_id UPDATE"), ("UPDATE channels SET(name, community_id) = ($1, $2) WHERE id = $3", "channels.community_id UPDATE"), ("UPDATE communities SET (icon, deletion_state) = (NULL, 'active') WHERE id = $1 AND deletion_state = 'active'", "lifecycle UPDATE"), ("UPDATE community_deletion_requests SET (stage, community_id) = ($1, $2) WHERE id = $3", "identity/provenance UPDATE"), ("UPDATE community_deletion_requests SET (inventory_digest, inventory_manifest) = (NULL, NULL) WHERE id = $1", "inventory_frozen_at IS NULL"), ("UPDATE community_deletion_requests SET (destructive_storage_manifest, destructive_storage_frozen_at) = (NULL, NULL) WHERE id = $1", "frozen-or-equal guard"), ] { let source = format!("async fn bypass() {{ query(\"{sql}\"); }}"); let violations = single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()); assert!(violations.iter().any(|violation| violation.contains(reason)), "{sql}: {violations:?}"); } let guarded = r#"async fn freeze() { query("UPDATE community_deletion_requests SET (inventory_manifest, inventory_digest) = ($2, $3) WHERE id = $1 AND inventory_frozen_at IS NULL"); }"#; assert!( single_table_guard_violations(DELETION_STORE_PATH, guarded, &mut Default::default()) .is_empty() ); } #[test] fn single_table_policy_rejects_community_lifecycle_bypasses() { for column in ["deletion_state", "deletion_fence_generation", "deleted_at"] { let source = format!("async fn bypass() {{ query(\"UPDATE communities SET {column} = $1 WHERE id = $2 AND deletion_state = 'active'\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{column}" ); let transition = source.replace("bypass", "transition_community"); assert!(single_table_guard_violations( DELETION_STORE_PATH, &transition, &mut Default::default() ) .is_empty()); assert_eq!( single_table_guard_violations( "buzz-relay/src/bypass.rs", &transition, &mut Default::default() ) .len(), 1 ); } for column in ["deletion_state", "deletion_fence_generation", "deleted_at"] { let source = format!("async fn bypass() {{ query(\"INSERT INTO communities (id, {column}) VALUES ($1, $2)\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{column}" ); } let deletion = r#"async fn bypass() { query("DELETE FROM communities WHERE id = $1"); }"#; assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, deletion, &mut Default::default()).len(), 1 ); } #[test] fn single_table_policy_rejects_request_retargeting() { for column in [ "community_id", "community_host", "request_origin", "owner_pubkey", "mediating_operator_pubkey", "acknowledgement_version", ] { let source = format!("async fn bypass() {{ query(\"UPDATE community_deletion_requests SET {column} = $1 WHERE id = $2\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{column}" ); } } #[test] fn single_table_policy_rejects_approval_mutations() { for sql in [ "UPDATE community_deletion_approvals SET approved_by = $1 WHERE request_id = $2", "DELETE FROM community_deletion_approvals WHERE request_id = $1", "INSERT INTO community_deletion_approvals (request_id, note) VALUES ($1, $2) ON CONFLICT (request_id) DO UPDATE SET note = EXCLUDED.note", "INSERT INTO community_deletion_approvals (request_id, note) VALUES ($1, $2) ON CONFLICT(request_id) DO UPDATE SET note = EXCLUDED.note", "INSERT INTO community_deletion_approvals (request_id, note) VALUES ($1, $2) ON CONFLICT(request_id) DO UPDATE SET(note) = ROW(EXCLUDED.note)", ] { let source = format!("async fn bypass() {{ query(\"{sql}\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{sql}" ); } let append = r#"async fn approve() { query("INSERT INTO community_deletion_approvals (request_id, note) VALUES ($1, $2)"); query("INSERT INTO community_deletion_approvals (request_id, note) VALUES ($1, $2) ON CONFLICT (request_id) DO NOTHING"); query("INSERT INTO community_deletion_approvals (request_id, note) VALUES ($1, $2) ON CONFLICT(request_id) DO NOTHING"); }"#; assert!( single_table_guard_violations(DELETION_STORE_PATH, append, &mut Default::default()) .is_empty() ); } #[test] fn single_table_policy_rejects_unguarded_manifest_writers() { for sql in [ "INSERT INTO community_deletion_manifest_keys (keys) VALUES ($1)", "DELETE FROM community_deletion_manifest_keys WHERE request_id = $1", ] { let source = format!("async fn bypass() {{ query(\"{sql}\"); }}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()) .len(), 1, "{sql}" ); // A guard in another function or a literal does not admit this writer. let mixed = format!("async fn guarded() {{ guard_manifest_chunk_write(); }}\n{source}"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &mixed, &mut Default::default()) .len(), 1 ); let fake = source.replace("query(", "let _ = \"guard_manifest_chunk_write(\"; query("); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &fake, &mut Default::default()) .len(), 1 ); let guarded = source.replace("query(", "guard_manifest_chunk_write(); query("); assert!(single_table_guard_violations( DELETION_STORE_PATH, &guarded, &mut Default::default() ) .is_empty()); assert_eq!( single_table_guard_violations( "buzz-relay/src/bypass.rs", &guarded, &mut Default::default() ) .len(), 1 ); } } #[test] fn single_table_policy_rejects_manifest_content_updates() { // The chunk guard admits INSERT and DELETE only: content never changes. for sql in [ "UPDATE community_deletion_manifest_keys SET keys = $1 WHERE request_id = $2", "INSERT INTO community_deletion_manifest_keys (request_id, chunk_no, keys) VALUES ($1, $2, $3) ON CONFLICT (request_id, chunk_no) DO UPDATE SET keys = EXCLUDED.keys", "INSERT INTO community_deletion_manifest_keys (request_id, chunk_no, keys) VALUES ($1, $2, $3) ON CONFLICT(request_id, chunk_no) DO UPDATE SET keys = EXCLUDED.keys", ] { let source = format!("async fn append() {{ guard_manifest_chunk_write(); query(\"{sql}\"); }}"); let violations = single_table_guard_violations(DELETION_STORE_PATH, &source, &mut Default::default()); assert_eq!(violations.len(), 1, "{sql}: {violations:?}"); assert!(violations[0].contains("other than the one-way deleted_at stamp")); } } #[test] fn single_table_policy_holds_the_manifest_stamp_to_plain_conjuncts() { let stamp = r#"pub async fn mark_manifest_chunk_deleted() { query("UPDATE community_deletion_manifest_keys SET deleted_at = now() WHERE request_id = $1 AND chunk_no = $2 AND deleted_at IS NULL"); }"#; let mut hits: [Vec; 5] = Default::default(); assert!(single_table_guard_violations(DELETION_STORE_PATH, stamp, &mut hits).is_empty()); assert_eq!(hits[1], ["mark_manifest_chunk_deleted"]); for (from, to) in [ (" AND deleted_at IS NULL", ""), ("deleted_at = now()", "deleted_at = now(), keys = $3"), ("deleted_at = now()", "deleted_at = NULL"), ("deleted_at IS NULL", "deleted_at IS NULL OR true"), ( "chunk_no = $2 AND deleted_at IS NULL", "chunk_no IN (SELECT chunk_no FROM chunks WHERE request_id = $1 AND deleted_at IS NULL)", ), ("request_id = $1 AND ", ""), ("chunk_no = $2 AND ", ""), // A second write in the stamp function does not share its exemption. ( "deleted_at IS NULL\");", "deleted_at IS NULL\"); query(\"DELETE FROM community_deletion_manifest_keys WHERE request_id = $1\");", ), // The stamp must be a plain UPDATE, not a conflict upsert. ( "UPDATE community_deletion_manifest_keys SET", "INSERT INTO community_deletion_manifest_keys (request_id, chunk_no) VALUES ($1, $2) ON CONFLICT (request_id, chunk_no) DO UPDATE SET", ), ] { let weakened = stamp.replace(from, to); assert_ne!(weakened, stamp); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &weakened, &mut Default::default()) .len(), 1, "{weakened}" ); } let renamed_stamp = stamp.replace("mark_manifest_chunk_deleted", "restamp"); assert_eq!( single_table_guard_violations(DELETION_STORE_PATH, &renamed_stamp, &mut Default::default()) .len(), 1 ); assert_eq!( single_table_guard_violations("buzz-relay/src/bypass.rs", stamp, &mut Default::default()) .len(), 1 ); } #[test] fn every_production_single_table_guard_writer_preserves_its_invariants() { use std::path::Path; let crates_root = Path::new(env!("CARGO_MANIFEST_DIR")) .parent() .expect("crates root"); let mut files = Vec::new(); for entry in std::fs::read_dir(crates_root).expect("read crates directory") { let src = entry.expect("read crate entry").path().join("src"); if src.is_dir() { collect_production_rs_files(&src, &mut files); } } let mut writers = [0usize; 5]; let mut rule_hits: [Vec; 5] = Default::default(); let mut violations = Vec::new(); for path in files { let source = std::fs::read_to_string(&path).expect("read production source"); let production = strip_cfg_test_items(&source); for function in function_slices(&production) { let sql = normalized_sql(function); for (index, table) in SINGLE_TABLE_GUARD_TABLES.iter().enumerate() { if ["insert into", "update", "delete from"] .iter() .any(|verb| !sql_table_suffixes(&sql, verb, table).is_empty()) { writers[index] += 1; } } } let relative = path .strip_prefix(crates_root) .expect("crate source") .to_string_lossy() .replace('\\', "/"); violations.extend( single_table_guard_violations(&relative, &production, &mut rule_hits) .into_iter() .map(|violation| format!("{relative}: {violation}")), ); } assert!( violations.is_empty(), "single-table guard policy: {violations:#?}" ); // Exact rule hits pin the parser to the known production seams. for (hits, expected) in rule_hits.iter_mut().zip([ vec!["transition_community"], vec!["mark_manifest_chunk_deleted"], vec![ "append_manifest_key_chunk", "clear_manifest_key_chunks", "mark_logically_verified", ], vec![ "archive_community_owned_by", "ensure_configured_community_with_operation", "set_community_icon", "set_community_nip_fi_policy", "set_policy_in_transaction", "soft_delete_on", "unarchive_community_owned_by", "update_channel_on", ], vec![ "complete_owner_preparation", "freeze_destructive_storage_manifest", "freeze_inventory", ], ]) { hits.sort(); assert_eq!(*hits, expected, "production single-table rule hits"); } // Lower bounds pin discovery without fixing the exact number of writers. for ((table, seen), floor) in SINGLE_TABLE_GUARD_TABLES .iter() .zip(writers) .zip([7, 4, 15, 2, 4]) { assert!( seen >= floor, "{table}: expected at least {floor} writers, found {seen}" ); } }