Skip to content

Commit ba11d66

Browse files
npub1cc3ha7z055mu0rwwu7806t2wt8mj3pvu0uv5mfp2c50dahaqhczshdalg6Tyler Longwell
andcommitted
feat(audit): per-community hash chain on the frozen audit_log DDL
Convert the audit log from one global hash chain to an independent per-community chain, conforming to the frozen Lane-0 0001 schema. - Collapse to one DDL: delete schema.rs / AUDIT_SCHEMA_SQL and their lib.rs exports. The 0001 migration is the sole owner of audit_log. - Chain shape: PK (community_id, seq), seq monotonic per-community, UNIQUE (community_id, hash); hash/prev_hash/actor_pubkey as BYTEA; object_id TEXT generalizes the old event_id/channel_id; detail JSONB. - community_id is folded into the SHA-256 (leads the hash) so a row cannot be lifted out of one community's chain and re-verified in another. Per-community advisory lock — communities never serialize each other's audit writes (no throughput bottleneck, no timing oracle). - verify_chain / get_entries scoped to a CommunityId. - Error variants carry only per-community seq (meaningless without its chain) — never community_id, hash values, or raw action strings. - AUTH-body protection becomes caller discipline + the AuditAction enum (AuthSuccess/AuthFailure carry outcome metadata, never the token); the dropped event_kind column is not persisted. 13/13 green (7 unit + 6 Postgres isolation). Adversarial: disabling the community_id line in compute_hash turns community_id_is_part_of_identity RED (two communities hash identically); restored to green. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent e349d76 commit ba11d66

6 files changed

Lines changed: 425 additions & 285 deletions

File tree

‎crates/buzz-audit/src/entry.rs‎

Lines changed: 46 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,46 +4,60 @@ use uuid::Uuid;
44

55
use crate::action::AuditAction;
66

7-
/// Materialised audit log entry as stored in the DB.
8-
#[derive(Debug, Clone, Serialize, Deserialize)]
7+
/// A materialised audit log entry as stored in `audit_log`.
8+
///
9+
/// Rows are keyed `(community_id, seq)`: `seq` is monotonic *within one
10+
/// community*, and `prev_hash` chains to the previous entry *of the same
11+
/// community*. The chain is independent per tenant.
12+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
913
pub struct AuditEntry {
10-
/// Monotonically increasing sequence number.
14+
/// Server-resolved community this entry belongs to. Leads the primary key.
15+
pub community_id: Uuid,
16+
/// Sequence number, monotonic within `community_id` (starts at 1).
1117
pub seq: i64,
12-
/// When the entry was recorded.
13-
pub timestamp: DateTime<Utc>,
14-
/// Nostr event ID that triggered this action.
15-
pub event_id: String,
16-
/// Nostr event kind number.
17-
pub event_kind: u32,
18-
/// Hex-encoded Nostr pubkey.
19-
pub actor_pubkey: String,
18+
/// SHA-256 of this entry's fields including `community_id` and `prev_hash`.
19+
pub hash: Vec<u8>,
20+
/// SHA-256 of the previous entry in *this community's* chain, or `None` for
21+
/// the community's first entry (hashed as [`crate::hash::GENESIS_HASH`]).
22+
pub prev_hash: Option<Vec<u8>>,
2023
/// Action that was performed.
2124
pub action: AuditAction,
22-
/// Channel this action applies to, if any.
23-
pub channel_id: Option<Uuid>,
24-
/// Arbitrary JSON context. **Included in hash computation** (serialized with
25-
/// sorted keys for determinism) so that metadata tampering is detectable.
26-
pub metadata: serde_json::Value,
27-
/// SHA-256 hex hash of the previous entry (or [`crate::hash::GENESIS_HASH`] for the first).
28-
pub prev_hash: String,
29-
/// SHA-256 hex hash of this entry's fields including `prev_hash`.
30-
pub hash: String,
25+
/// Raw bytes of the actor's Nostr pubkey, if the action has one.
26+
pub actor_pubkey: Option<Vec<u8>>,
27+
/// Generic identifier of the object acted upon (event id hex, channel UUID,
28+
/// media sha256, …), if any. The relay resolves it under `community_id`;
29+
/// it never names an object in another community.
30+
pub object_id: Option<String>,
31+
/// Arbitrary JSON context. **Included in the hash** (serialized with sorted
32+
/// keys for determinism) so tampering with it is detectable.
33+
pub detail: serde_json::Value,
34+
/// When the entry was recorded.
35+
pub created_at: DateTime<Utc>,
3136
}
3237

33-
/// Input for creating a new audit entry. `seq`, `prev_hash`, `hash` are computed by `AuditService::log`.
34-
#[derive(Debug, Clone, Serialize, Deserialize)]
38+
/// Input for appending a new audit entry. `seq`, `prev_hash`, `hash`, and
39+
/// `created_at` are assigned by [`crate::service::AuditService::log`].
40+
///
41+
/// `community_id` is the **server-resolved** tenant (from the request's
42+
/// `TenantContext`), never a client-supplied value — the same provenance rule
43+
/// the whole multi-tenant model rests on.
44+
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3545
pub struct NewAuditEntry {
36-
/// Nostr event ID that triggered this action.
37-
pub event_id: String,
38-
/// Must not be 22242 (NIP-42 AUTH).
39-
pub event_kind: u32,
40-
/// Hex-encoded Nostr pubkey of the actor.
41-
pub actor_pubkey: String,
46+
/// Server-resolved community this entry belongs to.
47+
pub community_id: Uuid,
4248
/// Action that was performed.
4349
pub action: AuditAction,
44-
/// Channel this action applies to, if any.
45-
pub channel_id: Option<Uuid>,
46-
/// Arbitrary JSON context included in hash computation.
50+
/// Raw bytes of the actor's Nostr pubkey, if the action has one.
51+
pub actor_pubkey: Option<Vec<u8>>,
52+
/// Generic identifier of the object acted upon, if any.
53+
pub object_id: Option<String>,
54+
/// Arbitrary JSON context included in the hash.
55+
///
56+
/// **Never bearer-token material.** This field is opaque to the audit
57+
/// crate and persisted verbatim; callers must not write tokens, passwords,
58+
/// or other secrets here. `AuthSuccess`/`AuthFailure` entries carry only
59+
/// outcome metadata — the token has no slot in this type, and `detail` must
60+
/// not become one.
4761
#[serde(default)]
48-
pub metadata: serde_json::Value,
62+
pub detail: serde_json::Value,
4963
}

‎crates/buzz-audit/src/error.rs‎

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,41 @@
11
use thiserror::Error;
22

33
/// Errors that can occur during audit log operations.
4+
///
5+
/// These are **operator-internal** diagnostics (logged by the audit worker, or
6+
/// returned to an operator-scoped verification call) — they are never relayed to
7+
/// a client on the wire. Even so, no variant embeds a `community_id` or any
8+
/// cross-community object identifier: a `seq` is per-community and meaningless
9+
/// without its chain, and hashes are opaque. An error raised while verifying
10+
/// community A's chain therefore cannot reveal a fact about community B.
411
#[derive(Debug, Error)]
512
pub enum AuditError {
613
/// A database operation failed.
714
#[error("database error: {0}")]
815
Database(#[from] sqlx::Error),
916

10-
/// Attempted to log a NIP-42 AUTH event (kind 22242), which is forbidden.
11-
#[error("auth events (kind 22242) must never appear in the audit log")]
12-
AuthEventForbidden,
13-
14-
/// The `prev_hash` of an entry does not match the hash of the preceding entry.
17+
/// The `prev_hash` of an entry does not match the hash of the preceding
18+
/// entry in the same community's chain.
1519
#[error(
16-
"hash chain integrity violation at seq {seq}: expected prev_hash {expected}, got {actual}"
20+
"hash chain integrity violation at seq {seq}: prev_hash does not match preceding entry"
1721
)]
1822
ChainViolation {
19-
/// Sequence number of the offending entry.
23+
/// Per-community sequence number of the offending entry.
2024
seq: i64,
21-
/// Hash that was expected based on the previous entry.
22-
expected: String,
23-
/// Hash that was actually found in the entry.
24-
actual: String,
2525
},
2626

2727
/// The stored hash of an entry does not match the recomputed hash.
28-
#[error("hash mismatch at seq {seq}: stored {stored}, computed {computed}")]
28+
#[error("hash mismatch at seq {seq}: stored hash does not match recomputed hash")]
2929
HashMismatch {
30-
/// Sequence number of the offending entry.
30+
/// Per-community sequence number of the offending entry.
3131
seq: i64,
32-
/// Hash value stored in the database.
33-
stored: String,
34-
/// Hash value recomputed from the entry fields.
35-
computed: String,
3632
},
3733

3834
/// An unrecognised action string was found in the database.
39-
#[error("unknown audit action in DB: {0:?}")]
40-
UnknownAction(String),
35+
#[error("unknown audit action in database")]
36+
UnknownAction,
4137

42-
/// A JSON serialization error occurred (e.g. while canonicalising metadata).
38+
/// A JSON serialization error occurred (e.g. while canonicalising `detail`).
4339
#[error("serialization error: {0}")]
4440
Serialization(#[from] serde_json::Error),
4541
}

‎crates/buzz-audit/src/hash.rs‎

Lines changed: 77 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -3,41 +3,53 @@ use sha2::{Digest, Sha256};
33
use crate::entry::AuditEntry;
44
use crate::error::AuditError;
55

6-
/// Sentinel `prev_hash` value used for the first entry in the chain.
7-
pub const GENESIS_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000";
6+
/// The 32-byte sentinel hashed in place of `prev_hash` for a community's first
7+
/// entry. Stored as `prev_hash = NULL`; hashed as all-zero bytes.
8+
pub const GENESIS_HASH: [u8; 32] = [0u8; 32];
89

9-
/// SHA-256 over all identity, chain, and context fields.
10-
/// Field order is fixed — changing it invalidates all existing chains.
10+
/// SHA-256 over the entry's identity, chain, and context fields.
1111
///
12-
/// Metadata is serialized via `BTreeMap` to guarantee key ordering across
13-
/// machines and Rust versions. `serde_json::Value` does not guarantee order.
12+
/// Field order is fixed — changing it invalidates all existing chains. The
13+
/// `community_id` is hashed first so chain identity carries the tenant: an entry
14+
/// cannot be lifted out of one community's chain and re-verified inside another.
1415
///
15-
/// Returns `Err(AuditError::Serialization)` if metadata cannot be serialized.
16-
/// Never hashes a default/empty value as a stand-in for a real payload —
17-
/// a serialization failure is a hard error, not a silent degradation.
18-
pub fn compute_hash(entry: &AuditEntry) -> Result<String, AuditError> {
16+
/// `detail` is serialized via [`canonical_json`] (sorted keys) so the hash is
17+
/// stable across machines and Rust versions. A serialization failure is a hard
18+
/// error, never silently hashed as empty.
19+
pub fn compute_hash(entry: &AuditEntry) -> Result<[u8; 32], AuditError> {
1920
let mut hasher = Sha256::new();
21+
// Tenant binding: community_id leads the hash.
22+
hasher.update(entry.community_id.as_bytes());
2023
hasher.update(entry.seq.to_be_bytes());
21-
hasher.update(entry.timestamp.to_rfc3339().as_bytes());
22-
hasher.update(entry.event_id.as_bytes());
23-
// event_kind is u32 — 4 bytes in big-endian for the hash chain.
24-
hasher.update(entry.event_kind.to_be_bytes());
25-
hasher.update(entry.actor_pubkey.as_bytes());
24+
hasher.update(entry.created_at.to_rfc3339().as_bytes());
2625
hasher.update(entry.action.as_str().as_bytes());
27-
match &entry.channel_id {
28-
Some(id) => hasher.update(id.as_bytes()),
29-
None => hasher.update([0u8; 16]),
26+
match &entry.actor_pubkey {
27+
Some(pk) => {
28+
hasher.update([1u8]); // presence tag — distinguishes Some(empty) from None
29+
hasher.update(pk);
30+
}
31+
None => hasher.update([0u8]),
32+
}
33+
match &entry.object_id {
34+
Some(id) => {
35+
hasher.update([1u8]);
36+
hasher.update(id.as_bytes());
37+
}
38+
None => hasher.update([0u8]),
3039
}
31-
hasher.update(canonical_json(&entry.metadata)?.as_bytes());
32-
hasher.update(entry.prev_hash.as_bytes());
33-
Ok(hex::encode(hasher.finalize()))
40+
hasher.update(canonical_json(&entry.detail)?.as_bytes());
41+
match &entry.prev_hash {
42+
Some(h) => hasher.update(h),
43+
None => hasher.update(GENESIS_HASH),
44+
}
45+
Ok(hasher.finalize().into())
3446
}
3547

36-
/// Serialize a JSON value with sorted keys for deterministic output.
48+
/// Serialize a JSON value with sorted object keys for deterministic output.
3749
///
38-
/// Returns `Err` if any scalar value cannot be serialized. This should never
39-
/// happen for well-formed `serde_json::Value`, but we propagate rather than
40-
/// silently substitute an empty string.
50+
/// Propagates any scalar serialization error rather than substituting a
51+
/// placeholder — a hash must never silently stand in an empty value for a real
52+
/// payload.
4153
fn canonical_json(value: &serde_json::Value) -> Result<String, serde_json::Error> {
4254
use serde_json::Value;
4355
use std::collections::BTreeMap;
@@ -81,29 +93,39 @@ mod tests {
8193
use super::*;
8294
use crate::{action::AuditAction, entry::AuditEntry};
8395
use chrono::Utc;
96+
use uuid::Uuid;
8497

8598
fn sample_entry() -> AuditEntry {
8699
AuditEntry {
100+
community_id: Uuid::from_u128(1),
87101
seq: 1,
88-
timestamp: chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
102+
hash: Vec::new(),
103+
prev_hash: None,
104+
action: AuditAction::EventCreated,
105+
actor_pubkey: Some(vec![0xab; 32]),
106+
object_id: Some("abc123".into()),
107+
detail: serde_json::Value::Null,
108+
created_at: chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
89109
.unwrap()
90110
.with_timezone(&Utc),
91-
event_id: "abc123".to_string(),
92-
event_kind: 1,
93-
actor_pubkey: "pubkey_alice".to_string(),
94-
action: AuditAction::EventCreated,
95-
channel_id: None,
96-
metadata: serde_json::Value::Null,
97-
prev_hash: GENESIS_HASH.to_string(),
98-
hash: String::new(),
99111
}
100112
}
101113

102114
#[test]
103115
fn deterministic() {
104116
let entry = sample_entry();
105117
assert_eq!(compute_hash(&entry).unwrap(), compute_hash(&entry).unwrap());
106-
assert_eq!(compute_hash(&entry).unwrap().len(), 64);
118+
assert_eq!(compute_hash(&entry).unwrap().len(), 32);
119+
}
120+
121+
#[test]
122+
fn community_id_is_part_of_identity() {
123+
// The whole point: the same logical entry in two communities hashes
124+
// differently, so a row can't be replayed across chains.
125+
let a = sample_entry();
126+
let mut b = a.clone();
127+
b.community_id = Uuid::from_u128(2);
128+
assert_ne!(compute_hash(&a).unwrap(), compute_hash(&b).unwrap());
107129
}
108130

109131
#[test]
@@ -112,37 +134,44 @@ mod tests {
112134
let h0 = compute_hash(&base).unwrap();
113135

114136
let mut e = base.clone();
115-
e.event_id = "different_event".into();
137+
e.seq = 2;
116138
assert_ne!(h0, compute_hash(&e).unwrap());
117139

118140
let mut e = base.clone();
119-
e.seq = 2;
141+
e.action = AuditAction::EventDeleted;
120142
assert_ne!(h0, compute_hash(&e).unwrap());
121143

122144
let mut e = base.clone();
123-
e.actor_pubkey = "pubkey_bob".into();
145+
e.actor_pubkey = Some(vec![0xcd; 32]);
124146
assert_ne!(h0, compute_hash(&e).unwrap());
125147

126148
let mut e = base.clone();
127-
e.channel_id = Some(uuid::Uuid::new_v4());
149+
e.object_id = Some("different".into());
128150
assert_ne!(h0, compute_hash(&e).unwrap());
129151

130-
let mut e = base;
131-
e.metadata = serde_json::json!({"key": "value"});
152+
let mut e = base.clone();
153+
e.detail = serde_json::json!({"key": "value"});
132154
assert_ne!(h0, compute_hash(&e).unwrap());
155+
156+
let mut e = base.clone();
157+
e.prev_hash = Some(vec![0xff; 32]);
158+
assert_ne!(h0, compute_hash(&e).unwrap());
159+
}
160+
161+
#[test]
162+
fn presence_tag_distinguishes_none_from_empty() {
163+
// Some(empty) must not collide with None — the presence tag prevents it.
164+
let mut none = sample_entry();
165+
none.actor_pubkey = None;
166+
let mut empty = sample_entry();
167+
empty.actor_pubkey = Some(Vec::new());
168+
assert_ne!(compute_hash(&none).unwrap(), compute_hash(&empty).unwrap());
133169
}
134170

135171
#[test]
136172
fn canonical_json_key_order_is_stable() {
137-
// Same keys in different insertion order must produce the same hash.
138173
let a = serde_json::json!({"z": 1, "a": 2, "m": 3});
139174
let b = serde_json::json!({"a": 2, "m": 3, "z": 1});
140175
assert_eq!(canonical_json(&a).unwrap(), canonical_json(&b).unwrap());
141176
}
142-
143-
#[test]
144-
fn genesis_hash_format() {
145-
assert_eq!(GENESIS_HASH.len(), 64);
146-
assert!(GENESIS_HASH.chars().all(|c| c == '0'));
147-
}
148177
}

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

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
11
#![deny(unsafe_code)]
22
#![warn(missing_docs)]
3-
//! Tamper-evident hash-chain audit log. Each entry chains to the previous via
4-
//! SHA-256. Single-writer via Postgres `pg_advisory_lock`. AUTH events (kind 22242)
5-
//! are rejected — they carry bearer tokens.
3+
//! Tamper-evident, **per-community** hash-chain audit log.
4+
//!
5+
//! Each community owns an independent chain: rows are keyed `(community_id, seq)`,
6+
//! `seq` is monotonic *within a community*, and each entry chains to the previous
7+
//! entry *of the same community* via SHA-256. The `community_id` is folded into the
8+
//! hash, so a row lifted out of one community's chain can never verify inside
9+
//! another's — chain identity carries the tenant. This is the audit half of the
10+
//! non-interference floor (`auditHeads[c]` in `MultiTenantRelay.tla`): an audit
11+
//! observation reveals only its own community's head.
12+
//!
13+
//! Writes for a given community are serialized by a **per-community** Postgres
14+
//! advisory lock, so the chain stays consistent across relay processes without one
15+
//! global lock serializing (and timing-coupling) every tenant.
16+
//!
17+
//! The `audit_log` table is owned by the consolidated `0001` migration — this crate
18+
//! is pure chain logic and ships no DDL.
619
720
/// Audit action types recorded in the log.
821
pub mod action;
@@ -12,14 +25,11 @@ pub mod entry;
1225
pub mod error;
1326
/// SHA-256 hash computation for audit entries.
1427
pub mod hash;
15-
/// SQL schema for the audit log table.
16-
pub mod schema;
1728
/// Audit log service — append and verify entries.
1829
pub mod service;
1930

2031
pub use action::AuditAction;
2132
pub use entry::{AuditEntry, NewAuditEntry};
2233
pub use error::AuditError;
2334
pub use hash::{compute_hash, GENESIS_HASH};
24-
pub use schema::AUDIT_SCHEMA_SQL;
2535
pub use service::AuditService;

0 commit comments

Comments
 (0)