Skip to content

Commit 5ba7edd

Browse files
committed
fix(proxy): make debug CA generation recoverable
1 parent 3da3318 commit 5ba7edd

2 files changed

Lines changed: 400 additions & 25 deletions

File tree

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

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
// Proxy capture CA tests cover bounded and recoverable certificate generation.
2+
import { mkdir, readdir, readFile, stat, utimes, writeFile } from "node:fs/promises";
3+
import path from "node:path";
4+
import { afterEach, beforeEach, 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(),
9+
runExecMock: vi.fn(),
10+
}));
11+
12+
vi.mock("../infra/resolve-system-bin.js", () => ({ resolveSystemBin: resolveSystemBinMock }));
13+
vi.mock("../process/exec.js", () => ({ runExec: runExecMock }));
14+
15+
import { ensureDebugProxyCa } from "./ca.js";
16+
17+
const tempDirs = createTrackedTempDirs();
18+
19+
function argAfter(args: string[], flag: string): string {
20+
const index = args.indexOf(flag);
21+
expect(index).toBeGreaterThanOrEqual(0);
22+
const value = args[index + 1];
23+
expect(value).toBeDefined();
24+
return value as string;
25+
}
26+
27+
function mockSuccessfulGeneration() {
28+
runExecMock.mockImplementation(async (_command: string, args: string[]) => {
29+
await writeFile(argAfter(args, "-keyout"), "generated key\n", "utf8");
30+
await writeFile(argAfter(args, "-out"), "generated cert\n", "utf8");
31+
return { stdout: "", stderr: "" };
32+
});
33+
}
34+
35+
async function sortedDirEntries(dir: string): Promise<string[]> {
36+
return (await readdir(dir)).sort();
37+
}
38+
39+
beforeEach(() => {
40+
resolveSystemBinMock.mockReturnValue("/usr/bin/openssl");
41+
runExecMock.mockReset();
42+
});
43+
44+
afterEach(async () => {
45+
await tempDirs.cleanup();
46+
});
47+
48+
describe("ensureDebugProxyCa", () => {
49+
it("reuses an existing CA pair without invoking OpenSSL", async () => {
50+
const certDir = await tempDirs.make("openclaw-proxy-ca-");
51+
const certPath = path.join(certDir, "root-ca.pem");
52+
const keyPath = path.join(certDir, "root-ca-key.pem");
53+
await writeFile(certPath, "existing cert\n", "utf8");
54+
await writeFile(keyPath, "existing key\n", "utf8");
55+
56+
await expect(ensureDebugProxyCa(certDir)).resolves.toEqual({ certPath, keyPath });
57+
58+
expect(runExecMock).not.toHaveBeenCalled();
59+
});
60+
61+
it("generates into temporary files before promoting the reusable CA pair", async () => {
62+
const certDir = await tempDirs.make("openclaw-proxy-ca-");
63+
const certPath = path.join(certDir, "root-ca.pem");
64+
const keyPath = path.join(certDir, "root-ca-key.pem");
65+
mockSuccessfulGeneration();
66+
67+
await expect(ensureDebugProxyCa(certDir)).resolves.toEqual({ certPath, keyPath });
68+
69+
expect(await readFile(certPath, "utf8")).toBe("generated cert\n");
70+
expect(await readFile(keyPath, "utf8")).toBe("generated key\n");
71+
await expect(sortedDirEntries(certDir)).resolves.toEqual(["root-ca-key.pem", "root-ca.pem"]);
72+
73+
const [command, args, options] = runExecMock.mock.calls[0] as [
74+
string,
75+
string[],
76+
Record<string, unknown>,
77+
];
78+
expect(command).toBe("/usr/bin/openssl");
79+
expect(options).toEqual({ logOutput: false, timeoutMs: 30_000 });
80+
expect(argAfter(args, "-keyout").startsWith(`${keyPath}.tmp-`)).toBe(true);
81+
expect(argAfter(args, "-out").startsWith(`${certPath}.tmp-`)).toBe(true);
82+
expect(args).not.toContain(keyPath);
83+
expect(args).not.toContain(certPath);
84+
});
85+
86+
it("cleans partial CA output after a generation failure so a retry can regenerate", async () => {
87+
const certDir = await tempDirs.make("openclaw-proxy-ca-");
88+
const certPath = path.join(certDir, "root-ca.pem");
89+
const keyPath = path.join(certDir, "root-ca-key.pem");
90+
await writeFile(certPath, "stale partial cert\n", "utf8");
91+
runExecMock
92+
.mockImplementationOnce(async (_command: string, args: string[]) => {
93+
await writeFile(argAfter(args, "-keyout"), "partial key\n", "utf8");
94+
await writeFile(argAfter(args, "-out"), "partial cert\n", "utf8");
95+
throw new Error("openssl timed out");
96+
})
97+
.mockImplementationOnce(async (_command: string, args: string[]) => {
98+
await writeFile(argAfter(args, "-keyout"), "retry key\n", "utf8");
99+
await writeFile(argAfter(args, "-out"), "retry cert\n", "utf8");
100+
return { stdout: "", stderr: "" };
101+
});
102+
103+
await expect(ensureDebugProxyCa(certDir)).rejects.toThrow("openssl timed out");
104+
await expect(sortedDirEntries(certDir)).resolves.toEqual([]);
105+
106+
await expect(ensureDebugProxyCa(certDir)).resolves.toEqual({ certPath, keyPath });
107+
await expect(readFile(certPath, "utf8")).resolves.toBe("retry cert\n");
108+
await expect(readFile(keyPath, "utf8")).resolves.toBe("retry key\n");
109+
});
110+
111+
it("does not recursively remove existing directories at CA output paths", async () => {
112+
const certDir = await tempDirs.make("openclaw-proxy-ca-");
113+
const certPath = path.join(certDir, "root-ca.pem");
114+
const nestedPath = path.join(certPath, "keep.txt");
115+
await mkdir(certPath);
116+
await writeFile(nestedPath, "user data\n", "utf8");
117+
runExecMock.mockRejectedValueOnce(new Error("openssl failed"));
118+
119+
await expect(ensureDebugProxyCa(certDir)).rejects.toThrow("openssl failed");
120+
121+
expect((await stat(certPath)).isDirectory()).toBe(true);
122+
await expect(readFile(nestedPath, "utf8")).resolves.toBe("user data\n");
123+
});
124+
125+
it("reclaims abandoned lock tokens before regenerating", async () => {
126+
const certDir = await tempDirs.make("openclaw-proxy-ca-");
127+
const certPath = path.join(certDir, "root-ca.pem");
128+
const keyPath = path.join(certDir, "root-ca-key.pem");
129+
const lockDir = path.join(certDir, ".root-ca-generation.lock");
130+
const lockTokenPath = path.join(lockDir, "abandoned.lock");
131+
const nowMs = Date.parse("2026-07-17T00:00:00.000Z");
132+
await mkdir(lockDir);
133+
await writeFile(lockTokenPath, String(nowMs - 40_000), "utf8");
134+
await utimes(lockTokenPath, new Date(nowMs - 40_000), new Date(nowMs - 40_000));
135+
mockSuccessfulGeneration();
136+
137+
vi.useFakeTimers();
138+
vi.setSystemTime(nowMs);
139+
try {
140+
await expect(ensureDebugProxyCa(certDir)).resolves.toEqual({ certPath, keyPath });
141+
} finally {
142+
vi.useRealTimers();
143+
}
144+
145+
await expect(readFile(certPath, "utf8")).resolves.toBe("generated cert\n");
146+
await expect(readFile(keyPath, "utf8")).resolves.toBe("generated key\n");
147+
await expect(sortedDirEntries(certDir)).resolves.toEqual(["root-ca-key.pem", "root-ca.pem"]);
148+
});
149+
150+
it("times out instead of reclaiming active lock tokens across processes", async () => {
151+
const certDir = await tempDirs.make("openclaw-proxy-ca-");
152+
const lockDir = path.join(certDir, ".root-ca-generation.lock");
153+
const lockTokenPath = path.join(lockDir, "active.lock");
154+
const nowMs = Date.parse("2026-07-17T00:00:00.000Z");
155+
await mkdir(lockDir);
156+
await writeFile(lockTokenPath, String(nowMs), "utf8");
157+
158+
vi.useFakeTimers();
159+
vi.setSystemTime(nowMs);
160+
try {
161+
const generation = ensureDebugProxyCa(certDir);
162+
await vi.advanceTimersByTimeAsync(35_100);
163+
164+
await expect(generation).rejects.toThrow(
165+
"timed out waiting for debug proxy CA generation lock",
166+
);
167+
expect(runExecMock).not.toHaveBeenCalled();
168+
} finally {
169+
vi.useRealTimers();
170+
}
171+
});
172+
173+
it("serializes concurrent generation for a shared cert directory", async () => {
174+
const certDir = await tempDirs.make("openclaw-proxy-ca-");
175+
const certPath = path.join(certDir, "root-ca.pem");
176+
const keyPath = path.join(certDir, "root-ca-key.pem");
177+
let markStarted!: () => void;
178+
let finishGeneration!: () => void;
179+
const generationStarted = new Promise<void>((resolve) => {
180+
markStarted = resolve;
181+
});
182+
const generationMayFinish = new Promise<void>((resolve) => {
183+
finishGeneration = resolve;
184+
});
185+
runExecMock.mockImplementationOnce(async (_command: string, args: string[]) => {
186+
markStarted();
187+
await generationMayFinish;
188+
await writeFile(argAfter(args, "-keyout"), "shared key\n", "utf8");
189+
await writeFile(argAfter(args, "-out"), "shared cert\n", "utf8");
190+
return { stdout: "", stderr: "" };
191+
});
192+
193+
const first = ensureDebugProxyCa(certDir);
194+
await generationStarted;
195+
const second = ensureDebugProxyCa(certDir);
196+
await new Promise((resolve) => {
197+
setTimeout(resolve, 100);
198+
});
199+
expect(runExecMock).toHaveBeenCalledTimes(1);
200+
201+
finishGeneration();
202+
await expect(Promise.all([first, second])).resolves.toEqual([
203+
{ certPath, keyPath },
204+
{ certPath, keyPath },
205+
]);
206+
expect(runExecMock).toHaveBeenCalledTimes(1);
207+
await expect(sortedDirEntries(certDir)).resolves.toEqual(["root-ca-key.pem", "root-ca.pem"]);
208+
});
209+
});

0 commit comments

Comments
 (0)