Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions packages/credential-proxy/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
45 changes: 45 additions & 0 deletions packages/credential-proxy/src/main.mjs
Original file line number Diff line number Diff line change
@@ -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" });
}
});
38 changes: 38 additions & 0 deletions packages/credential-proxy/src/runtime.mjs
Original file line number Diff line number Diff line change
@@ -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<unknown[]>} loadRecords
* @property {(request: object) => Promise<unknown>} createEnrollment
* @property {(request: object) => Promise<unknown>} 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";
},
});
}
102 changes: 102 additions & 0 deletions packages/credential-proxy/test/runtime-process.test.mjs
Original file line number Diff line number Diff line change
@@ -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 });
}
});
5 changes: 4 additions & 1 deletion scripts/validation.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down
Loading