mirror of
https://github.com/block/buzz.git
synced 2026-11-25 18:52:52 +00:00
## Summary This makes every serving writer of a community-write-fenced table take community admission in application code. That's the "Dual enforcement" step of the Supported Writer Contract in `ARCHITECTURE.md`. Admission means the shared community deletion lock plus the active/not-deleted check from `deletion::guard_community_write`. It's taken before the transaction's first tenant write or row lock and held until commit. The 32 `community_write_fence_*` triggers, the six fence SQL functions and `validate_serving_catalog` are unchanged. They stay authoritative. Removing them is a separate migration that will be checked table by table. ## Changes - **New admission entry point.** `begin_community_write_transaction` (`runtime/mod.rs`) builds an `AdmittedTx` for non-event writers. It sits next to the existing event-write entry points and shares their implementation. - **Writers moved onto it:** - `api_tokens`, `archived_identities`, `channels`, `channel_members` (including DM and admin paths), `community_bans`, `git_repo_names` - `moderation_actions` and `moderation_reports`, `personal_read_accounts` and `personal_read_frontiers`, `pubkey_allowlist` - `push_leases`, `push_match_queue`, `push_wake_outbox` - `relay_invites`, `relay_members` (including the new-community owner bootstrap and the startup `pubkey_allowlist` backfill), `join_policy_acceptances` - `thread_metadata`, `users`, `workflows`, `workflow_runs`, `workflow_approvals`, `scheduled_workflow_fires` - Personal-read helpers now require `&mut AdmittedTx`. - **`buzz-audit`.** An append now passes admission first, then takes a transaction-scoped audit-chain lock (`pg_advisory_xact_lock`). This replaces the session lock and the `catch_unwind` unlock cleanup. The relay audit worker retries a `lock_timeout` on either lock and keeps the entry; an admission refusal is terminal, as the trigger's refusal was. - **Fleet-wide statements.** These keep `community_write_allowed(...)` in the same SQL statement, because there's no single community to admit up front: - scheduled-fire prune - invite expiry - push matcher claim and exhausted-job cleanup - startup `d_tag` backfill - channel TTL cleanup - **Relay-member removal.** `remove_relay_member` and `remove_relay_member_if_role` run `delete_member_with_acceptances` inside their admitted transaction. The helper no longer opens its own transaction, so the member lock, the `join_policy_acceptances` delete and the member delete all hold admission until commit. `delete_workflow` and `delete_workflow_for_owner` are gone on `main`, and the coordinate deletion path they used to back was already admitted. - **Unchanged exceptions.** The deletion-executor generation exception and the serving-lease path work as before. - **Tables with no production writer.** `delivery_log` and `subscriptions` are only written by a historical cutover script and a test fixture. Their triggers stay. - **No cross-community moves.** No production `community_id` move exists on a fenced table. The only `SET community_id = NULL` is the deletion-executor purge. So no dual-community lock ordering was needed. ## What got simpler - Per-store ad-hoc writer helpers are gone: `begin_event_write_transaction` and `acquire_event_write_connection` in `channel.rs`, and `begin_operation_transaction` in `push.rs`. - Audit append drops the session advisory unlock, the `catch_unwind`/`resume_unwind` panic handling, `log_inner` and the `futures-util` dependency. ## Notes for reviewers - **New crate dependency.** `buzz-audit` now depends on `buzz-db` only to call the free function `buzz_db::deletion::guard_community_write`. `ARCHITECTURE.md` names this as the one sanctioned subsystem edge, and its audit section is updated to match. - **Hot paths.** `ensure_user` first checks whether the user exists and returns without admission when it does (no write happens). Only a real insert takes admission. `touch_api_token` has no production caller today. - **No-op writers stay read-only.** The startup allowlist backfill returns early on plain reads when the legacy table is gone, it has no rows for the community, or the community already has members, so a quiescing deployment community still starts. It re-checks under admission before inserting. - **Owner mutations.** When admission refuses a transfer or a provisioning and a deletion request exists, both report `DeletionPending`, as before. For a transfer, the operator API keeps its coded `deletion_lifecycle_conflict` 409. For provisioning, it keeps the existing uncoded 409, `owner_conflict: community deletion is pending`. - **Per-community worker loops.** `claim_due_push_wakes` and similar now return `AccessDenied` for a community that goes quiescing between the active-host scan and the claim. The worker logs it at `debug` and the next scan skips the community. - **Kick side effects.** `membership_removal_fence` admits before the membership lock to keep the lock order of `add_member`. A community that leaves `active` between the kick and the fence skips live subscription eviction; the membership cache is already invalidated and fan-out re-checks membership. This is documented on the function. ## Testing - **New refusal tests.** 19 tests: the 18 in `store::admission_postgres_tests`, plus `audit_append_requires_application_admission_with_triggers_bypassed`. Each runs with ordinary triggers disabled (`session_replication_role = replica`), checks that a raw fenced insert would succeed, and asserts that the writer is refused for both `quiescing` and `fenced` communities. Active writes still succeed. - **The tests catch a missing check.** Measured in review at `6fc073c3f`: with the guard in `AdmittedTx::admit` bypassed, 25 tests fail. That includes 16 of the 18 database admission tests. The audit test stays green there, because audit calls `guard_community_write` directly. - **Affected PG suites, with triggers on:** 183/183 passed across 16 store suites, push 18/18 run isolated, audit 7/7. The existing artifact, reaction and replaceable admission tests pass. - **Review fixes, each checked to fail without its fix:** - `allowlist_backfill_requires_application_admission` and `owner_mutations_report_pending_deletion_when_admission_refuses` fail with the old `relay_members.rs`. - `empty_allowlist_backfill_skips_admission` fails (`AccessDenied … write-fenced (quiescing)`) without the allowlist-rows early return. - `audit_worker_retries_admission_lock_timeout_until_original_entry_is_appended_once` holds the community deletion lock exclusive and fails without the admission retry arm. - The existing audit-chain retry test now looks for the transaction-scoped lock and passes. - The two owner-revoke mini-schema tests (`bridge.rs`, `ingest.rs`) now include `communities` and `community_deletion_lock_key`, which admission reads; both failed without that. - **Static checks:** `cargo fmt --check` and workspace `cargo clippy --all-targets -D warnings` pass. - **Not run locally:** the `mobile-check` step of `just ci` (the build machine couldn't reach pub.dev, and clean base fails the same way) and the full `just test` lane. CI on this PR covers both. `mesh_demo::demo_join_forwarded_arm_round_trips_echo` fails on the build machine at base `394d4a434` as well; it uses no database. Refs BUZZ-314. --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
586 lines
20 KiB
Rust
586 lines
20 KiB
Rust
use chrono::{DateTime, Utc};
|
|
use sqlx::{PgPool, Row};
|
|
use tracing::{debug, warn};
|
|
use uuid::Uuid;
|
|
|
|
use buzz_core::CommunityId;
|
|
use buzz_datastore_tracing::datastore_span;
|
|
|
|
use crate::{
|
|
action::AuditAction,
|
|
entry::{AuditEntry, NewAuditEntry},
|
|
error::AuditError,
|
|
hash::{compute_hash, to_storage_precision, CURRENT_HASH_VERSION},
|
|
};
|
|
|
|
/// The `created_at` stamped on a new entry.
|
|
///
|
|
/// Reduced to the precision Postgres round-trips before it is hashed — see
|
|
/// [`to_storage_precision`]. Split out from [`AuditService::log`] so the
|
|
/// invariant is testable without a database.
|
|
fn log_timestamp() -> DateTime<Utc> {
|
|
to_storage_precision(Utc::now())
|
|
}
|
|
|
|
/// Per-community audit-chain advisory lock key. Admission takes the community
|
|
/// deletion lock first; this key then serializes appends within that community.
|
|
const AUDIT_LOCK_NAMESPACE: &str = "buzz_audit:";
|
|
|
|
/// Append-only, per-community hash-chain audit log backed by Postgres.
|
|
///
|
|
/// Each community has an independent chain keyed `(community_id, seq)`. Writes
|
|
/// for one community are serialized by a per-community advisory lock so the chain
|
|
/// stays consistent across relay processes; different communities proceed in
|
|
/// parallel.
|
|
pub struct AuditService {
|
|
pool: PgPool,
|
|
}
|
|
|
|
impl AuditService {
|
|
/// Creates a new `AuditService` using the given connection pool.
|
|
pub fn new(pool: PgPool) -> Self {
|
|
Self { pool }
|
|
}
|
|
|
|
/// Append a new entry to the calling community's chain.
|
|
///
|
|
/// Community admission precedes the transaction-scoped audit-chain lock.
|
|
/// Both locks are released on commit or rollback, including a dropped future.
|
|
#[datastore_span(
|
|
name = "audit_log",
|
|
system = "postgresql",
|
|
fields(action = %entry.action)
|
|
)]
|
|
pub async fn log(&self, entry: NewAuditEntry) -> Result<AuditEntry, AuditError> {
|
|
let mut tx = self.pool.begin().await?;
|
|
buzz_db::deletion::guard_community_write(&mut tx, entry.community_id).await?;
|
|
let lock_key = format!("{AUDIT_LOCK_NAMESPACE}{}", entry.community_id);
|
|
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
|
|
.bind(&lock_key)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
|
|
// The stored row keys on the raw UUID; the typed `CommunityId` on the
|
|
// input is the provenance fence, dereferenced here at the DB boundary.
|
|
let community_id = *entry.community_id.as_uuid();
|
|
|
|
// Head of THIS community's chain — scoped by community_id.
|
|
let head = sqlx::query(
|
|
"SELECT seq, hash FROM audit_log
|
|
WHERE community_id = $1
|
|
ORDER BY seq DESC LIMIT 1",
|
|
)
|
|
.bind(community_id)
|
|
.fetch_optional(&mut *tx)
|
|
.await?;
|
|
|
|
let (prev_seq, prev_hash): (i64, Option<Vec<u8>>) = match head {
|
|
Some(row) => (
|
|
row.get::<i64, _>("seq"),
|
|
Some(row.get::<Vec<u8>, _>("hash")),
|
|
),
|
|
None => (0, None), // community's first entry
|
|
};
|
|
let seq = prev_seq + 1;
|
|
|
|
let created_at: DateTime<Utc> = log_timestamp();
|
|
|
|
let mut audit_entry = AuditEntry {
|
|
community_id,
|
|
seq,
|
|
hash_version: CURRENT_HASH_VERSION,
|
|
hash: Vec::new(),
|
|
prev_hash,
|
|
action: entry.action,
|
|
actor_pubkey: entry.actor_pubkey,
|
|
object_id: entry.object_id,
|
|
detail: entry.detail,
|
|
created_at,
|
|
};
|
|
|
|
audit_entry.hash = compute_hash(&audit_entry)?.to_vec();
|
|
|
|
debug!(seq, "writing audit entry");
|
|
|
|
sqlx::query(
|
|
r#"
|
|
INSERT INTO audit_log
|
|
(community_id, seq, hash, prev_hash, action, actor_pubkey, object_id, detail, created_at, hash_version)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
"#,
|
|
)
|
|
.bind(audit_entry.community_id)
|
|
.bind(audit_entry.seq)
|
|
.bind(&audit_entry.hash)
|
|
.bind(audit_entry.prev_hash.as_deref())
|
|
.bind(audit_entry.action.as_str())
|
|
.bind(audit_entry.actor_pubkey.as_deref())
|
|
.bind(audit_entry.object_id.as_deref())
|
|
.bind(&audit_entry.detail)
|
|
.bind(audit_entry.created_at)
|
|
.bind(audit_entry.hash_version)
|
|
.execute(&mut *tx)
|
|
.await?;
|
|
|
|
tx.commit().await?;
|
|
|
|
Ok(audit_entry)
|
|
}
|
|
|
|
/// Verify the hash chain for one community over `[from_seq, to_seq]`.
|
|
///
|
|
/// Reads exactly that community's chain — it can never observe another
|
|
/// community's entries or head. Returns `Ok(false)` if the range is empty,
|
|
/// `Ok(true)` if the segment is internally consistent.
|
|
#[datastore_span(
|
|
name = "audit_verify_chain",
|
|
system = "postgresql",
|
|
fields(from_seq = from_seq, to_seq = to_seq)
|
|
)]
|
|
pub async fn verify_chain(
|
|
&self,
|
|
community: CommunityId,
|
|
from_seq: i64,
|
|
to_seq: i64,
|
|
) -> Result<bool, AuditError> {
|
|
let rows = sqlx::query(
|
|
r#"
|
|
SELECT community_id, seq, hash, prev_hash, action, actor_pubkey,
|
|
object_id, detail, created_at, hash_version
|
|
FROM audit_log
|
|
WHERE community_id = $1 AND seq BETWEEN $2 AND $3
|
|
ORDER BY seq ASC
|
|
"#,
|
|
)
|
|
.bind(community.as_uuid())
|
|
.bind(from_seq)
|
|
.bind(to_seq)
|
|
.fetch_all(&self.pool)
|
|
.await?;
|
|
|
|
if rows.is_empty() {
|
|
return Ok(false);
|
|
}
|
|
|
|
let mut expected_prev: Option<Vec<u8>> = None;
|
|
|
|
for row in &rows {
|
|
let entry = row_to_audit_entry(row)?;
|
|
|
|
if let Some(ref expected) = expected_prev {
|
|
// The previous entry's hash must equal this entry's prev_hash.
|
|
if entry.prev_hash.as_deref() != Some(expected.as_slice()) {
|
|
return Err(AuditError::ChainViolation { seq: entry.seq });
|
|
}
|
|
}
|
|
|
|
let computed = compute_hash(&entry)?;
|
|
if computed.as_slice() != entry.hash.as_slice() {
|
|
return Err(AuditError::HashMismatch { seq: entry.seq });
|
|
}
|
|
|
|
expected_prev = Some(entry.hash);
|
|
}
|
|
|
|
Ok(true)
|
|
}
|
|
|
|
/// Returns up to `limit` entries from one community's chain starting at
|
|
/// `from_seq`, ordered by sequence number. Scoped to `community` — never
|
|
/// returns another community's rows.
|
|
#[datastore_span(
|
|
name = "audit_get_entries",
|
|
system = "postgresql",
|
|
fields(from_seq = from_seq, limit = limit)
|
|
)]
|
|
pub async fn get_entries(
|
|
&self,
|
|
community: CommunityId,
|
|
from_seq: i64,
|
|
limit: i64,
|
|
) -> Result<Vec<AuditEntry>, AuditError> {
|
|
let rows = sqlx::query(
|
|
r#"
|
|
SELECT community_id, seq, hash, prev_hash, action, actor_pubkey,
|
|
object_id, detail, created_at, hash_version
|
|
FROM audit_log
|
|
WHERE community_id = $1 AND seq >= $2
|
|
ORDER BY seq ASC
|
|
LIMIT $3
|
|
"#,
|
|
)
|
|
.bind(community.as_uuid())
|
|
.bind(from_seq)
|
|
.bind(limit)
|
|
.fetch_all(&self.pool)
|
|
.await?;
|
|
|
|
rows.iter().map(row_to_audit_entry).collect()
|
|
}
|
|
}
|
|
|
|
fn row_to_audit_entry(row: &sqlx::postgres::PgRow) -> Result<AuditEntry, AuditError> {
|
|
let action_str: String = row.get("action");
|
|
let action: AuditAction = action_str.parse().map_err(|_| {
|
|
warn!("unknown action in audit log");
|
|
AuditError::UnknownAction
|
|
})?;
|
|
|
|
Ok(AuditEntry {
|
|
community_id: row.get::<Uuid, _>("community_id"),
|
|
seq: row.get("seq"),
|
|
hash_version: row.get("hash_version"),
|
|
hash: row.get("hash"),
|
|
prev_hash: row.get("prev_hash"),
|
|
action,
|
|
actor_pubkey: row.get("actor_pubkey"),
|
|
object_id: row.get("object_id"),
|
|
detail: row.get("detail"),
|
|
created_at: row.get("created_at"),
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod postgres_tests {
|
|
use super::*;
|
|
use crate::action::AuditAction;
|
|
use crate::entry::NewAuditEntry;
|
|
use chrono::SubsecRound;
|
|
use std::sync::OnceLock;
|
|
use tokio::sync::Mutex;
|
|
use uuid::Uuid;
|
|
|
|
// The per-community advisory lock means different communities don't contend,
|
|
// but tests share one table; serialize them so seq assertions are stable.
|
|
static DB_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
|
fn db_lock() -> &'static Mutex<()> {
|
|
DB_LOCK.get_or_init(|| Mutex::new(()))
|
|
}
|
|
|
|
async fn test_pool() -> Option<PgPool> {
|
|
let url = std::env::var("DATABASE_URL")
|
|
.unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".into()); // sadscan:disable np.postgres.1 -- local test fixture
|
|
PgPool::connect(&url).await.ok()
|
|
}
|
|
|
|
/// Runs without Postgres, so a regression here is caught by `just
|
|
/// test-unit` rather than only by the `#[ignore]` chain tests below.
|
|
#[test]
|
|
fn log_timestamp_carries_no_sub_microsecond_digits() {
|
|
let ts = log_timestamp();
|
|
assert_eq!(
|
|
ts,
|
|
ts.trunc_subsecs(6),
|
|
"created_at is hashed and then stored in a TIMESTAMPTZ column; \
|
|
sub-microsecond digits make every entry fail verify_chain"
|
|
);
|
|
}
|
|
|
|
/// A `community_id` known to exist in `communities` (FK target). Inserts a
|
|
/// throwaway community row with a unique host and returns its id.
|
|
async fn make_community(pool: &PgPool) -> Uuid {
|
|
let id = Uuid::new_v4();
|
|
let host = format!("test-{id}.example");
|
|
sqlx::query("INSERT INTO communities (id, host) VALUES ($1, $2)")
|
|
.bind(id)
|
|
.bind(host)
|
|
.execute(pool)
|
|
.await
|
|
.expect("insert test community");
|
|
id
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn audit_append_requires_application_admission_with_triggers_bypassed() {
|
|
let _g = db_lock().lock().await;
|
|
let url = std::env::var("DATABASE_URL").expect("Postgres lane must provide DATABASE_URL");
|
|
let pool = sqlx::postgres::PgPoolOptions::new()
|
|
.max_connections(1)
|
|
.connect(&url)
|
|
.await
|
|
.expect("connect test database");
|
|
let active = make_community(&pool).await;
|
|
for state in ["quiescing", "fenced"] {
|
|
let id = make_community(&pool).await;
|
|
let mut tx = pool.begin().await.expect("begin lifecycle transition");
|
|
sqlx::query(
|
|
"SELECT set_config('buzz.deletion_executor_community', $1, true), \
|
|
set_config('buzz.deletion_fence_generation', \
|
|
(SELECT deletion_fence_generation::text FROM communities WHERE id = $2), true)",
|
|
)
|
|
.bind(id.to_string())
|
|
.bind(id)
|
|
.execute(&mut *tx)
|
|
.await
|
|
.expect("authorize lifecycle transition");
|
|
sqlx::query("UPDATE communities SET deletion_state = $2 WHERE id = $1")
|
|
.bind(id)
|
|
.bind(state)
|
|
.execute(&mut *tx)
|
|
.await
|
|
.expect("set lifecycle state");
|
|
tx.commit().await.expect("commit lifecycle state");
|
|
|
|
sqlx::query("SET session_replication_role = replica")
|
|
.execute(&pool)
|
|
.await
|
|
.expect("disable ordinary triggers");
|
|
let error = AuditService::new(pool.clone())
|
|
.log(new_entry(id, AuditAction::EventCreated))
|
|
.await
|
|
.expect_err("fenced audit append must reject before chain lock");
|
|
assert!(
|
|
matches!(error, AuditError::Admission(buzz_db::DbError::AccessDenied(message)) if message.contains("write-fenced")),
|
|
"expected application admission failure"
|
|
);
|
|
}
|
|
let entry = AuditService::new(pool.clone())
|
|
.log(new_entry(active, AuditAction::EventCreated))
|
|
.await
|
|
.expect("active audit append succeeds");
|
|
assert_eq!(entry.seq, 1);
|
|
}
|
|
|
|
fn new_entry(community_id: Uuid, action: AuditAction) -> NewAuditEntry {
|
|
NewAuditEntry {
|
|
community_id: CommunityId::from_uuid(community_id),
|
|
action,
|
|
actor_pubkey: Some(vec![0xab; 32]),
|
|
object_id: Some(format!("obj_{}", Uuid::new_v4())),
|
|
detail: serde_json::json!({"test": true}),
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn community_chain_starts_at_seq_1_with_null_prev() {
|
|
let _g = db_lock().lock().await;
|
|
let Some(pool) = test_pool().await else {
|
|
return;
|
|
};
|
|
let svc = AuditService::new(pool.clone());
|
|
let c = make_community(&pool).await;
|
|
|
|
let e = svc
|
|
.log(new_entry(c, AuditAction::EventCreated))
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(e.seq, 1, "first entry in a community starts at seq 1");
|
|
assert_eq!(e.hash_version, CURRENT_HASH_VERSION);
|
|
assert!(e.prev_hash.is_none(), "genesis entry has NULL prev_hash");
|
|
assert_eq!(e.hash.len(), 32);
|
|
assert_eq!(e.community_id, c);
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn chain_links_within_one_community() {
|
|
let _g = db_lock().lock().await;
|
|
let Some(pool) = test_pool().await else {
|
|
return;
|
|
};
|
|
let svc = AuditService::new(pool.clone());
|
|
let c = make_community(&pool).await;
|
|
|
|
let mut e1 = svc
|
|
.log(new_entry(c, AuditAction::EventCreated))
|
|
.await
|
|
.unwrap();
|
|
// Model a historical row, including the migration's version default.
|
|
e1.hash_version = 1;
|
|
e1.hash = compute_hash(&e1).unwrap().to_vec();
|
|
sqlx::query("UPDATE audit_log SET hash_version = DEFAULT, hash = $1 WHERE community_id = $2 AND seq = $3")
|
|
.bind(&e1.hash)
|
|
.bind(c)
|
|
.bind(e1.seq)
|
|
.execute(&pool)
|
|
.await
|
|
.unwrap();
|
|
let e2 = svc
|
|
.log(new_entry(c, AuditAction::ChannelCreated))
|
|
.await
|
|
.unwrap();
|
|
let e3 = svc
|
|
.log(new_entry(c, AuditAction::MemberAdded))
|
|
.await
|
|
.unwrap();
|
|
|
|
assert_eq!(e1.seq, 1);
|
|
assert_eq!(e2.seq, 2);
|
|
assert_eq!(e3.seq, 3);
|
|
assert_eq!(e2.hash_version, CURRENT_HASH_VERSION);
|
|
assert_eq!(e3.hash_version, CURRENT_HASH_VERSION);
|
|
assert!(e1.prev_hash.is_none());
|
|
assert_eq!(e2.prev_hash.as_deref(), Some(e1.hash.as_slice()));
|
|
assert_eq!(e3.prev_hash.as_deref(), Some(e2.hash.as_slice()));
|
|
assert!(svc
|
|
.verify_chain(CommunityId::from_uuid(c), 1, 3)
|
|
.await
|
|
.unwrap());
|
|
let rows = svc
|
|
.get_entries(CommunityId::from_uuid(c), 1, 3)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(rows[0].hash_version, 1);
|
|
assert_eq!(rows[0].hash, e1.hash);
|
|
assert_eq!(rows[1].hash_version, CURRENT_HASH_VERSION);
|
|
}
|
|
|
|
/// THE isolation property: two communities keep independent chains. Each
|
|
/// starts at seq 1; interleaving writes does not link them; verifying one
|
|
/// never traverses the other.
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn chains_are_independent_per_community() {
|
|
let _g = db_lock().lock().await;
|
|
let Some(pool) = test_pool().await else {
|
|
return;
|
|
};
|
|
let svc = AuditService::new(pool.clone());
|
|
let a = make_community(&pool).await;
|
|
let b = make_community(&pool).await;
|
|
|
|
// Interleave A and B writes.
|
|
let a1 = svc
|
|
.log(new_entry(a, AuditAction::EventCreated))
|
|
.await
|
|
.unwrap();
|
|
let b1 = svc
|
|
.log(new_entry(b, AuditAction::EventCreated))
|
|
.await
|
|
.unwrap();
|
|
let a2 = svc
|
|
.log(new_entry(a, AuditAction::ChannelCreated))
|
|
.await
|
|
.unwrap();
|
|
let b2 = svc
|
|
.log(new_entry(b, AuditAction::ChannelCreated))
|
|
.await
|
|
.unwrap();
|
|
|
|
// Each community's seq is independent and starts at 1.
|
|
assert_eq!((a1.seq, a2.seq), (1, 2));
|
|
assert_eq!((b1.seq, b2.seq), (1, 2));
|
|
|
|
// A's chain links only within A; B's only within B. A2 must NOT chain to
|
|
// B1 even though B1 was written between A1 and A2.
|
|
assert_eq!(a2.prev_hash.as_deref(), Some(a1.hash.as_slice()));
|
|
assert_eq!(b2.prev_hash.as_deref(), Some(b1.hash.as_slice()));
|
|
assert_ne!(a2.prev_hash, b1.prev_hash);
|
|
|
|
// Verifying A's chain traverses only A; same for B.
|
|
assert!(svc
|
|
.verify_chain(CommunityId::from_uuid(a), 1, 2)
|
|
.await
|
|
.unwrap());
|
|
assert!(svc
|
|
.verify_chain(CommunityId::from_uuid(b), 1, 2)
|
|
.await
|
|
.unwrap());
|
|
|
|
// get_entries scoped to A returns only A's rows.
|
|
let a_rows = svc
|
|
.get_entries(CommunityId::from_uuid(a), 1, 100)
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
a_rows.iter().all(|e| e.community_id == a),
|
|
"A read leaked another community"
|
|
);
|
|
assert_eq!(a_rows.len(), 2);
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn verify_detects_tampering_within_a_community() {
|
|
let _g = db_lock().lock().await;
|
|
let Some(pool) = test_pool().await else {
|
|
return;
|
|
};
|
|
let svc = AuditService::new(pool.clone());
|
|
let c = make_community(&pool).await;
|
|
|
|
svc.log(new_entry(c, AuditAction::EventCreated))
|
|
.await
|
|
.unwrap();
|
|
let mut input = new_entry(c, AuditAction::EventDeleted);
|
|
input.actor_pubkey = Some(vec![1; 32]);
|
|
let e2 = svc.log(input).await.unwrap();
|
|
svc.log(new_entry(c, AuditAction::ChannelDeleted))
|
|
.await
|
|
.unwrap();
|
|
|
|
// This shift preserved the old concatenated bytes, but changes TLV.
|
|
sqlx::query("UPDATE audit_log SET actor_pubkey = $1, object_id = $4 WHERE community_id = $2 AND seq = $3")
|
|
.bind(vec![1_u8; 31])
|
|
.bind(c)
|
|
.bind(e2.seq)
|
|
.bind(format!("\u{1}{}", e2.object_id.as_deref().unwrap()))
|
|
.execute(&pool)
|
|
.await
|
|
.unwrap();
|
|
|
|
let r = svc.verify_chain(CommunityId::from_uuid(c), 1, 3).await;
|
|
assert!(matches!(r, Err(AuditError::HashMismatch { seq }) if seq == e2.seq));
|
|
}
|
|
|
|
/// A row forged with another community's id cannot pass verification against
|
|
/// the chain it was stamped for, because community_id is hashed in. (Models
|
|
/// "a row can't be replayed across chains and still verify".)
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn cross_community_row_does_not_verify() {
|
|
let _g = db_lock().lock().await;
|
|
let Some(pool) = test_pool().await else {
|
|
return;
|
|
};
|
|
let svc = AuditService::new(pool.clone());
|
|
let a = make_community(&pool).await;
|
|
let b = make_community(&pool).await;
|
|
|
|
let a1 = svc
|
|
.log(new_entry(a, AuditAction::EventCreated))
|
|
.await
|
|
.unwrap();
|
|
|
|
// Forge: copy A's seq-1 row's hash into B's chain at seq 1.
|
|
sqlx::query(
|
|
"INSERT INTO audit_log (community_id, seq, hash, prev_hash, action, actor_pubkey, object_id, detail, created_at, hash_version)
|
|
VALUES ($1, 1, $2, NULL, $3, $4, $5, $6, $7, $8)",
|
|
)
|
|
.bind(b)
|
|
.bind(&a1.hash) // A's hash, which was computed over community_id = A
|
|
.bind(a1.action.as_str())
|
|
.bind(a1.actor_pubkey.as_deref())
|
|
.bind(a1.object_id.as_deref())
|
|
.bind(&a1.detail)
|
|
.bind(a1.created_at)
|
|
.bind(a1.hash_version)
|
|
.execute(&pool)
|
|
.await
|
|
.unwrap();
|
|
|
|
// Verifying B's chain recomputes the hash with community_id = B, which
|
|
// won't match A's stored hash → HashMismatch. The forge is rejected.
|
|
let r = svc.verify_chain(CommunityId::from_uuid(b), 1, 1).await;
|
|
assert!(matches!(r, Err(AuditError::HashMismatch { seq: 1 })));
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn verify_empty_range_is_false() {
|
|
let _g = db_lock().lock().await;
|
|
let Some(pool) = test_pool().await else {
|
|
return;
|
|
};
|
|
let svc = AuditService::new(pool.clone());
|
|
let c = make_community(&pool).await;
|
|
// No entries for this fresh community.
|
|
assert!(!svc
|
|
.verify_chain(CommunityId::from_uuid(c), 1, 100)
|
|
.await
|
|
.unwrap());
|
|
}
|
|
}
|