Pular para o conteúdo

Audit Log

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.

passos
4
arquivos
7
testes
0
tecnologias
6

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

Fluxo
8/8
Alteração de limitecommitauditAppendTrava audit_chain_headFOR UPDATEhash = SHA-256 dehash anterior,campos, timestamp#1 hash A#2 anterior A, hash BauditVerifyrecalcula tudovalidbrokenAtSeqconferediverge
8

8 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.

  1. 1

    Entrada gravada só após o commit da alteração

  2. 2

    Append trava audit_chain_head: concorrentes em fila

  3. 3

    Hash = SHA-256 do anterior, campos e timestamp

  4. 4

    RULE ... DO INSTEAD NOTHING; auditVerify recalcula e aponta a quebra

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec audit-log-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f audit-log-db

Saída: {"valid":true} após as duas alterações de limite; depois da reescrita, {"valid":false,"brokenAtSeq":2}.

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

Linhas de TypeScript
53
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • Crédito/Empréstimo
  • Limite

Padrões do catálogo que implementa

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • credit_limits
  • audit_log
  • audit_chain_head

Variáveis de ambiente

AUDIT_LOG_DATABASE_URL
postgres://postgres:postgres@localhost:5432/audit_db

Trilhapasso 6 de 6

Segurança de API bancária

  1. 1API Key Management
  2. 2Token Auth
  3. 3Federated Identity
  4. 4Zero Trust
  5. 5Gerenciamento de Segredos
  6. 6Audit Log

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Audit Log?

Próximo projeto, Segurança & AuditoriaTransação Bancária com Auditoria
Esc

↑ ↓ navegarEnter abrir239 resultados