Pular para o conteúdo

Gatekeeper

Processo dedicado entre a internet e o core: única porta pública, autentica, limita, valida e limpa o payload e repassa com segredo compartilhado. O core recusa qualquer chamada sem o segredo.

passos
4
arquivos
7
testes
0
tecnologias
8

Cenário

Transferência com campo injetado (isAdmin) é limpa e repassada; chamada direta ao core recebe 403.

Planta

Fluxo
4/4
Internetgatekeepercanal, tamanho, schemacore-bank127.0.0.1PostgreSQLx-gatekeeper-secretsem o segredo: 403
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

Processo dedicado entre a internet e o core que autentica, limita, valida e repassa com segredo compartilhado

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

timingSafeEqual+1
  1. 1

    onRequest confere o token do canal em tempo constante; maxRequestBodySize limita o corpo

  2. 2

    Schema valida e remove campos não declarados

  3. 3

    Repasse com x-gatekeeper-secret e timeout; erro do core → 502 genérico

  4. 4

    Core em 127.0.0.1, timingSafeEqual e schema validado de novo

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Core nunca exposto

  • Rede e segredo se cobrem

Custos

  • Um salto a mais

  • Ponto crítico; segredo exige rotação

Código

pattern/security/gatekeeper

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 gatekeeper-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 gatekeeper-db

Saída: pelo gatekeeper, 201 com a transferência gravada sem o isAdmin; direto no core, 403 calls must come through the gatekeeper.

Requisitos
BunDocker
Sobe junto
PostgreSQL

Código

src/demo.ts

// Demo: the gatekeeper is the only entry — it checks the channel, validates and strips the transfer, and forwards it to
// the core with a shared secret; the core refuses anything that did not come through it.
import { timingSafeEqual } from "node:crypto";
import { Elysia, t } from "elysia";
import pg from "pg";

const pool = new pg.Pool({ connectionString: Bun.env.GATEKEEPER_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/core_bank_db" });
const SHARED_SECRET = Bun.env.GATEKEEPER_SHARED_SECRET ?? "change-me-internal-only-secret-32b";
const CHANNEL_TOKEN = Bun.env.GATEKEEPER_CHANNEL_TOKEN ?? "mobile-app-token-change-me-2026";
const CORE_URL = "http://127.0.0.1:8705";
const CORE_TIMEOUT_MS = 3_000;
const BODY_MAX_BYTES = 2_048;

// Constant time; the length is checked first because timingSafeEqual throws on a size mismatch.
const secretMatches = (received: string | null | undefined, expected: string) => Buffer.from(received ?? "").length === Buffer.from(expected).length && timingSafeEqual(Buffer.from(received ?? ""), Buffer.from(expected));

// Undeclared fields are dropped by Elysia before the handler sees the body.
const schemaTransfer = t.Object({
  fromAccount: t.String({ pattern: "^[0-9]{4}-[0-9]{4,10}$" }),
  toAccount: t.String({ pattern: "^[0-9]{4}-[0-9]{4,10}$" }),
  amountCents: t.Integer({ minimum: 1, maximum: 100_000_000 }),
});

// The core: the only writer of the database, bound to 127.0.0.1, and still refusing calls without the secret.
const core = new Elysia()
  .onBeforeHandle(({ headers, status }) => (secretMatches(headers["x-gatekeeper-secret"], SHARED_SECRET) ? undefined : status(403, "calls must come through the gatekeeper")))
  .post("/transfers", async ({ body, status }) => {
    const { rows: [transfer] } = await pool.query<{ id: string }>("INSERT INTO transfers (from_account, to_account, amount_cents) VALUES ($1, $2, $3) RETURNING id", [body.fromAccount, body.toAccount, body.amountCents]);
    return status(201, { id: transfer?.id, status: "completed", stored: body });
  }, { body: schemaTransfer })
  .listen({ hostname: "127.0.0.1", port: new URL(CORE_URL).port });

// The gatekeeper: unknown channel and oversized body are refused before any parse; the schema validates and strips.
const gatekeeper = new Elysia({ serve: { maxRequestBodySize: BODY_MAX_BYTES } })
  .onRequest(({ request, status }) => (secretMatches(request.headers.get("x-channel-token"), CHANNEL_TOKEN) ? undefined : status(401, "unknown channel")))
  .post("/transfers", async ({ body }) => {
    const response = await fetch(`${CORE_URL}/transfers`, { method: "POST", headers: { "content-type": "application/json", "x-gatekeeper-secret": SHARED_SECRET }, body: JSON.stringify(body), signal: AbortSignal.timeout(CORE_TIMEOUT_MS) });
    // The core's own errors are not relayed as they are: the internet gets a generic 502.
    return response.status >= 500 ? new Response("core unavailable", { status: 502 }) : new Response(await response.text(), { status: response.status });
  }, { body: schemaTransfer });

const injected = { fromAccount: "0001-11112222", toAccount: "0002-33334444", amountCents: 250_000, isAdmin: true };
const viaGatekeeper = await gatekeeper.handle(new Request("http://bank/transfers", { method: "POST", headers: { "content-type": "application/json", "x-channel-token": CHANNEL_TOKEN }, body: JSON.stringify(injected) }));
console.log(`  [GATEKEEPER] transfer with injected isAdmin → ${viaGatekeeper.status} ${await viaGatekeeper.text()}`);
const direct = await fetch(`${CORE_URL}/transfers`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(injected) });
console.log(`  [DIRECT]     straight to the core → ${direct.status} ${await direct.text()}`);
await core.stop(true);
await pool.end();

Nível

intermediário

4/13

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

Padrões do catálogo que implementa

  • Gatekeeper

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

Banco

sql/01_schema.sql

  • transfers

Variáveis de ambiente

GATEKEEPER_DATABASE_URL
postgres://postgres:postgres@localhost:5432/core_bank_db
GATEKEEPER_SHARED_SECRET
change-me-internal-only-secret-32b
Secret between gatekeeper and core only.
GATEKEEPER_CHANNEL_TOKEN
mobile-app-token-change-me-2026
Token of the bank's own mobile app, the only channel the gatekeeper accepts.

Por que se relacionam

Teste rápido

Qual destes combina com Gatekeeper?

Próximo projeto, Segurança & AuditoriaGerenciamento de Segredos
Esc

↑ ↓ navegarEnter abrir239 resultados