mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-09-05 00:56:23 +00:00
fix(cli): signal only processes the OS says own the port (#3307)
* fix(cli): signal only processes the OS says own the port `/__hyperframes_config` is unauthenticated and the PID it reports is what `--stop` and `--kill-all` send signals to, so any local process answering on a scanned port could name an arbitrary PID and have the CLI kill it. Reproduced with a twenty-line HTTP server on a scanned port self-reporting an unrelated PID: before this, `--kill-all` killed that process; after it, the process survives and only the real listener is stopped. The listening PID now comes from the OS — `lsof`, and `netstat` on Windows, where the lookup was previously unavailable and the self-reported value was taken on trust. The response's own PID is used only where the OS lookup fails, which is also the only case where it is unfalsifiable. Orphan cleanup moves to the last step before a launch. It reaches outside the process and kills other people's PIDs, so it must not run for an invocation that turns out to be a validation error and never starts anything. * fix(cli): fail closed when the OS cannot confirm who owns a port Review follow-up. The two halves of this change picked opposite directions for the same condition. `isProcessDescendant` fails closed by design; `activeServerOnPort` fell back to the self-reported PID whenever the OS lookup came back empty — and that is not only "unsupported platform". `lsof` may be absent (the default on many slim images), may time out, or may not see a socket owned by another user. On such a machine every scanned port silently reverted to pre-change behaviour, with nothing said. Provenance is now part of the type rather than a convention: `ActiveServer` carries `pidSource`, so a caller cannot mistake a self-report for the kernel's answer. `--kill-all` requires `"os"` and skips the rest, naming the ports it left alone and why. That is the deliberate trade — a blind sweep of a port range has no evidence beyond an unauthenticated response, so an unconfirmed PID must not be signalled. Managed previews are unaffected: they stop through their session record, which proves ownership by process birth identity. The fallback branch — the one with the security consequence — now has the coverage it lacked, via an injected lookup matching the seam `testPortOnAllHosts` and `isProcessDescendant` already use, including a live process that survives because nothing confirmed it owns the socket. Also state that `killProcessTree` honours `signal` on POSIX only: Windows always passes `/F`, deliberately, since taskkill without it posts WM_CLOSE that a console process may ignore. The caller-side comment claiming Windows cleanup is a no-op described the code before this change and now says the opposite.
This commit is contained in:
@@ -1,13 +1,52 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { spawn } from "node:child_process";
|
||||
import { killProcessTree, killOrphanedProcesses } from "./orphanCleanup.js";
|
||||
import {
|
||||
isProcessDescendant,
|
||||
killProcessTree,
|
||||
killOrphanedProcesses,
|
||||
processIdentity,
|
||||
windowsProcessTreeKillArgs,
|
||||
} from "./orphanCleanup.js";
|
||||
|
||||
const IS_UNIX = process.platform !== "win32";
|
||||
|
||||
describe("Windows process-tree cleanup", () => {
|
||||
it("uses taskkill recursively and forcefully for the owned PID", () => {
|
||||
expect(windowsProcessTreeKillArgs(4321)).toEqual(["/PID", "4321", "/T", "/F"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("process-tree ownership", () => {
|
||||
it("captures a stable birth token for the current process", () => {
|
||||
const first = processIdentity(process.pid);
|
||||
expect(first).toMatch(/^(?:linux|posix|windows):/);
|
||||
expect(processIdentity(process.pid)).toBe(first);
|
||||
expect(processIdentity(-1)).toBeNull();
|
||||
});
|
||||
|
||||
it("proves ancestry through every intermediate wrapper", () => {
|
||||
const parents = new Map([
|
||||
[400, 300],
|
||||
[300, 200],
|
||||
[200, 1],
|
||||
]);
|
||||
|
||||
expect(isProcessDescendant(400, 200, (pid) => parents.get(pid) ?? null)).toBe(true);
|
||||
expect(isProcessDescendant(400, 999, (pid) => parents.get(pid) ?? null)).toBe(false);
|
||||
});
|
||||
|
||||
it("fails closed on missing or cyclic process metadata", () => {
|
||||
expect(isProcessDescendant(400, 200, () => null)).toBe(false);
|
||||
expect(isProcessDescendant(400, 200, (pid) => (pid === 400 ? 300 : 400))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!IS_UNIX)("killProcessTree", () => {
|
||||
it("kills a process and all its children", async () => {
|
||||
// Spawn a parent that spawns two sleeping children
|
||||
const parent = spawn("bash", ["-c", "sleep 60 & sleep 60 & wait"], { stdio: "ignore" });
|
||||
const parent = spawn("bash", ["-c", "sleep 60 & sleep 60 & wait"], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
// Let children spawn
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
|
||||
@@ -27,7 +66,9 @@ describe.skipIf(!IS_UNIX)("killProcessTree", () => {
|
||||
|
||||
it("escalates to SIGKILL after grace period", async () => {
|
||||
// Spawn a process that traps SIGTERM
|
||||
const proc = spawn("bash", ["-c", "trap '' TERM; sleep 60"], { stdio: "ignore" });
|
||||
const proc = spawn("bash", ["-c", "trap '' TERM; sleep 60"], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
|
||||
const exitPromise = new Promise<void>((resolve) => proc.on("close", resolve));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { execSync } from "node:child_process";
|
||||
import { execFileSync, execSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
/**
|
||||
* Find and kill orphaned Chrome processes from previous crashed sessions.
|
||||
@@ -34,11 +35,27 @@ export function killOrphanedProcesses(): number {
|
||||
* depth-first so children are killed before parents, preventing
|
||||
* re-adoption races.
|
||||
*
|
||||
* No-op on Windows — process groups are managed differently and
|
||||
* the pgrep/ps utilities are not available.
|
||||
* Windows uses taskkill's tree mode because pgrep/ps are unavailable there.
|
||||
*
|
||||
* `signal` is honoured on POSIX only. The Windows path always passes `/F`, so a
|
||||
* caller asking for SIGTERM gets a forced tree kill with no grace period, while
|
||||
* the same call on POSIX gets 500 ms to flush and exit. That is deliberate —
|
||||
* `taskkill` without `/F` posts WM_CLOSE, which a console process is free to
|
||||
* ignore, and leaving a preview server alive is the worse failure here. Do not
|
||||
* pass SIGTERM expecting a clean shutdown on Windows.
|
||||
*/
|
||||
export function killProcessTree(pid: number, signal: NodeJS.Signals = "SIGTERM"): void {
|
||||
if (process.platform === "win32") return;
|
||||
if (process.platform === "win32") {
|
||||
try {
|
||||
execFileSync("taskkill", windowsProcessTreeKillArgs(pid), {
|
||||
stdio: "ignore",
|
||||
timeout: 5000,
|
||||
});
|
||||
} catch {
|
||||
// Process already exited or taskkill could not inspect it.
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const descendants = getDescendants(pid);
|
||||
const allPids = [...descendants.reverse(), pid];
|
||||
@@ -65,10 +82,111 @@ export function killProcessTree(pid: number, signal: NodeJS.Signals = "SIGTERM")
|
||||
}
|
||||
}
|
||||
|
||||
export function windowsProcessTreeKillArgs(pid: number): string[] {
|
||||
return ["/PID", String(pid), "/T", "/F"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a process birth token suitable for detecting PID reuse. The token is
|
||||
* diagnostic state only: callers must still prove the live server is a
|
||||
* descendant before treating a saved wrapper as the owned process-tree root.
|
||||
*/
|
||||
export function processIdentity(pid: number): string | null {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return null;
|
||||
try {
|
||||
if (process.platform === "win32") {
|
||||
const created = execFileSync(
|
||||
"powershell.exe",
|
||||
[
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
`(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').CreationDate.ToFileTimeUtc()`,
|
||||
],
|
||||
{ encoding: "utf8", timeout: 2000 },
|
||||
).trim();
|
||||
return created ? `windows:${created}` : null;
|
||||
}
|
||||
|
||||
if (process.platform === "linux") {
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
||||
const fields = stat
|
||||
.slice(stat.lastIndexOf(") ") + 2)
|
||||
.trim()
|
||||
.split(/\s+/);
|
||||
const startTicks = fields[19]; // field 22 overall; fields starts at process state (3)
|
||||
return startTicks ? `linux:${startTicks}` : null;
|
||||
}
|
||||
|
||||
const started = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
||||
encoding: "utf8",
|
||||
timeout: 2000,
|
||||
}).trim();
|
||||
return started ? `posix:${started}` : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
type ParentPidLookup = (pid: number) => number | null;
|
||||
|
||||
function processParentPid(pid: number): number | null {
|
||||
try {
|
||||
const output =
|
||||
process.platform === "win32"
|
||||
? execFileSync(
|
||||
"powershell.exe",
|
||||
[
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-Command",
|
||||
`(Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}').ParentProcessId`,
|
||||
],
|
||||
{ encoding: "utf8", timeout: 2000 },
|
||||
)
|
||||
: execFileSync("ps", ["-o", "ppid=", "-p", String(pid)], {
|
||||
encoding: "utf8",
|
||||
timeout: 2000,
|
||||
});
|
||||
const parentPid = Number(output.trim());
|
||||
return Number.isInteger(parentPid) && parentPid > 0 ? parentPid : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prove that `childPid` currently belongs to the process tree rooted at
|
||||
* `ancestorPid`. The walk fails closed on missing, invalid, or cyclic process
|
||||
* metadata so a stale saved PID can never authorize terminating a new process.
|
||||
*/
|
||||
export function isProcessDescendant(
|
||||
childPid: number,
|
||||
ancestorPid: number,
|
||||
parentPid: ParentPidLookup = processParentPid,
|
||||
): boolean {
|
||||
if (childPid <= 0 || ancestorPid <= 0 || childPid === ancestorPid) return false;
|
||||
|
||||
const visited = new Set<number>();
|
||||
let current = childPid;
|
||||
for (let depth = 0; depth < 64; depth++) {
|
||||
if (visited.has(current)) return false;
|
||||
visited.add(current);
|
||||
const parent = parentPid(current);
|
||||
if (parent === ancestorPid) return true;
|
||||
if (parent === null || parent <= 1) return false;
|
||||
current = parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function getDescendants(pid: number): number[] {
|
||||
let children: number[];
|
||||
try {
|
||||
const raw = execSync(`pgrep -P ${pid}`, { encoding: "utf-8", timeout: 2000 }).trim();
|
||||
const raw = execSync(`pgrep -P ${pid}`, {
|
||||
encoding: "utf-8",
|
||||
timeout: 2000,
|
||||
}).trim();
|
||||
if (!raw) return [];
|
||||
children = raw
|
||||
.split("\n")
|
||||
|
||||
Reference in New Issue
Block a user