fix(apple): distinguish cache loadability and propagate search uncertainty
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import {
|
||||
isOwnedClientRegistrationCommand,
|
||||
npxRegistrationCommand,
|
||||
} from "./ClientRegistrationIdentity.js";
|
||||
import { setupRegistrationCommand } from "./SetupHost.js";
|
||||
|
||||
it("uses a Windows executable for npm-run setup and preserves POSIX launchers", () => {
|
||||
expect(setupRegistrationCommand("win32", true)).toEqual([
|
||||
"cmd.exe",
|
||||
"/d",
|
||||
"/c",
|
||||
"npx",
|
||||
"-y",
|
||||
PRODUCT_IDENTITY.registrationPackageSpecifier,
|
||||
"mcp",
|
||||
]);
|
||||
for (const platform of ["linux", "darwin"] as const)
|
||||
expect(setupRegistrationCommand(platform, true)).toEqual([
|
||||
"npx",
|
||||
"-y",
|
||||
PRODUCT_IDENTITY.registrationPackageSpecifier,
|
||||
"mcp",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(
|
||||
[
|
||||
npxRegistrationCommand("win32"),
|
||||
["cmd", "/c", "npx", "-y", "rea-agents@5.0.0", "mcp"],
|
||||
["npx", "-y", "rea-agents@5.0.0", "mcp"],
|
||||
].map((command) => ({ command })),
|
||||
)("recognizes owned current and legacy launchers: $command", ({ command }) => {
|
||||
expect(isOwnedClientRegistrationCommand(command)).toBe(true);
|
||||
});
|
||||
|
||||
it.each(
|
||||
[
|
||||
["cmd.exe", "/d", "/c", "node", "custom.js", "mcp"],
|
||||
["cmd.exe", "/k", "npx", "-y", "rea-agents@5.0.0", "mcp"],
|
||||
["cmd.exe", "/c", "npx -y rea-agents@5.0.0 mcp"],
|
||||
["cmd.exe", "/c", "npx", "-y", "another-package", "mcp"],
|
||||
["cmd.exe", "/c", "npx", "-y", "rea-agents@5.0.0", "mcp", "&", "other"],
|
||||
["cmd.exe", "/c", "npx", "-y", "rea-agents@5.0.0 & other", "mcp"],
|
||||
].map((command) => ({ command })),
|
||||
)(
|
||||
"does not claim custom shell commands as REA-owned: $command",
|
||||
({ command }) => {
|
||||
expect(isOwnedClientRegistrationCommand(command)).toBe(false);
|
||||
},
|
||||
);
|
||||
@@ -3,6 +3,28 @@ import { valid } from "semver";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
|
||||
/** Resolve a pinned npx launcher that stdio clients can spawn on the host. */
|
||||
export const npxRegistrationCommand = (
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): readonly string[] => {
|
||||
const command = [
|
||||
"npx",
|
||||
"-y",
|
||||
PRODUCT_IDENTITY.registrationPackageSpecifier,
|
||||
"mcp",
|
||||
];
|
||||
return platform === "win32" ? ["cmd.exe", "/d", "/c", ...command] : command;
|
||||
};
|
||||
|
||||
const unwrapNpxCommand = (command: readonly string[]): readonly string[] => {
|
||||
const executable = command[0]?.toLowerCase();
|
||||
if (executable !== "cmd" && executable !== "cmd.exe") return command;
|
||||
if (command[1]?.toLowerCase() === "/c") return command.slice(2);
|
||||
if (command[1]?.toLowerCase() === "/d" && command[2]?.toLowerCase() === "/c")
|
||||
return command.slice(3);
|
||||
return [];
|
||||
};
|
||||
|
||||
/** Check that one parsed command points to REA's MCP entry point. */
|
||||
export const isOwnedClientRegistrationCommand = (
|
||||
command: readonly string[],
|
||||
@@ -27,15 +49,16 @@ export const isOwnedClientRegistrationCommand = (
|
||||
return true;
|
||||
}
|
||||
|
||||
const npxCommand = unwrapNpxCommand(command);
|
||||
if (
|
||||
command.length !== 4 ||
|
||||
command[0] !== "npx" ||
|
||||
command[1] !== "-y" ||
|
||||
command[3] !== "mcp"
|
||||
npxCommand.length !== 4 ||
|
||||
npxCommand[0] !== "npx" ||
|
||||
npxCommand[1] !== "-y" ||
|
||||
npxCommand[3] !== "mcp"
|
||||
)
|
||||
return false;
|
||||
|
||||
const packageReference = command[2] ?? "";
|
||||
const packageReference = npxCommand[2] ?? "";
|
||||
if (
|
||||
packageReference === PRODUCT_IDENTITY.packageName ||
|
||||
packageReference === PRODUCT_IDENTITY.packageSpecifier ||
|
||||
|
||||
@@ -9,7 +9,10 @@ import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import {
|
||||
isOwnedClientRegistrationCommand,
|
||||
npxRegistrationCommand,
|
||||
} from "./ClientRegistrationIdentity.js";
|
||||
import { supportedClients } from "./SupportedClients.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
@@ -108,7 +111,12 @@ export const readClientRegistrationStatuses = async (
|
||||
client.name,
|
||||
client.configPath,
|
||||
command,
|
||||
registrationAligned(registration, client, currentCommandPath)
|
||||
registrationAligned(
|
||||
registration,
|
||||
client,
|
||||
currentCommandPath,
|
||||
options.platform ?? process.platform,
|
||||
)
|
||||
? "aligned"
|
||||
: "stale",
|
||||
),
|
||||
@@ -132,6 +140,7 @@ const registrationAligned = (
|
||||
registration: z.output<typeof registrationSchema>,
|
||||
client: SetupClient,
|
||||
currentCommandPath: string,
|
||||
platform: NodeJS.Platform,
|
||||
): boolean => {
|
||||
const command = [registration.command, ...registration.args];
|
||||
if (registration.disabled === true || registration.enabled === false)
|
||||
@@ -160,12 +169,10 @@ const registrationAligned = (
|
||||
resolve(command[1] ?? "") === currentCommandPath
|
||||
)
|
||||
return true;
|
||||
const npxCommand = npxRegistrationCommand(platform);
|
||||
if (
|
||||
command.length === 4 &&
|
||||
command[0] === "npx" &&
|
||||
command[1] === "-y" &&
|
||||
command[2] === PRODUCT_IDENTITY.registrationPackageSpecifier &&
|
||||
command[3] === "mcp"
|
||||
command.length === npxCommand.length &&
|
||||
command.every((argument, index) => argument === npxCommand[index])
|
||||
)
|
||||
return true;
|
||||
return (
|
||||
|
||||
@@ -26,7 +26,8 @@ export const createDoctorHostFixture = (
|
||||
Promise.resolve({
|
||||
version: PRODUCT_IDENTITY.skillVersion,
|
||||
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
|
||||
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
|
||||
catalogDigest: null,
|
||||
canonical: true,
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
@@ -177,6 +177,7 @@ describe("doctor installation identity", () => {
|
||||
version: "10",
|
||||
toolCount: null,
|
||||
catalogDigest: null,
|
||||
canonical: false,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
readLinuxDistribution,
|
||||
type LinuxDistribution,
|
||||
} from "./LinuxHopper.js";
|
||||
import { canonicalSkillNeedsInstall } from "./SetupSkill.js";
|
||||
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../identity.js";
|
||||
import {
|
||||
@@ -95,11 +96,13 @@ export interface DoctorHost {
|
||||
ilspyCmdVersion?(path: string): Promise<string | undefined>;
|
||||
}
|
||||
|
||||
/** Parsed identity committed by an installed REA skill. */
|
||||
/** Observed skill metadata and comparison with the packaged instruction bundle. */
|
||||
interface InstalledSkillIdentity {
|
||||
readonly version: string | null;
|
||||
readonly toolCount: number | null;
|
||||
readonly catalogDigest: string | null;
|
||||
/** Whether all managed instruction and reference files match this package. */
|
||||
readonly canonical: boolean;
|
||||
}
|
||||
|
||||
/** Structured result returned by the read-only doctor workflow. */
|
||||
@@ -139,6 +142,7 @@ interface DoctorIdentity {
|
||||
readonly skill: {
|
||||
readonly installed_version: string | null;
|
||||
readonly installed_tool_count: number | null;
|
||||
/** Legacy catalog digest observed in older bundles; current bundles omit it. */
|
||||
readonly installed_catalog_digest: string | null;
|
||||
readonly state: "aligned" | "stale" | "missing";
|
||||
readonly remediation: string | null;
|
||||
@@ -253,7 +257,7 @@ const skillIdentityAligned = (
|
||||
): boolean =>
|
||||
identity?.version === PRODUCT_IDENTITY.skillVersion &&
|
||||
identity.toolCount === CATALOG_IDENTITY.counts.mcp_tools &&
|
||||
identity.catalogDigest === CATALOG_IDENTITY.digests.combined_sha256;
|
||||
identity.canonical;
|
||||
|
||||
const skillIdentityCheck = (
|
||||
identity: InstalledSkillIdentity | undefined,
|
||||
@@ -507,6 +511,7 @@ const installedSkillIdentity = async (
|
||||
const content = await readInstalledSkill(home);
|
||||
const countText = /^\s{2}tool_count:\s*(\d+)\s*$/mu.exec(content)?.[1];
|
||||
return {
|
||||
canonical: !(await canonicalSkillNeedsInstall(home)),
|
||||
version: /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(content)?.[1] ?? null,
|
||||
toolCount:
|
||||
countText === undefined ? null : Number.parseInt(countText, 10),
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import {
|
||||
describeEvidenceBundleFailure,
|
||||
describeValidationFailure,
|
||||
parseEvidenceBundle,
|
||||
serializeEvidenceBundle,
|
||||
type EvidenceBundle,
|
||||
@@ -20,20 +22,31 @@ export const readEvidenceBundle = async (
|
||||
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> => {
|
||||
const loaded = await readJsonFile(path);
|
||||
if (!loaded.ok) return loaded;
|
||||
let bundle: EvidenceBundle;
|
||||
try {
|
||||
const bundle = parseEvidenceBundle(loaded.value);
|
||||
for (const record of bundle.records) {
|
||||
if (record.predicate_type === "rea.process-capture")
|
||||
parseProcessCapture(record.normalized_result);
|
||||
}
|
||||
return ok(bundle);
|
||||
bundle = parseEvidenceBundle(loaded.value);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
userMessage: describeEvidenceBundleFailure(loaded.value, cause),
|
||||
}),
|
||||
);
|
||||
}
|
||||
for (const record of bundle.records) {
|
||||
if (record.predicate_type !== "rea.process-capture") continue;
|
||||
try {
|
||||
parseProcessCapture(record.normalized_result);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
userMessage: `Process capture record ${record.evidence_id} has an invalid normalized_result (${describeValidationFailure(cause)}). Recreate or re-export the bundle, then try again.`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
return ok(bundle);
|
||||
};
|
||||
|
||||
/** Atomically write deterministic evidence JSON at the caller-supplied path. */
|
||||
|
||||
@@ -10,10 +10,14 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
export const readJsonFile = async (
|
||||
path: string,
|
||||
): Promise<Result<unknown, EvidenceFileError>> => {
|
||||
const requestedPath = resolve(path);
|
||||
try {
|
||||
const canonicalPath = await realpath(resolve(path));
|
||||
const canonicalPath = await realpath(requestedPath);
|
||||
const stats = await lstat(canonicalPath);
|
||||
if (!stats.isFile()) return err(new EvidenceFileError("read", "not-file"));
|
||||
if (!stats.isFile())
|
||||
return err(
|
||||
new EvidenceFileError("read", "not-file", { path: requestedPath }),
|
||||
);
|
||||
const encoded = await readFile(canonicalPath);
|
||||
let decoded: unknown;
|
||||
try {
|
||||
@@ -23,11 +27,21 @@ export const readJsonFile = async (
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "invalid-json", { cause }));
|
||||
return err(
|
||||
new EvidenceFileError("read", "invalid-json", {
|
||||
cause,
|
||||
path: requestedPath,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return ok(decoded);
|
||||
} catch (cause: unknown) {
|
||||
return err(new EvidenceFileError("read", "io", { cause }));
|
||||
return err(
|
||||
new EvidenceFileError("read", missingOrIo(cause), {
|
||||
cause,
|
||||
path: requestedPath,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -40,8 +54,8 @@ export const writeTextFile = async (
|
||||
Result<{ readonly path: string; readonly bytes: number }, EvidenceFileError>
|
||||
> => {
|
||||
const bytes = Buffer.byteLength(encoded, "utf8");
|
||||
const requestedPath = resolve(path);
|
||||
try {
|
||||
const requestedPath = resolve(path);
|
||||
const canonicalParent = await realpath(dirname(requestedPath));
|
||||
const destination = resolve(canonicalParent, basename(requestedPath));
|
||||
const existing = await lstat(destination).catch((cause: unknown) => {
|
||||
@@ -49,9 +63,14 @@ export const writeTextFile = async (
|
||||
throw cause;
|
||||
});
|
||||
if (existing !== undefined) {
|
||||
if (!overwrite) return err(new EvidenceFileError("write", "exists"));
|
||||
if (!overwrite)
|
||||
return err(
|
||||
new EvidenceFileError("write", "exists", { path: requestedPath }),
|
||||
);
|
||||
if (!existing.isFile() || existing.isSymbolicLink())
|
||||
return err(new EvidenceFileError("write", "not-file"));
|
||||
return err(
|
||||
new EvidenceFileError("write", "not-file", { path: requestedPath }),
|
||||
);
|
||||
}
|
||||
if (overwrite)
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
@@ -63,11 +82,27 @@ export const writeTextFile = async (
|
||||
return ok({ path: requestedPath, bytes });
|
||||
} catch (cause: unknown) {
|
||||
if (!overwrite && fileErrorCode(cause) === "EEXIST")
|
||||
return err(new EvidenceFileError("write", "exists", { cause }));
|
||||
return err(new EvidenceFileError("write", "io", { cause }));
|
||||
return err(
|
||||
new EvidenceFileError("write", "exists", {
|
||||
cause,
|
||||
path: requestedPath,
|
||||
}),
|
||||
);
|
||||
return err(
|
||||
new EvidenceFileError("write", missingOrIo(cause), {
|
||||
cause,
|
||||
path: requestedPath,
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** A missing path or parent is a selection error, not a permission failure. */
|
||||
const missingOrIo = (cause: unknown): "missing" | "io" => {
|
||||
const code = fileErrorCode(cause);
|
||||
return code === "ENOENT" || code === "ENOTDIR" ? "missing" : "io";
|
||||
};
|
||||
|
||||
const publishNewFile = async (
|
||||
destination: string,
|
||||
encoded: string,
|
||||
|
||||
@@ -15,6 +15,7 @@ import { dirname } from "node:path";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
|
||||
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
||||
import type {
|
||||
@@ -24,12 +25,7 @@ import type {
|
||||
} from "./SetupTypes.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
const defaultCommand = (): readonly string[] => [
|
||||
"npx",
|
||||
"-y",
|
||||
PRODUCT_IDENTITY.registrationPackageSpecifier,
|
||||
"mcp",
|
||||
];
|
||||
const defaultCommand = (): readonly string[] => npxRegistrationCommand();
|
||||
|
||||
/** Back up, atomically update, and semantically read back one JSON MCP configuration. */
|
||||
export const configureJsonClient = (
|
||||
|
||||
@@ -3,6 +3,7 @@ import { homedir } from "node:os";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import {
|
||||
SUPPORTED_NODE_VERSION_PROSE,
|
||||
supportsNodeVersion,
|
||||
@@ -35,7 +36,7 @@ export const setupRegistrationCommand = (
|
||||
useNpmRunner: boolean = process.env.npm_command === "exec",
|
||||
): readonly string[] =>
|
||||
useNpmRunner
|
||||
? PRODUCT_IDENTITY.mcpCommand.split(" ")
|
||||
? npxRegistrationCommand(platform)
|
||||
: platform === "win32"
|
||||
? [
|
||||
process.execPath,
|
||||
|
||||
@@ -2,6 +2,7 @@ import canonicalize from "canonicalize";
|
||||
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
describeEvidenceBundleFailure,
|
||||
parseEvidenceBundle,
|
||||
validateResidualUnknownAddition,
|
||||
type EvidenceBundle,
|
||||
@@ -68,6 +69,7 @@ export class EvidenceLedger {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Evidence bundle validation failed", {
|
||||
cause,
|
||||
userMessage: describeEvidenceBundleFailure(input, cause),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,10 @@ import {
|
||||
type ArtifactAnalysisOperation,
|
||||
} from "../contracts/artifactToolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
|
||||
import { type AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
@@ -116,10 +119,15 @@ class ArtifactClient implements AnalysisClient {
|
||||
parameters.path !== "." &&
|
||||
parameters.path !== basename(this.target.path)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"For an active plist, path must select that archive (omit path or use its basename)",
|
||||
);
|
||||
throw new AnalysisInputError(operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"For an active plist, path must select that archive (omit path or use its basename).",
|
||||
expected: basename(this.target.path),
|
||||
},
|
||||
]);
|
||||
const bundlePath = standalone
|
||||
? dirname(this.target.path)
|
||||
: this.target.sourcePath;
|
||||
@@ -352,6 +360,8 @@ const translateFailure = (
|
||||
cause.details,
|
||||
cause.message,
|
||||
);
|
||||
// Caller-selection failures are already typed; keep their correction details.
|
||||
if (cause instanceof AnalysisInputError) return cause;
|
||||
return new ArtifactOperationError(operation, "io");
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { collectInterfaceBuilderResourceKeys } from "./AppleAssetCatalogAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
|
||||
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||
import {
|
||||
analyzeAppleAssetCatalogs,
|
||||
collectInterfaceBuilderResourceKeys,
|
||||
} from "./AppleAssetCatalogAnalysis.js";
|
||||
|
||||
describe("Apple asset catalog application workflow", () => {
|
||||
it("joins only explicit resource-key fields with archive provenance", () => {
|
||||
@@ -40,4 +48,70 @@ describe("Apple asset catalog application workflow", () => {
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports an app without compiled catalogs as an empty observed inventory", async () => {
|
||||
const bundle = await createTestTempDirectory("rea-asset-catalog-absent-");
|
||||
await mkdir(join(bundle, "Contents", "Resources"), { recursive: true });
|
||||
await writeFile(join(bundle, "Contents", "Resources", "icon.icns"), "");
|
||||
const result = await analyzeAppleAssetCatalogs({
|
||||
bundlePath: bundle,
|
||||
targetSha256: "a".repeat(64),
|
||||
runAssetUtil: () => {
|
||||
throw new Error("assetutil must not run without a catalog");
|
||||
},
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
catalogs: [],
|
||||
total_records: 0,
|
||||
records: [],
|
||||
resource_key_matches: [],
|
||||
next_offset: null,
|
||||
truncated: false,
|
||||
});
|
||||
expect(result.limitations).toContain(
|
||||
"No compiled Assets.car catalog was found among the app bundle's regular files (symlinks are not followed); any resource keys are reported as unmatched.",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not report absence when the only catalog entry is a symlink", async () => {
|
||||
const bundle = await createTestTempDirectory("rea-asset-catalog-link-");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
await writeFile(join(bundle, "outside.car"), "catalog");
|
||||
await symlink("../../outside.car", join(resources, "Assets.car"));
|
||||
const rejected = await analyzeAppleAssetCatalogs({
|
||||
bundlePath: bundle,
|
||||
targetSha256: "a".repeat(64),
|
||||
runAssetUtil: () => Promise.resolve("[]"),
|
||||
}).catch((cause: unknown) => cause);
|
||||
expect(rejected).toBeInstanceOf(ArtifactReaderFailure);
|
||||
expect(rejected).toMatchObject({
|
||||
reason: "path",
|
||||
message: expect.stringContaining(
|
||||
"Contents/Resources/Assets.car (symlink)",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it("discloses skipped catalog entries beside inspected catalogs", async () => {
|
||||
const bundle = await createTestTempDirectory("rea-asset-catalog-mixed-");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
await mkdir(join(resources, "Nested"), { recursive: true });
|
||||
await writeFile(join(resources, "Assets.car"), "catalog");
|
||||
await symlink("../Assets.car", join(resources, "Nested", "Assets.car"));
|
||||
const result = await analyzeAppleAssetCatalogs({
|
||||
bundlePath: bundle,
|
||||
targetSha256: "a".repeat(64),
|
||||
runAssetUtil: () => Promise.resolve("[]"),
|
||||
});
|
||||
expect(result.catalogs.map(({ path }) => path)).toEqual([
|
||||
"Contents/Resources/Assets.car",
|
||||
]);
|
||||
expect(result.limitations).toContainEqual(
|
||||
expect.stringContaining("Contents/Resources/Nested/Assets.car (symlink)"),
|
||||
);
|
||||
expect(result.limitations).not.toContainEqual(
|
||||
expect.stringContaining("No compiled Assets.car catalog"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -48,10 +48,15 @@ export const analyzeAppleAssetCatalogs = async (input: {
|
||||
sha256: string;
|
||||
records: ReturnType<typeof parseAppleAssetCatalogRecords>;
|
||||
}[] = [];
|
||||
const uninspected: string[] = [];
|
||||
let totalMetadataBytes = 0;
|
||||
try {
|
||||
for await (const entry of reader.entries(input.signal)) {
|
||||
if (entry.kind !== "file" || !entry.path.endsWith("Assets.car")) continue;
|
||||
if (!entry.path.endsWith("Assets.car")) continue;
|
||||
if (entry.kind !== "file") {
|
||||
uninspected.push(`${entry.path} (${entry.kind})`);
|
||||
continue;
|
||||
}
|
||||
const inspected = await inspectAssetCatalogEntry({
|
||||
reader,
|
||||
entry,
|
||||
@@ -69,10 +74,12 @@ export const analyzeAppleAssetCatalogs = async (input: {
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
if (catalogs.length === 0)
|
||||
// Without any readable catalog, unmatched resource keys would overstate an
|
||||
// absence that a skipped catalog entry may contradict.
|
||||
if (catalogs.length === 0 && uninspected.length > 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"No compiled Assets.car catalogs were found in the app bundle",
|
||||
"path",
|
||||
`Asset catalog entries are not regular files and were not inspected: ${uninspected.join(", ")}`,
|
||||
);
|
||||
const interfaceBuilder = await analyzeInterfaceBuilderBundle({
|
||||
bundlePath: input.bundlePath,
|
||||
@@ -93,6 +100,18 @@ export const analyzeAppleAssetCatalogs = async (input: {
|
||||
...result,
|
||||
limitations: [
|
||||
...result.limitations,
|
||||
// An app without a compiled catalog is an observed empty inventory, not
|
||||
// a missing host tool.
|
||||
...(catalogs.length === 0
|
||||
? [
|
||||
"No compiled Assets.car catalog was found among the app bundle's regular files (symlinks are not followed); any resource keys are reported as unmatched.",
|
||||
]
|
||||
: []),
|
||||
...(uninspected.length === 0
|
||||
? []
|
||||
: [
|
||||
`Asset catalog entries that are not regular files were not inspected, so resource keys reported as unmatched may resolve there: ${uninspected.join(", ")}`,
|
||||
]),
|
||||
"Exact resource-key joins use only recognized image or asset key fields on decoded Interface Builder resource objects; other archive resource references are not inferred.",
|
||||
...(interfaceBuilder.graph.truncated
|
||||
? [
|
||||
|
||||
@@ -125,6 +125,16 @@ describe("inert keyed archive decoding", () => {
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
}),
|
||||
).toThrow("does not exist");
|
||||
).toThrow(
|
||||
expect.objectContaining({
|
||||
issues: [
|
||||
expect.objectContaining({
|
||||
path: ["root"],
|
||||
message: expect.stringContaining("does not exist"),
|
||||
expected: ["root", "other"],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
||||
import { TextDecoder } from "node:util";
|
||||
import { parseBinary } from "plist";
|
||||
import { z } from "zod";
|
||||
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { projectPlistValue } from "../../domain/apple/plistValue.js";
|
||||
import {
|
||||
@@ -25,6 +26,10 @@ export const decodeKeyedArchiveBytes = (
|
||||
) => {
|
||||
if (bytes.length > MAX_BYTES)
|
||||
throw new RangeError("Keyed archive exceeds 64 MiB");
|
||||
if (bytes.subarray(0, 10).toString("ascii") === "NIBArchive")
|
||||
throw new TypeError(
|
||||
"Selected file is a compiled NIBArchive, not a Foundation plist archive; decode it with decode_interface_builder",
|
||||
);
|
||||
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
|
||||
const parsed = binary
|
||||
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
|
||||
@@ -83,18 +88,20 @@ export const inspectBundleKeyedArchive = async (input: {
|
||||
.split("/")
|
||||
.some((part) => part === ".." || part === "." || part.length === 0)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Archive path must be a canonical relative bundle path",
|
||||
throw archivePathError(
|
||||
"invalid_format",
|
||||
selected.path === "."
|
||||
? "Select a keyed archive path relative to the active app bundle."
|
||||
: `Archive path must be a canonical relative bundle path without empty, '.', or '..' segments: ${selected.path}`,
|
||||
);
|
||||
const reader = new DirectoryArtifactReader(input.bundlePath);
|
||||
try {
|
||||
for await (const entry of reader.entries(input.signal)) {
|
||||
if (entry.path !== selected.path) continue;
|
||||
if (entry.kind !== "file")
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Archive must be a regular file, not a symlink or directory",
|
||||
throw archivePathError(
|
||||
"invalid_value",
|
||||
`Archive path selects a ${entry.kind}, not a regular file: ${selected.path}`,
|
||||
);
|
||||
if ((entry.declaredSize ?? 0) > MAX_BYTES)
|
||||
throw new ArtifactReaderFailure(
|
||||
@@ -132,18 +139,28 @@ export const inspectBundleKeyedArchive = async (input: {
|
||||
...decodeKeyedArchiveBytes(bytes, selected),
|
||||
});
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisInputError) throw cause;
|
||||
throw new ArtifactReaderFailure(
|
||||
cause instanceof RangeError ? "limit" : "format",
|
||||
"Cannot decode selected Foundation keyed archive",
|
||||
`Cannot decode selected Foundation keyed archive: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Archive not found in bundle: ${selected.path}`,
|
||||
throw archivePathError(
|
||||
"invalid_value",
|
||||
`No regular file exists at ${selected.path} in the active app bundle.`,
|
||||
);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** A caller-selected archive path, not the artifact, failed its constraint. */
|
||||
const archivePathError = (
|
||||
reason: "invalid_format" | "invalid_value",
|
||||
message: string,
|
||||
) =>
|
||||
new AnalysisInputError("inspect_keyed_archive", undefined, [
|
||||
{ path: ["path"], reason, message },
|
||||
]);
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
type OwnedProcessGroup,
|
||||
type ProcessCleanupResult,
|
||||
type ProcessLineageObservation,
|
||||
type OwnershipSweepUnverifiedProcess,
|
||||
} from "../process/ProcessOwnership.js";
|
||||
import {
|
||||
observeOwnedProcessLineage,
|
||||
@@ -238,6 +239,17 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
),
|
||||
);
|
||||
if (closeError !== undefined) return err(providerError(closeError));
|
||||
if (outcome.ok && cleanup.unverified !== undefined)
|
||||
outcome = ok({
|
||||
...outcome.value,
|
||||
limitations: [
|
||||
...outcome.value.limitations,
|
||||
...cleanup.unverified.map(
|
||||
({ pid, diagnostic }) =>
|
||||
`Ownership of unrelated process ${String(pid)} could not be verified; it was left untouched: ${diagnostic}`,
|
||||
),
|
||||
],
|
||||
});
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
@@ -280,6 +292,7 @@ const cleanupElectronProcesses = async (
|
||||
})),
|
||||
);
|
||||
let signaled = false;
|
||||
const unverified: OwnershipSweepUnverifiedProcess[] = [];
|
||||
for (const processGroupId of groupIds) {
|
||||
const cleanupOwnership: OwnedProcessGroup =
|
||||
processGroupId === ownership.processGroupId
|
||||
@@ -292,14 +305,38 @@ const cleanupElectronProcesses = async (
|
||||
const result = await cleanupOwnedProcessGroup(cleanupOwnership);
|
||||
if (!result.cleaned) return result;
|
||||
signaled ||= result.signaled;
|
||||
unverified.push(...(result.unverified ?? []));
|
||||
}
|
||||
const remaining = await verifyNoTokenOwnedProcesses(
|
||||
ownership.runId,
|
||||
undefined,
|
||||
ownership.captureBaseline,
|
||||
{
|
||||
leaderPid: ownership.leaderPid,
|
||||
processGroupId: ownership.processGroupId,
|
||||
...(ownership.sampledProcessGroupIds === undefined
|
||||
? {}
|
||||
: { sampledProcessGroupIds: ownership.sampledProcessGroupIds }),
|
||||
},
|
||||
);
|
||||
if (!remaining.cleaned) return remaining;
|
||||
return { cleaned: true, signaled };
|
||||
unverified.push(...(remaining.unverified ?? []));
|
||||
return {
|
||||
cleaned: true,
|
||||
signaled,
|
||||
...(unverified.length === 0
|
||||
? {}
|
||||
: {
|
||||
unverified: [
|
||||
...new Map(
|
||||
unverified.map((item) => [
|
||||
`${String(item.pid)}:${item.diagnostic}`,
|
||||
item,
|
||||
]),
|
||||
).values(),
|
||||
],
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const createResult = (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { lstat, realpath } from "node:fs/promises";
|
||||
import { dirname, isAbsolute, join, relative, sep } from "node:path";
|
||||
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
|
||||
import { normalizeArtifactPath } from "../../artifacts/ArtifactPaths.js";
|
||||
@@ -55,7 +55,7 @@ export class LocalWebScriptArtifacts implements WebScriptArtifactPort {
|
||||
"path",
|
||||
`Selected source path changes during normalization: ${selected.content.relative_path}`,
|
||||
);
|
||||
const root = dirname(input.manifest_path);
|
||||
const root = resolve(dirname(input.manifest_path));
|
||||
const sourcePath = join(root, "files", portable);
|
||||
targetPath = sourcePath;
|
||||
await assertContained(root, sourcePath);
|
||||
|
||||
@@ -161,14 +161,28 @@ it("rejects identical duplicate core fields before schema validation", () => {
|
||||
expect(() => decodeHarCapture(text, [])).toThrow("duplicate");
|
||||
});
|
||||
|
||||
it("reports an unsupported JSON schema boundary instead of dropping a producer property", () => {
|
||||
it("preserves prototype-named producer members through the capture boundary", () => {
|
||||
const text = JSON.stringify(historicalHar()).replace(
|
||||
'"cache":{}',
|
||||
'"cache":{},"_extension":{"__proto__":{"preserved":7},"constructor":"ordinary"}',
|
||||
);
|
||||
expect(() => decodeHarCapture(text, [])).toThrow(
|
||||
"JSON schema boundary cannot preserve",
|
||||
);
|
||||
const result = decodeHarCapture(text, []);
|
||||
const reported = result.records[0]?.reported;
|
||||
expect(reported).toBeDefined();
|
||||
if (
|
||||
reported === undefined ||
|
||||
reported === null ||
|
||||
typeof reported !== "object" ||
|
||||
Array.isArray(reported)
|
||||
)
|
||||
throw new Error("No HAR object record was retained");
|
||||
const extension = reported["_extension"];
|
||||
expect(extension).toEqual({
|
||||
["__proto__"]: { preserved: 7 },
|
||||
constructor: "ordinary",
|
||||
});
|
||||
expect(Object.getPrototypeOf(extension)).toBe(Object.prototype);
|
||||
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves Unicode, offsets, sizes, duplicate URLs and opaque extensions without inventing bytes", () => {
|
||||
|
||||
@@ -58,11 +58,9 @@ export const parseHarJson = (text: string): unknown => {
|
||||
});
|
||||
},
|
||||
onObjectProperty: (key) => {
|
||||
if (key === "__proto__")
|
||||
throw new CaptureFormatError(
|
||||
"unsupported",
|
||||
"HAR object contains a __proto__ member that the current JSON schema boundary cannot preserve.",
|
||||
);
|
||||
// Prototype-named members are kept as ordinary own properties: the
|
||||
// members map keys them without prototype setters, and
|
||||
// Object.fromEntries materializes them as own data properties.
|
||||
const frame = frames.at(-1);
|
||||
if (frame?.kind !== "object")
|
||||
throw new TypeError(
|
||||
|
||||
+2
-1
@@ -4,6 +4,7 @@ import { Cli } from "incur";
|
||||
|
||||
import { createLogger, parseLogLevel } from "./logger.js";
|
||||
import { PRODUCT_IDENTITY } from "./identity.js";
|
||||
import { npxRegistrationCommand } from "./application/ClientRegistrationIdentity.js";
|
||||
import { registerSetupCommands } from "./cli/setupCommands.js";
|
||||
import { registerCoreAnalysisCommands } from "./cli/coreAnalysisCommands.js";
|
||||
import { registerUtilityCommands } from "./cli/utilityCommands.js";
|
||||
@@ -47,7 +48,7 @@ export const createCli = (
|
||||
version: PRODUCT_IDENTITY.packageVersion,
|
||||
description: "Reverse engineer anything from your terminal or agent.",
|
||||
mcp: {
|
||||
command: PRODUCT_IDENTITY.mcpCommand,
|
||||
command: npxRegistrationCommand().join(" "),
|
||||
instructions:
|
||||
"Ask what software, artifact, protocol, or behavior the user wants to understand, then choose the available investigation capabilities that can produce evidence.",
|
||||
},
|
||||
|
||||
@@ -12,7 +12,7 @@ export const WEB_NETWORK_CAPTURE_TOOL_CONTRACTS = [
|
||||
name: "inspect_web_network_capture",
|
||||
...toolContractMetadata("inspect_web_network_capture"),
|
||||
description:
|
||||
"Inspect retained local HAR 1.2 or native mitmproxy capture records without contacting recorded URLs. Returns original ordinals, pointers/byte ranges, preserved producer fields, precise numeric representations and exact exposed binary bytes inline. Excludes known transport credentials and explicitly marked values. Decodes every record before optional ordinal selection; malformed or oversized captures return no partial success. Duplicate HAR members are invalid; prototype-named __proto__ members are unsupported by the current shared JSON boundary. Uses pinned upstream parsers, owned temporary files and bounded offline processes. Native mitmproxy requires caller-supplied mitmdump 12.2.3 on Linux. Browser transaction IDs, runtime attribution and original bytes of HAR Unicode text remain unknown.",
|
||||
"Inspect retained local HAR 1.2 or native mitmproxy capture records without contacting recorded URLs. Returns original ordinals, pointers/byte ranges, preserved producer fields, precise numeric representations and exact exposed binary bytes inline. Excludes known transport credentials and explicitly marked values. Decodes every record before optional ordinal selection; malformed or oversized captures return no partial success. Duplicate HAR members are invalid; prototype-named members such as __proto__ are preserved as ordinary own JSON members without prototype mutation. Uses pinned upstream parsers, owned temporary files and bounded offline processes. Native mitmproxy requires caller-supplied mitmdump 12.2.3 on Linux. Browser transaction IDs, runtime attribution and original bytes of HAR Unicode text remain unknown.",
|
||||
kind: "browser-provider",
|
||||
inputSchema: inspectWebNetworkCaptureInputSchema,
|
||||
outputSchema: evidenceResultOf(webNetworkCaptureSchema),
|
||||
|
||||
@@ -162,8 +162,7 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
|
||||
: `Evidence ${error.evidenceId} does not match the requested reference (${error.reason}). Check the expected and actual identity in the diagnostic details.`;
|
||||
if (error instanceof EvidenceIntegrityError)
|
||||
return "Evidence is invalid or has changed. Recreate or re-import it, then try again.";
|
||||
if (error instanceof EvidenceFileError)
|
||||
return evidenceFileMessage(error.reason);
|
||||
if (error instanceof EvidenceFileError) return evidenceFileMessage(error);
|
||||
if (error instanceof UnknownRegistryError && error.reason === "not-found")
|
||||
return "The requested residual unknown does not exist in this session. Check the unknown_id and try again.";
|
||||
if (error instanceof UnknownRegistryError)
|
||||
@@ -258,7 +257,14 @@ const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
|
||||
return "Artifact could not be read or written. Check file access and try again.";
|
||||
};
|
||||
|
||||
const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
|
||||
const evidenceFileMessage = ({
|
||||
operation,
|
||||
reason,
|
||||
}: EvidenceFileError): string => {
|
||||
if (reason === "missing")
|
||||
return operation === "read"
|
||||
? "Evidence file does not exist at the selected path. Check the path and try again."
|
||||
: "Evidence output directory does not exist. Choose an existing directory and try again.";
|
||||
if (reason === "not-file")
|
||||
return "Evidence path does not point to a regular file. Choose a file and try again.";
|
||||
if (reason === "exists")
|
||||
|
||||
@@ -259,7 +259,11 @@ const artifactStateErrorDetails = (
|
||||
};
|
||||
if (error instanceof UnknownRegistryError) return { reason: error.reason };
|
||||
if (error instanceof EvidenceFileError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
return {
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
...(error.path === undefined ? {} : { path: error.path }),
|
||||
};
|
||||
return undefined;
|
||||
};
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ describe("dyld path expansion", () => {
|
||||
}),
|
||||
[plugin]: parsed(
|
||||
slice({
|
||||
file_type: "bundle",
|
||||
file_type: "dylib",
|
||||
dependencies: [dependency("@rpath/libshared.dylib")],
|
||||
}),
|
||||
),
|
||||
@@ -302,10 +302,13 @@ describe("dyld resolution outcomes", () => {
|
||||
trace.findings.map(({ kind, edge_index: index }) => [kind, index]),
|
||||
).toEqual([
|
||||
["earlier-rpath-candidate-absent", 0],
|
||||
["weak-load-unresolved", 1],
|
||||
["required-load-unresolved", 2],
|
||||
["dyld-environment-present", null],
|
||||
]);
|
||||
expect(trace.edges.map(({ resolution }) => resolution.status)).toEqual([
|
||||
"conditional",
|
||||
"undetermined",
|
||||
"undetermined",
|
||||
]);
|
||||
expect(trace.findings[0]?.explanation).toContain(
|
||||
"Contents/MacOS/../Overrides/libfound.dylib",
|
||||
);
|
||||
@@ -540,7 +543,7 @@ const cache = (
|
||||
].includes(path)
|
||||
? "mapped"
|
||||
: "absent",
|
||||
image: () => Promise.resolve(parsed(slice())),
|
||||
image: () => Promise.resolve(parsed(slice({ architecture: "arm64e" }))),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
@@ -830,3 +833,96 @@ describe("conditional loads", () => {
|
||||
).toContain(`${VENDOR} loads only conditionally; if it loads,`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dependency loadability", () => {
|
||||
it.each(["execute", "bundle", "other"] as const)(
|
||||
"does not load cached or in-root %s images as dependencies",
|
||||
async (fileType) => {
|
||||
for (const useCache of [true, false]) {
|
||||
const path = useCache
|
||||
? "/usr/lib/libSystem.B.dylib"
|
||||
: "@executable_path/libinvalid.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({ dependencies: [dependency(path)] }),
|
||||
"Contents/MacOS/libinvalid.dylib": parsed(
|
||||
slice({ file_type: fileType }),
|
||||
),
|
||||
}),
|
||||
{
|
||||
roots: [MAIN],
|
||||
...(useCache
|
||||
? {
|
||||
sharedCache: cache({
|
||||
image: async () =>
|
||||
parsed(
|
||||
slice({ architecture: "arm64e", file_type: fileType }),
|
||||
),
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
expect(trace.edges[0]?.resolution).toEqual({
|
||||
status: "undetermined",
|
||||
image: null,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
it.each([{ platforms: [] }, { platforms: [{ id: 2, name: "ios" }] }])(
|
||||
"keeps cached unknown or incompatible platforms uncertain (%j)",
|
||||
async ({ platforms }) => {
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
|
||||
}),
|
||||
}),
|
||||
{
|
||||
roots: [MAIN],
|
||||
sharedCache: cache({
|
||||
image: async () =>
|
||||
parsed(slice({ architecture: "arm64e", platforms })),
|
||||
}),
|
||||
},
|
||||
);
|
||||
expect(trace.edges[0]?.resolution.status).toBe("undetermined");
|
||||
expect(trace.coverage.status).toBe("partial");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("propagates embedded search-path uncertainty through found, missing, lazy and descendant edges", async () => {
|
||||
const child = "Contents/MacOS/child.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dyld_environment: ["DYLD_LIBRARY_PATH=/tmp"],
|
||||
dependencies: [
|
||||
dependency("@executable_path/child.dylib"),
|
||||
dependency("@executable_path/missing.dylib"),
|
||||
dependency("@executable_path/lazy.dylib", {
|
||||
command: "LC_LAZY_LOAD_DYLIB",
|
||||
}),
|
||||
dependency("/usr/lib/libSystem.B.dylib"),
|
||||
],
|
||||
}),
|
||||
[child]: parsed(
|
||||
slice({ dependencies: [dependency("@loader_path/gone.dylib")] }),
|
||||
),
|
||||
}),
|
||||
{ roots: [MAIN], sharedCache: cache() },
|
||||
);
|
||||
expect(trace.edges.map(({ resolution }) => resolution.status)).toEqual([
|
||||
"conditional",
|
||||
"undetermined",
|
||||
"undetermined",
|
||||
"conditional",
|
||||
"undetermined",
|
||||
]);
|
||||
expect(trace.edges.at(-1)?.loader_conditional).toBe(true);
|
||||
expect(trace.findings.map(({ kind }) => kind)).toEqual([
|
||||
"dyld-environment-present",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
compatibleSlice,
|
||||
cacheServes,
|
||||
directoryOf,
|
||||
expandPrefix,
|
||||
joinPath,
|
||||
@@ -55,13 +56,15 @@ interface ProcessContext {
|
||||
readonly view: DylibTreeView;
|
||||
readonly root: string;
|
||||
readonly architecture: string;
|
||||
readonly platforms: MachoSlice["platforms"];
|
||||
readonly searchPathsUnknown: boolean;
|
||||
readonly executable: string | null;
|
||||
readonly loaded: Map<string, LoadedImage>;
|
||||
readonly byInstallName: Map<string, string>;
|
||||
readonly images: Map<string, MachoImageFacts>;
|
||||
/** The supplied cache, when it serves this process's architecture and platform. */
|
||||
readonly sharedCache: DylibSharedCacheView | undefined;
|
||||
/** Cached install paths whose subcache bytes were unavailable, across processes. */
|
||||
/** Cached install paths whose bytes or loadability could not be verified. */
|
||||
readonly unverifiedCacheImages: Set<string>;
|
||||
}
|
||||
|
||||
@@ -135,7 +138,14 @@ const evaluateCandidate = async (
|
||||
const facts = await sharedCache.image(template.expansion.path);
|
||||
if (
|
||||
facts?.status === "parsed" &&
|
||||
compatibleSlice(facts.slices, context.architecture) !== undefined
|
||||
facts.slices.some(
|
||||
(slice) =>
|
||||
cacheServes(slice.architecture, context.architecture) &&
|
||||
slice.file_type === "dylib" &&
|
||||
slice.platforms.some(({ id }) =>
|
||||
context.platforms.some((platform) => platform.id === id),
|
||||
),
|
||||
)
|
||||
)
|
||||
return {
|
||||
...base,
|
||||
@@ -160,13 +170,24 @@ const evaluateCandidate = async (
|
||||
if (lookup.kind !== "file")
|
||||
return { ...base, outcome: "absent", resolved_path: null };
|
||||
const facts = await imageFacts(context, lookup.path);
|
||||
const outcome: Candidate["outcome"] =
|
||||
facts.status !== "parsed"
|
||||
? facts.status
|
||||
: compatibleSlice(facts.slices, context.architecture) === undefined
|
||||
? "architecture-missing"
|
||||
: "resolved";
|
||||
return { ...base, outcome, resolved_path: lookup.path };
|
||||
if (facts.status !== "parsed")
|
||||
return { ...base, outcome: facts.status, resolved_path: lookup.path };
|
||||
const slice = compatibleSlice(facts.slices, context.architecture);
|
||||
if (slice === undefined)
|
||||
return {
|
||||
...base,
|
||||
outcome: "architecture-missing",
|
||||
resolved_path: lookup.path,
|
||||
};
|
||||
if (slice.file_type !== "dylib")
|
||||
return { ...base, outcome: "unsupported", resolved_path: lookup.path };
|
||||
if (
|
||||
!slice.platforms.some(({ id }) =>
|
||||
context.platforms.some((platform) => platform.id === id),
|
||||
)
|
||||
)
|
||||
return { ...base, outcome: "undetermined", resolved_path: lookup.path };
|
||||
return { ...base, outcome: "resolved", resolved_path: lookup.path };
|
||||
};
|
||||
|
||||
const imageFacts = async (
|
||||
@@ -234,7 +255,13 @@ const resolveDependency = async (
|
||||
)
|
||||
break;
|
||||
}
|
||||
const searched = resolution(candidates);
|
||||
const modeled = resolution(candidates);
|
||||
const searched: Edge["resolution"] = context.searchPathsUnknown
|
||||
? {
|
||||
...modeled,
|
||||
status: modeled.image === null ? "undetermined" : "conditional",
|
||||
}
|
||||
: modeled;
|
||||
// Reusing an image that itself loads only conditionally is conditional too.
|
||||
const resolved: Edge["resolution"] =
|
||||
loaded !== undefined &&
|
||||
@@ -368,6 +395,8 @@ export const traceDylibLoading = async (
|
||||
view,
|
||||
root,
|
||||
architecture: slice.architecture,
|
||||
platforms: slice.platforms,
|
||||
searchPathsUnknown: slice.dyld_environment.length > 0,
|
||||
executable: slice.file_type === "execute" ? root : null,
|
||||
loaded: new Map(),
|
||||
byInstallName: new Map(),
|
||||
|
||||
@@ -82,7 +82,7 @@ export interface DylibSharedCacheView {
|
||||
/**
|
||||
* `mapped`: listed and inside an admitted mapping. That is address coverage,
|
||||
* not a load: a shared-cache hit also requires `image` to parse a slice this
|
||||
* process can load. `unverified`: listed, but the subcache holding it is
|
||||
* process can load as a dylib on its platform. `unverified`: listed, but the subcache holding it is
|
||||
* unavailable. `absent`: not listed.
|
||||
*/
|
||||
lookup(path: string): "mapped" | "unverified" | "absent";
|
||||
@@ -191,7 +191,7 @@ export const dylibResolutionResultSchema = z.strictObject({
|
||||
status: z.enum(["complete", "partial"]),
|
||||
unparsed_images: z.array(z.string()),
|
||||
roots_without_architecture: z.array(z.string()),
|
||||
/** Install paths the supplied cache lists in subcaches that were unavailable. */
|
||||
/** Listed cache paths whose bytes or process-compatible dylib representation could not be verified. */
|
||||
unverified_shared_cache_images: z.array(z.string()),
|
||||
}),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { AnalysisInputError } from "../analysisErrorCore.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
|
||||
|
||||
/** Select one archive within the active bundle and optionally one named root. */
|
||||
@@ -85,7 +86,14 @@ export const projectKeyedArchive = (
|
||||
if (top === undefined || Object.keys(top).length === 0)
|
||||
throw new TypeError("Keyed archive has no $top roots");
|
||||
if (selection.root !== undefined && !Object.hasOwn(top, selection.root))
|
||||
throw new TypeError(`Archive root does not exist: ${selection.root}`);
|
||||
throw new AnalysisInputError("inspect_keyed_archive", undefined, [
|
||||
{
|
||||
path: ["root"],
|
||||
reason: "invalid_value",
|
||||
message: `Archive root does not exist: ${selection.root}. Select one of the archive's $top roots or omit root.`,
|
||||
expected: Object.keys(top),
|
||||
},
|
||||
]);
|
||||
const roots =
|
||||
selection.root === undefined
|
||||
? top
|
||||
|
||||
@@ -44,13 +44,27 @@ it("snapshots caller-owned payloads before deriving their identity", () => {
|
||||
});
|
||||
|
||||
describe("analysis evidence identity", () => {
|
||||
it("normalizes prototype-named parameter keys", () => {
|
||||
it("preserves prototype-named parameter keys and their semantic identity", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: Object.fromEntries([["__proto__", false]]),
|
||||
result: true,
|
||||
});
|
||||
expect(evidence.parameters).toEqual({ ["__proto__"]: false });
|
||||
expect(Object.hasOwn(evidence.parameters, "__proto__")).toBe(true);
|
||||
expect(parseEvidence(evidence)).toEqual(evidence);
|
||||
const stripped = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
expect(stripped.evidence_id).not.toBe(evidence.evidence_id);
|
||||
expect(() =>
|
||||
parseEvidence({
|
||||
...evidence,
|
||||
parameters: { ["__proto__"]: true },
|
||||
}),
|
||||
).toThrow(/semantic identifier/u);
|
||||
});
|
||||
|
||||
it.prop([
|
||||
@@ -280,3 +294,27 @@ describe("evidence parameter depth bound", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves prototype-named raw and normalized results with aligned identity", () => {
|
||||
const result = { ["__proto__"]: { preserved: 7 }, constructor: "ordinary" };
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result,
|
||||
rawResult: result,
|
||||
});
|
||||
const parsed = parseEvidence(evidence);
|
||||
expect(parsed.normalized_result).toEqual(result);
|
||||
expect(parsed.raw_result).toEqual(result);
|
||||
expect(Object.getPrototypeOf(parsed.normalized_result)).toBe(
|
||||
Object.prototype,
|
||||
);
|
||||
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
|
||||
const stripped = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: { constructor: "ordinary" },
|
||||
rawResult: { constructor: "ordinary" },
|
||||
});
|
||||
expect(stripped.evidence_id).not.toBe(evidence.evidence_id);
|
||||
});
|
||||
|
||||
@@ -7,7 +7,11 @@ import {
|
||||
type AnalysisProfileCommitment,
|
||||
} from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "./jsonValue.js";
|
||||
import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
|
||||
@@ -89,7 +93,7 @@ const evidenceBaseSchema = z
|
||||
provider: providerSchema,
|
||||
predicate_type: z.string().min(1),
|
||||
operation: z.string().min(1),
|
||||
parameters: z.record(z.string(), jsonValueSchema),
|
||||
parameters: jsonObjectSchema,
|
||||
raw_result: jsonValueSchema.nullable(),
|
||||
normalized_result: jsonValueSchema,
|
||||
confidence: z.enum(["observed", "derived", "inferred"]),
|
||||
|
||||
@@ -182,6 +182,34 @@ const referencedEvidenceIds = (unknown: ResidualUnknown): readonly string[] => [
|
||||
...(unknown.resolution?.evidence_ids ?? []),
|
||||
];
|
||||
|
||||
/**
|
||||
* Name the bundle constraint that failed and how to recover. A single
|
||||
* Evidence record, such as one command result, is not a bundle.
|
||||
*/
|
||||
export const describeEvidenceBundleFailure = (
|
||||
input: unknown,
|
||||
cause: unknown,
|
||||
): string => {
|
||||
const record = evidenceRecordSchema.safeParse(input);
|
||||
if (record.success)
|
||||
return `Expected an Evidence bundle with records and manifest arrays, but this JSON is one Evidence record (${record.data.evidence_id}). Export a session bundle with the MCP export_evidence_bundle tool and supply that file.`;
|
||||
return cause instanceof z.ZodError
|
||||
? `Evidence bundle does not match the bundle schema ${describeValidationFailure(cause)}. Supply an unmodified bundle written by export_evidence_bundle or rea evidence-export.`
|
||||
: `Evidence bundle validation failed: ${describeValidationFailure(cause)}. Recreate or re-export the bundle, then try again.`;
|
||||
};
|
||||
|
||||
/** Locate the first schema issue, or keep a thrown constraint message. */
|
||||
export const describeValidationFailure = (cause: unknown): string => {
|
||||
if (!(cause instanceof z.ZodError))
|
||||
return cause instanceof Error ? cause.message : String(cause);
|
||||
const [first, ...rest] = cause.issues;
|
||||
const location =
|
||||
first === undefined || first.path.length === 0
|
||||
? "the document root"
|
||||
: first.path.map(String).join(".");
|
||||
return `at ${location}: ${first?.message ?? "invalid value"}${rest.length === 0 ? "" : ` (${String(rest.length)} more issues)`}`;
|
||||
};
|
||||
|
||||
/** Parse records, verify semantic IDs, and reject inconsistent manifests. */
|
||||
export const parseEvidenceBundle = (input: unknown): EvidenceBundle => {
|
||||
const parsed = evidenceBundleSchema.parse(input);
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { AnalysisError } from "./analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
type AnalysisErrorOptions,
|
||||
} from "./analysisErrorBase.js";
|
||||
|
||||
/** Evidence identity, schema, or bundle manifests failed integrity checks. */
|
||||
export class EvidenceIntegrityError extends AnalysisError {
|
||||
readonly _tag = "EvidenceIntegrityError";
|
||||
override readonly userMessage: string | undefined;
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
options?: AnalysisErrorOptions & { readonly userMessage?: string },
|
||||
) {
|
||||
super(message, options);
|
||||
this.userMessage = options?.userMessage;
|
||||
}
|
||||
}
|
||||
|
||||
/** A session Evidence reference is missing or has the wrong semantic identity. */
|
||||
@@ -25,11 +37,15 @@ export class EvidenceReferenceError extends EvidenceIntegrityError {
|
||||
export class EvidenceFileError extends AnalysisError {
|
||||
readonly _tag = "EvidenceFileError";
|
||||
|
||||
/** Caller-selected path that failed, resolved against the working directory. */
|
||||
readonly path: string | undefined;
|
||||
|
||||
constructor(
|
||||
readonly operation: "read" | "write",
|
||||
readonly reason: "not-file" | "exists" | "invalid-json" | "io",
|
||||
options?: ErrorOptions,
|
||||
readonly reason: "not-file" | "exists" | "invalid-json" | "missing" | "io",
|
||||
options?: ErrorOptions & { readonly path?: string },
|
||||
) {
|
||||
super(`Evidence bundle ${operation} failed: ${reason}`, options);
|
||||
this.path = options?.path;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,16 +12,21 @@ import { digestSchema } from "../digests.js";
|
||||
import { prefixedDigestSchema } from "../digests.js";
|
||||
|
||||
const semanticNodeIdSchema = prefixedDigestSchema("jsrg_node");
|
||||
const literalValueSchema = jsonValueSchema.refine(
|
||||
(value) =>
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean",
|
||||
"Literal seeds accept only JSON primitive values",
|
||||
);
|
||||
// Zod derivations drop the shared schema's JSON Schema projection override;
|
||||
// re-apply it so MCP catalog generation keeps projecting `{}`.
|
||||
literalValueSchema._zod.toJSONSchema = () => ({});
|
||||
|
||||
const literalSeedSchema = z.strictObject({
|
||||
kind: z.literal("literal"),
|
||||
value: jsonValueSchema.refine(
|
||||
(value) =>
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean",
|
||||
"Literal seeds accept only JSON primitive values",
|
||||
),
|
||||
value: literalValueSchema,
|
||||
});
|
||||
|
||||
/** Authenticated starting points accepted by semantic tracing. */
|
||||
|
||||
@@ -99,3 +99,34 @@ describe("jsonValueSchema depth bound", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves prototype-named members without prototype mutation", () => {
|
||||
const input: unknown = JSON.parse(
|
||||
'{"__proto__":{"preserved":7},"constructor":"ordinary","prototype":[1],"nested":{"\\u005f\\u005fproto\\u005f\\u005f":"escaped"},"list":[{"__proto__":null}]}',
|
||||
);
|
||||
const parsed = jsonObjectSchema.parse(input);
|
||||
expect(parsed).toEqual(input);
|
||||
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype);
|
||||
expect(Object.hasOwn(parsed, "__proto__")).toBe(true);
|
||||
expect(parsed["__proto__"]).toEqual({ preserved: 7 });
|
||||
expect(parsed["constructor"]).toBe("ordinary");
|
||||
expect(parsed["prototype"]).toEqual([1]);
|
||||
expect(parsed["nested"]).toEqual({ ["__proto__"]: "escaped" });
|
||||
expect(parsed["list"]).toEqual([{ ["__proto__"]: null }]);
|
||||
expect(Object.getPrototypeOf(parsed["nested"])).toBe(Object.prototype);
|
||||
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
|
||||
expect(JSON.parse(JSON.stringify(parsed))).toEqual(input);
|
||||
});
|
||||
|
||||
it.each([undefined, Number.NaN, Infinity, 1n, () => 0, new Date(0)])(
|
||||
"rejects non-JSON values in prototype-named members (%s)",
|
||||
(value) => {
|
||||
for (const input of [
|
||||
{ ["__proto__"]: value },
|
||||
{ nested: [{ ["__proto__"]: value }] },
|
||||
]) {
|
||||
expect(jsonValueSchema.safeParse(input).success).toBe(false);
|
||||
expect(jsonObjectSchema.safeParse(input).success).toBe(false);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
+63
-43
@@ -1,67 +1,87 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Maximum nesting depth accepted for JSON values.
|
||||
*
|
||||
* Sits well below the point where the recursive `z.json()` core overflows its
|
||||
* stack (measured between 2000 and 3000 on Node 24) while leaving room for
|
||||
* legitimately deep target-derived trees such as compiled NIB view hierarchies.
|
||||
*/
|
||||
/** Maximum JSON nesting accepted before recursive result cloning. */
|
||||
export const MAX_JSON_DEPTH = 1000;
|
||||
|
||||
/** JSON-safe value shared by domain, application, and adapter boundaries. */
|
||||
export type JsonValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| JsonValue[]
|
||||
| { [key: string]: JsonValue };
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
const recordShape = z.record(z.string(), z.unknown());
|
||||
|
||||
const exceedsMaxDepth = (root: unknown): boolean => {
|
||||
// Depth counts edges from the root.
|
||||
const jsonValidationIssue = (root: unknown): string | undefined => {
|
||||
const pending: { value: unknown; depth: number }[] = [
|
||||
{ value: root, depth: 0 },
|
||||
];
|
||||
while (pending.length > 0) {
|
||||
const item = pending.pop();
|
||||
if (item === undefined) break;
|
||||
if (item.depth > MAX_JSON_DEPTH) return true;
|
||||
if (item.depth > MAX_JSON_DEPTH)
|
||||
return `JSON value exceeds maximum nesting depth of ${MAX_JSON_DEPTH}`;
|
||||
const value = item.value;
|
||||
if (Array.isArray(value)) {
|
||||
if (
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "boolean"
|
||||
)
|
||||
continue;
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value)) return "JSON numbers must be finite";
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const child of value)
|
||||
pending.push({ value: child, depth: item.depth + 1 });
|
||||
} else if (isRecord(value)) {
|
||||
for (const key of Object.keys(value))
|
||||
pending.push({ value: value[key], depth: item.depth + 1 });
|
||||
}
|
||||
} else if (isRecord(value) && recordShape.safeParse(value).success) {
|
||||
// Inspect every own member, including keys Zod's record parser skips.
|
||||
for (const child of Object.values(value))
|
||||
pending.push({ value: child, depth: item.depth + 1 });
|
||||
} else return "Invalid JSON value";
|
||||
}
|
||||
return false;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* JSON-safe value shared by domain, application, and adapter boundaries.
|
||||
*
|
||||
* An iterative depth guard runs before the recursive `z.json()` core so
|
||||
* hostile nested payloads surface as validation issues instead of RangeErrors.
|
||||
* The guard only refuses over-deep values; ordinary JSON parsing semantics
|
||||
* (including which members `z.json()` keeps) are unchanged.
|
||||
*/
|
||||
const jsonCore = z.json();
|
||||
// Every JSON value satisfies `{}`. Advertise that instead of Zod's
|
||||
// self-referential `$defs` projection, which MCP clients and model APIs that
|
||||
// reject recursive JSON Schemas refuse. Runtime parsing still admits only JSON.
|
||||
// The override sits on the core as well as on the pipe because the standard
|
||||
// JSON Schema projection walks into pipe stages without consulting the outer
|
||||
// node, while the public toJSONSchema projection stops at the pipe.
|
||||
jsonCore._zod.toJSONSchema = () => ({});
|
||||
const preserveJsonValue = (value: JsonValue): JsonValue => {
|
||||
if (Array.isArray(value)) return value.map(preserveJsonValue);
|
||||
if (value !== null && typeof value === "object")
|
||||
return Object.fromEntries<JsonValue>(
|
||||
Object.entries(value).map(([key, child]) => [
|
||||
key,
|
||||
preserveJsonValue(child),
|
||||
]),
|
||||
);
|
||||
return value;
|
||||
};
|
||||
|
||||
const validatedJsonValue = z.custom<JsonValue>(
|
||||
(value) => jsonValidationIssue(value) === undefined,
|
||||
{
|
||||
error: (issue) => jsonValidationIssue(issue.input) ?? "Invalid JSON value",
|
||||
},
|
||||
);
|
||||
// Keep both stages nonrecursive in public and Standard Schema projections.
|
||||
validatedJsonValue._zod.toJSONSchema = () => ({});
|
||||
|
||||
/** Parse bounded JSON and retain all own data members without prototype setters. */
|
||||
export const jsonValueSchema = z
|
||||
.unknown()
|
||||
.superRefine((value, context) => {
|
||||
if (exceedsMaxDepth(value))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `JSON value exceeds maximum nesting depth of ${MAX_JSON_DEPTH}`,
|
||||
});
|
||||
})
|
||||
.pipe(jsonCore);
|
||||
.nonoptional()
|
||||
.pipe(validatedJsonValue)
|
||||
.transform(preserveJsonValue);
|
||||
jsonValueSchema._zod.toJSONSchema = () => ({});
|
||||
|
||||
/** JSON object boundary for caller-visible parameter maps. */
|
||||
export const jsonObjectSchema = z.record(z.string(), jsonValueSchema);
|
||||
const objectValidation = z.custom<Record<string, JsonValue>>(
|
||||
isRecord,
|
||||
"Expected JSON object",
|
||||
);
|
||||
const objectProjection = () => ({ type: "object", additionalProperties: {} });
|
||||
objectValidation._zod.toJSONSchema = objectProjection;
|
||||
|
||||
export type JsonValue = z.infer<typeof jsonValueSchema>;
|
||||
/** JSON object boundary for caller-visible parameter maps. */
|
||||
export const jsonObjectSchema = jsonValueSchema.pipe(objectValidation);
|
||||
jsonObjectSchema._zod.toJSONSchema = objectProjection;
|
||||
|
||||
@@ -223,6 +223,10 @@ export interface UnverifiedProcessCapture {
|
||||
readonly cleanup: {
|
||||
readonly owned_process_group: "verified";
|
||||
readonly temporary_root: "removed";
|
||||
/** Unrelated processes whose ownership token the host could not expose. */
|
||||
readonly unverified_processes?:
|
||||
| readonly UnverifiedCleanupProcess[]
|
||||
| undefined;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -232,10 +236,19 @@ const fileStateShape = {
|
||||
size: z.number().int().nonnegative(),
|
||||
};
|
||||
|
||||
/** An unrelated process left untouched because its ownership is unknown. */
|
||||
export interface UnverifiedCleanupProcess {
|
||||
readonly pid: number;
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
/** A resource cleanup result retained when observations cannot be verified. */
|
||||
export interface ProcessCaptureResourceCleanup {
|
||||
readonly state: "cleaned" | "failed" | "unverified" | "not_required";
|
||||
readonly reason: string | null;
|
||||
readonly unverified_processes?:
|
||||
| readonly UnverifiedCleanupProcess[]
|
||||
| undefined;
|
||||
}
|
||||
|
||||
export interface ProcessCaptureCleanupReport {
|
||||
@@ -348,6 +361,10 @@ const processSettlementSchema = z.discriminatedUnion("state", [
|
||||
}),
|
||||
]);
|
||||
|
||||
const unverifiedCleanupProcessesSchema = z.array(
|
||||
z.strictObject({ pid: z.number().int().positive(), reason: z.string() }),
|
||||
);
|
||||
|
||||
const processCaptureShapeSchema = z.strictObject({
|
||||
manifest: z.strictObject({
|
||||
rea_version: z.string().min(1),
|
||||
@@ -478,12 +495,14 @@ const processCaptureShapeSchema = z.strictObject({
|
||||
cleanup: z.object({
|
||||
owned_process_group: z.literal("verified"),
|
||||
temporary_root: z.literal("removed"),
|
||||
unverified_processes: unverifiedCleanupProcessesSchema.optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
const processCleanupResourceSchema = z.strictObject({
|
||||
state: z.enum(["cleaned", "failed", "unverified", "not_required"]),
|
||||
reason: z.string().nullable(),
|
||||
unverified_processes: unverifiedCleanupProcessesSchema.optional(),
|
||||
});
|
||||
|
||||
const partialObservationFieldSchema = <Schema extends z.ZodType>(
|
||||
|
||||
@@ -99,92 +99,102 @@ describe("capture-local process ownership", () => {
|
||||
expect(signalGroup).toHaveBeenCalledWith(process.processGroupId, "SIGKILL");
|
||||
});
|
||||
|
||||
it("cleans verified owners before reporting an unrelated opaque process", async () => {
|
||||
const owned: ProcessTableEntry = {
|
||||
pid: 905,
|
||||
parentPid: 1,
|
||||
processGroupId: 905,
|
||||
state: "S",
|
||||
command: "owned-detached-child",
|
||||
};
|
||||
const opaque: ProcessTableEntry = {
|
||||
pid: 906,
|
||||
parentPid: 1,
|
||||
processGroupId: 906,
|
||||
state: "S",
|
||||
command: "unrelated-process",
|
||||
};
|
||||
const malformed: ProcessTableEntry = {
|
||||
...opaque,
|
||||
pid: 907,
|
||||
processGroupId: 907,
|
||||
command: "malformed-procargs-process",
|
||||
};
|
||||
const sysctlDenied: ProcessTableEntry = {
|
||||
...opaque,
|
||||
pid: 908,
|
||||
processGroupId: 908,
|
||||
command: "sysctl-denied-process",
|
||||
};
|
||||
const signalGroup = vi.fn();
|
||||
const host: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([owned, opaque, malformed, sysctlDenied]),
|
||||
environment: (pid) =>
|
||||
pid === owned.pid
|
||||
? Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" })
|
||||
: Promise.reject(new Error("permission denied")),
|
||||
runTokens: (entries) =>
|
||||
Promise.resolve(
|
||||
new Map(
|
||||
entries.map(({ pid }) => [
|
||||
pid,
|
||||
pid === owned.pid
|
||||
? { state: "readable", runId: "run-token" as const }
|
||||
: {
|
||||
state: "unavailable",
|
||||
reason:
|
||||
pid === malformed.pid
|
||||
? ("malformed_procargs" as const)
|
||||
: pid === sysctlDenied.pid
|
||||
? ("sysctl_failed_1" as const)
|
||||
: ("environment_unavailable" as const),
|
||||
},
|
||||
]),
|
||||
it.skipIf(typeof process.getuid !== "function")(
|
||||
"cleans verified owners and records unrelated opaque candidates as unverified",
|
||||
async () => {
|
||||
const owned: ProcessTableEntry = {
|
||||
pid: 905,
|
||||
parentPid: 1,
|
||||
processGroupId: 905,
|
||||
state: "S",
|
||||
command: "owned-detached-child",
|
||||
};
|
||||
const opaque: ProcessTableEntry = {
|
||||
pid: 906,
|
||||
parentPid: 1,
|
||||
processGroupId: 906,
|
||||
state: "S",
|
||||
command: "/usr/bin/unrelated-process",
|
||||
};
|
||||
const malformed: ProcessTableEntry = {
|
||||
...opaque,
|
||||
pid: 907,
|
||||
processGroupId: 907,
|
||||
uid: process.getuid?.() === 0 ? 1 : 0,
|
||||
command: "/usr/bin/malformed-procargs-process",
|
||||
};
|
||||
const sysctlDenied: ProcessTableEntry = {
|
||||
...opaque,
|
||||
pid: 908,
|
||||
processGroupId: 908,
|
||||
uid: process.getuid?.() === 0 ? 1 : 0,
|
||||
command: "/usr/bin/sysctl-denied-process",
|
||||
};
|
||||
const signalGroup = vi.fn();
|
||||
const host: ProcessOwnershipHost = {
|
||||
platform: "darwin",
|
||||
listProcesses: () =>
|
||||
Promise.resolve([owned, opaque, malformed, sysctlDenied]),
|
||||
environment: (pid) =>
|
||||
pid === owned.pid
|
||||
? Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" })
|
||||
: Promise.reject(new Error("permission denied")),
|
||||
runTokens: (entries) =>
|
||||
Promise.resolve(
|
||||
new Map(
|
||||
entries.map(({ pid }) => [
|
||||
pid,
|
||||
pid === owned.pid
|
||||
? { state: "readable", runId: "run-token" as const }
|
||||
: {
|
||||
state: "unavailable",
|
||||
reason:
|
||||
pid === malformed.pid
|
||||
? ("malformed_procargs" as const)
|
||||
: pid === sysctlDenied.pid
|
||||
? ("sysctl_failed_1" as const)
|
||||
: ("platform_binary_environment_withheld" as const),
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
signalGroup,
|
||||
};
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
await expect(
|
||||
cleanupOwnedProcessGroup(
|
||||
{
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
},
|
||||
host,
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
cleaned: false,
|
||||
reason:
|
||||
"process ownership token could not be read for 3 live process(es): environment_unavailable=1, malformed_procargs=1, sysctl_errno_1=1",
|
||||
});
|
||||
expect(signalGroup).toHaveBeenCalledWith(owned.processGroupId, "SIGKILL");
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(
|
||||
opaque.processGroupId,
|
||||
"SIGKILL",
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(
|
||||
malformed.processGroupId,
|
||||
"SIGKILL",
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(
|
||||
sysctlDenied.processGroupId,
|
||||
"SIGKILL",
|
||||
);
|
||||
});
|
||||
await expect(
|
||||
cleanupOwnedProcessGroup(
|
||||
{
|
||||
runId: "run-token",
|
||||
leaderPid: 100,
|
||||
processGroupId: 100,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
},
|
||||
host,
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
unverified: [
|
||||
{ pid: 906, diagnostic: "platform_binary_environment_withheld" },
|
||||
{ pid: 907, diagnostic: "malformed_procargs" },
|
||||
{ pid: 908, diagnostic: "sysctl_failed_1" },
|
||||
],
|
||||
});
|
||||
expect(signalGroup).toHaveBeenCalledWith(owned.processGroupId, "SIGKILL");
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(
|
||||
opaque.processGroupId,
|
||||
"SIGKILL",
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(
|
||||
malformed.processGroupId,
|
||||
"SIGKILL",
|
||||
);
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(
|
||||
sysctlDenied.processGroupId,
|
||||
"SIGKILL",
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("capture-local process identity baselines", () => {
|
||||
|
||||
@@ -214,4 +214,38 @@ describe("process environment permission diagnostics", () => {
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(typeof process.getuid !== "function")(
|
||||
"records a foreign-uid unreadable candidate as unverified without signaling",
|
||||
async () => {
|
||||
const foreignUid = process.getuid?.() === 0 ? 1 : 0;
|
||||
const signalGroup = vi.fn();
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
uid: foreignUid,
|
||||
state: "S",
|
||||
command: "unverifiable-process",
|
||||
},
|
||||
]),
|
||||
environment: () => Promise.reject(new Error("EINVAL: sysctl failed")),
|
||||
signalGroup,
|
||||
};
|
||||
await expect(
|
||||
cleanupOwnedProcessGroup(
|
||||
{ ...ownership, sweepTokenOwnedProcesses: true },
|
||||
adapter,
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
unverified: [{ pid: 900, diagnostic: "EINVAL: sysctl failed" }],
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -67,7 +67,7 @@ describe("owned process-group cleanup discovery", () => {
|
||||
});
|
||||
|
||||
describe("opaque process neighbors during cleanup", () => {
|
||||
it("cleans verified run-owned groups while reporting an opaque neighbor", async () => {
|
||||
it("cleans verified run-owned groups and records a withheld unrelated neighbor", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100, command: "capture" },
|
||||
{
|
||||
@@ -76,6 +76,71 @@ describe("opaque process neighbors during cleanup", () => {
|
||||
processGroupId: 200,
|
||||
command: "detached-child",
|
||||
},
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
processGroupId: 900,
|
||||
command: "/usr/bin/opaque-neighbor",
|
||||
},
|
||||
].map((process) => ({ ...process, state: "S" }));
|
||||
const signalGroup = vi.fn();
|
||||
const identities = new Map(
|
||||
processes.map(({ pid }) => [
|
||||
pid,
|
||||
{ state: "readable" as const, identity: `start-${String(pid)}` },
|
||||
]),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
platform: "darwin",
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
REA_PROCESS_RUN_ID: pid === 900 ? "unowned" : "run-token",
|
||||
}),
|
||||
processIdentities: () => Promise.resolve(identities),
|
||||
runTokens: (members) =>
|
||||
Promise.resolve(
|
||||
new Map(
|
||||
members.map(({ pid }) => [
|
||||
pid,
|
||||
pid === 900
|
||||
? {
|
||||
state: "unavailable" as const,
|
||||
reason: "platform_binary_environment_withheld",
|
||||
}
|
||||
: { state: "readable" as const, runId: "run-token" },
|
||||
]),
|
||||
),
|
||||
),
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
const result = await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
captureBaseline: [],
|
||||
},
|
||||
adapter,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
unverified: [
|
||||
{ pid: 900, diagnostic: "platform_binary_environment_withheld" },
|
||||
],
|
||||
});
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[200, "SIGKILL"],
|
||||
]);
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(900, "SIGKILL");
|
||||
});
|
||||
|
||||
it("fails closed for an unrelated unreadable candidate the OS should expose", async () => {
|
||||
const processes = [
|
||||
{ pid: 100, parentPid: 1, processGroupId: 100, command: "capture" },
|
||||
{
|
||||
pid: 900,
|
||||
parentPid: 1,
|
||||
@@ -91,6 +156,7 @@ describe("opaque process neighbors during cleanup", () => {
|
||||
]),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
platform: "darwin",
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: (pid) =>
|
||||
Promise.resolve({
|
||||
@@ -127,14 +193,83 @@ describe("opaque process neighbors during cleanup", () => {
|
||||
cleaned: false,
|
||||
reason: expect.stringContaining("environment_unavailable=1"),
|
||||
});
|
||||
expect(signalGroup.mock.calls).toEqual([
|
||||
[100, "SIGKILL"],
|
||||
[200, "SIGKILL"],
|
||||
]);
|
||||
expect(signalGroup.mock.calls).toEqual([[100, "SIGKILL"]]);
|
||||
expect(signalGroup).not.toHaveBeenCalledWith(900, "SIGKILL");
|
||||
});
|
||||
});
|
||||
|
||||
describe("related sweep candidates during cleanup", () => {
|
||||
it.each(["environment_unavailable", "platform_binary_environment_withheld"])(
|
||||
"fails closed for a related candidate with %s",
|
||||
async (diagnostic) => {
|
||||
const processes = [
|
||||
{
|
||||
pid: 100,
|
||||
parentPid: 1,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
command: "capture",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
parentPid: 100,
|
||||
processGroupId: 100,
|
||||
state: "S",
|
||||
uid: process.getuid?.() === 0 ? 1 : 0,
|
||||
command: "ready-hang",
|
||||
},
|
||||
];
|
||||
const signalGroup = vi.fn();
|
||||
const identities = new Map(
|
||||
processes.map(({ pid }) => [
|
||||
pid,
|
||||
{ state: "readable" as const, identity: `start-${String(pid)}` },
|
||||
]),
|
||||
);
|
||||
const adapter: ProcessOwnershipHost = {
|
||||
listProcesses: () => Promise.resolve(processes),
|
||||
environment: (pid) =>
|
||||
pid === 100
|
||||
? Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" })
|
||||
: Promise.reject(new Error("EACCES: permission denied")),
|
||||
processIdentities: () => Promise.resolve(identities),
|
||||
runTokens: (members) =>
|
||||
Promise.resolve(
|
||||
new Map(
|
||||
members.map(({ pid }) => [
|
||||
pid,
|
||||
pid === 100
|
||||
? { state: "readable" as const, runId: "run-token" }
|
||||
: {
|
||||
state: "unavailable" as const,
|
||||
reason: diagnostic,
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
signalGroup,
|
||||
};
|
||||
|
||||
const result = await cleanupOwnedProcessGroup(
|
||||
{
|
||||
...ownership,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
captureBaseline: [],
|
||||
},
|
||||
adapter,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
cleaned: false,
|
||||
reason: expect.stringContaining(
|
||||
"process ownership token could not be read",
|
||||
),
|
||||
});
|
||||
expect(signalGroup).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("sampled detached process groups during cleanup", () => {
|
||||
it("signals only token-authenticated sampled groups and reports an unowned sample", async () => {
|
||||
const processes = [
|
||||
|
||||
+272
-52
@@ -41,6 +41,8 @@ export interface ProcessTableEntry {
|
||||
readonly pid: number;
|
||||
readonly parentPid: number;
|
||||
readonly processGroupId: number;
|
||||
/** Effective owner when the process table reports it. */
|
||||
readonly uid?: number;
|
||||
readonly state: string;
|
||||
readonly command: string;
|
||||
}
|
||||
@@ -123,9 +125,33 @@ interface ProcessOwnershipValidationFailure {
|
||||
readonly diagnostic?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One live process the ownership sweep could not attribute or exonerate.
|
||||
* Recorded as evidence instead of failing the capture: the process is not
|
||||
* related to the owned tree, so cleanup cannot act on it and the operating
|
||||
* system withheld or removed its token (for example, macOS strips the
|
||||
* environment of Apple platform binaries, and foreign-uid processes return
|
||||
* EINVAL for KERN_PROCARGS2).
|
||||
*/
|
||||
export interface OwnershipSweepUnverifiedProcess {
|
||||
readonly pid: number;
|
||||
readonly diagnostic: string;
|
||||
}
|
||||
|
||||
/** Capture-owned process structures used to classify sweep candidates. */
|
||||
export interface OwnershipSweepRelation {
|
||||
readonly leaderPid: number;
|
||||
readonly processGroupId: number;
|
||||
readonly sampledProcessGroupIds?: readonly number[];
|
||||
}
|
||||
|
||||
/** Cleanup outcome with per-member diagnostics when ownership is uncertain. */
|
||||
export type ProcessCleanupResult =
|
||||
| { readonly cleaned: true; readonly signaled: boolean }
|
||||
| {
|
||||
readonly cleaned: true;
|
||||
readonly signaled: boolean;
|
||||
readonly unverified?: readonly OwnershipSweepUnverifiedProcess[];
|
||||
}
|
||||
| {
|
||||
readonly cleaned: false;
|
||||
readonly reason: string;
|
||||
@@ -137,6 +163,7 @@ export type ProcessCleanupResult =
|
||||
| "process-identity-unavailable";
|
||||
readonly diagnostic?: string;
|
||||
}[];
|
||||
readonly unverified?: readonly OwnershipSweepUnverifiedProcess[];
|
||||
};
|
||||
|
||||
/** Token-verified liveness result used by post-root-exit settlement. */
|
||||
@@ -242,8 +269,12 @@ export const cleanupOwnedProcessGroup = async (
|
||||
}
|
||||
}
|
||||
if (plan.unresolved.length > 0)
|
||||
return cleanupValidationFailure(plan.unresolved);
|
||||
return { cleaned: true, signaled };
|
||||
return cleanupValidationFailure(plan.unresolved, plan.unverified);
|
||||
return {
|
||||
cleaned: true,
|
||||
signaled,
|
||||
...(plan.unverified.length === 0 ? {} : { unverified: plan.unverified }),
|
||||
};
|
||||
};
|
||||
|
||||
/** Verify that no live process still carries an owned capture run token. */
|
||||
@@ -251,6 +282,7 @@ export const verifyNoTokenOwnedProcesses = async (
|
||||
runId: string,
|
||||
host: ProcessOwnershipHost = systemHost,
|
||||
captureBaseline?: ProcessOwnershipBaseline,
|
||||
relation?: OwnershipSweepRelation,
|
||||
): Promise<ProcessCleanupResult> => {
|
||||
const processTable = await readLiveProcessTable(host);
|
||||
if (!processTable.available)
|
||||
@@ -263,11 +295,21 @@ export const verifyNoTokenOwnedProcesses = async (
|
||||
runId,
|
||||
host,
|
||||
captureBaseline,
|
||||
relation,
|
||||
);
|
||||
if (scan.failures.length > 0) return cleanupValidationFailure(scan.failures);
|
||||
return scan.owned.length === 0
|
||||
? { cleaned: true, signaled: false }
|
||||
: { cleaned: false, reason: "token-owned process remained after cleanup" };
|
||||
if (scan.failures.length > 0)
|
||||
return cleanupValidationFailure(scan.failures, scan.unverified);
|
||||
if (scan.owned.length > 0)
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "token-owned process remained after cleanup",
|
||||
...(scan.unverified.length === 0 ? {} : { unverified: scan.unverified }),
|
||||
};
|
||||
return {
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
...(scan.unverified.length === 0 ? {} : { unverified: scan.unverified }),
|
||||
};
|
||||
};
|
||||
|
||||
const readLiveProcessTable = async (
|
||||
@@ -293,6 +335,7 @@ interface OwnedCleanupPlan {
|
||||
readonly signalOrder: readonly number[];
|
||||
readonly tokenOwnedIdentities: ReadonlyMap<number, string | null>;
|
||||
readonly unresolved: readonly ProcessOwnershipValidationFailure[];
|
||||
readonly unverified: readonly OwnershipSweepUnverifiedProcess[];
|
||||
}
|
||||
|
||||
const createOwnedCleanupPlan = async (
|
||||
@@ -313,8 +356,15 @@ const createOwnedCleanupPlan = async (
|
||||
ownership.runId,
|
||||
host,
|
||||
ownership.captureBaseline,
|
||||
{
|
||||
leaderPid: ownership.leaderPid,
|
||||
processGroupId: ownership.processGroupId,
|
||||
...(sampledProcessGroupIds.size === 0
|
||||
? {}
|
||||
: { sampledProcessGroupIds: [...sampledProcessGroupIds] }),
|
||||
},
|
||||
)
|
||||
: { owned: [], failures: [], identities: new Map() };
|
||||
: { owned: [], failures: [], unverified: [], identities: new Map() };
|
||||
const tokenOwnedGroupIds = new Set(
|
||||
tokenOwned.owned.map(({ processGroupId }) => processGroupId),
|
||||
);
|
||||
@@ -335,8 +385,15 @@ const createOwnedCleanupPlan = async (
|
||||
signalOrder: [],
|
||||
tokenOwnedIdentities: tokenOwned.identities,
|
||||
unresolved: tokenOwned.failures,
|
||||
unverified: tokenOwned.unverified,
|
||||
}
|
||||
: { cleaned: true, signaled: false };
|
||||
: {
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
...(tokenOwned.unverified.length === 0
|
||||
? {}
|
||||
: { unverified: tokenOwned.unverified }),
|
||||
};
|
||||
let descendants: readonly ProcessTableEntry[] = [];
|
||||
if (launcher !== undefined) {
|
||||
const identityFailure = launcherIdentityFailure(launcher, ownership);
|
||||
@@ -413,7 +470,7 @@ const createOwnedCleanupPlan = async (
|
||||
signalableGroups.add(processGroupId);
|
||||
}
|
||||
if (ownership.sweepTokenOwnedProcesses !== true && unresolved.length > 0)
|
||||
return cleanupValidationFailure(unresolved);
|
||||
return cleanupValidationFailure(unresolved, tokenOwned.unverified);
|
||||
return {
|
||||
signalOrder: [...signalableGroups]
|
||||
.filter((groupId) => processGroupIds.has(groupId))
|
||||
@@ -426,6 +483,7 @@ const createOwnedCleanupPlan = async (
|
||||
),
|
||||
tokenOwnedIdentities: tokenOwned.identities,
|
||||
unresolved,
|
||||
unverified: tokenOwned.unverified,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -478,7 +536,9 @@ const revalidateOwnedProcessGroup = async (
|
||||
|
||||
const cleanupValidationFailure = (
|
||||
failures: readonly ProcessOwnershipValidationFailure[],
|
||||
unverified: readonly OwnershipSweepUnverifiedProcess[] = [],
|
||||
): ProcessCleanupResult => {
|
||||
const unverifiedEntry = unverified.length === 0 ? {} : { unverified };
|
||||
const unreadable = failures.filter(
|
||||
({ reason }) => reason === "environment-unreadable",
|
||||
);
|
||||
@@ -487,12 +547,14 @@ const cleanupValidationFailure = (
|
||||
cleaned: false,
|
||||
reason: "process tree contains an unowned or PID-reused process",
|
||||
failures,
|
||||
...unverifiedEntry,
|
||||
};
|
||||
if (failures.some(({ reason }) => reason === "process-identity-unavailable"))
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "process identity could not be revalidated",
|
||||
failures,
|
||||
...unverifiedEntry,
|
||||
};
|
||||
if (unreadable.length > 0) {
|
||||
const counts = new Map<string, number>();
|
||||
@@ -508,17 +570,20 @@ const cleanupValidationFailure = (
|
||||
cleaned: false,
|
||||
reason: `process ownership token could not be read for ${String(unreadable.length)} live process(es): ${breakdown}`,
|
||||
failures,
|
||||
...unverifiedEntry,
|
||||
};
|
||||
}
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "process ownership could not be revalidated",
|
||||
failures,
|
||||
...unverifiedEntry,
|
||||
};
|
||||
};
|
||||
|
||||
const sanitizedTokenReadFailure = (diagnostic: string | undefined): string => {
|
||||
if (diagnostic === "environment_unavailable") return diagnostic;
|
||||
if (diagnostic === "platform_binary_environment_withheld") return diagnostic;
|
||||
const environmentErrno = /^(EACCES|EPERM|ENOENT|ESRCH):/u.exec(
|
||||
diagnostic ?? "",
|
||||
);
|
||||
@@ -630,14 +695,50 @@ const processOwnershipFailures = async (
|
||||
interface TokenOwnedProcessScan {
|
||||
readonly owned: readonly ProcessTableEntry[];
|
||||
readonly failures: readonly ProcessOwnershipValidationFailure[];
|
||||
readonly unverified: readonly OwnershipSweepUnverifiedProcess[];
|
||||
readonly identities: ReadonlyMap<number, string | null>;
|
||||
}
|
||||
|
||||
/** One sweep candidate whose run token could not be read. */
|
||||
interface UnreadableTokenCandidate {
|
||||
readonly process: ProcessTableEntry;
|
||||
readonly diagnostic: string;
|
||||
}
|
||||
|
||||
const TOKEN_READ_RETRY_ATTEMPTS = 3;
|
||||
const TOKEN_READ_RETRY_DELAY_MS = 40;
|
||||
|
||||
/** Darwin reports this when the kernel withholds a platform binary's environment. */
|
||||
const PLATFORM_BINARY_ENVIRONMENT_WITHHELD =
|
||||
"platform_binary_environment_withheld";
|
||||
|
||||
const currentProcessUid = (): number | undefined =>
|
||||
typeof process.getuid === "function" ? process.getuid() : undefined;
|
||||
|
||||
/**
|
||||
* Whether the operating system provably withheld this candidate's run token:
|
||||
* current macOS omits the environment of Apple platform binaries from
|
||||
* KERN_PROCARGS2 and fails with EINVAL for processes owned by another
|
||||
* account, and neither class can be token-verified by any caller. Such a
|
||||
* candidate is recorded as unverified instead of failing an otherwise clean
|
||||
* capture; every other unreadable candidate stays fail-closed.
|
||||
*/
|
||||
const environmentWithheldFromInspection = (
|
||||
entry: ProcessTableEntry,
|
||||
diagnostic: string,
|
||||
): boolean => {
|
||||
const uid = currentProcessUid();
|
||||
if (uid !== undefined && entry.uid !== undefined && entry.uid !== uid)
|
||||
return true;
|
||||
return diagnostic === PLATFORM_BINARY_ENVIRONMENT_WITHHELD;
|
||||
};
|
||||
|
||||
const scanTokenOwnedProcesses = async (
|
||||
processes: readonly ProcessTableEntry[],
|
||||
runId: string,
|
||||
host: ProcessOwnershipHost,
|
||||
captureBaseline?: ProcessOwnershipBaseline,
|
||||
relation?: OwnershipSweepRelation,
|
||||
): Promise<TokenOwnedProcessScan> => {
|
||||
let candidates = processes;
|
||||
let candidateIdentities: ReadonlyMap<number, ProcessIdentityObservation> =
|
||||
@@ -678,61 +779,98 @@ const scanTokenOwnedProcesses = async (
|
||||
}
|
||||
candidates = stableCandidates;
|
||||
}
|
||||
const owned: ProcessTableEntry[] = [];
|
||||
const ownedIdentities = new Map<number, string | null>();
|
||||
const recordOwned = (process: ProcessTableEntry): void => {
|
||||
owned.push(process);
|
||||
const identity = candidateIdentities.get(process.pid);
|
||||
ownedIdentities.set(
|
||||
process.pid,
|
||||
identity?.state === "readable" ? identity.identity : null,
|
||||
);
|
||||
};
|
||||
let bulkTokens: ReadonlyMap<number, ProcessRunTokenObservation> | undefined;
|
||||
if (host.runTokens !== undefined)
|
||||
bulkTokens = await host.runTokens(candidates);
|
||||
const owned: ProcessTableEntry[] = [];
|
||||
const ownedIdentities = new Map<number, string | null>();
|
||||
const unreadable: UnreadableTokenCandidate[] = [];
|
||||
for (const process of candidates) {
|
||||
const bulkToken = bulkTokens?.get(process.pid);
|
||||
if (bulkToken !== undefined) {
|
||||
if (bulkToken.state === "readable") {
|
||||
if (bulkToken.runId === runId) {
|
||||
owned.push(process);
|
||||
const identity = candidateIdentities.get(process.pid);
|
||||
ownedIdentities.set(
|
||||
process.pid,
|
||||
identity?.state === "readable" ? identity.identity : null,
|
||||
);
|
||||
}
|
||||
if (bulkToken.runId === runId) recordOwned(process);
|
||||
continue;
|
||||
}
|
||||
if (!(await processIsGone(host, process.pid)))
|
||||
failures.push({
|
||||
pid: process.pid,
|
||||
reason: "environment-unreadable",
|
||||
diagnostic: bulkToken.reason,
|
||||
});
|
||||
unreadable.push({ process, diagnostic: bulkToken.reason });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if ((await host.environment(process.pid)).REA_PROCESS_RUN_ID === runId) {
|
||||
owned.push(process);
|
||||
const identity = candidateIdentities.get(process.pid);
|
||||
ownedIdentities.set(
|
||||
process.pid,
|
||||
identity?.state === "readable" ? identity.identity : null,
|
||||
);
|
||||
}
|
||||
if ((await host.environment(process.pid)).REA_PROCESS_RUN_ID === runId)
|
||||
recordOwned(process);
|
||||
} catch (cause: unknown) {
|
||||
try {
|
||||
const live = liveProcesses(await host.listProcesses());
|
||||
if (!live.some(({ pid }) => pid === process.pid)) continue;
|
||||
} catch (recheckCause: unknown) {
|
||||
failures.push({
|
||||
pid: process.pid,
|
||||
reason: "environment-unreadable",
|
||||
diagnostic: `${errorMessage(cause)}; process liveness recheck failed: ${errorMessage(recheckCause)}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
failures.push({
|
||||
pid: process.pid,
|
||||
reason: "environment-unreadable",
|
||||
diagnostic: errorMessage(cause),
|
||||
});
|
||||
unreadable.push({ process, diagnostic: errorMessage(cause) });
|
||||
}
|
||||
}
|
||||
const remaining = await settleUnreadableTokenCandidates(
|
||||
unreadable,
|
||||
runId,
|
||||
host,
|
||||
recordOwned,
|
||||
);
|
||||
const relatedPids = new Set<number>();
|
||||
const relatedGroupIds = new Set<number>();
|
||||
if (relation !== undefined) {
|
||||
relatedPids.add(relation.leaderPid);
|
||||
for (const descendant of descendantsOf(relation.leaderPid, processes))
|
||||
relatedPids.add(descendant.pid);
|
||||
relatedGroupIds.add(relation.processGroupId);
|
||||
for (const processGroupId of relation.sampledProcessGroupIds ?? [])
|
||||
if (Number.isSafeInteger(processGroupId) && processGroupId > 0)
|
||||
relatedGroupIds.add(processGroupId);
|
||||
for (const process of owned) relatedGroupIds.add(process.processGroupId);
|
||||
}
|
||||
const unverified: OwnershipSweepUnverifiedProcess[] = [];
|
||||
const strict: UnreadableTokenCandidate[] = [];
|
||||
const withheld: UnreadableTokenCandidate[] = [];
|
||||
for (const candidate of remaining) {
|
||||
const isRelated =
|
||||
relation === undefined ||
|
||||
relatedPids.has(candidate.process.pid) ||
|
||||
relatedGroupIds.has(candidate.process.processGroupId);
|
||||
if (
|
||||
!isRelated &&
|
||||
environmentWithheldFromInspection(candidate.process, candidate.diagnostic)
|
||||
) {
|
||||
withheld.push(candidate);
|
||||
continue;
|
||||
}
|
||||
strict.push(candidate);
|
||||
}
|
||||
let finalLive: ReadonlySet<number> | undefined;
|
||||
try {
|
||||
finalLive = new Set(
|
||||
liveProcesses(await host.listProcesses()).map(({ pid }) => pid),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
finalLive = undefined;
|
||||
}
|
||||
for (const candidate of strict) {
|
||||
if (finalLive !== undefined && !finalLive.has(candidate.process.pid))
|
||||
continue;
|
||||
failures.push({
|
||||
pid: candidate.process.pid,
|
||||
reason: "environment-unreadable",
|
||||
diagnostic: candidate.diagnostic,
|
||||
});
|
||||
}
|
||||
for (const candidate of withheld) {
|
||||
if (finalLive !== undefined && !finalLive.has(candidate.process.pid))
|
||||
continue;
|
||||
unverified.push({
|
||||
pid: candidate.process.pid,
|
||||
diagnostic: candidate.diagnostic,
|
||||
});
|
||||
}
|
||||
if (candidates.length > 0 && host.processIdentities !== undefined) {
|
||||
const afterRead = await host.processIdentities(candidates);
|
||||
const stillOwned: ProcessTableEntry[] = [];
|
||||
@@ -756,9 +894,91 @@ const scanTokenOwnedProcesses = async (
|
||||
"process identity changed or became unavailable during token validation",
|
||||
});
|
||||
}
|
||||
return { owned: stillOwned, failures, identities: ownedIdentities };
|
||||
return {
|
||||
owned: stillOwned,
|
||||
failures,
|
||||
unverified,
|
||||
identities: ownedIdentities,
|
||||
};
|
||||
}
|
||||
return { owned, failures, unverified, identities: ownedIdentities };
|
||||
};
|
||||
|
||||
/**
|
||||
* Re-read run tokens for unresolved sweep candidates so transient exec and
|
||||
* exit states settle before classification. Each attempt revalidates
|
||||
* liveness, refreshes the diagnostic, and is bounded by a fixed attempt
|
||||
* budget; a still-unreadable candidate keeps its latest diagnostic.
|
||||
*/
|
||||
const settleUnreadableTokenCandidates = async (
|
||||
pending: readonly UnreadableTokenCandidate[],
|
||||
runId: string,
|
||||
host: ProcessOwnershipHost,
|
||||
recordOwned: (process: ProcessTableEntry) => void,
|
||||
): Promise<readonly UnreadableTokenCandidate[]> => {
|
||||
let remaining = pending;
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < TOKEN_READ_RETRY_ATTEMPTS && remaining.length > 0;
|
||||
attempt += 1
|
||||
) {
|
||||
await new Promise<void>((resolve) =>
|
||||
setTimeout(resolve, TOKEN_READ_RETRY_DELAY_MS),
|
||||
);
|
||||
let live: ReadonlySet<number> | undefined;
|
||||
try {
|
||||
live = new Set(
|
||||
liveProcesses(await host.listProcesses()).map(({ pid }) => pid),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
live = undefined;
|
||||
}
|
||||
let observations:
|
||||
| ReadonlyMap<number, ProcessRunTokenObservation>
|
||||
| undefined;
|
||||
if (host.runTokens !== undefined) {
|
||||
try {
|
||||
observations = await host.runTokens(
|
||||
remaining.map(({ process }) => process),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
void cause;
|
||||
observations = undefined;
|
||||
}
|
||||
}
|
||||
const stillUnreadable: UnreadableTokenCandidate[] = [];
|
||||
for (const candidate of remaining) {
|
||||
const pid = candidate.process.pid;
|
||||
if (live !== undefined && !live.has(pid)) continue;
|
||||
const observation =
|
||||
observations?.get(pid) ?? (await readEnvironmentRunToken(host, pid));
|
||||
if (observation.state === "readable") {
|
||||
if (observation.runId === runId) recordOwned(candidate.process);
|
||||
continue;
|
||||
}
|
||||
stillUnreadable.push({
|
||||
process: candidate.process,
|
||||
diagnostic: observation.reason,
|
||||
});
|
||||
}
|
||||
remaining = stillUnreadable;
|
||||
}
|
||||
return remaining;
|
||||
};
|
||||
|
||||
const readEnvironmentRunToken = async (
|
||||
host: ProcessOwnershipHost,
|
||||
pid: number,
|
||||
): Promise<ProcessRunTokenObservation> => {
|
||||
try {
|
||||
return {
|
||||
state: "readable",
|
||||
runId: (await host.environment(pid)).REA_PROCESS_RUN_ID,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
return { state: "unavailable", reason: errorMessage(cause) };
|
||||
}
|
||||
return { owned, failures, identities: ownedIdentities };
|
||||
};
|
||||
|
||||
const processIsGone = async (
|
||||
|
||||
@@ -192,19 +192,22 @@ export const createSystemProcessOwnershipHost = (
|
||||
if (platform === "win32") return [];
|
||||
const { stdout } = await execFileOutput(
|
||||
"ps",
|
||||
["-axo", "pid=,ppid=,pgid=,stat=,command="],
|
||||
["-axo", "pid=,ppid=,pgid=,uid=,stat=,command="],
|
||||
{ env: hostEnvironment, ...(signal === undefined ? {} : { signal }) },
|
||||
);
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => /\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)/u.exec(line))
|
||||
.map((line) =>
|
||||
/\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)/u.exec(line),
|
||||
)
|
||||
.filter((match): match is RegExpExecArray => match !== null)
|
||||
.map((match) => ({
|
||||
pid: Number(match[1]),
|
||||
parentPid: Number(match[2]),
|
||||
processGroupId: Number(match[3]),
|
||||
state: match[4] ?? "",
|
||||
command: match[5] ?? "",
|
||||
uid: Number(match[4]),
|
||||
state: match[5] ?? "",
|
||||
command: match[6] ?? "",
|
||||
}));
|
||||
};
|
||||
const processIdentities: NonNullable<
|
||||
|
||||
@@ -704,10 +704,18 @@ export const releaseProcessResources = async (options: {
|
||||
"owned process cleanup is unverifiable on Windows without process-job authority",
|
||||
};
|
||||
} else {
|
||||
const terminalPid = options.terminal.pid;
|
||||
const relation = {
|
||||
leaderPid: terminalPid,
|
||||
processGroupId: terminalPid,
|
||||
...(options.sampledProcessGroupIds === undefined
|
||||
? {}
|
||||
: { sampledProcessGroupIds: options.sampledProcessGroupIds }),
|
||||
};
|
||||
const cleaned = await host.cleanupProcessGroup({
|
||||
runId: options.runId,
|
||||
leaderPid: options.terminal.pid,
|
||||
processGroupId: options.terminal.pid,
|
||||
leaderPid: terminalPid,
|
||||
processGroupId: terminalPid,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
...(options.sampledProcessGroupIds === undefined
|
||||
? {}
|
||||
@@ -716,6 +724,7 @@ export const releaseProcessResources = async (options: {
|
||||
? {}
|
||||
: { captureBaseline: options.captureBaseline }),
|
||||
});
|
||||
const unverified = [...(cleaned.unverified ?? [])];
|
||||
if (!cleaned.cleaned) {
|
||||
ownedProcessGroup = { state: "unverified", reason: cleaned.reason };
|
||||
} else {
|
||||
@@ -724,11 +733,25 @@ export const releaseProcessResources = async (options: {
|
||||
options.runId,
|
||||
undefined,
|
||||
options.captureBaseline,
|
||||
relation,
|
||||
),
|
||||
);
|
||||
unverified.push(...(verified.unverified ?? []));
|
||||
if (!verified.cleaned)
|
||||
ownedProcessGroup = { state: "unverified", reason: verified.reason };
|
||||
}
|
||||
if (unverified.length > 0)
|
||||
ownedProcessGroup = {
|
||||
...ownedProcessGroup,
|
||||
unverified_processes: [
|
||||
...new Map(
|
||||
unverified.map(({ pid, diagnostic }) => [
|
||||
`${String(pid)}:${diagnostic}`,
|
||||
{ pid, reason: diagnostic },
|
||||
]),
|
||||
).values(),
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
let temporaryRoot: ProcessCaptureCleanupReport["temporary_root"] = {
|
||||
@@ -892,7 +915,8 @@ export const resolveProcessResult = (
|
||||
}
|
||||
if (capture === undefined)
|
||||
throw new ProcessCaptureError("process capture produced no result");
|
||||
if ("cleanup" in capture) return capture;
|
||||
const unverifiedProcesses = cleanup.owned_process_group.unverified_processes;
|
||||
if ("cleanup" in capture && unverifiedProcesses === undefined) return capture;
|
||||
|
||||
const settlement: UnverifiedProcessCapture["settlement"] =
|
||||
capture.settlement.state === "quiesced"
|
||||
@@ -902,9 +926,20 @@ export const resolveProcessResult = (
|
||||
return parseProcessCapture({
|
||||
...capture,
|
||||
settlement,
|
||||
residual_unknowns: [
|
||||
...capture.residual_unknowns,
|
||||
...(unverifiedProcesses ?? []).map(({ pid, reason }) => ({
|
||||
scope: "process" as const,
|
||||
reason: `Ownership of unrelated process ${String(pid)} could not be verified; it was left untouched: ${reason}`,
|
||||
})),
|
||||
],
|
||||
cleanup: {
|
||||
...("cleanup" in capture ? capture.cleanup : {}),
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
...(unverifiedProcesses === undefined
|
||||
? {}
|
||||
: { unverified_processes: unverifiedProcesses }),
|
||||
},
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
|
||||
@@ -142,6 +142,64 @@ it("waits for token-owned processes to exit after one cleanup signal", async ()
|
||||
}
|
||||
});
|
||||
|
||||
it("retains unrelated withheld processes through cleanup, capture, and JSON", async () => {
|
||||
const host: ProcessCaptureCleanupHost = {
|
||||
platform: "darwin",
|
||||
cleanupProcessGroup: async () => ({
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
unverified: [
|
||||
{ pid: 900, diagnostic: "platform_binary_environment_withheld" },
|
||||
],
|
||||
}),
|
||||
verifyTokenOwnedProcesses: async () => ({
|
||||
cleaned: true,
|
||||
signaled: false,
|
||||
unverified: [{ pid: 901, diagnostic: "foreign uid: EINVAL" }],
|
||||
}),
|
||||
removeTemporaryRoot: async () => undefined,
|
||||
};
|
||||
const report = await releaseProcessResources({
|
||||
timers: new Set(),
|
||||
terminal: { pid: 321 },
|
||||
renderer: undefined,
|
||||
runId: "fixture-run",
|
||||
temporaryRoot: "/fixture/root",
|
||||
host,
|
||||
});
|
||||
const unverified = [
|
||||
{ pid: 900, reason: "platform_binary_environment_withheld" },
|
||||
{ pid: 901, reason: "foreign uid: EINVAL" },
|
||||
];
|
||||
expect(report.owned_process_group).toEqual({
|
||||
state: "cleaned",
|
||||
reason: null,
|
||||
unverified_processes: unverified,
|
||||
});
|
||||
const original = emptyProcessCapture();
|
||||
const { cleanup: previousCleanup, ...pending } = original;
|
||||
for (const input of [pending, original]) {
|
||||
const resolved = resolveProcessResult(input, undefined, report);
|
||||
const serialized: unknown = JSON.parse(JSON.stringify(resolved));
|
||||
const capture = parseProcessCapture(serialized);
|
||||
expect(capture.cleanup).toEqual({
|
||||
...previousCleanup,
|
||||
unverified_processes: unverified,
|
||||
});
|
||||
expect(capture.residual_unknowns).toEqual([
|
||||
...original.residual_unknowns,
|
||||
{
|
||||
scope: "process",
|
||||
reason: expect.stringContaining("900 could not be verified"),
|
||||
},
|
||||
{
|
||||
scope: "process",
|
||||
reason: expect.stringContaining("901 could not be verified"),
|
||||
},
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("retains the last ownership failure when the verification grace expires", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
@@ -246,6 +304,9 @@ it("retains observations and both causes when process cleanup is unverifiable",
|
||||
state: "unverified" as const,
|
||||
reason:
|
||||
"process ownership token could not be read for 1 live process(es): environment_unavailable=1",
|
||||
unverified_processes: [
|
||||
{ pid: 900, reason: "platform_binary_environment_withheld" },
|
||||
],
|
||||
},
|
||||
terminal_renderer: { state: "cleaned" as const, reason: null },
|
||||
temporary_root: { state: "cleaned" as const, reason: null },
|
||||
|
||||
Reference in New Issue
Block a user