pattern/api/gateway
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
- jose
Entrada única para os serviços internos: autenticação, roteamento e proxy na mesma cadeia; o cliente nunca vê endereço interno.
pattern/api/gateway
Cenário
O app chama contas e pagamentos via gateway com JWT; contas confia no x-subject escrito só pelo gateway, mesmo se o cliente forjar.
Planta
Sequência6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Entrada única para os serviços internos com autenticação, roteamento e proxy na mesma cadeia
Esconde cada passo: lembre antes de tocar para revelar.
Valida o JWT (algoritmo, issuer, audience, expiração)
Primeiro segmento do caminho escolhe o upstream; desconhecido → 404
Remove authorization e x-subject do cliente e escreve o seu
Proxy com timeout
Trade-offs
O que se ganha, o que se paga
Vantagens
Autenticação e log uniformes
Topologia interna oculta
Custos
Ponto único de falha
Um hop a mais
Código
pattern/api/gateway
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: 200 vindo de accounts, com subject app-mobile (o x-subject forjado é descartado) e tokenForwarded false.
Código
src/demo.ts// Demo: the app calls one public entry; the gateway authenticates the JWT, routes by prefix and forwards the subject.
import { Elysia } from "elysia";
import { SignJWT, jwtVerify } from "jose";
// The upstreams only the gateway knows; clients never see these addresses.
const UPSTREAMS: Record<string, string> = { accounts: Bun.env.GATEWAY_ACCOUNTS_URL ?? "http://localhost:3001", payments: Bun.env.GATEWAY_PAYMENTS_URL ?? "http://localhost:3002" };
const UPSTREAM_TIMEOUT_MS = 1_000;
// HS256 key the identity provider signs client tokens with. The default exists only so the demo runs as is.
const secret = new TextEncoder().encode(Bun.env.GATEWAY_JWT_SECRET ?? "demo-only-secret-change-me-0123456789");
// Internal services trust x-subject because only the gateway can reach them; they echo what they received.
const upstreams = Object.entries(UPSTREAMS).map(([service, url]) =>
new Elysia().all("/*", ({ request }) => ({ service, path: new URL(request.url).pathname, subject: request.headers.get("x-subject"), tokenForwarded: request.headers.has("authorization") })).listen(new URL(url).port),
);
async function subjectAuthenticate(authorization: string | null): Promise<string | undefined> {
if (!authorization?.startsWith("Bearer ")) return undefined;
const verified = await jwtVerify(authorization.slice(7), secret, { algorithms: ["HS256"], issuer: "bank-idp", audience: "bank-gateway" }).catch(() => undefined);
return verified ? String(verified.payload.sub) : undefined;
}
// The single public entry: authenticate, route by the first path segment, strip the token, assert the subject.
const gateway = new Elysia().all("/*", async ({ request }) => {
const subject = await subjectAuthenticate(request.headers.get("authorization"));
if (!subject) return Response.json({ error: "unauthenticated" }, { status: 401 });
const url = new URL(request.url);
const base = UPSTREAMS[url.pathname.split("/")[1] ?? ""];
if (!base) return Response.json({ error: "route-not-found" }, { status: 404 });
const headers = new Headers(request.headers);
// A client must never assert the subject itself: only the gateway writes x-subject.
for (const name of ["authorization", "host", "x-subject"]) headers.delete(name);
headers.set("x-subject", subject);
return fetch(`${base}${url.pathname}${url.search}`, { method: request.method, headers, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
}, { parse: "none" });
const token = await new SignJWT({}).setProtectedHeader({ alg: "HS256" }).setSubject("app-mobile").setIssuer("bank-idp").setAudience("bank-gateway").setExpirationTime("5m").sign(secret);
const response = await gateway.handle(new Request("http://gateway/accounts/0001/balance", { headers: { authorization: `Bearer ${token}`, "x-subject": "admin" } }));
console.log(` [APP] GET /accounts/0001/balance → ${response.status} ${await response.text()}`);
await Promise.all(upstreams.map((upstream) => upstream.stop(true)));
Nível
introdutório
0/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 6 de 6
Do monólito aos serviços
Parecidos
Por que se relacionam
Próximo passo
Combina com
Teste rápido
Qual é o próximo passo depois de API Gateway?
Autentica na entrada. Abrir Token Auth
Seu progresso
0/157 estudados
Fica salvo só neste navegador.