diff --git a/package-lock.json b/package-lock.json index dc0bfade..b6d2b8fa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2285,6 +2285,10 @@ "node": ">=18" } }, + "node_modules/@factorize/credential-proxy": { + "resolved": "packages/credential-proxy", + "link": true + }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -9660,6 +9664,10 @@ } } }, + "packages/credential-proxy": { + "name": "@factorize/credential-proxy", + "version": "0.1.0" + }, "packages/docs": { "name": "factorize-docs", "version": "0.1.0" diff --git a/packages/credential-proxy/package.json b/packages/credential-proxy/package.json new file mode 100644 index 00000000..20c1c5c9 --- /dev/null +++ b/packages/credential-proxy/package.json @@ -0,0 +1,10 @@ +{ + "name": "@factorize/credential-proxy", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "start": "node src/main.mjs", + "test": "node --test test/*.test.mjs" + } +} diff --git a/packages/credential-proxy/src/main.mjs b/packages/credential-proxy/src/main.mjs new file mode 100644 index 00000000..20c32377 --- /dev/null +++ b/packages/credential-proxy/src/main.mjs @@ -0,0 +1,45 @@ +import { createInterface } from "node:readline"; +import { createProxyRuntime } from "./runtime.mjs"; + +const runtime = createProxyRuntime(); +const lines = createInterface({ input: process.stdin, crlfDelay: Infinity }); +let closing = false; +let shutdownDeadline; + +function respond(value) { + process.stdout.write(`${JSON.stringify(value)}\n`); +} + +function stop() { + if (closing) return; + closing = true; + runtime.shutdown(); + lines.close(); + clearTimeout(shutdownDeadline); + process.exit(0); +} + +process.once("SIGTERM", stop); +process.once("SIGINT", stop); +shutdownDeadline = setTimeout(() => process.exit(1), 2_000); +shutdownDeadline.unref(); +respond({ type: "ready", state: runtime.state }); + +lines.on("line", (line) => { + if (closing) return; + let command; + 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 respond({ type: "error", error: "unsupported command" }); + } catch { + respond({ type: "error", error: "invalid command" }); + } +}); diff --git a/packages/credential-proxy/src/runtime.mjs b/packages/credential-proxy/src/runtime.mjs new file mode 100644 index 00000000..e85401c7 --- /dev/null +++ b/packages/credential-proxy/src/runtime.mjs @@ -0,0 +1,38 @@ +/** + * Internal adapter contracts for the follow-up record, enrollment and forwarding + * slices. This runtime deliberately does not call or implement these adapters. + * + * @typedef {object} ProxyAdapters + * @property {(identity: object) => Promise} loadRecords + * @property {(request: object) => Promise} createEnrollment + * @property {(request: object) => Promise} forwardRequest + */ + +export function createProxyRuntime() { + let unlockMaterial; + let state = "locked"; + let shutdown = false; + + return Object.freeze({ + get state() { + return state; + }, + unlock(key) { + if (shutdown) throw new Error("runtime is shutting down"); + if (typeof key !== "string" || key.length === 0) throw new TypeError("unlock key must be a non-empty string"); + unlockMaterial?.fill(0); + unlockMaterial = Buffer.from(key, "utf8"); + state = "unlocked"; + }, + lock() { + unlockMaterial?.fill(0); + unlockMaterial = undefined; + if (!shutdown) state = "locked"; + }, + shutdown() { + this.lock(); + shutdown = true; + state = "stopped"; + }, + }); +} diff --git a/packages/credential-proxy/test/runtime-process.test.mjs b/packages/credential-proxy/test/runtime-process.test.mjs new file mode 100644 index 00000000..64fb7fe7 --- /dev/null +++ b/packages/credential-proxy/test/runtime-process.test.mjs @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { test } from "node:test"; + +const entry = fileURLToPath(new URL("../src/main.mjs", import.meta.url)); +const keyMarker = "synthetic-unlock-key-marker"; +const tokenMarker = "synthetic-upstream-token-marker"; + +async function waitFor(predicate, label) { + const deadline = Date.now() + 3_000; + while (!predicate()) { + if (Date.now() >= deadline) throw new Error(`deadline exceeded: ${label}`); + await new Promise((resolve) => setImmediate(resolve)); + } +} + +async function startProxy() { + const child = spawn(process.execPath, [entry], { stdio: ["pipe", "pipe", "pipe"] }); + let pending = ""; + let log = ""; + let stderr = ""; + const messages = []; + child.stdout.setEncoding("utf8").on("data", (chunk) => { + log += chunk; + pending += chunk; + for (;;) { + const end = pending.indexOf("\n"); + if (end < 0) break; + const line = pending.slice(0, end); + pending = pending.slice(end + 1); + try { messages.push(JSON.parse(line)); } catch { messages.push({ malformed: line }); } + } + }); + child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk; }); + await waitFor(() => messages.length > 0, "proxy startup"); + assert.deepEqual(messages.shift(), { type: "ready", state: "locked" }); + return { + child, + get logs() { return `${log}${stderr}`; }, + command(command) { + child.stdin.write(`${JSON.stringify(command)}\n`); + return waitFor(() => messages.length > 0, `response to ${command.type}`).then(() => messages.shift()); + }, + }; +} + +test("process starts locked, unlocks in memory, shuts down bounded, and restarts locked", async () => { + const directory = await mkdtemp(join(tmpdir(), "credential-proxy-")); + const processes = []; + try { + await writeFile(join(directory, "identity.json"), JSON.stringify({ identity: "public-fixture", generation: 1 })); + await writeFile(join(directory, "public-metadata.json"), JSON.stringify({ displayName: "fixture" })); + 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" }); + first.child.kill("SIGTERM"); + await waitFor(() => first.child.exitCode !== null || first.child.signalCode !== null, "first process stop"); + assert.equal(first.child.exitCode, 0); + + 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" }); + 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" }); + crashed.child.kill("SIGKILL"); + await waitFor(() => crashed.child.exitCode !== null || crashed.child.signalCode !== null, "crash stop"); + assert.equal(crashed.child.signalCode, "SIGKILL"); + + const afterCrash = await startProxy(); + processes.push(afterCrash); + assert.deepEqual(await afterCrash.command({ type: "status" }), { type: "status", state: "locked" }); + afterCrash.child.kill("SIGTERM"); + await waitFor(() => afterCrash.child.exitCode !== null || afterCrash.child.signalCode !== null, "post-crash shutdown"); + assert.equal(afterCrash.child.exitCode, 0); + + const persisted = await Promise.all((await readdir(directory)).map((name) => readFile(join(directory, name), "utf8"))); + for (const content of [...persisted, ...processes.map((process) => process.logs)]) { + assert.equal(content.includes(keyMarker), false, "unlock key was persisted or logged"); + assert.equal(content.includes(tokenMarker), false, "token marker was persisted or logged"); + } + } finally { + for (const process of processes) { + if (process.child.exitCode === null && process.child.signalCode === null) { + process.child.kill("SIGKILL"); + await once(process.child, "exit"); + } + } + await rm(directory, { recursive: true, force: true }); + } +}); diff --git a/scripts/validation.mjs b/scripts/validation.mjs index b1a853c2..e5f710e7 100644 --- a/scripts/validation.mjs +++ b/scripts/validation.mjs @@ -19,7 +19,10 @@ const lanes = { ["functional browser checks", "npm", ["run", "test:functional", "--workspace=factorize-app"], 90_000], ["application unit checks", "npm", ["test", "--workspace=factorize-app"], 180_000], ], - proxy: [["portable proxy harness checks", process.execPath, ["--test", "scripts/validation-runner.test.mjs"], 30_000]], + proxy: [ + ["portable proxy harness checks", process.execPath, ["--test", "scripts/validation-runner.test.mjs"], 30_000], + ["credential proxy process checks", process.execPath, ["--test", "packages/credential-proxy/test/runtime-process.test.mjs"], 30_000], + ], }; if (lane === "--check-chromium") {