pattern/security/zero-trust
- Bun
- ElysiaJS
- PostgreSQL
- TypeScript
- jose
- node-postgres
- Docker
Nenhuma rede é confiável: cada chamada entre serviços prova identidade e é autorizada por política explícita, negada por padrão; toda decisão é registrada.
pattern/security/zero-trust
Cenário
Só pagamentos tem política para POST /fraud/score; token para outro serviço → 401; relatórios com token válido → 403.
Planta
Sequência6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Cada chamada entre serviços prova identidade e é autorizada por política explícita, negada por padrão
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
STS emite ES256 de 5 min com sub, aud e scope
Verificação com a chave públicaOutro aud ou emissor → 401
Política por origem + destino + método + recurso; sem linha ou escopo → 403
Toda decisão gravada com o motivo
Trade-offs
O que se ganha, o que se paga
Vantagens
Serviço comprometido não alcança o que não tem política
Movimento lateral visível
Custos
STS e políticas a operar
Consulta e escrita por chamada
Código
pattern/security/zero-trust
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec zero-trust-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 zero-trust-dbSaída: pagamentos com token para svc-fraud → 200 (score 120); token para svc-ledger → 401; relatórios → 403 no policy; o log registra ALLOW, DENY e DENY com o motivo.
Código
src/demo.ts// Demo: every call to svc-fraud proves who it is (STS token) and needs an explicit policy (deny by default); every decision lands in PostgreSQL.
import { Elysia, t } from "elysia";
import { SignJWT, generateKeyPair, jwtVerify } from "jose";
import pg from "pg";
const pool = new pg.Pool({ connectionString: Bun.env.ZERO_TRUST_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/zero_trust_db" });
const STS_ISSUER = "sts.bank.internal";
const SERVICE = "svc-fraud";
const STS_TOKEN_TTL = "5m";
const FRAUD_HIGH_AMOUNT_CENTS = 1_000_000;
// The internal STS: short-lived ES256 tokens naming the caller (sub), the one service it is for (aud) and its scopes.
const { publicKey, privateKey } = await generateKeyPair("ES256");
const stsIssue = (sub: string, aud: string, scope: string) =>
new SignJWT({ scope }).setProtectedHeader({ alg: "ES256" }).setIssuer(STS_ISSUER).setSubject(sub).setAudience(aud).setIssuedAt().setExpirationTime(STS_TOKEN_TTL).sign(privateKey);
// Identity first (401), then policy and scope (403). Being inside the network grants nothing.
async function authorize(token: string, method: string, resource: string): Promise<{ source?: string; denied?: 401 | 403; reason: string }> {
const verified = await jwtVerify(token, publicKey, { issuer: STS_ISSUER, audience: SERVICE }).catch(() => undefined);
const source = verified?.payload.sub;
if (!source) return { denied: 401, reason: "missing or invalid service token" };
const { rows } = await pool.query<{ required_scope: string }>("SELECT required_scope FROM access_policies WHERE source_service = $1 AND target_service = $2 AND method = $3 AND resource = $4", [source, SERVICE, method, resource]);
if (!rows[0]) return { source, denied: 403, reason: "no policy" };
if (!String(verified.payload.scope).split(" ").includes(rows[0].required_scope)) return { source, denied: 403, reason: `scope ${rows[0].required_scope} missing` };
return { source, reason: "allowed" };
}
const fraud = new Elysia()
.resolve(async ({ headers, request, path, status }) => {
const decision = await authorize(headers.authorization?.replace(/^Bearer /, "") ?? "", request.method, path);
// A denied call between services is evidence of lateral movement: record allowed and denied alike.
await pool.query("INSERT INTO access_decisions (source_service, target_service, method, resource, allowed, reason) VALUES ($1, $2, $3, $4, $5, $6)", [decision.source ?? null, SERVICE, request.method, path, !decision.denied, decision.reason]);
return decision.denied ? status(decision.denied, decision.reason) : { caller: decision.source };
})
.post("/fraud/score", ({ caller, body }) => ({ caller, pixId: body.pixId, score: body.amountCents > FRAUD_HIGH_AMOUNT_CENTS ? 870 : 120 }), { body: t.Object({ pixId: t.String(), amountCents: t.Integer({ minimum: 1 }) }) });
const calls: [string, string][] = [
["svc-payments, token for svc-fraud", await stsIssue("svc-payments", SERVICE, "fraud:score")],
["svc-payments, token for svc-ledger", await stsIssue("svc-payments", "svc-ledger", "fraud:score")],
["svc-reports, no policy", await stsIssue("svc-reports", SERVICE, "fraud:score")],
];
for (const [label, token] of calls) {
const response = await fraud.handle(new Request("http://localhost/fraud/score", { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ pixId: "E2026", amountCents: 150_000 }) }));
console.log(` [CALL] ${label.padEnd(36)} → ${response.status} ${await response.text()}`);
}
const { rows } = await pool.query<{ source: string; allowed: boolean; reason: string }>("SELECT coalesce(source_service, '?') AS source, allowed, reason FROM access_decisions ORDER BY created_at DESC LIMIT 3");
for (const row of rows.toReversed()) console.log(` [LOG] ${row.source.padEnd(13)} ${row.allowed ? "ALLOW" : "DENY "} ${row.reason}`);
await pool.end();
Nível
intermediário
5/13
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 4 de 6
Segurança de API bancária
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Zero Trust?
mTLS e política entre serviços. Abrir Service Mesh
Seu progresso
0/157 estudados
Fica salvo só neste navegador.