SPB Git

Repository Public

index.ts 8.1 KB 96 lines typescript

1// SP Vault managed-secrets process. Separate process, separate key, loopback only.2// This is the ONLY component that can decrypt managed secrets; it never touches the personal vault tables.3import crypto from "node:crypto";4import dns from "node:dns/promises";5import fs from "node:fs";6import net from "node:net";7import Fastify from "fastify";8import postgres from "postgres";910const env = (k: string) => { const v = process.env[k]; if (!v) throw new Error(`missing ${k}`); return v; };11const PORT = Number(process.env.SPV_MANAGED_PORT ?? 8742);12const keyFile = env("SPV_MANAGED_KEY_FILE"), tokenFile = env("SPV_MANAGED_TOKEN_FILE");13for (const f of [keyFile, tokenFile]) if ((fs.statSync(f).mode & 0o077) !== 0) throw new Error(`${f} must not be readable by group/others`);14const master = Buffer.from(fs.readFileSync(keyFile, "utf8").trim(), "base64");15if (master.length !== 32) throw new Error("managed master key must be 32 bytes (base64)");16const token = fs.readFileSync(tokenFile, "utf8").trim();17const allowPrivate = process.env.SPV_MANAGED_ALLOW_PRIVATE === "1"; // tests only18const sql = postgres(env("SPV_MANAGED_DATABASE_URL"), { onnotice: () => {}, max: 4 });19await sql`create table if not exists secret_values (id uuid primary key, account_id uuid not null, version int not null, nonce bytea not null, ct bytea not null, updated_at timestamptz not null default now())`;2021const keyFor = (accountId: string) => Buffer.from(crypto.hkdfSync("sha256", master, Buffer.from(accountId), Buffer.from("SPV managed secret v1"), 32));22const aad = (id: string, accountId: string, version: number) => Buffer.from(`SPVM1|${id}|${accountId}|${version}`);2324async function store(id: string, accountId: string, version: number, value: string) {25  const nonce = crypto.randomBytes(12), c = crypto.createCipheriv("aes-256-gcm", keyFor(accountId), nonce);26  c.setAAD(aad(id, accountId, version));27  const ct = Buffer.concat([c.update(value, "utf8"), c.final(), c.getAuthTag()]);28  await sql`insert into secret_values (id, account_id, version, nonce, ct) values (${id}, ${accountId}, ${version}, ${nonce}, ${ct})29            on conflict (id) do update set version = excluded.version, nonce = excluded.nonce, ct = excluded.ct, updated_at = now() where secret_values.account_id = excluded.account_id`;30}31async function load(id: string, accountId: string): Promise<string> {32  const [r] = await sql`select version, nonce, ct from secret_values where id = ${id} and account_id = ${accountId}`;33  if (!r) throw Object.assign(new Error("secret not found"), { statusCode: 404 });34  const ct = Buffer.from(r.ct), d = crypto.createDecipheriv("aes-256-gcm", keyFor(accountId), Buffer.from(r.nonce));35  d.setAAD(aad(id, accountId, r.version)); d.setAuthTag(ct.subarray(ct.length - 16));36  return Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]).toString("utf8");37}3839function isPrivate(ip: string): boolean {40  if (net.isIPv4(ip)) { const [a, b] = ip.split(".").map(Number) as [number, number]; return a === 10 || a === 127 || a === 0 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127) || a >= 224; }41  const x = ip.toLowerCase();42  return x === "::1" || x === "::" || x.startsWith("fc") || x.startsWith("fd") || x.startsWith("fe80") || x.startsWith("::ffff:");43}44export function hostAllowed(host: string, allowed: string[]): boolean {45  const h = host.toLowerCase();46  return allowed.some((a) => { const x = a.toLowerCase(); return x.startsWith("*.") ? h.endsWith(x.slice(1)) && h.length > x.length - 1 : h === x; });47}48const fail = (statusCode: number, message: string) => Object.assign(new Error(message), { statusCode });49const FORBIDDEN_HEADERS = new Set(["host", "authorization", "cookie", "proxy-authorization", "content-length", "connection", "transfer-encoding", "upgrade", "te", "trailer"]);5051const app = Fastify({ logger: { level: process.env.SPV_LOG_LEVEL ?? "info" }, disableRequestLogging: true, bodyLimit: 2 * 1024 * 1024 });52app.addHook("onRequest", async (req) => {53  const given = Buffer.from(String(req.headers["x-spv-managed"] ?? "")), want = Buffer.from(token);54  if (given.length !== want.length || !crypto.timingSafeEqual(given, want)) throw fail(401, "unauthorized");55});56app.setErrorHandler((err: any, _req, reply) => reply.code(err.statusCode ?? 500).send({ error: err.statusCode ? "managed_error" : "internal", message: err.statusCode ? err.message : "internal error" }));57app.get("/health", async () => ({ ok: true }));58app.put("/secrets/:id", async (req) => { const b = req.body as any; if (typeof b.value !== "string" || !b.value || b.value.length > 65536) throw fail(400, "invalid value"); await store((req.params as any).id, b.accountId, b.version, b.value); return { ok: true }; });59app.delete("/secrets/:id", async (req) => { await sql`delete from secret_values where id = ${(req.params as any).id} and account_id = ${(req.body as any).accountId}`; return { ok: true }; });60app.post("/secrets/:id/reveal", async (req) => ({ value: await load((req.params as any).id, (req.body as any).accountId) }));61app.post("/secrets/:id/hmac", async (req) => {62  const b = req.body as any;63  return { signature: crypto.createHmac("sha256", await load((req.params as any).id, b.accountId)).update(Buffer.from(String(b.payload), "base64url")).digest("base64url"), algorithm: "HMAC-SHA256" };64});65/** Brokered HTTP call: the secret is injected here and never returned to the caller. */66app.post("/secrets/:id/http", async (req) => {67  const b = req.body as { accountId: string; kind: string; config: any; request: { method: string; url: string; headers?: Record<string, string>; body?: string } };68  let u: URL;69  try { u = new URL(b.request.url); } catch { throw fail(400, "invalid URL"); }70  if (u.protocol !== "https:" && !(allowPrivate && u.protocol === "http:")) throw fail(400, "only https:// upstreams are allowed");71  if (u.username || u.password) throw fail(400, "credentials in the URL are not allowed");72  if (!hostAllowed(u.hostname, b.config.allowedHosts ?? [])) throw fail(403, `host ${u.hostname} is not in this secret's allow-list`);73  const method = String(b.request.method ?? "GET").toUpperCase();74  if (!(b.config.allowedMethods ?? ["GET", "POST"]).includes(method)) throw fail(403, `method ${method} is not allowed for this secret`);75  if (!allowPrivate) {76    const addrs = net.isIP(u.hostname) ? [{ address: u.hostname }] : await dns.lookup(u.hostname, { all: true }).catch(() => []);77    if (!addrs.length || addrs.some((a) => isPrivate(a.address))) throw fail(403, "upstream resolves to a private or unroutable address");78  }79  const secret = await load((req.params as any).id, b.accountId);80  const headers = new Headers();81  for (const [k, v] of Object.entries(b.request.headers ?? {})) if (!FORBIDDEN_HEADERS.has(k.toLowerCase()) && k.toLowerCase() !== String(b.config.header ?? "").toLowerCase() && typeof v === "string") headers.set(k, v);82  if (b.kind === "http-bearer") headers.set("authorization", `Bearer ${secret}`);83  else if (b.kind === "http-basic") headers.set("authorization", `Basic ${Buffer.from(`${b.config.username ?? ""}:${secret}`).toString("base64")}`);84  else if (b.kind === "http-header") headers.set(String(b.config.header), `${b.config.prefix ?? ""}${secret}`);85  else throw fail(400, "this secret kind cannot be used for HTTP calls");86  const res = await fetch(u, { method, headers, body: method === "GET" || method === "HEAD" ? undefined : b.request.body, redirect: "manual", signal: AbortSignal.timeout(15000) }).catch((e) => { throw fail(502, `upstream error: ${String(e.cause?.code ?? e.name)}`); });87  const buf = Buffer.from(await res.arrayBuffer());88  if (buf.length > 1024 * 1024) throw fail(502, "upstream response larger than 1 MiB");89  // the secret must not come back through an echoing upstream90  const scrub = (s: string) => s.split(secret).join("[redacted]");91  const out: Record<string, string> = {};92  for (const k of ["content-type", "retry-after", "x-request-id", "x-ratelimit-remaining"]) { const v = res.headers.get(k); if (v) out[k] = scrub(v); }93  return { status: res.status, headers: out, body: scrub(buf.toString("utf8")) };94});95await app.listen({ port: PORT, host: "127.0.0.1" });96
Files main
Menu

Theme