Files
rea/src/process/ProcessOwnership.ts
T

262 lines
8.7 KiB
TypeScript
Raw Normal View History

2026-07-12 21:12:18 +00:00
import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
/** Identity proof required before REA may signal an owned process group. */
2026-07-12 21:12:18 +00:00
export interface OwnedProcessGroup {
readonly runId: string;
readonly leaderPid: number;
readonly processGroupId: number;
/** Expected launcher identity, checked only while the leader exists. */
readonly expectedCommand?: string;
/** Expected launcher parent, checked only while the leader exists. */
readonly expectedParentPid?: number;
2026-07-12 21:12:18 +00:00
}
/** One operating-system observation of a process-group member. */
2026-07-12 21:12:18 +00:00
interface ProcessGroupMember {
readonly pid: number;
readonly parentPid: number;
readonly processGroupId: number;
2026-07-14 21:16:53 +00:00
readonly state: string;
2026-07-12 21:12:18 +00:00
readonly command: string;
}
2026-07-13 17:15:22 +08:00
/** Narrow operating-system seam used to inspect and signal process groups. */
2026-07-12 21:12:18 +00:00
export interface ProcessOwnershipHost {
listMembers(processGroupId: number): Promise<
readonly {
readonly pid: number;
readonly parentPid: number;
readonly processGroupId: number;
readonly state: string;
readonly command: string;
}[]
>;
2026-07-12 21:12:18 +00:00
environment(pid: number): Promise<Readonly<Record<string, string>>>;
signalGroup(processGroupId: number, signal: NodeJS.Signals): void;
}
/** Per-member reason that token-verified cleanup failed closed. */
interface ProcessOwnershipValidationFailure {
2026-07-14 21:16:53 +00:00
readonly pid: number;
readonly reason: "environment-unreadable" | "run-token-mismatch";
}
/** Cleanup outcome with per-member diagnostics when ownership is uncertain. */
2026-07-12 21:12:18 +00:00
export type ProcessCleanupResult =
| { readonly cleaned: true; readonly signaled: boolean }
2026-07-14 21:16:53 +00:00
| {
readonly cleaned: false;
readonly reason: string;
readonly failures?: readonly {
readonly pid: number;
readonly reason: "environment-unreadable" | "run-token-mismatch";
}[];
2026-07-14 21:16:53 +00:00
};
2026-07-12 21:12:18 +00:00
/** Token-verified liveness result used by post-root-exit settlement. */
export type ProcessGroupObservation =
| { readonly state: "empty" }
| { readonly state: "alive" }
| { readonly state: "unverifiable"; readonly reason: string };
/** Select the PTY root group and groups led by an observed captured process. */
export const selectCapturedProcessGroupIds = (
rootPid: number,
samples: readonly {
readonly pid: number;
readonly process_group_id: number | null;
}[],
): readonly number[] => {
const processGroupIds = new Set<number>([rootPid]);
for (const sample of samples) {
// A sampled member may transiently inherit an unrelated group. POSIX group
// leaders have pid === pgid, so only that observation establishes that the
// group leader itself belonged to the captured tree. Token checks below
// remain the final authority immediately before observation or signaling.
if (sample.pid === sample.process_group_id) processGroupIds.add(sample.pid);
}
return [...processGroupIds];
};
2026-07-14 14:39:02 +08:00
/** Parse the NUL-delimited Linux process environment without nameless keys. */
export const parseProcessEnvironment = (
value: string,
): Readonly<Record<string, string>> =>
2026-07-12 21:12:18 +00:00
Object.fromEntries(
value
.split("\0")
2026-07-14 14:39:02 +08:00
.filter((entry) => entry.indexOf("=") > 0)
2026-07-12 21:12:18 +00:00
.map((entry) => {
const separator = entry.indexOf("=");
return [entry.slice(0, separator), entry.slice(separator + 1)];
}),
);
const systemHost: ProcessOwnershipHost = {
async listMembers(processGroupId) {
if (process.platform === "win32") return [];
const { stdout } = await execFileAsync("ps", [
"-axo",
2026-07-14 21:16:53 +00:00
"pid=,ppid=,pgid=,stat=,command=",
2026-07-12 21:12:18 +00:00
]);
return stdout
.split("\n")
2026-07-14 21:16:53 +00:00
.map((line) => /\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)/u.exec(line))
2026-07-12 21:12:18 +00:00
.filter((match): match is RegExpExecArray => match !== null)
.map((match) => ({
pid: Number(match[1]),
parentPid: Number(match[2]),
processGroupId: Number(match[3]),
2026-07-14 21:16:53 +00:00
state: match[4] ?? "",
command: match[5] ?? "",
2026-07-12 21:12:18 +00:00
}))
.filter((member) => member.processGroupId === processGroupId);
},
async environment(pid) {
if (process.platform === "linux") {
2026-07-14 14:39:02 +08:00
return parseProcessEnvironment(
await readFile(`/proc/${pid}/environ`, "utf8"),
);
2026-07-12 21:12:18 +00:00
}
const { stdout } = await execFileAsync("ps", ["eww", "-p", String(pid)]);
const environment: Record<string, string> = {};
for (const match of stdout.matchAll(
/(?:^|\s)([A-Za-z_][A-Za-z0-9_]*)=([^\s]*)/gu,
))
environment[match[1]!] = match[2] ?? "";
return environment;
},
signalGroup(processGroupId, signal) {
process.kill(-processGroupId, signal);
},
};
/** Read the capture run token currently exposed by one live process. */
export const readProcessRunId = async (
pid: number,
host: ProcessOwnershipHost = systemHost,
): Promise<string | undefined> =>
(await host.environment(pid)).REA_PROCESS_RUN_ID;
2026-07-13 17:15:22 +08:00
/**
* Verify run-token ownership before signaling a POSIX process group.
*
* Process IDs and group IDs can be reused. REA therefore re-reads every live
* member's environment immediately before signaling and fails closed if any
* member cannot be inspected or lacks the per-capture run token.
*/
2026-07-12 21:12:18 +00:00
export const cleanupOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessCleanupResult> => {
let members: readonly ProcessGroupMember[];
try {
members = await host.listMembers(ownership.processGroupId);
} catch {
return { cleaned: false, reason: "process group could not be inspected" };
}
2026-07-14 21:16:53 +00:00
const liveMembers = liveProcessGroupMembers(members);
if (liveMembers.length === 0) return { cleaned: true, signaled: false };
const leader = liveMembers.find(
(member) => member.pid === ownership.leaderPid,
);
if (leader !== undefined) {
if (
ownership.expectedParentPid !== undefined &&
leader.parentPid !== ownership.expectedParentPid
)
return {
cleaned: false,
reason: "owned launcher parent identity did not match",
};
if (
ownership.expectedCommand !== undefined &&
!commandMatches(leader.command, ownership.expectedCommand)
)
return {
cleaned: false,
reason: "owned launcher command identity did not match",
};
}
2026-07-14 21:16:53 +00:00
const failures: ProcessOwnershipValidationFailure[] = [];
for (const member of liveMembers) {
2026-07-12 21:12:18 +00:00
try {
2026-07-14 21:16:53 +00:00
const environment = await host.environment(member.pid);
if (environment.REA_PROCESS_RUN_ID !== ownership.runId)
failures.push({ pid: member.pid, reason: "run-token-mismatch" });
2026-07-12 21:12:18 +00:00
} catch {
2026-07-14 21:16:53 +00:00
failures.push({ pid: member.pid, reason: "environment-unreadable" });
2026-07-12 21:12:18 +00:00
}
}
2026-07-14 21:16:53 +00:00
if (failures.length > 0)
return {
cleaned: false,
reason: failures.some(({ reason }) => reason === "run-token-mismatch")
? "process group contains an unowned or PID-reused process"
: "process ownership could not be revalidated",
failures,
};
2026-07-12 21:12:18 +00:00
try {
host.signalGroup(ownership.processGroupId, "SIGKILL");
} catch (cause: unknown) {
const code =
cause instanceof Error && "code" in cause ? cause.code : undefined;
if (code !== "ESRCH")
return { cleaned: false, reason: "owned process group signal failed" };
}
return { cleaned: true, signaled: true };
};
/** Observe one group without signaling it, failing closed on identity doubt. */
export const observeOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessGroupObservation> => {
let members: readonly ProcessGroupMember[];
try {
members = await host.listMembers(ownership.processGroupId);
} catch {
return {
state: "unverifiable",
reason: "process group could not be inspected",
};
}
2026-07-14 21:16:53 +00:00
const liveMembers = liveProcessGroupMembers(members);
if (liveMembers.length === 0) return { state: "empty" };
for (const member of liveMembers) {
try {
if (
(await host.environment(member.pid)).REA_PROCESS_RUN_ID !==
ownership.runId
)
return {
state: "unverifiable",
reason: "process ownership did not match",
};
} catch {
return {
state: "unverifiable",
reason: "process ownership could not be revalidated",
};
}
}
return { state: "alive" };
};
2026-07-14 21:16:53 +00:00
const liveProcessGroupMembers = (
members: readonly ProcessGroupMember[],
): readonly ProcessGroupMember[] =>
members.filter(({ state }) => !state.startsWith("Z"));
const commandMatches = (actual: string, expected: string): boolean => {
const normalizedActual = actual.trim();
const normalizedExpected = expected.trim();
return (
normalizedActual === normalizedExpected ||
normalizedActual.startsWith(`${normalizedExpected} `)
);
};