From 367b85c8b059d3749731d449fb92dbbbc59e5f4f Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Wed, 11 Nov 2026 04:44:46 +0000 Subject: [PATCH] Add authenticated credential proxy unlock adapter --- packages/credential-proxy/src/control.mjs | 107 ++++++++++++++++++ packages/credential-proxy/src/main.mjs | 20 ++-- .../credential-proxy/test/control.test.mjs | 93 +++++++++++++++ .../test/runtime-process.test.mjs | 8 +- 4 files changed, 218 insertions(+), 10 deletions(-) create mode 100644 packages/credential-proxy/src/control.mjs create mode 100644 packages/credential-proxy/test/control.test.mjs diff --git a/packages/credential-proxy/src/control.mjs b/packages/credential-proxy/src/control.mjs new file mode 100644 index 00000000..8ee4a69e --- /dev/null +++ b/packages/credential-proxy/src/control.mjs @@ -0,0 +1,107 @@ +import { createServer } from "node:http"; +import { createPublicKey, verify } from "node:crypto"; +import { readFile, rename, writeFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; + +const MAX_CAPABILITY_SECONDS = 60; +const DEFAULT_BODY_LIMIT = 4096; + +function decodePart(value) { + if (!/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("invalid token"); + return Buffer.from(value, "base64url"); +} + +function capabilityClaims(token, publicKey, expected, now) { + try { + if (typeof token !== "string" || token.length > 4096) return null; + const parts = token.split("."); + if (parts.length !== 3) return null; + const [head, payload, signature] = parts; + const header = JSON.parse(decodePart(head)); + const claims = JSON.parse(decodePart(payload)); + if (header.alg !== "EdDSA" || header.typ !== "JWT") return null; + if (!verify(null, Buffer.from(`${head}.${payload}`), publicKey, decodePart(signature))) return null; + if (claims.iss !== expected.issuer || claims.aud !== expected.proxyId || claims.action !== "proxy:unlock" + || claims.origin !== expected.origin || claims.generation !== expected.generation + || claims.sub !== expected.ownerId || typeof claims.jti !== "string" || !claims.jti + || !Number.isSafeInteger(claims.exp) || claims.exp <= now || claims.exp > now + MAX_CAPABILITY_SECONDS) return null; + return claims; + } catch { return null; } +} + +function json(response, status, value, headers = {}) { + response.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store", ...headers }); + response.end(JSON.stringify(value)); +} + +export function createControlServer({ runtime, proxyId, ownerId, issuer = "factorize", origin, generation, publicKey, now = () => Math.floor(Date.now() / 1000), maxBodyBytes = DEFAULT_BODY_LIMIT, serverFactory = createServer }) { + if (!runtime || typeof runtime.unlock !== "function" || !proxyId || !ownerId || !origin || !Number.isSafeInteger(generation) || !publicKey) throw new TypeError("proxy control configuration is incomplete"); + const verificationKey = createPublicKey(publicKey); + const consumed = new Map(); + const handler = async (request, response) => { + const requestOrigin = request.headers.origin; + if (request.method === "OPTIONS") { + if (request.url !== "/unlock" || requestOrigin !== origin || request.headers["access-control-request-method"] !== "POST" + || (request.headers["access-control-request-headers"] ?? "").split(",").map(value => value.trim().toLowerCase()).filter(Boolean).sort().join(",") !== "authorization,content-type") { + response.writeHead(403).end(); return; + } + response.writeHead(204, { "Access-Control-Allow-Origin": origin, "Access-Control-Allow-Methods": "POST", "Access-Control-Allow-Headers": "Authorization, Content-Type", "Vary": "Origin", "Cache-Control": "no-store" }).end(); + return; + } + if (request.url !== "/unlock") { response.writeHead(404).end(); return; } + if (requestOrigin !== origin) { response.writeHead(403).end(); return; } + const cors = { "Access-Control-Allow-Origin": origin, "Vary": "Origin" }; + if (request.method !== "POST") { response.writeHead(405, { Allow: "POST", ...cors }).end(); return; } + if (request.headers["content-type"]?.split(";", 1)[0].trim().toLowerCase() !== "application/json") { json(response, 415, { error: "unsupported media type" }, cors); return; } + const auth = request.headers.authorization ?? ""; + const token = auth.startsWith("Bearer ") ? auth.slice(7) : ""; + const claims = capabilityClaims(token, verificationKey, { issuer, proxyId, ownerId, origin, generation }, now()); + if (!claims) { json(response, 401, { error: "invalid capability" }, cors); return; } + for (const [nonce, expiry] of consumed) if (expiry <= now()) consumed.delete(nonce); + if (consumed.has(claims.jti)) { json(response, 409, { error: "capability already used" }, cors); return; } + consumed.set(claims.jti, claims.exp); + let bytes = 0; + const chunks = []; + try { + for await (const chunk of request) { + bytes += chunk.length; + if (bytes > maxBodyBytes) { request.resume(); json(response, 413, { error: "request body exceeds limit" }, cors); return; } + chunks.push(chunk); + } + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).length !== 1 || typeof body.key !== "string" || body.key.length < 1 || body.key.length > 2048) { + json(response, 400, { error: "invalid unlock request" }, cors); return; + } + try { runtime.unlock(body.key); } + catch { json(response, 503, { error: "unlock unavailable" }, cors); return; } + json(response, 200, { unlocked: true }, cors); + } catch { + if (!response.headersSent) json(response, 400, { error: "invalid unlock request" }, cors); + } + }; + return serverFactory(handler); +} + +const identityKeys = ["proxyId", "flyMachineId", "httpsOrigin", "sshFingerprint", "generation"]; +function normalizeIdentity(value) { + if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== [...identityKeys].sort().join(",") + || identityKeys.slice(0, 4).some(key => typeof value[key] !== "string" || !value[key]) + || !Number.isSafeInteger(value.generation) || value.generation < 1) throw new TypeError("invalid proxy identity"); + return Object.fromEntries(identityKeys.map(key => [key, value[key]])); +} + +export async function persistProxyIdentity(path, candidate, { approveReplacement = false } = {}) { + const next = normalizeIdentity(candidate); + let previous; + try { previous = normalizeIdentity(JSON.parse(await readFile(path, "utf8"))); } + catch (error) { if (error.code !== "ENOENT") throw new Error("stored proxy identity is invalid"); } + if (previous) { + if (JSON.stringify(previous) === JSON.stringify(next)) return previous; + if (!approveReplacement || next.generation !== previous.generation + 1) throw new Error("proxy identity replacement requires explicit owner approval and next generation"); + } + const temporary = `${path}.${randomUUID()}.tmp`; + await writeFile(temporary, `${JSON.stringify(next)}\n`, { mode: 0o600, flag: "wx" }); + try { await rename(temporary, path); } + catch (error) { await import("node:fs/promises").then(fs => fs.rm(temporary, { force: true })); throw error; } + return next; +} diff --git a/packages/credential-proxy/src/main.mjs b/packages/credential-proxy/src/main.mjs index 20c32377..1b84acb0 100644 --- a/packages/credential-proxy/src/main.mjs +++ b/packages/credential-proxy/src/main.mjs @@ -1,7 +1,18 @@ import { createInterface } from "node:readline"; import { createProxyRuntime } from "./runtime.mjs"; +import { createControlServer } from "./control.mjs"; const runtime = createProxyRuntime(); +const controlConfigured = ["PROXY_ID", "PROXY_OWNER_ID", "PROXY_GENERATION", "FACTORIZE_WEB_ORIGIN", "FACTORIZE_CAPABILITY_PUBLIC_KEY"].every((name) => process.env[name]); +const controlServer = controlConfigured ? createControlServer({ + runtime, + proxyId: process.env.PROXY_ID, + ownerId: process.env.PROXY_OWNER_ID, + generation: Number(process.env.PROXY_GENERATION), + origin: process.env.FACTORIZE_WEB_ORIGIN, + publicKey: process.env.FACTORIZE_CAPABILITY_PUBLIC_KEY, +}) : undefined; +if (controlServer) controlServer.listen(Number(process.env.PROXY_CONTROL_PORT ?? 8787), process.env.PROXY_CONTROL_HOST ?? "0.0.0.0"); const lines = createInterface({ input: process.stdin, crlfDelay: Infinity }); let closing = false; let shutdownDeadline; @@ -14,6 +25,7 @@ function stop() { if (closing) return; closing = true; runtime.shutdown(); + controlServer?.close(); lines.close(); clearTimeout(shutdownDeadline); process.exit(0); @@ -31,13 +43,7 @@ lines.on("line", (line) => { try { command = JSON.parse(line); if (command?.type === "status") respond({ type: "status", state: runtime.state }); - else if (command?.type === "unlock") { - runtime.unlock(command.key); - respond({ type: "status", state: runtime.state }); - } else if (command?.type === "lock") { - runtime.lock(); - respond({ type: "status", state: runtime.state }); - } else if (command?.type === "stop") stop(); + else if (command?.type === "stop") stop(); else respond({ type: "error", error: "unsupported command" }); } catch { respond({ type: "error", error: "invalid command" }); diff --git a/packages/credential-proxy/test/control.test.mjs b/packages/credential-proxy/test/control.test.mjs new file mode 100644 index 00000000..d5ab1a79 --- /dev/null +++ b/packages/credential-proxy/test/control.test.mjs @@ -0,0 +1,93 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { Agent, createServer as createHttpsServer, request as httpsRequest } from "node:https"; +import { createPrivateKey, generateKeyPairSync, sign } from "node:crypto"; +import { once } from "node:events"; +import { mkdtemp, readFile as readFileAgain, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { createControlServer, persistProxyIdentity } from "../src/control.mjs"; + +const fixture = new URL("../../app/test/fixtures/https-pairing/", import.meta.url); +const [key, cert] = await Promise.all([readFile(new URL("localhost-key.pem", fixture)), readFile(new URL("localhost-cert.pem", fixture))]); +const { publicKey, privateKey } = generateKeyPairSync("ed25519"); +const signingKey = createPrivateKey(privateKey.export({ type: "pkcs8", format: "pem" })); +const verificationKey = publicKey.export({ type: "spki", format: "pem" }); +const origin = "https://factorize.example"; +const now = 2_000_000_000; +let sequence = 0; + +function token({ aud = "proxy-1", sub = "owner-1", exp = now + 30, generation = 2, jti = `nonce-${++sequence}` } = {}) { + const head = Buffer.from(JSON.stringify({ alg: "EdDSA", typ: "JWT" })).toString("base64url"); + const body = Buffer.from(JSON.stringify({ iss: "factorize", aud, sub, action: "proxy:unlock", origin, generation, exp, jti })).toString("base64url"); + const input = `${head}.${body}`; + return `${input}.${sign(null, Buffer.from(input), signingKey).toString("base64url")}`; +} + +function listen(server) { + server.listen(0, "127.0.0.1"); + return once(server, "listening"); +} + +function request(port, agent, { method = "POST", path = "/unlock", requestOrigin = origin, capability = token(), body = { key: "unlock-secret" }, headers = {} } = {}) { + return new Promise((resolve, reject) => { + const req = httpsRequest(`https://localhost:${port}${path}`, { method, agent, headers: { Origin: requestOrigin, Authorization: `Bearer ${capability}`, "Content-Type": "application/json", ...headers } }, response => { + const chunks = []; + response.on("data", chunk => chunks.push(chunk)); + response.on("end", () => resolve({ status: response.statusCode, headers: response.headers, json: () => JSON.parse(Buffer.concat(chunks).toString("utf8")) })); + }); + req.on("error", reject); + if (method === "POST" && body !== undefined) req.end(typeof body === "string" ? body : JSON.stringify(body)); + else req.end(); + }); +} + +test("HTTPS control accepts a one-use paired capability and rejects invalid origin, identity, expiry, audience, replay and key", async () => { + const unlocked = []; + const runtime = { unlock(value) { if (value !== "unlock-secret") throw new Error("wrong key"); unlocked.push(value); } }; + const server = createControlServer({ runtime, proxyId: "proxy-1", ownerId: "owner-1", origin, generation: 2, publicKey: verificationKey, now: () => now, serverFactory: handler => createHttpsServer({ key, cert }, handler) }); + await listen(server); + try { + const port = server.address().port; + const agent = new Agent({ rejectUnauthorized: false }); + try { + const valid = await request(port, agent); + assert.equal(valid.status, 200); + assert.deepEqual(await valid.json(), { unlocked: true }); + assert.deepEqual(unlocked, ["unlock-secret"]); + const replay = await request(port, agent, { capability: token({ jti: "reused" }) }); + const replayAgain = await request(port, agent, { capability: token({ jti: "reused" }) }); + assert.equal(replay.status, 200); + assert.equal(replayAgain.status, 409); + for (const capability of [token({ aud: "proxy-other" }), token({ sub: "owner-other" }), token({ exp: now - 1 }), token({ generation: 1 })]) { + assert.equal((await request(port, agent, { capability })).status, 401); + } + assert.equal((await request(port, agent, { requestOrigin: "https://foreign.example" })).status, 403); + const wrongKey = await request(port, agent, { body: { key: "wrong-key" }, capability: token() }); + assert.equal(wrongKey.status, 503); + assert.equal(unlocked.length, 2); + assert.equal((await request(port, agent, { body: { key: "x".repeat(5000) } })).status, 413); + assert.equal((await request(port, agent, { method: "OPTIONS", body: undefined, headers: { "Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "authorization, content-type" } })).status, 204); + assert.equal((await request(port, agent, { method: "OPTIONS", requestOrigin: "https://foreign.example", body: undefined, headers: { "Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "authorization, content-type" } })).status, 403); + } finally { + agent.destroy(); + } + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +test("proxy identity persistence requires explicit approval for replacement", async () => { + const directory = await mkdtemp(join(tmpdir(), "proxy-identity-")); + const path = join(directory, "identity.json"); + const current = { proxyId: "proxy-1", flyMachineId: "machine-1", httpsOrigin: "https://proxy.fly.dev", sshFingerprint: "SHA256:one", generation: 1 }; + const replacement = { ...current, flyMachineId: "machine-2", sshFingerprint: "SHA256:two", generation: 2 }; + try { + await persistProxyIdentity(path, current); + assert.deepEqual(JSON.parse(await readFileAgain(path, "utf8")), current); + await assert.rejects(persistProxyIdentity(path, replacement), /explicit owner approval/); + assert.deepEqual(await persistProxyIdentity(path, replacement, { approveReplacement: true }), replacement); + assert.deepEqual(JSON.parse(await readFileAgain(path, "utf8")), replacement); + } finally { await rm(directory, { recursive: true, force: true }); } +}); diff --git a/packages/credential-proxy/test/runtime-process.test.mjs b/packages/credential-proxy/test/runtime-process.test.mjs index 64fb7fe7..6f1a678e 100644 --- a/packages/credential-proxy/test/runtime-process.test.mjs +++ b/packages/credential-proxy/test/runtime-process.test.mjs @@ -58,7 +58,8 @@ test("process starts locked, unlocks in memory, shuts down bounded, and restarts const first = await startProxy(); processes.push(first); assert.deepEqual(await first.command({ type: "status" }), { type: "status", state: "locked" }); - assert.deepEqual(await first.command({ type: "unlock", key: keyMarker }), { type: "status", state: "unlocked" }); + assert.deepEqual(await first.command({ type: "unlock", key: keyMarker }), { type: "error", error: "unsupported command" }); + assert.deepEqual(await first.command({ type: "status" }), { type: "status", state: "locked" }); first.child.kill("SIGTERM"); await waitFor(() => first.child.exitCode !== null || first.child.signalCode !== null, "first process stop"); assert.equal(first.child.exitCode, 0); @@ -66,14 +67,15 @@ test("process starts locked, unlocks in memory, shuts down bounded, and restarts const restarted = await startProxy(); processes.push(restarted); assert.deepEqual(await restarted.command({ type: "status" }), { type: "status", state: "locked" }); - assert.deepEqual(await restarted.command({ type: "unlock", key: tokenMarker }), { type: "status", state: "unlocked" }); + assert.deepEqual(await restarted.command({ type: "unlock", key: tokenMarker }), { type: "error", error: "unsupported command" }); + assert.deepEqual(await restarted.command({ type: "status" }), { type: "status", state: "locked" }); restarted.child.stdin.write('{"type":"stop"}\n'); await waitFor(() => restarted.child.exitCode !== null || restarted.child.signalCode !== null, "command shutdown"); assert.equal(restarted.child.exitCode, 0); const crashed = await startProxy(); processes.push(crashed); - assert.deepEqual(await crashed.command({ type: "unlock", key: keyMarker }), { type: "status", state: "unlocked" }); + assert.deepEqual(await crashed.command({ type: "unlock", key: keyMarker }), { type: "error", error: "unsupported command" }); crashed.child.kill("SIGKILL"); await waitFor(() => crashed.child.exitCode !== null || crashed.child.signalCode !== null, "crash stop"); assert.equal(crashed.child.signalCode, "SIGKILL");