pattern/security/audit-log
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- node:crypto
- Docker
Trilha imutável: cada ação sensível grava quem, o quê, quando, de onde, antes e depois, encadeada pelo hash do registro anterior. UPDATE e DELETE são anulados por RULE; adulteração quebra a cadeia.
pattern/security/audit-log
Cenário
Analista altera limite de crédito e fica auditado; um DBA esconde um aumento para R$ 15.000,00 e a verificação aponta o seq.
Planta
Fluxo8 passos — reproduza para seguir o fluxo
Como funciona
4passos
Trilha imutável de cada ação sensível, encadeada pelo hash do registro anterior
Esconde cada passo: lembre antes de tocar para revelar.
Entrada gravada só após o commit da alteração
Append trava audit_chain_head: concorrentes em fila
Hash = SHA-256 do anterior, campos e timestamp
RULE ... DO INSTEAD NOTHING; auditVerify recalcula e aponta a quebra
Trade-offs
O que se ganha, o que se paga
Vantagens
Adulteração localizada pelo seq
RULE resiste a DISABLE TRIGGER
Custos
Appends serializados
Reescrita completa passa: ancore o último hash fora do banco
Código
pattern/security/audit-log
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec audit-log-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f audit-log-dbSaída: {"valid":true} após as duas alterações de limite; depois da reescrita, {"valid":false,"brokenAtSeq":2}.
Código
src/demo.ts// Demo: credit limit changes in a hash-chained audit log; a DBA rewrites an entry and the verification names the seq.
import { createHash } from "node:crypto";
import pg from "pg";
type AuditEntry = { actorId: string; eventType: string; aggregateId: string; ipAddress: string; dataBefore: object; dataAfter: object };
const pool = new pg.Pool({ connectionString: Bun.env.AUDIT_LOG_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/audit_db" });
// SHA-256 over the previous hash, every field and the timestamp: without the timestamp two identical actions would collide.
const auditHash = (previousHash: string, entry: AuditEntry, createdAtIso: string) =>
createHash("sha256").update([previousHash, entry.actorId, entry.eventType, entry.aggregateId, entry.ipAddress, JSON.stringify(entry.dataBefore), JSON.stringify(entry.dataAfter), createdAtIso].join("|")).digest("hex");
// Locking the single chain-head row serializes appends, even on an empty log.
async function auditAppend(entry: AuditEntry): Promise<void> {
const client = await pool.connect();
try {
await client.query("BEGIN");
const { rows: [head] } = await client.query<{ last_hash: string }>("SELECT last_hash FROM audit_chain_head WHERE id = 1 FOR UPDATE");
if (!head) throw new Error("audit chain head missing");
const createdAt = new Date().toISOString();
const hash = auditHash(head.last_hash, entry, createdAt);
await client.query("INSERT INTO audit_log (actor_id, event_type, aggregate_id, ip_address, data_before, data_after, previous_hash, hash, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", [entry.actorId, entry.eventType, entry.aggregateId, entry.ipAddress, entry.dataBefore, entry.dataAfter, head.last_hash, hash, createdAt]);
await client.query("UPDATE audit_chain_head SET last_hash = $1 WHERE id = 1", [hash]);
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
// Recompute every hash in seq order and name the first entry whose hash or link no longer matches.
async function auditVerify(): Promise<{ valid: boolean; brokenAtSeq?: number }> {
const { rows } = await pool.query<AuditEntry & { seq: string; previousHash: string; hash: string; createdAt: Date }>(`SELECT seq, actor_id AS "actorId", event_type AS "eventType", aggregate_id AS "aggregateId", ip_address AS "ipAddress", data_before AS "dataBefore", data_after AS "dataAfter", previous_hash AS "previousHash", hash, created_at AS "createdAt" FROM audit_log ORDER BY seq`);
let expectedPrevious = "GENESIS";
for (const row of rows) {
if (row.previousHash !== expectedPrevious || auditHash(row.previousHash, row, row.createdAt.toISOString()) !== row.hash) return { valid: false, brokenAtSeq: Number(row.seq) };
expectedPrevious = row.hash;
}
return { valid: true };
}
// The limit change commits first; the entry is appended after, so a rolled-back change leaves no false trail.
async function creditLimitChange(customerId: string, limitCents: number, actorId: string): Promise<void> {
const { rows: [old] } = await pool.query<{ limit_cents: string }>("UPDATE credit_limits c SET limit_cents = $2 FROM (SELECT limit_cents FROM credit_limits WHERE customer_id = $1 FOR UPDATE) old WHERE c.customer_id = $1 RETURNING old.limit_cents", [customerId, limitCents]);
if (!old) throw new Error(`credit limit of ${customerId} not found`);
const beforeCents = Number(old.limit_cents);
await auditAppend({ actorId, eventType: limitCents > beforeCents ? "credit_limit.increased" : "credit_limit.decreased", aggregateId: `credit_limit:${customerId}`, ipAddress: "10.0.4.21", dataBefore: { limitCents: beforeCents }, dataAfter: { limitCents } });
}
await creditLimitChange("CLI-1001", 800_000, "analyst:maria.souza");
await creditLimitChange("CLI-1001", 1_500_000, "analyst:joao.lima");
console.log(` [VERIFY] ${JSON.stringify(await auditVerify())}`);
// The RULE turns UPDATE into nothing; a DBA who disables it to hide the 1,500,000 limit still breaks the chain.
await pool.query("ALTER TABLE audit_log DISABLE RULE audit_log_no_update");
await pool.query(`UPDATE audit_log SET data_after = '{"limitCents": 800000}' WHERE seq = (SELECT max(seq) FROM audit_log)`);
await pool.query("ALTER TABLE audit_log ENABLE RULE audit_log_no_update");
console.log(` [VERIFY] after the rewrite: ${JSON.stringify(await auditVerify())}`);
await pool.end();
Nível
intermediário
6/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 6 de 6
Segurança de API bancária
Parecidos
Por que se relacionam
Combina com
Alternativa a
Teste rápido
Qual destes combina com Audit Log?
Histórico de cada versão. Abrir Temporal Tables
Seu progresso
0/157 estudados
Fica salvo só neste navegador.