Órbita
- Código
- Arquitetura
- Dados
- Integração
- Resiliência
Quando usar
Ponto único para roteamento, autenticação e rate limit
Órbita
Quando usar
Ponto único para roteamento, autenticação e rate limit
Problema
Clientes chamando dezenas de serviços diretamente
Quando usar
Ponto único para roteamento, autenticação e rate limit
api-gateway
Entrada única que roteia, agrega e protege as chamadas aos serviços internos.
Planta de sequência
Reproduzir passo a passoComo funciona
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
README.mdpattern/api/gateway
thiagoeti/pattern/api-gatewayEntrada única para os serviços internos: autenticação, roteamento e proxy na mesma cadeia; o cliente nunca vê endereço interno.
O app chama contas e pagamentos via gateway com JWT; contas confia no x-subject escrito só pelo gateway, mesmo se o cliente forjar.
authorization e x-subject do cliente e escreve o seusrc/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)));
bun install
bun run demo
Saída: 200 vindo de accounts, com subject app-mobile (o x-subject forjado é descartado) e tokenForwarded false.
| Vantagem | Desvantagem |
|---|---|
| Autenticação e log uniformes | Ponto único de falha |
| Topologia interna oculta | Um hop a mais |