Pular para o conteúdo

Valet Key

O serviço com a credencial real assina uma URL temporária por objeto, método e prazo; o cliente fala direto com o storage e a credencial nunca sai do servidor.

passos
4
arquivos
6
testes
0
tecnologias
6

Cenário

Upload do documento de KYC direto ao SeaweedFS; a mesma URL em outro objeto recebe 403.

Planta

Sequência
8/8
POST /accounts/0001-7700880/kyc/upload-url1conta do cliente? assina PUT por 120 s2URL pré-assinada3PUT do PDF direto na URL42005POST /accounts/0001-7700880/kyc/confirm6stat: tipo e tamanho7aceito8App do clienteAPI (valet)SeaweedFS (S3)
8

8 passos — reproduza para seguir o fluxo

Como funciona

4passos

O serviço com a credencial real assina uma URL temporária por objeto, método e prazo

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Conta da rota ≠ cliente autenticado403 sem assinar

  2. 2

    presign de PUT em kyc/<conta>/identity.pdf, TTL 120 s

  3. 3

    O SeaweedFS valida assinatura, método, objeto e expiração

  4. 4

    Tamanho não travadostat após o upload

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Bytes não passam pela API

  • Escopo aplicado pelo storage

Custos

  • URL não revogável antes do TTL

  • Upload precisa ser conferido

Código

pattern/security/valet-key

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 valet-key-storage wget -qO /dev/null http://localhost:8333/healthz 2>/dev/null && docker exec valet-key-storage wget -qO /dev/null http://localhost:8888/buckets/customer-documents/ 2>/dev/null; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f valet-key-storage

Saída: URL de PUT por 120s; upload direto ao SeaweedFS → 200; confirmação accepted: true (PDF de 48 bytes); a mesma URL em outro objeto → 403; chave para conta alheia → 403.

Requisitos
BunDocker

Código

src/demo.ts

// Demo: the API signs a short-lived PUT URL for one KYC object; the customer uploads straight to the storage, and the storage refuses the URL for any other object.
import { S3Client } from "bun";
import { Elysia } from "elysia";

// The real storage credentials stay in this service; the client only ever sees a signed URL.
const storage = new S3Client({
  endpoint: Bun.env.VALET_KEY_S3_ENDPOINT ?? "http://localhost:9000",
  bucket: Bun.env.VALET_KEY_S3_BUCKET ?? "customer-documents",
  region: "us-east-1",
  accessKeyId: Bun.env.VALET_KEY_S3_ACCESS_KEY_ID ?? "valet-issuer",
  secretAccessKey: Bun.env.VALET_KEY_S3_SECRET_ACCESS_KEY ?? "valet-issuer-secret",
});
const KYC_UPLOAD_TTL_SECONDS = 120;
const KYC_SIZE_MAX_BYTES = 5 * 1024 * 1024;
const kycKey = (accountId: string) => `kyc/${accountId}/identity.pdf`;

const api = new Elysia()
  // The account comes from authentication (here the x-account-id header): no key for someone else's account.
  .post("/accounts/:accountId/kyc/upload-url", ({ params, headers, status }) => {
    if (headers["x-account-id"] !== params.accountId) return status(403, "not your account");
    // presign is local HMAC math: no call to the storage, and the URL is never logged — it is a credential.
    return { url: storage.presign(kycKey(params.accountId), { method: "PUT", expiresIn: KYC_UPLOAD_TTL_SECONDS, type: "application/pdf" }), expiresInSeconds: KYC_UPLOAD_TTL_SECONDS };
  })
  // The signed PUT does not lock size: the API checks the object after the upload.
  .post("/accounts/:accountId/kyc/confirm", async ({ params }) => {
    const stat = await storage.stat(kycKey(params.accountId));
    return { accepted: stat.type === "application/pdf" && stat.size <= KYC_SIZE_MAX_BYTES, size: stat.size, type: stat.type };
  });

const ACCOUNT = "0001-7700880";
const apiPost = (path: string, accountId = ACCOUNT) => api.handle(new Request(`http://localhost${path}`, { method: "POST", headers: { "x-account-id": accountId } }));
const { url, expiresInSeconds } = (await (await apiPost(`/accounts/${ACCOUNT}/kyc/upload-url`)).json()) as { url: string; expiresInSeconds: number };
console.log(`  [ISSUE] PUT ${kycKey(ACCOUNT)} for ${expiresInSeconds}s`);
const pdf = new Blob([`%PDF-1.7\nidentity document of ${ACCOUNT}\n%%EOF`], { type: "application/pdf" });
console.log(`  [CLIENT] PUT straight to storage → ${(await fetch(url, { method: "PUT", body: pdf, headers: { "content-type": "application/pdf" } })).status}`);
console.log(`  [CONFIRM] ${await (await apiPost(`/accounts/${ACCOUNT}/kyc/confirm`)).text()}`);
console.log(`  [CLIENT] same URL on another account's object → ${(await fetch(url.replace(ACCOUNT, "0002-1234567"), { method: "PUT", body: pdf, headers: { "content-type": "application/pdf" } })).status}`);
console.log(`  [ISSUE] key for someone else's account → ${(await apiPost(`/accounts/${ACCOUNT}/kyc/upload-url`, "0002-1234567")).status}`);

Nível

introdutório

2/13

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

Domínio financeiro

  • Conta corrente
  • KYC

Padrões do catálogo que implementa

  • Valet Key

Infraestrutura

  • MinIOobject storage S3

    bitnamilegacy/minio:2025.7.23:9000

Variáveis de ambiente

VALET_KEY_S3_ENDPOINT
http://localhost:9000
SeaweedFS S3 gateway. The bucket is created by docker.sh, never by the application.
VALET_KEY_S3_BUCKET
customer-documents
VALET_KEY_S3_ACCESS_KEY_ID
valet-issuer
The real storage credentials: only the issuing service holds them, never the client.
VALET_KEY_S3_SECRET_ACCESS_KEY
valet-issuer-secret

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Valet Key?

Próximo projeto, Segurança & AuditoriaZero Trust
Esc

↑ ↓ navegarEnter abrir239 resultados