|
| 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 | +}); |
0 commit comments