use std::fmt;
use std::sync::Arc;
use id_effect::{Effect, HCons, HList, HNil, Layer, Selector, fail, hlist, need, succeed, suspend};
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::client::{SqlClient, SqlClientService};
use crate::error::SqlError;
use crate::row::SqlRow;
use crate::transaction::{SqlTransaction, SqlTransactionService};
use crate::value::SqlValue;
#[cfg(test)]
mod tests;
pub const DEFAULT_TABLE: &str = "audit_log";
pub const GENESIS_HASH: [u8; 32] = [0; 32];
pub const MIGRATIONS: [(&str, &str); 2] = [
(
"0001_audit_log.up.sql",
include_str!("../migrations/audit/0001_audit_log.up.sql"),
),
(
"0001_audit_log.down.sql",
include_str!("../migrations/audit/0001_audit_log.down.sql"),
),
];
pub const MIGRATIONS_TABLE: &str = "_id_effect_audit_migrations";
#[cfg(feature = "migrate")]
pub fn migrator() -> crate::migrate::Migrator {
crate::migrate::Migrator::from_files(MIGRATIONS)
.expect("the bundled audit migrations are well-formed")
.with_table(MIGRATIONS_TABLE)
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct AuditContext {
actor: String,
tenant: Option<String>,
}
impl AuditContext {
pub fn new(actor: impl Into<String>) -> Self {
Self {
actor: actor.into(),
tenant: None,
}
}
pub fn for_tenant(actor: impl Into<String>, tenant: impl Into<String>) -> Self {
Self::new(actor).with_tenant(tenant)
}
#[must_use]
pub fn with_tenant(mut self, tenant: impl Into<String>) -> Self {
self.tenant = Some(tenant.into());
self
}
pub fn actor(&self) -> &str {
&self.actor
}
pub fn tenant(&self) -> Option<&str> {
self.tenant.as_deref()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct AuditEntry {
action: String,
entity: String,
before: Option<Value>,
after: Option<Value>,
}
impl AuditEntry {
pub fn new(action: impl Into<String>, entity: impl Into<String>) -> Self {
Self {
action: action.into(),
entity: entity.into(),
before: None,
after: None,
}
}
#[must_use]
pub fn with_before(mut self, before: Value) -> Self {
self.before = Some(before);
self
}
#[must_use]
pub fn with_after(mut self, after: Value) -> Self {
self.after = Some(after);
self
}
pub fn action(&self) -> &str {
&self.action
}
pub fn entity(&self) -> &str {
&self.entity
}
pub fn before(&self) -> Option<&Value> {
self.before.as_ref()
}
pub fn after(&self) -> Option<&Value> {
self.after.as_ref()
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct AuditRecord {
pub id: i64,
pub seq: i64,
pub actor: String,
pub tenant: Option<String>,
pub action: String,
pub entity: String,
pub before: Option<Value>,
pub after: Option<Value>,
pub at: jiff::Timestamp,
pub prev_hash: Vec<u8>,
pub hash: Vec<u8>,
}
impl AuditRecord {
pub fn chain(&self) -> &str {
chain_of(self.tenant.as_deref())
}
pub fn canonical(&self) -> String {
let at = self.at.as_microsecond();
let record = serde_json::json!({
"action": self.action,
"actor": self.actor,
"after": self.after,
"at": at,
"before": self.before,
"entity": self.entity,
"seq": self.seq,
"tenant": self.tenant,
});
let mut out = String::new();
write_canonical(&record, &mut out);
out
}
pub fn computed_hash(&self) -> Vec<u8> {
Sha256::new()
.chain_update(&self.prev_hash)
.chain_update(self.canonical().as_bytes())
.finalize()
.to_vec()
}
pub fn from_row(row: &SqlRow) -> Result<Self, SqlError> {
Ok(Self {
id: row.get("id")?,
seq: row.get("seq")?,
actor: row.get("actor")?,
tenant: row.get("tenant")?,
action: row.get("action")?,
entity: row.get("entity")?,
before: row.get("before")?,
after: row.get("after")?,
at: row.get("at")?,
prev_hash: row.get("prev_hash")?,
hash: row.get("hash")?,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BreakKind {
Sequence,
PrevHash,
Hash,
Head,
}
impl fmt::Display for BreakKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
BreakKind::Sequence => "sequence gap",
BreakKind::PrevHash => "prev_hash mismatch",
BreakKind::Hash => "hash mismatch",
BreakKind::Head => "chain does not reach its head",
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct BrokenLink {
pub id: Option<i64>,
pub seq: i64,
pub kind: BreakKind,
pub expected: String,
pub actual: String,
}
impl fmt::Display for BrokenLink {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.id {
Some(id) => write!(f, "record {id} (seq {})", self.seq)?,
None => write!(f, "head (seq {})", self.seq)?,
}
write!(
f,
": {}: expected {}, found {}",
self.kind, self.expected, self.actual
)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChainReport {
pub tenant: Option<String>,
pub records: u64,
pub head: Option<String>,
pub first_broken: Option<BrokenLink>,
}
impl ChainReport {
pub fn is_intact(&self) -> bool {
self.first_broken.is_none()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct AuditLog {
table: Arc<str>,
}
pub type AuditLogEnv = HCons<AuditLog, HNil>;
impl Default for AuditLog {
fn default() -> Self {
Self::new()
}
}
impl AuditLog {
pub fn new() -> Self {
Self {
table: Arc::from(DEFAULT_TABLE),
}
}
#[must_use]
pub fn with_table(mut self, table: impl Into<String>) -> Self {
let table = table.into();
assert!(valid_table(&table), "invalid audit table name `{table}`");
self.table = table.into();
self
}
pub fn table(&self) -> &str {
&self.table
}
pub fn layer<E: Send + 'static>(self) -> Layer<AuditLogEnv, E> {
Layer::succeed(hlist![self])
}
pub fn append(
&self,
tx: &Arc<dyn SqlTransaction>,
ctx: &AuditContext,
entry: AuditEntry,
) -> Effect<AuditRecord, SqlError> {
let (tx, ctx) = (Arc::clone(tx), ctx.clone());
let (lock_sql, insert_sql, move_sql) = (self.lock_sql(), self.insert_sql(), self.move_sql());
suspend(move || {
let chain = chain_of(ctx.tenant()).to_owned();
let lock = tx.query(&lock_sql, &[chain.clone().into(), GENESIS_HASH[..].into()]);
lock.flat_map(move |rows| {
let (seq, prev_hash, at) = match locked_head(&rows) {
Ok(head) => head,
Err(e) => return fail(e),
};
let mut record = AuditRecord {
id: 0,
seq: seq + 1,
actor: ctx.actor,
tenant: ctx.tenant,
action: entry.action,
entity: entry.entity,
before: entry.before,
after: entry.after,
at,
prev_hash,
hash: Vec::new(),
};
record.hash = record.computed_hash();
let insert = tx.query(&insert_sql, &insert_params(&chain, &record));
insert.flat_map(move |rows| {
match rows.first().map(|r| r.get::<i64>("id")) {
Some(Ok(id)) => record.id = id,
Some(Err(e)) => return fail(e),
None => return fail(SqlError::RowNotFound),
}
let params = [chain.into(), record.seq.into(), record.hash.clone().into()];
tx.execute(&move_sql, ¶ms).map(move |_| record)
})
})
})
}
pub fn verify_chain_on(
&self,
client: Arc<dyn SqlClient>,
tenant: Option<&str>,
) -> Effect<ChainReport, SqlError> {
let tenant = tenant.map(str::to_owned);
let (head_sql, rows_sql) = (self.head_sql(), self.rows_sql());
suspend(move || {
let chain = chain_of(tenant.as_deref()).to_owned();
let head = client.query(&head_sql, &[chain.clone().into()]);
head.flat_map(move |rows| {
let head = match rows.first().map(stored_head).transpose() {
Ok(head) => head,
Err(e) => return fail(e),
};
let limit = head.as_ref().map(|(seq, _)| *seq);
let mut verifier = Verifier::default();
let mut ended = false;
client
.query_stream(&rows_sql, &[chain.into()])
.map_serial(|row| AuditRecord::from_row(&row))
.take_while(move |r| match (r, limit) {
(Ok(r), Some(last)) => r.seq <= last,
_ => true,
})
.map_serial(move |r| r.map(|record| verifier.check(&record)))
.take_while(move |checked| {
let take = !ended;
ended = !matches!(checked, Ok(Checked { broken: None, .. }));
take
})
.run_fold_effect(Fold::default(), |mut acc, checked| match checked {
Err(e) => fail(e),
Ok(Checked {
broken: Some(b), ..
}) => {
acc.broken = Some(b);
succeed(acc)
}
Ok(Checked { seq, hash, .. }) => {
acc.records += 1;
acc.last = Some((seq, hash));
succeed(acc)
}
})
.map(move |acc| acc.report(tenant, head))
})
})
}
fn lock_sql(&self) -> String {
format!(
"INSERT INTO {head} AS h (chain, seq, hash) VALUES ($1, 0, $2) \
ON CONFLICT (chain) DO UPDATE SET seq = h.seq RETURNING h.seq, h.hash, now() AS at",
head = self.head_table()
)
}
fn insert_sql(&self) -> String {
format!(
"INSERT INTO {} (chain, seq, actor, tenant, action, entity, before, after, at, prev_hash, \
hash) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id",
self.table
)
}
fn move_sql(&self) -> String {
format!(
"UPDATE {} SET seq = $2, hash = $3 WHERE chain = $1",
self.head_table()
)
}
fn head_sql(&self) -> String {
format!(
"SELECT seq, hash FROM {} WHERE chain = $1",
self.head_table()
)
}
fn rows_sql(&self) -> String {
format!(
"SELECT id, seq, actor, tenant, action, entity, before, after, at, prev_hash, hash \
FROM {} WHERE chain = $1 ORDER BY seq",
self.table
)
}
fn head_table(&self) -> String {
format!("{}_head", self.table)
}
}
pub fn append<R, I>(
tx: &Arc<dyn SqlTransaction>,
ctx: &AuditContext,
entry: AuditEntry,
) -> Effect<AuditRecord, SqlError, R>
where
R: Selector<AuditLog, I> + HList,
{
let (tx, ctx) = (Arc::clone(tx), ctx.clone());
need::<AuditLog>().flat_map(move |log| log.append(&tx, &ctx, entry).narrow())
}
pub fn record<R, I, J, K>(entry: AuditEntry) -> Effect<AuditRecord, SqlError, R>
where
R: Selector<AuditLog, I> + Selector<AuditContext, J> + Selector<SqlTransactionService, K> + HList,
{
need::<SqlTransactionService>().flat_map::<_, _, R, K>(move |tx| {
need::<AuditContext>().flat_map::<_, _, R, J>(move |ctx| append::<R, I>(&tx.0, &ctx, entry))
})
}
pub fn verify_chain<R, I, J>(tenant: Option<&str>) -> Effect<ChainReport, SqlError, R>
where
R: Selector<AuditLog, I> + Selector<SqlClientService, J> + HList,
{
let tenant = tenant.map(str::to_owned);
need::<AuditLog>().flat_map::<_, _, R, I>(move |log| {
need::<SqlClientService>().flat_map::<_, _, R, J>(move |client| {
log
.verify_chain_on(Arc::clone(&client.0), tenant.as_deref())
.narrow()
})
})
}
fn chain_of(tenant: Option<&str>) -> &str {
tenant.unwrap_or("")
}
fn locked_head(rows: &[SqlRow]) -> Result<(i64, Vec<u8>, jiff::Timestamp), SqlError> {
let row = rows.first().ok_or(SqlError::RowNotFound)?;
Ok((row.get("seq")?, row.get("hash")?, row.get("at")?))
}
fn stored_head(row: &SqlRow) -> Result<(i64, Vec<u8>), SqlError> {
Ok((row.get("seq")?, row.get("hash")?))
}
fn insert_params(chain: &str, r: &AuditRecord) -> Vec<SqlValue> {
vec![
chain.into(),
r.seq.into(),
r.actor.as_str().into(),
r.tenant.clone().into(),
r.action.as_str().into(),
r.entity.as_str().into(),
r.before.clone().into(),
r.after.clone().into(),
r.at.into(),
r.prev_hash.clone().into(),
r.hash.clone().into(),
]
}
struct Checked {
seq: i64,
hash: Vec<u8>,
broken: Option<BrokenLink>,
}
struct Verifier {
seq: i64,
hash: Vec<u8>,
}
impl Default for Verifier {
fn default() -> Self {
Self {
seq: 0,
hash: GENESIS_HASH.to_vec(),
}
}
}
impl Verifier {
fn check(&mut self, r: &AuditRecord) -> Checked {
let link = |kind, expected: String, actual: String| BrokenLink {
id: Some(r.id),
seq: r.seq,
kind,
expected,
actual,
};
let broken = if r.seq != self.seq + 1 {
Some(link(
BreakKind::Sequence,
(self.seq + 1).to_string(),
r.seq.to_string(),
))
} else if r.prev_hash != self.hash {
Some(link(
BreakKind::PrevHash,
hex(&self.hash),
hex(&r.prev_hash),
))
} else {
let computed = r.computed_hash();
(computed != r.hash).then(|| link(BreakKind::Hash, hex(&computed), hex(&r.hash)))
};
self.seq = r.seq;
self.hash.clone_from(&r.hash);
Checked {
seq: r.seq,
hash: r.hash.clone(),
broken,
}
}
}
#[derive(Default)]
struct Fold {
records: u64,
last: Option<(i64, Vec<u8>)>,
broken: Option<BrokenLink>,
}
impl Fold {
fn report(self, tenant: Option<String>, head: Option<(i64, Vec<u8>)>) -> ChainReport {
let broken = self.broken.or_else(|| {
let (head_seq, head_hash) = head?;
let (seq, hash) = self.last.clone().unwrap_or((0, GENESIS_HASH.to_vec()));
(seq != head_seq || hash != head_hash).then(|| BrokenLink {
id: None,
seq: head_seq,
kind: BreakKind::Head,
expected: format!("{head_seq}:{}", hex(&head_hash)),
actual: format!("{seq}:{}", hex(&hash)),
})
});
ChainReport {
tenant,
records: self.records,
head: self.last.map(|(_, hash)| hex(&hash)),
first_broken: broken,
}
}
}
fn write_canonical(v: &Value, out: &mut String) {
match v {
Value::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
write_canonical(item, out);
}
out.push(']');
}
Value::Object(map) => {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_unstable_by(|a, b| a.0.cmp(b.0));
out.push('{');
for (i, (key, value)) in entries.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&Value::from(key.as_str()).to_string());
out.push(':');
write_canonical(value, out);
}
out.push('}');
}
Value::Number(n) if !n.is_i64() && !n.is_u64() && n.as_f64() == Some(0.0) => {
out.push_str("0.0");
}
scalar => out.push_str(&scalar.to_string()),
}
}
fn hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
bytes.iter().fold(String::new(), |mut s, b| {
let _ = write!(s, "{b:02x}");
s
})
}
fn valid_table(name: &str) -> bool {
let ident = |p: &str| {
let mut chars = p.chars();
chars
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
&& p.len() <= 63
};
let mut parts = name.rsplit('.');
let last = parts.next().unwrap_or_default();
let schema = parts.next();
ident(last) && last.len() <= 58 && schema.is_none_or(ident) && parts.next().is_none()
}