Pular para o conteúdo

Gerenciamento de Segredos

Credenciais centralizadas no HashiCorp Vault: cada serviço se autentica com a própria identidade, recebe token curto e lê só o que sua política permite.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

Pagamentos lê a credencial do PIX e recebe 403 na do data warehouse de relatórios.

Planta

Sequência
9/9
política payments: read secret/data/payments/*1AppRole payments (token_ttl 30s)2grava payments/pix-db3POST auth/approle/login (role_id, secret_id)4token com lease de 30s5GET secret/data/payments/pix-db6credencial7GET secret/data/reports/warehouse-db84039Admin (setup)VaultServiço de pagamentos
9

9 passos — reproduza para seguir o fluxo

Como funciona

4passos

Credenciais centralizadas no HashiCorp Vault, com token curto e política por serviço

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    AppRole, política por serviço (só read no próprio caminho) e token_ttl

  2. 2

    Login com role_id e secret_id devolve token com lease

  3. 3

    Fora da política403

  4. 4

    A aplicação loga só caminho e formato mascarado

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Rotação e auditoria num lugar

  • Política e token curto limitam vazamento

Custos

  • Vault fora = serviços não sobem

  • secret_id ainda precisa chegar com segurança

Código

pattern/security/secrets-management

6 arquivos

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec -e VAULT_ADDR=http://127.0.0.1:8200 secrets-management-vault vault status >/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 secrets-management-vault

Saída: login com lease de 30s; payments/pix-db lida com valores mascarados (svc…); reports/warehouse-db → 403.

Requisitos
BunDocker

Código

src/demo.ts

// Demo: the payments service logs in to Vault with its AppRole, reads its PIX database credential and is refused the reports one.
import { randomUUID } from "node:crypto";

const VAULT_URL = Bun.env.SECRETS_MANAGEMENT_VAULT_URL ?? "http://localhost:8200";
// The admin token only sets things up; services never use it.
const ADMIN_TOKEN = Bun.env.SECRETS_MANAGEMENT_VAULT_ADMIN_TOKEN ?? "dev-root-token";
const PAYMENTS_TOKEN_TTL = "30s";

async function vaultCall<T>(token: string, method: string, path: string, body?: unknown): Promise<T> {
  const response = await fetch(`${VAULT_URL}/v1/${path}`, { method, headers: { "x-vault-token": token, "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
  // Vault's error names the path, never the secret value; the value itself is never logged here.
  if (!response.ok) throw new Error(`${method} ${path}: ${response.status}`);
  return (response.status === 204 ? undefined : await response.json()) as T;
}

// Setup with the admin token: AppRole auth, a policy that reads only payments/*, a role with a short-lived token, the secrets.
await vaultCall(ADMIN_TOKEN, "POST", "sys/auth/approle", { type: "approle" }).catch(() => undefined);
await vaultCall(ADMIN_TOKEN, "PUT", "sys/policies/acl/payments", { policy: `path "secret/data/payments/*" { capabilities = ["read"] }` });
await vaultCall(ADMIN_TOKEN, "POST", "auth/approle/role/payments", { token_policies: ["payments"], token_ttl: PAYMENTS_TOKEN_TTL, token_max_ttl: PAYMENTS_TOKEN_TTL });
await vaultCall(ADMIN_TOKEN, "POST", "secret/data/payments/pix-db", { data: { username: "svc_payments", password: randomUUID() } });
await vaultCall(ADMIN_TOKEN, "POST", "secret/data/reports/warehouse-db", { data: { username: "svc_reports", password: randomUUID() } });
const { data: role } = await vaultCall<{ data: { role_id: string } }>(ADMIN_TOKEN, "GET", "auth/approle/role/payments/role-id");
const { data: secret } = await vaultCall<{ data: { secret_id: string } }>(ADMIN_TOKEN, "POST", "auth/approle/role/payments/secret-id", {});

// The service authenticates with its own identity and gets a token whose lease bounds the exposure window.
const { auth } = await vaultCall<{ auth: { client_token: string; lease_duration: number } }>("", "POST", "auth/approle/login", { role_id: role.role_id, secret_id: secret.secret_id });
console.log(`  [PAYMENTS] logged in, token lease ${auth.lease_duration}s`);
for (const path of ["payments/pix-db", "reports/warehouse-db"]) {
  const outcome = await vaultCall<{ data: { data: Record<string, string> } }>(auth.client_token, "GET", `secret/data/${path}`).then(
    // Only the shape is printed; the value is masked to prove it was read without ever logging it.
    ({ data }) => `read ${JSON.stringify(Object.fromEntries(Object.entries(data.data).map(([key, value]) => [key, `${value.slice(0, 3)}…`])))}`,
    (error: Error) => error.message,
  );
  console.log(`  [PAYMENTS] ${path.padEnd(22)} → ${outcome}`);
}

Nível

introdutório

2/13

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

Domínio financeiro

  • PIX

Padrões do catálogo que implementa

  • Gerenciamento de Segredos

Infraestrutura

  • HashiCorp Vaultcofre de segredos

    hashicorp/vault:1.17:8200

Variáveis de ambiente

SECRETS_MANAGEMENT_VAULT_URL
http://localhost:8200
Vault in dev mode. The admin token only sets things up; services never use it.
SECRETS_MANAGEMENT_VAULT_ADMIN_TOKEN
dev-root-token

Trilhapasso 5 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

Por que se relacionam

Teste rápido

Qual destes combina com Gerenciamento de Segredos?

Próximo projeto, Segurança & AuditoriaToken Auth
Esc

↑ ↓ navegarEnter abrir239 resultados