Pular para o conteúdo

Zero Trust

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.

passos
4
arquivos
7
testes
0
tecnologias
7

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ência
6/6
POST /fraud/score (Bearer token do STS, aud svc-fraud)1assinatura, iss, aud, exp2política svc-payments para svc-fraud POST /fraud/score?3escopo exigido fraud:score4registra a decisão5200, ou 401/403 com o motivo6svc-paymentssvc-fraudPostgreSQL
6

6 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

  1. 1

    STS emite ES256 de 5 min com sub, aud e scope

  2. 2

    Verificação com a chave públicaOutro aud ou emissor → 401

  3. 3

    Política por origem + destino + método + recurso; sem linha ou escopo → 403

  4. 4

    Toda decisão gravada com o motivo

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 zero-trust-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 zero-trust-db

Saí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.

Requisitos
BunDocker
Sobe junto
PostgreSQL

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

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

Padrões do catálogo que implementa

  • Zero Trust

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • access_policies
  • access_decisions

Variáveis de ambiente

ZERO_TRUST_DATABASE_URL
postgres://postgres:postgres@localhost:5432/zero_trust_db

Trilhapasso 4 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 é o próximo passo depois de Zero Trust?

Próximo projeto, Princípios de DesignSOLID
Esc

↑ ↓ navegarEnter abrir239 resultados