|
| 1 | +import { ChildProcess } from "node:child_process"; |
| 2 | +import { createHash } from "node:crypto"; |
| 3 | +import { PassThrough } from "node:stream"; |
| 4 | +import { createPluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-store-runtime"; |
| 5 | +import { createOpenClawTestState } from "openclaw/plugin-sdk/test-state"; |
| 6 | +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest"; |
| 7 | +import { terminateCodexAppServerOrphan } from "./transport-process-containment.js"; |
| 8 | +import { prepareCodexAppServerProcessRegistration } from "./transport-process-registration.js"; |
| 9 | +import { readCodexAppServerProcessSnapshot } from "./transport-process-snapshot.js"; |
| 10 | + |
| 11 | +const procfs = vi.hoisted(() => ({ files: new Map<string, string | Error>() })); |
| 12 | +vi.mock("node:fs/promises", async (importOriginal) => { |
| 13 | + const original = await importOriginal<typeof import("node:fs/promises")>(); |
| 14 | + return { |
| 15 | + ...original, |
| 16 | + readFile: (...args: Parameters<typeof original.readFile>) => { |
| 17 | + const file = args[0]; |
| 18 | + if (typeof file !== "string" || !file.startsWith("/proc/")) { |
| 19 | + return original.readFile(...args); |
| 20 | + } |
| 21 | + const value = procfs.files.get(file); |
| 22 | + return typeof value === "string" |
| 23 | + ? Promise.resolve(value) |
| 24 | + : Promise.reject(value ?? Object.assign(new Error("gone"), { code: "ENOENT" })); |
| 25 | + }, |
| 26 | + readdir: (...args: Parameters<typeof original.readdir>) => |
| 27 | + args[0] === "/proc" |
| 28 | + ? Promise.resolve( |
| 29 | + [...procfs.files.keys()].flatMap( |
| 30 | + (file) => /^\/proc\/(\d+)\/stat$/.exec(file)?.[1] ?? [], |
| 31 | + ), |
| 32 | + ) |
| 33 | + : original.readdir(...args), |
| 34 | + }; |
| 35 | +}); |
| 36 | + |
| 37 | +const bootId = "00000000-0000-0000-0000-000000000001"; |
| 38 | +const identity = (pid: number) => ({ pid, pgid: pid, startedAt: `${bootId}:12345` }); |
| 39 | +const parent = identity(500001); |
| 40 | +const child = identity(500002); |
| 41 | +const neighbor = 500003; |
| 42 | +const command = "/opt/codex app-server --listen stdio://"; |
| 43 | +const commandFingerprint = createHash("sha256").update(command).digest("hex"); |
| 44 | + |
| 45 | +function addProcess(pid: number, ppid: number) { |
| 46 | + procfs.files.set( |
| 47 | + `/proc/${pid}/stat`, |
| 48 | + `${pid} (worker) S ${ppid} ${pid}${" 0".repeat(16)} 12345\n`, |
| 49 | + ); |
| 50 | + procfs.files.set(`/proc/${pid}/cmdline`, command.replaceAll(" ", "\0")); |
| 51 | +} |
| 52 | + |
| 53 | +describe("Codex registration procfs boundary", () => { |
| 54 | + let state: Awaited<ReturnType<typeof createOpenClawTestState>>; |
| 55 | + let store: ReturnType< |
| 56 | + typeof createPluginStateSyncKeyedStore<{ |
| 57 | + parent: ReturnType<typeof identity>; |
| 58 | + child: ReturnType<typeof identity> & { commandFingerprint: string }; |
| 59 | + }> |
| 60 | + >; |
| 61 | + let kill: MockInstance<typeof process.kill>; |
| 62 | + |
| 63 | + beforeEach(async () => { |
| 64 | + state = await createOpenClawTestState({ prefix: "codex-registration-procfs-" }); |
| 65 | + store = createPluginStateSyncKeyedStore("codex", { |
| 66 | + namespace: "app-server-processes", |
| 67 | + maxEntries: 512, |
| 68 | + overflowPolicy: "reject-new", |
| 69 | + }); |
| 70 | + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); |
| 71 | + // Synthetic PIDs must never reach the real signal syscall, even on regression. |
| 72 | + kill = vi.spyOn(process, "kill").mockImplementation(() => { |
| 73 | + throw new Error("unexpected signal"); |
| 74 | + }); |
| 75 | + procfs.files.set("/proc/sys/kernel/random/boot_id", bootId); |
| 76 | + addProcess(process.pid, process.ppid); |
| 77 | + addProcess(parent.pid, 1); |
| 78 | + addProcess(child.pid, parent.pid); |
| 79 | + procfs.files.set( |
| 80 | + `/proc/${neighbor}/stat`, |
| 81 | + Object.assign(new Error("unreadable neighbor"), { code: "EACCES" }), |
| 82 | + ); |
| 83 | + }); |
| 84 | + |
| 85 | + afterEach(async () => { |
| 86 | + store.clear(); |
| 87 | + vi.restoreAllMocks(); |
| 88 | + procfs.files.clear(); |
| 89 | + await state.cleanup(); |
| 90 | + }); |
| 91 | + |
| 92 | + it("preserves a live owner's registration despite an unreadable unrelated process", async () => { |
| 93 | + const registration = { parent, child: { ...child, commandFingerprint } }; |
| 94 | + store.register("owned", registration); |
| 95 | + |
| 96 | + await expect( |
| 97 | + Promise.all([ |
| 98 | + prepareCodexAppServerProcessRegistration(), |
| 99 | + prepareCodexAppServerProcessRegistration(), |
| 100 | + ]), |
| 101 | + ).resolves.toHaveLength(2); |
| 102 | + |
| 103 | + expect(store.lookup("owned")).toEqual(registration); |
| 104 | + expect(kill).not.toHaveBeenCalled(); |
| 105 | + }); |
| 106 | + |
| 107 | + it.for(["readable", "permission", "malformed", "deadline", "missing-observer"])( |
| 108 | + "registers a direct child despite an unreadable unrelated process only with usable ownership: %s", |
| 109 | + async (mode, ctx) => { |
| 110 | + addProcess(child.pid, process.pid); |
| 111 | + const stdin = new PassThrough(); |
| 112 | + const stdout = new PassThrough(); |
| 113 | + const stderr = new PassThrough(); |
| 114 | + const spawned = Object.assign(new ChildProcess(), { |
| 115 | + pid: child.pid, |
| 116 | + stdin, |
| 117 | + stdout, |
| 118 | + stderr, |
| 119 | + stdio: [stdin, stdout, stderr, null, null] as [ |
| 120 | + PassThrough, |
| 121 | + PassThrough, |
| 122 | + PassThrough, |
| 123 | + null, |
| 124 | + null, |
| 125 | + ], |
| 126 | + }); |
| 127 | + ctx.onTestFinished(() => { |
| 128 | + stdin.destroy(); |
| 129 | + stdout.destroy(); |
| 130 | + stderr.destroy(); |
| 131 | + spawned.removeAllListeners(); |
| 132 | + }); |
| 133 | + const register = await prepareCodexAppServerProcessRegistration(); |
| 134 | + if (mode === "missing-observer") { |
| 135 | + procfs.files.delete(`/proc/${process.pid}/stat`); |
| 136 | + } else if (mode !== "readable") { |
| 137 | + procfs.files.set( |
| 138 | + `/proc/${child.pid}/stat`, |
| 139 | + mode === "malformed" |
| 140 | + ? "" |
| 141 | + : Object.assign(new Error("child inspection failed"), { |
| 142 | + code: mode === "deadline" ? "ABORT_ERR" : "EACCES", |
| 143 | + }), |
| 144 | + ); |
| 145 | + } |
| 146 | + const registered = register(spawned); |
| 147 | + spawned.emit("spawn"); |
| 148 | + |
| 149 | + if (mode !== "readable") { |
| 150 | + await expect(registered).rejects.toMatchObject({ |
| 151 | + reason: mode === "permission" || mode === "deadline" ? mode : "unavailable", |
| 152 | + }); |
| 153 | + expect(store.entries()).toEqual([]); |
| 154 | + expect(kill).not.toHaveBeenCalled(); |
| 155 | + return; |
| 156 | + } |
| 157 | + await registered; |
| 158 | + |
| 159 | + expect(store.entries().map((entry) => entry.value)).toEqual([ |
| 160 | + { parent: identity(process.pid), child: { ...child, commandFingerprint } }, |
| 161 | + ]); |
| 162 | + expect(kill).not.toHaveBeenCalled(); |
| 163 | + spawned.emit("exit", 0, null); |
| 164 | + expect(store.entries()).toEqual([]); |
| 165 | + }, |
| 166 | + ); |
| 167 | + |
| 168 | + it.for([ |
| 169 | + ["permission", "EACCES"], |
| 170 | + ["unavailable", "EIO"], |
| 171 | + ["deadline", "ABORT_ERR"], |
| 172 | + ["unavailable", "empty"], |
| 173 | + ["unavailable", "group-zero"], |
| 174 | + ["unavailable", "missing-observer"], |
| 175 | + ] as const)( |
| 176 | + "retains registrations when required identity inspection fails: %s/%s", |
| 177 | + async ([reason, fault]) => { |
| 178 | + const registration = { parent, child: { ...child, commandFingerprint } }; |
| 179 | + store.register("owned", registration); |
| 180 | + if (fault === "missing-observer") { |
| 181 | + procfs.files.delete(`/proc/${process.pid}/stat`); |
| 182 | + } else { |
| 183 | + procfs.files.set( |
| 184 | + `/proc/${parent.pid}/stat`, |
| 185 | + fault === "empty" |
| 186 | + ? "" |
| 187 | + : fault === "group-zero" |
| 188 | + ? `${parent.pid} (worker) S 1 0${" 0".repeat(16)} 12345\n` |
| 189 | + : Object.assign(new Error("required inspection failed"), { code: fault }), |
| 190 | + ); |
| 191 | + } |
| 192 | + |
| 193 | + await expect(prepareCodexAppServerProcessRegistration()).rejects.toMatchObject({ reason }); |
| 194 | + expect(store.lookup("owned")).toEqual(registration); |
| 195 | + expect(kill).not.toHaveBeenCalled(); |
| 196 | + }, |
| 197 | + ); |
| 198 | + |
| 199 | + it("keeps full-tree inspection fail-closed with the same unreadable neighbor", async () => { |
| 200 | + await expect(readCodexAppServerProcessSnapshot()).rejects.toMatchObject({ |
| 201 | + reason: "permission", |
| 202 | + }); |
| 203 | + await expect(terminateCodexAppServerOrphan(child)).resolves.toBe(false); |
| 204 | + expect(kill).not.toHaveBeenCalled(); |
| 205 | + }); |
| 206 | + |
| 207 | + it.for(["ENOENT", "ESRCH"])( |
| 208 | + "retires verified disappeared identities only after full containment inspection: %s", |
| 209 | + async (code) => { |
| 210 | + store.register("orphan", { parent, child: { ...child, commandFingerprint } }); |
| 211 | + for (const pid of [parent.pid, child.pid]) { |
| 212 | + procfs.files.set(`/proc/${pid}/stat`, Object.assign(new Error("gone"), { code })); |
| 213 | + } |
| 214 | + // Selected identities are gone, but an unreadable full tree still blocks retirement. |
| 215 | + await expect(prepareCodexAppServerProcessRegistration()).rejects.toThrow( |
| 216 | + "Cannot reap registered Codex process", |
| 217 | + ); |
| 218 | + expect(store.lookup("orphan")).toBeDefined(); |
| 219 | + procfs.files.delete(`/proc/${neighbor}/stat`); |
| 220 | + await prepareCodexAppServerProcessRegistration(); |
| 221 | + expect(store.lookup("orphan")).toBeUndefined(); |
| 222 | + expect(kill).not.toHaveBeenCalled(); |
| 223 | + }, |
| 224 | + ); |
| 225 | +}); |
0 commit comments