fix: harden PTY events and configured roots

This commit is contained in:
N0zoM1z0
2026-07-14 15:21:39 +08:00
parent 2575b30dfc
commit 31b40f39e4
14 changed files with 180 additions and 40 deletions
@@ -8,6 +8,7 @@ import {
type ArtifactIntegrityPolicy,
type ArtifactInventorySnapshot,
} from "./ArtifactInventory.js";
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
/** Resolve, authorize, and scan one artifact without a second path resolution. */
export const scanAuthorizedArtifactInventory = async (
@@ -24,7 +25,7 @@ export const scanAuthorizedArtifactInventory = async (
);
const [path, approved] = await Promise.all([
realpath(inputPath),
Promise.all(roots.map(async (root) => realpath(root))),
canonicalizeConfiguredRoots(roots),
]);
if (!approved.some((root) => withinRoot(root, path)))
throw new ArtifactReaderFailure(
+4 -2
View File
@@ -6,6 +6,7 @@ import writeFileAtomic from "write-file-atomic";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
import { EvidenceFileError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
/** Read bounded JSON data from a regular file beneath an approved root. */
export const readBoundedJson = async (
@@ -82,8 +83,9 @@ const isApproved = async (
candidate: string,
roots: readonly string[],
): Promise<boolean> => {
for (const configuredRoot of roots) {
const root = await realpath(resolve(configuredRoot));
for (const root of await canonicalizeConfiguredRoots(
roots.map((configuredRoot) => resolve(configuredRoot)),
)) {
const relation = relative(root, candidate);
if (
relation === "" ||
+22
View File
@@ -0,0 +1,22 @@
import { realpath } from "node:fs/promises";
/** Canonicalize configured policy roots while ignoring stale missing entries. */
export const canonicalizeConfiguredRoots = async (
roots: readonly string[],
): Promise<string[]> => {
const canonical: string[] = [];
for (const root of roots) {
try {
canonical.push(await realpath(root));
} catch (cause: unknown) {
if (!isMissingPath(cause)) throw cause;
}
}
return canonical;
};
const isMissingPath = (cause: unknown): boolean =>
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
cause.code === "ENOENT";
+4 -5
View File
@@ -8,6 +8,7 @@ import {
ProcessCaptureError,
processCaptureCancelled,
} from "./ProcessCaptureError.js";
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
const isWithin = (candidate: string, root: string): boolean =>
candidate === root ||
@@ -18,17 +19,15 @@ export const assertRealPathAuthority = async (
policy: ProcessExecutionPolicy,
): Promise<void> => {
const executable = await realpath(scenario.executable);
const executableRoots = await Promise.all(
policy.executableRoots.map((root) => realpath(root)),
const executableRoots = await canonicalizeConfiguredRoots(
policy.executableRoots,
);
if (!executableRoots.some((root) => isWithin(executable, root)))
throw new ProcessCaptureError(
"resolved executable is outside approved roots",
);
const workingDirectory = await realpath(scenario.working_directory);
const workingRoots = await Promise.all(
policy.workingRoots.map((root) => realpath(root)),
);
const workingRoots = await canonicalizeConfiguredRoots(policy.workingRoots);
if (!workingRoots.some((root) => isWithin(workingDirectory, root)))
throw new ProcessCaptureError(
"resolved working directory is outside approved roots",
@@ -338,14 +338,12 @@ export const captureTerminalFrames = (options: {
readonly started: number;
readonly temporaryRoot: string;
readonly onOutput: () => void;
readonly onFirstOutput: () => void;
readonly renderer: TerminalRenderer;
readonly checkpoints: ProcessCheckpoints;
}): (() => boolean) => {
let outputBytes = 0;
let truncated = false;
options.terminal.onData((data) => {
options.onFirstOutput();
options.onOutput();
const bytes = Buffer.byteLength(data);
if (
+6 -22
View File
@@ -130,20 +130,6 @@ const scheduleScenarioEvents = (options: ScenarioEventOptions): void => {
}
};
const startScenarioEvents = (options: ScenarioEventOptions): (() => void) => {
let eventsStarted = false;
return () => {
if (eventsStarted) return;
eventsStarted = true;
scheduleScenarioEvents(options);
};
};
const eventsRequireReadiness = (scenario: ProcessScenario): boolean =>
scenario.events.some(
(event) => event.type === "input" || event.type === "resize",
);
interface StartedCaptureRuntime {
readonly replay: LoopbackReplay;
readonly renderer: TerminalRenderer;
@@ -243,22 +229,20 @@ const startCaptureRuntime = async (options: {
rows: scenario.terminal.rows,
name: "xterm-256color",
});
const startEvents = startScenarioEvents({
...options,
getTerminal: () => terminal,
renderer,
started,
});
if (!eventsRequireReadiness(scenario)) startEvents();
const framesTruncated = captureTerminalFrames({
...options,
terminal,
started,
onOutput: () => (lastOutput = Date.now()),
onFirstOutput: startEvents,
renderer,
checkpoints,
});
scheduleScenarioEvents({
...options,
getTerminal: () => terminal,
renderer,
started,
});
const stopSampler = startProcessSampler(
terminal.pid,
started,
+8 -3
View File
@@ -104,9 +104,14 @@ export const readProjectPermissionStore = async (
const metadata = await stat(path);
if ((metadata.mode & 0o077) !== 0)
return err(new ProjectPermissionStoreError("not_owner_only"));
const parsed = storeSchema.safeParse(
JSON.parse(await readFile(path, "utf8")),
);
const encoded = await readFile(path, "utf8");
let decoded: unknown;
try {
decoded = JSON.parse(encoded);
} catch (cause: unknown) {
return err(new ProjectPermissionStoreError("invalid", { cause }));
}
const parsed = storeSchema.safeParse(decoded);
if (
!parsed.success ||
parsed.data.project_id !== project.value.id ||
@@ -12,6 +12,7 @@ import {
type ReferenceSourceImportError,
type ReferenceSourceImportOptions,
} from "./ReferenceSourceImportTypes.js";
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
/** Validated, authorized inputs ready for filesystem traversal. */
export interface PreparedReferenceSourceImport {
@@ -66,8 +67,10 @@ const authorizeRoot = async (
failure("invalid-root", "Reference source root is not a directory"),
);
const canonicalRoot = await realpath(resolve(requestedRoot));
for (const approvedRoot of approvedRoots) {
const canonicalApproved = await realpath(resolve(approvedRoot));
const canonicalApprovedRoots = await canonicalizeConfiguredRoots(
approvedRoots.map((approvedRoot) => resolve(approvedRoot)),
);
for (const canonicalApproved of canonicalApprovedRoots) {
if (withinRoot(canonicalApproved, canonicalRoot))
return ok(canonicalRoot);
}