Add evidence-backed investigation workflows

This commit is contained in:
morluto
2026-07-12 21:12:18 +00:00
parent 4110a4d717
commit 4ff4c11a00
178 changed files with 26320 additions and 1222 deletions
+236 -252
View File
@@ -1,17 +1,7 @@
import { createHash } from "node:crypto";
import {
lstat,
mkdtemp,
readdir,
readFile,
readlink,
realpath,
rm,
} from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { mkdtemp, realpath, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { join } from "node:path";
import { spawn, type IPty } from "node-pty";
import type {
FileState,
@@ -25,8 +15,14 @@ import { authorizeProcessScenario } from "../domain/processCapture.js";
import { err, ok, type Result } from "../domain/result.js";
import { AnalysisError } from "../domain/errors.js";
import { startLoopbackReplay, type LoopbackReplay } from "./LoopbackReplay.js";
const execFileAsync = promisify(execFile);
import { cleanupOwnedProcessGroup } from "./ProcessOwnership.js";
import { startProcessSampler } from "./ProcessSampling.js";
import { snapshotRoots, type SnapshotResult } from "./FilesystemSnapshot.js";
import {
normalizeProcessSamples,
normalizeProcessText,
redactProtocolEvents,
} from "./ProcessNormalization.js";
const isWithin = (candidate: string, root: string): boolean =>
candidate === root ||
@@ -66,6 +62,11 @@ export class ProcessCaptureError extends AnalysisError {
readonly _tag = "ProcessCaptureError";
}
const assertNotCancelled = (signal: AbortSignal | undefined): void => {
if (signal?.aborted === true)
throw new ProcessCaptureError("process capture was cancelled");
};
/** Runtime availability of the native PTY adapter on this host. */
export type ProcessCaptureCapability =
| { readonly available: true; readonly backend: "node-pty" }
@@ -103,129 +104,17 @@ export const probeProcessCaptureCapability =
}
};
interface SnapshotResult {
readonly files: readonly FileState[];
readonly truncated: boolean;
}
const hashFile = async (
path: string,
maxBytes: number,
): Promise<string | null> => {
const value = await readFile(path);
if (value.byteLength > maxBytes) return null;
return createHash("sha256").update(value).digest("hex");
};
const snapshotRoots = async (
scenario: ProcessScenario,
): Promise<SnapshotResult> => {
const entries: FileState[] = [];
let remainingBytes = scenario.limits.file_bytes;
let truncated = false;
const visit = async (root: string, path: string): Promise<void> => {
if (entries.length >= scenario.limits.files) {
truncated = true;
return;
}
let stats;
try {
stats = await lstat(path);
} catch (error: unknown) {
if (error instanceof Error && "code" in error && error.code === "ENOENT")
return;
throw error;
}
const relativePath = relative(root, path) || ".";
if (stats.isSymbolicLink()) {
entries.push({
path: `${root}:${relativePath}`,
type: "symlink",
mode: stats.mode,
size: stats.size,
sha256: null,
symlink_target: await readlink(path),
});
return;
}
if (stats.isFile()) {
const allowedBytes = Math.max(
0,
Math.min(remainingBytes, scenario.limits.file_bytes),
);
const sha256 =
allowedBytes >= stats.size ? await hashFile(path, allowedBytes) : null;
remainingBytes -= sha256 === null ? 0 : stats.size;
if (sha256 === null) truncated = true;
entries.push({
path: `${root}:${relativePath}`,
type: "file",
mode: stats.mode,
size: stats.size,
sha256,
symlink_target: null,
});
return;
}
const type = stats.isDirectory() ? "directory" : "other";
entries.push({
path: `${root}:${relativePath}`,
type,
mode: stats.mode,
size: stats.size,
sha256: null,
symlink_target: null,
});
if (type !== "directory") return;
for (const child of (await readdir(path)).sort())
await visit(root, join(path, child));
};
for (const root of scenario.filesystem_roots) await visit(root, root);
return { files: entries, truncated };
};
const sampleProcesses = async (
rootPid: number,
elapsedMs: number,
limit: number,
): Promise<readonly ProcessSample[]> => {
if (process.platform === "win32") return [];
const { stdout } = await execFileAsync("ps", ["-axo", "pid=,ppid=,command="]);
const rows = stdout
.split("\n")
.map((line) => /\s*(\d+)\s+(\d+)\s+(.*)/.exec(line))
.filter((match): match is RegExpExecArray => match !== null)
.map((match) => ({
pid: Number(match[1]),
parent_pid: Number(match[2]),
command: match[3] ?? "",
}));
const owned = new Set([rootPid]);
let changed = true;
while (changed) {
changed = false;
for (const row of rows) {
if (owned.has(row.parent_pid) && !owned.has(row.pid)) {
owned.add(row.pid);
changed = true;
}
}
}
return rows
.filter((row) => owned.has(row.pid))
.slice(0, limit)
.map((row) => ({ at_ms: elapsedMs, ...row }));
};
const makeEnvironment = (
scenario: ProcessScenario,
home: string,
replay: LoopbackReplay,
runId: string,
): Record<string, string> => {
const environment: Record<string, string> = {
...scenario.environment,
HOME: home,
TERM: "xterm-256color",
...scenario.environment,
REA_PROCESS_RUN_ID: runId,
};
for (const name of scenario.inherit_environment) {
const value = process.env[name];
@@ -236,29 +125,6 @@ const makeEnvironment = (
return environment;
};
const normalizeTerminalData = (
value: string,
scenario: ProcessScenario,
temporaryRoot: string,
pid: number,
): string => {
let normalized = value;
for (const alias of scenario.secret_aliases) {
const secret = scenario.environment[alias];
if (secret !== undefined && secret.length > 0)
normalized = normalized.replaceAll(secret, "<redacted>");
}
if (scenario.normalization.paths)
normalized = normalized.replaceAll(temporaryRoot, "<temporary-root>");
if (scenario.normalization.pids)
normalized = normalized.replaceAll(String(pid), "<pid>");
if (scenario.normalization.ports)
normalized = normalized.replaceAll(/(?<=[:=])\d{2,5}\b/g, "<port>");
for (const pattern of scenario.normalization.patterns)
normalized = normalized.replaceAll(pattern.pattern, pattern.replacement);
return normalized;
};
const scheduleScenarioEvents = (
scenario: ProcessScenario,
getTerminal: () => IPty | undefined,
@@ -276,6 +142,24 @@ const scheduleScenarioEvents = (
}
};
const startScenarioEvents = (
scenario: ProcessScenario,
getTerminal: () => IPty | undefined,
timers: Set<NodeJS.Timeout>,
): (() => void) => {
let started = false;
return () => {
if (started) return;
started = true;
scheduleScenarioEvents(scenario, getTerminal, timers);
};
};
const eventsRequireReadiness = (scenario: ProcessScenario): boolean =>
scenario.events.some(
(event) => event.type === "input" || event.type === "resize",
);
interface TerminalExitOptions {
readonly terminal: IPty;
readonly scenario: ProcessScenario;
@@ -287,7 +171,11 @@ interface TerminalExitOptions {
interface CaptureResultOptions {
readonly frames: readonly TerminalFrame[];
readonly exit: { readonly exitCode: number; readonly signal?: number };
readonly exit: {
readonly exitCode: number;
readonly signal?: number;
readonly reason: "exited" | "timeout" | "idle_timeout";
};
readonly samples: readonly ProcessSample[];
readonly replay: LoopbackReplay;
readonly before: SnapshotResult;
@@ -297,56 +185,40 @@ interface CaptureResultOptions {
readonly rootPid: number;
}
const normalizeSamples = (
samples: readonly ProcessSample[],
scenario: ProcessScenario,
rootPid: number,
): readonly ProcessSample[] => {
const identifiers = [
rootPid,
...samples.flatMap((sample) => [sample.pid, sample.parent_pid]),
];
const mapping = new Map<number, number>();
for (const identifier of identifiers)
if (identifier > 0 && !mapping.has(identifier))
mapping.set(identifier, mapping.size + 1);
return samples.map((sample) => ({
at_ms:
Math.floor(sample.at_ms / scenario.normalization.time_bucket_ms) *
scenario.normalization.time_bucket_ms,
pid: mapping.get(sample.pid) ?? 1,
parent_pid: mapping.get(sample.parent_pid) ?? 0,
command: normalizeTerminalData(
sample.command,
scenario,
"<no-temporary-root>",
rootPid,
),
}));
const classifyFilesystemEffects = (
before: readonly FileState[],
after: readonly FileState[],
): ProcessCapture["filesystem_effects"] => {
const beforeByPath = new Map(before.map((file) => [file.path, file]));
const afterByPath = new Map(after.map((file) => [file.path, file]));
const paths = [
...new Set([...beforeByPath.keys(), ...afterByPath.keys()]),
].sort();
return paths.map((path) => {
const beforeFile = beforeByPath.get(path) ?? null;
const afterFile = afterByPath.get(path) ?? null;
const status =
beforeFile === null
? "created"
: afterFile === null
? "deleted"
: JSON.stringify(beforeFile) === JSON.stringify(afterFile)
? "unchanged"
: "modified";
return { path, status, before: beforeFile, after: afterFile };
});
};
const redactProtocolEvents = (
events: readonly ProcessCapture["protocol_events"][number][],
scenario: ProcessScenario,
): readonly ProcessCapture["protocol_events"][number][] =>
events.map((event) => ({
...event,
data: normalizeTerminalData(
event.data,
scenario,
"<no-temporary-root>",
-1,
),
}));
const buildCaptureResult = (options: CaptureResultOptions): ProcessCapture => ({
schema_version: 1,
schema_version: 2,
normalization: options.scenario.normalization,
frames: options.frames,
exit: {
code: options.exit.exitCode < 0 ? null : options.exit.exitCode,
signal: options.exit.signal ?? null,
reason: options.exit.reason,
},
process_samples: normalizeSamples(
process_samples: normalizeProcessSamples(
options.samples,
options.scenario,
options.rootPid,
@@ -357,12 +229,30 @@ const buildCaptureResult = (options: CaptureResultOptions): ProcessCapture => ({
),
files_before: options.before.files,
files_after: options.after.files,
filesystem_effects: classifyFilesystemEffects(
options.before.files,
options.after.files,
),
truncated: options.truncated,
limitations: [
"Process trees are sampled and may omit short-lived descendants.",
"Filesystem observations are before/after snapshots, not syscall traces.",
"The harness does not enforce external network isolation.",
],
residual_unknowns: [
{
scope: "process",
reason: "Process trees are sampled and may omit short-lived descendants.",
},
{
scope: "network",
reason: "External network isolation is not enforced by this adapter.",
},
],
cleanup: {
owned_process_group: "verified",
temporary_root: "removed",
},
});
const awaitTerminalExit = async ({
@@ -372,21 +262,117 @@ const awaitTerminalExit = async ({
lastOutput,
signal,
timers,
}: TerminalExitOptions): Promise<{ exitCode: number; signal?: number }> =>
}: TerminalExitOptions): Promise<{
exitCode: number;
signal?: number;
reason: "exited" | "timeout" | "idle_timeout" | "cancelled";
}> =>
new Promise((resolveExit) => {
terminal.onExit(resolveExit);
let reason: "exited" | "timeout" | "idle_timeout" | "cancelled" = "exited";
terminal.onExit((exit) => resolveExit({ ...exit, reason }));
const timeout = setInterval(() => {
if (
Date.now() - started >= scenario.timeout_ms ||
Date.now() - lastOutput() >= scenario.idle_timeout_ms ||
signal?.aborted === true
) {
if (signal?.aborted === true) {
reason = "cancelled";
terminal.kill("SIGKILL");
} else if (Date.now() - started >= scenario.timeout_ms) {
reason = "timeout";
terminal.kill("SIGKILL");
} else if (Date.now() - lastOutput() >= scenario.idle_timeout_ms) {
reason = "idle_timeout";
terminal.kill("SIGKILL");
}
}, 20);
timers.add(timeout);
});
const releaseProcessResources = async (options: {
readonly timers: ReadonlySet<NodeJS.Timeout>;
readonly replay: LoopbackReplay | undefined;
readonly terminal: IPty | undefined;
readonly runId: string;
readonly temporaryRoot: string;
}): Promise<string | undefined> => {
for (const timer of options.timers) clearTimeout(timer);
let failure: string | undefined;
try {
await options.replay?.close();
} catch {
failure = "loopback replay cleanup failed";
}
if (options.terminal !== undefined && process.platform !== "win32") {
const cleaned = await cleanupOwnedProcessGroup({
runId: options.runId,
leaderPid: options.terminal.pid,
processGroupId: options.terminal.pid,
});
if (!cleaned.cleaned) failure ??= cleaned.reason;
}
try {
await rm(options.temporaryRoot, { recursive: true, force: true });
} catch {
failure ??= "temporary process root cleanup failed";
}
return failure;
};
const captureTerminalFrames = (options: {
readonly terminal: IPty;
readonly scenario: ProcessScenario;
readonly frames: TerminalFrame[];
readonly started: number;
readonly temporaryRoot: string;
readonly onOutput: () => void;
readonly onFirstOutput: () => void;
}): (() => boolean) => {
let outputBytes = 0;
let truncated = false;
options.terminal.onData((data) => {
options.onFirstOutput();
options.onOutput();
const bytes = Buffer.byteLength(data);
if (
options.frames.length >= options.scenario.limits.frames ||
outputBytes + bytes > options.scenario.limits.output_bytes
) {
truncated = true;
return;
}
outputBytes += bytes;
options.frames.push({
sequence: options.frames.length,
at_ms:
Math.floor(
(Date.now() - options.started) /
options.scenario.normalization.time_bucket_ms,
) * options.scenario.normalization.time_bucket_ms,
data: normalizeProcessText(
data,
options.scenario,
options.temporaryRoot,
options.terminal.pid,
),
});
});
return () => truncated;
};
const resolveProcessResult = (
capture: ProcessCapture | undefined,
executionFailure: unknown,
cleanupFailure: string | undefined,
): ProcessCapture => {
if (cleanupFailure !== undefined)
throw new ProcessCaptureError(cleanupFailure);
if (executionFailure instanceof ProcessCaptureError) throw executionFailure;
if (executionFailure !== undefined)
throw new ProcessCaptureError("process capture failed", {
cause: executionFailure,
});
if (capture === undefined)
throw new ProcessCaptureError("process capture produced no result");
return capture;
};
/** Execute one authorized scenario and return bounded observations. */
const runProcessScenario = async (
scenario: ProcessScenario,
@@ -396,68 +382,54 @@ const runProcessScenario = async (
const decision = authorizeProcessScenario(scenario, policy);
if (!decision.allowed) throw new ProcessCaptureError(decision.reason);
await assertRealPathAuthority(scenario, policy);
if (signal?.aborted === true)
throw new ProcessCaptureError("process capture was cancelled");
assertNotCancelled(signal);
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-process-"));
const runId = randomUUID();
const home = join(temporaryRoot, "home");
await import("node:fs/promises").then(({ mkdir }) => mkdir(home));
const before = await snapshotRoots(scenario);
const frames: TerminalFrame[] = [];
const samples: ProcessSample[] = [];
let outputBytes = 0;
let truncated = before.truncated;
let terminal: IPty | undefined;
let replay: LoopbackReplay | undefined;
const started = Date.now();
let lastOutput = started;
let started = 0;
let lastOutput = 0;
const timers = new Set<NodeJS.Timeout>();
let capture: ProcessCapture | undefined;
let executionFailure: unknown;
let framesTruncated = (): boolean => false;
let stopSampler: () => Promise<void> = async () => undefined;
try {
replay = await startLoopbackReplay(scenario);
started = Date.now();
lastOutput = started;
terminal = spawn(scenario.executable, [...scenario.arguments], {
cwd: scenario.working_directory,
env: makeEnvironment(scenario, home, replay),
env: makeEnvironment(scenario, home, replay, runId),
cols: 80,
rows: 24,
name: "xterm-256color",
});
terminal.onData((data) => {
lastOutput = Date.now();
const bytes = Buffer.byteLength(data);
if (
frames.length >= scenario.limits.frames ||
outputBytes + bytes > scenario.limits.output_bytes
) {
truncated = true;
return;
}
outputBytes += bytes;
frames.push({
sequence: frames.length,
at_ms:
Math.floor(
(Date.now() - started) / scenario.normalization.time_bucket_ms,
) * scenario.normalization.time_bucket_ms,
data: normalizeTerminalData(
data,
scenario,
temporaryRoot,
terminal?.pid ?? -1,
),
});
const startEvents = startScenarioEvents(scenario, () => terminal, timers);
if (!eventsRequireReadiness(scenario)) startEvents();
framesTruncated = captureTerminalFrames({
terminal,
scenario,
frames,
started,
temporaryRoot,
onOutput: () => (lastOutput = Date.now()),
onFirstOutput: startEvents,
});
scheduleScenarioEvents(scenario, () => terminal, timers);
const sampler = setInterval(() => {
void sampleProcesses(
terminal?.pid ?? -1,
Date.now() - started,
scenario.limits.processes - samples.length,
)
.then((values) => samples.push(...values))
.catch(() => undefined);
}, 50);
timers.add(sampler);
stopSampler = startProcessSampler(
terminal.pid,
started,
scenario.limits.processes,
samples,
);
const exit = await awaitTerminalExit({
terminal,
scenario,
@@ -466,15 +438,22 @@ const runProcessScenario = async (
signal,
timers,
});
const exitReason = exit.reason;
await stopSampler();
if (exitReason === "cancelled")
throw new ProcessCaptureError("process capture was cancelled");
await new Promise((resolveSettle) =>
setTimeout(resolveSettle, scenario.settle_ms),
);
const after = await snapshotRoots(scenario);
truncated ||=
after.truncated || samples.length >= scenario.limits.processes;
return buildCaptureResult({
after.truncated ||
replay.truncated ||
framesTruncated() ||
samples.length >= scenario.limits.processes;
capture = buildCaptureResult({
frames,
exit,
exit: { ...exit, reason: exitReason },
samples,
replay,
before,
@@ -485,12 +464,17 @@ const runProcessScenario = async (
});
} catch (cause: unknown) {
terminal?.kill("SIGKILL");
throw new ProcessCaptureError("process capture failed", { cause });
} finally {
for (const timer of timers) clearTimeout(timer);
await replay?.close();
await rm(temporaryRoot, { recursive: true, force: true });
executionFailure = cause;
}
await stopSampler();
const cleanupFailure = await releaseProcessResources({
timers,
replay,
terminal,
runId,
temporaryRoot,
});
return resolveProcessResult(capture, executionFailure, cleanupFailure);
};
/** Execute one scenario through a typed expected-failure channel. */