Skip to content

Commit 7275bad

Browse files
Alix-007RomneyDa
authored andcommitted
fix(proxy): bound debug CA generation
1 parent a672065 commit 7275bad

4 files changed

Lines changed: 313 additions & 36 deletions

File tree

‎src/proxy-capture/ca.test.ts‎

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
// Proxy capture CA tests cover bounded certificate generation.
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { createTrackedTempDirs } from "../test-utils/tracked-temp-dirs.js";
6+
7+
const { resolveSystemBinMock, runExecMock } = vi.hoisted(() => ({
8+
resolveSystemBinMock: vi.fn(() => "/usr/bin/openssl"),
9+
runExecMock: vi.fn(),
10+
}));
11+
12+
vi.mock("node:crypto", async (importOriginal) => {
13+
const actual = await importOriginal<typeof import("node:crypto")>();
14+
const parseMarker = (value: Buffer, prefix: string): string => {
15+
const text = value.toString("utf8");
16+
if (!text.startsWith(prefix)) {
17+
throw new Error("invalid certificate material");
18+
}
19+
return text.slice(prefix.length);
20+
};
21+
const cryptoMock = { ...actual } as typeof actual;
22+
Object.defineProperties(cryptoMock, {
23+
createPrivateKey: {
24+
value: (value: Buffer) => ({ marker: parseMarker(value, "ca-material-marker:") }),
25+
},
26+
X509Certificate: {
27+
value: class {
28+
readonly ca: boolean;
29+
readonly marker: string;
30+
31+
constructor(value: Buffer) {
32+
this.marker = parseMarker(value, "ca-cert-marker:");
33+
this.ca = this.marker !== "not-ca";
34+
}
35+
36+
checkPrivateKey(key: { marker?: string }): boolean {
37+
return key.marker === this.marker;
38+
}
39+
},
40+
},
41+
});
42+
return cryptoMock;
43+
});
44+
vi.mock("../infra/resolve-system-bin.js", () => ({ resolveSystemBin: resolveSystemBinMock }));
45+
vi.mock("../process/exec.js", async (importOriginal) => ({
46+
...(await importOriginal<typeof import("../process/exec.js")>()),
47+
runExec: runExecMock,
48+
}));
49+
50+
import { ensureDebugProxyCa } from "./ca.js";
51+
52+
const tempDirs = createTrackedTempDirs();
53+
54+
function outputPath(args: string[], flag: "-config" | "-keyout" | "-out"): string {
55+
const index = args.indexOf(flag);
56+
const value = args[index + 1];
57+
if (!value) {
58+
throw new Error(`missing ${flag} output path`);
59+
}
60+
return value;
61+
}
62+
63+
function writeGeneratedPair(args: string[], marker: string): void {
64+
fs.writeFileSync(outputPath(args, "-out"), `ca-cert-marker:${marker}`);
65+
fs.writeFileSync(outputPath(args, "-keyout"), `ca-material-marker:${marker}`);
66+
}
67+
68+
async function makeCertPaths() {
69+
const certDir = await tempDirs.make("openclaw-proxy-ca-");
70+
return {
71+
certDir,
72+
certPath: path.join(certDir, "root-ca.pem"),
73+
keyPath: path.join(certDir, "root-ca-key.pem"),
74+
};
75+
}
76+
77+
function generatePair(marker: string): void {
78+
runExecMock.mockImplementationOnce(async (_command: string, args: string[]) => {
79+
writeGeneratedPair(args, marker);
80+
});
81+
}
82+
83+
afterEach(async () => {
84+
vi.restoreAllMocks();
85+
runExecMock.mockReset();
86+
await tempDirs.cleanup();
87+
});
88+
89+
describe("ensureDebugProxyCa", () => {
90+
it("regenerates after partial output timeout without reusing stale final files", async () => {
91+
const { certDir, certPath, keyPath } = await makeCertPaths();
92+
fs.writeFileSync(certPath, "stale partial cert");
93+
fs.writeFileSync(keyPath, "stale partial key");
94+
let generatedConfig = "";
95+
runExecMock
96+
.mockImplementationOnce(async (_command: string, args: string[]) => {
97+
generatedConfig = fs.readFileSync(outputPath(args, "-config"), "utf8");
98+
fs.writeFileSync(outputPath(args, "-out"), "partial cert");
99+
fs.writeFileSync(outputPath(args, "-keyout"), "partial key");
100+
throw new Error("openssl timed out");
101+
})
102+
.mockImplementationOnce(async (_command: string, args: string[]) => {
103+
writeGeneratedPair(args, "retry");
104+
});
105+
106+
await expect(ensureDebugProxyCa(certDir)).rejects.toThrow("openssl timed out");
107+
expect(fs.readFileSync(certPath, "utf8")).toBe("stale partial cert");
108+
expect(fs.readFileSync(keyPath, "utf8")).toBe("stale partial key");
109+
expect(fs.readdirSync(certDir).toSorted()).toEqual(["root-ca-key.pem", "root-ca.pem"]);
110+
111+
await expect(
112+
Promise.all([ensureDebugProxyCa(certDir), ensureDebugProxyCa(certDir)]),
113+
).resolves.toEqual([
114+
{ certPath, keyPath },
115+
{ certPath, keyPath },
116+
]);
117+
expect(runExecMock).toHaveBeenCalledTimes(2);
118+
const [command, args, options] = runExecMock.mock.calls[0] as [string, string[], object];
119+
expect(command).toBe("/usr/bin/openssl");
120+
expect(args).toEqual(expect.arrayContaining(["req", "-extensions", "v3_ca", "-x509"]));
121+
expect(path.dirname(outputPath(args, "-config"))).toBe(path.dirname(outputPath(args, "-out")));
122+
expect(path.dirname(outputPath(args, "-out")).startsWith(`${certDir}${path.sep}`)).toBe(true);
123+
expect(options).toEqual({ logOutput: false, timeoutMs: 30_000 });
124+
expect(generatedConfig).toContain("CN = OpenClaw Debug Proxy");
125+
expect(generatedConfig).toContain("basicConstraints = critical, CA:TRUE");
126+
expect(generatedConfig).toContain("keyUsage = critical, keyCertSign, cRLSign");
127+
});
128+
129+
it("rejects matching certificate material that is not a CA", async () => {
130+
const { certDir } = await makeCertPaths();
131+
generatePair("not-ca");
132+
133+
await expect(ensureDebugProxyCa(certDir)).rejects.toThrow(
134+
"openssl generated invalid debug proxy certificate material",
135+
);
136+
137+
expect(fs.readdirSync(certDir)).toEqual([]);
138+
});
139+
140+
it("waits for a live lock owner before generating", async () => {
141+
const { certDir, certPath, keyPath } = await makeCertPaths();
142+
const lockPath = `${keyPath}.lock`;
143+
fs.writeFileSync(lockPath, JSON.stringify({ pid: process.pid, createdAt: new Date() }));
144+
generatePair("live-owner-retry");
145+
const releaseOwner = setTimeout(() => fs.rmSync(lockPath, { force: true }), 150);
146+
147+
try {
148+
await expect(ensureDebugProxyCa(certDir)).resolves.toEqual({ certPath, keyPath });
149+
} finally {
150+
clearTimeout(releaseOwner);
151+
}
152+
153+
expect(runExecMock).toHaveBeenCalledTimes(1);
154+
});
155+
156+
it("recovers when publication is interrupted between the two renames", async () => {
157+
const { certDir, certPath, keyPath } = await makeCertPaths();
158+
fs.writeFileSync(certPath, "stale cert");
159+
fs.writeFileSync(keyPath, "stale key");
160+
runExecMock
161+
.mockImplementationOnce(async (_command: string, args: string[]) => {
162+
writeGeneratedPair(args, "failed-publication");
163+
})
164+
.mockImplementationOnce(async (_command: string, args: string[]) => {
165+
writeGeneratedPair(args, "retry-after-publication");
166+
});
167+
168+
const renameSync = fs.renameSync.bind(fs);
169+
let rejectedPublishedCert = false;
170+
const renameSpy = vi.spyOn(fs, "renameSync").mockImplementation((source, destination) => {
171+
const sourcePath = source.toString();
172+
if (
173+
!rejectedPublishedCert &&
174+
destination.toString() === certPath &&
175+
sourcePath.includes(`${path.sep}.root-ca-`)
176+
) {
177+
rejectedPublishedCert = true;
178+
throw Object.assign(new Error("certificate publication failed"), { code: "EACCES" });
179+
}
180+
renameSync(source, destination);
181+
});
182+
183+
await expect(ensureDebugProxyCa(certDir)).rejects.toThrow("certificate publication failed");
184+
185+
expect(fs.readFileSync(certPath, "utf8")).toBe("stale cert");
186+
expect(fs.readFileSync(keyPath, "utf8")).toBe("ca-material-marker:failed-publication");
187+
expect(fs.readdirSync(certDir).toSorted()).toEqual(["root-ca-key.pem", "root-ca.pem"]);
188+
189+
renameSpy.mockRestore();
190+
await expect(ensureDebugProxyCa(certDir)).resolves.toEqual({ certPath, keyPath });
191+
192+
expect(fs.readFileSync(certPath, "utf8")).toBe("ca-cert-marker:retry-after-publication");
193+
expect(fs.readFileSync(keyPath, "utf8")).toBe("ca-material-marker:retry-after-publication");
194+
expect(runExecMock).toHaveBeenCalledTimes(2);
195+
});
196+
});

‎src/proxy-capture/ca.ts‎

Lines changed: 106 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,63 @@
11
// Proxy capture CA helpers create and inspect local capture CA certificates.
2+
import { createPrivateKey, X509Certificate } from "node:crypto";
23
import fs from "node:fs";
34
import path from "node:path";
5+
import { type FileLockOptions, withFileLock } from "../infra/file-lock.js";
46
import { resolveSystemBin } from "../infra/resolve-system-bin.js";
7+
import { KeyedAsyncQueue } from "../plugin-sdk/keyed-async-queue.js";
58
import { runExec } from "../process/exec.js";
69

10+
const DEBUG_PROXY_CA_GENERATION_TIMEOUT_MS = 30_000;
11+
const DEBUG_PROXY_CA_OPENSSL_CONFIG = [
12+
"[req]",
13+
"distinguished_name = subject",
14+
"prompt = no",
15+
"",
16+
"[subject]",
17+
"CN = OpenClaw Debug Proxy",
18+
"",
19+
"[v3_ca]",
20+
"basicConstraints = critical, CA:TRUE",
21+
"keyUsage = critical, keyCertSign, cRLSign",
22+
"",
23+
].join("\n");
24+
const DEBUG_PROXY_CA_LOCK_OPTIONS: FileLockOptions = {
25+
retries: {
26+
// About 36s of minimum backoff covers one full 30s OpenSSL deadline.
27+
retries: 80,
28+
factor: 1.3,
29+
minTimeout: 25,
30+
maxTimeout: 500,
31+
randomize: true,
32+
},
33+
stale: 60_000,
34+
staleRecovery: "remove-if-unchanged",
35+
};
36+
const debugProxyCaGenerationQueue = new KeyedAsyncQueue();
37+
38+
function isValidDebugProxyCaPair(certPath: string, keyPath: string): boolean {
39+
try {
40+
const certStat = fs.lstatSync(certPath);
41+
const keyStat = fs.lstatSync(keyPath);
42+
if (!certStat.isFile() || !keyStat.isFile() || certStat.size === 0 || keyStat.size === 0) {
43+
return false;
44+
}
45+
const cert = new X509Certificate(fs.readFileSync(certPath));
46+
const key = createPrivateKey(fs.readFileSync(keyPath));
47+
return cert.ca && cert.checkPrivateKey(key);
48+
} catch {
49+
return false;
50+
}
51+
}
52+
53+
function removeStagingDirBestEffort(stagingDir: string): void {
54+
try {
55+
fs.rmSync(stagingDir, { recursive: true, force: true });
56+
} catch {
57+
// Cleanup failure must not replace a successful publication result.
58+
}
59+
}
60+
761
// Ensure a short-lived root CA for local MITM debug proxy runs. Existing certs
862
// are reused within the cert dir so repeated starts do not prompt regeneration.
963
export async function ensureDebugProxyCa(certDir: string): Promise<{
@@ -13,32 +67,57 @@ export async function ensureDebugProxyCa(certDir: string): Promise<{
1367
fs.mkdirSync(certDir, { recursive: true });
1468
const certPath = path.join(certDir, "root-ca.pem");
1569
const keyPath = path.join(certDir, "root-ca-key.pem");
16-
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
17-
return { certPath, keyPath };
18-
}
19-
const openssl = resolveSystemBin("openssl");
20-
if (!openssl) {
21-
throw new Error("openssl is required to generate debug proxy certificates");
22-
}
23-
await runExec(
24-
openssl,
25-
[
26-
"req",
27-
"-x509",
28-
"-newkey",
29-
"rsa:2048",
30-
"-sha256",
31-
"-days",
32-
"7",
33-
"-nodes",
34-
"-keyout",
35-
keyPath,
36-
"-out",
37-
certPath,
38-
"-subj",
39-
"/CN=OpenClaw Debug Proxy",
40-
],
41-
{ logOutput: false },
70+
const canonicalKeyPath = path.join(fs.realpathSync(certDir), "root-ca-key.pem");
71+
return await debugProxyCaGenerationQueue.enqueue(canonicalKeyPath, async () =>
72+
withFileLock(canonicalKeyPath, DEBUG_PROXY_CA_LOCK_OPTIONS, async () => {
73+
if (isValidDebugProxyCaPair(certPath, keyPath)) {
74+
return { certPath, keyPath };
75+
}
76+
const openssl = resolveSystemBin("openssl");
77+
if (!openssl) {
78+
throw new Error("openssl is required to generate debug proxy certificates");
79+
}
80+
const stagingDir = fs.mkdtempSync(path.join(certDir, ".root-ca-"));
81+
const stagedConfigPath = path.join(stagingDir, "openssl.cnf");
82+
const stagedCertPath = path.join(stagingDir, "root-ca.pem");
83+
const stagedKeyPath = path.join(stagingDir, "root-ca-key.pem");
84+
try {
85+
fs.writeFileSync(stagedConfigPath, DEBUG_PROXY_CA_OPENSSL_CONFIG, { mode: 0o600 });
86+
await runExec(
87+
openssl,
88+
[
89+
"req",
90+
"-config",
91+
stagedConfigPath,
92+
"-extensions",
93+
"v3_ca",
94+
"-x509",
95+
"-newkey",
96+
"rsa:2048",
97+
"-sha256",
98+
"-days",
99+
"7",
100+
"-nodes",
101+
"-keyout",
102+
stagedKeyPath,
103+
"-out",
104+
stagedCertPath,
105+
],
106+
{ logOutput: false, timeoutMs: DEBUG_PROXY_CA_GENERATION_TIMEOUT_MS },
107+
);
108+
if (!isValidDebugProxyCaPair(stagedCertPath, stagedKeyPath)) {
109+
throw new Error("openssl generated invalid debug proxy certificate material");
110+
}
111+
fs.chmodSync(stagedKeyPath, 0o600);
112+
fs.chmodSync(stagedCertPath, 0o644);
113+
// All OpenClaw writers hold this lock. Same-directory renames replace each
114+
// file atomically; validation repairs a pair interrupted between renames.
115+
fs.renameSync(stagedKeyPath, keyPath);
116+
fs.renameSync(stagedCertPath, certPath);
117+
return { certPath, keyPath };
118+
} finally {
119+
removeStagingDirBestEffort(stagingDir);
120+
}
121+
}),
42122
);
43-
return { certPath, keyPath };
44123
}

‎src/proxy-capture/proxy-server.managed-proxy.test.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
// Managed proxy tests cover proxy server lifecycle with managed capture files.
2-
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2+
import { mkdtemp, rm } from "node:fs/promises";
33
import { createServer as createHttpServer } from "node:http";
44
import { Socket, type AddressInfo } from "node:net";
55
import { tmpdir } from "node:os";
66
import { join } from "node:path";
7-
import { afterEach, beforeEach, describe, expect, it } from "vitest";
7+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
88
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
99
import type { DebugProxySettings } from "./env.js";
1010
import { startDebugProxyServer } from "./proxy-server.js";
1111
import { closeDebugProxyCaptureStore } from "./store.sqlite.js";
1212

13+
vi.mock("./ca.js", () => ({
14+
ensureDebugProxyCa: async () => ({ certPath: "test", keyPath: "test" }),
15+
}));
16+
1317
let testRoot: string | undefined;
1418
const originalStateDir = process.env.OPENCLAW_STATE_DIR;
1519

@@ -32,9 +36,6 @@ async function cleanupTestDirs(): Promise<void> {
3236
async function makeSettings(): Promise<DebugProxySettings> {
3337
testRoot = await mkdtemp(join(tmpdir(), "openclaw-debug-proxy-managed-proxy-"));
3438
const certDir = join(testRoot, "certs");
35-
await mkdir(certDir, { recursive: true });
36-
await writeFile(join(certDir, "root-ca.pem"), "test root cert\n", "utf8");
37-
await writeFile(join(certDir, "root-ca-key.pem"), "test root key\n", "utf8");
3839
process.env.OPENCLAW_STATE_DIR = testRoot;
3940
return {
4041
enabled: true,

0 commit comments

Comments
 (0)