Merge pull request #1159 from morluto/fix/dylib-resolution-root-input-errors

fix(apple): report unusable dylib-resolution roots as invalid input
This commit is contained in:
Kaoru0822
2026-10-08 19:23:22 -07:00
committed by GitHub
4 changed files with 132 additions and 28 deletions
+28 -14
View File
@@ -3,6 +3,7 @@ import { constants } from "node:fs";
import { lstat, open, readlink, realpath } from "node:fs/promises";
import { join, relative, sep } from "node:path";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { resolveTreePath } from "../../domain/apple/dyldPaths.js";
import {
dylibResolutionInputSchema,
@@ -13,10 +14,12 @@ import {
type DylibTreeView,
type MachoImageFacts,
} from "../../domain/apple/dylibResolution.js";
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { hasMachoMagic, readMachoImage } from "./MachoLoadCommandReader.js";
const OPERATION = "trace_dylib_resolution";
const HASH_CHUNK_BYTES = 1024 * 1024;
/** Device, inode, size and change times of the file whose bytes were parsed. */
@@ -86,9 +89,10 @@ export const traceDylibResolution = async (options: {
}): Promise<DylibResolutionResult> => {
const parsed = dylibResolutionInputSchema.safeParse(options.parameters);
if (!parsed.success)
throw new ArtifactReaderFailure(
"path",
"roots must be normalized paths relative to the analyzed root",
throw new AnalysisInputError(
OPERATION,
{ cause: parsed.error },
projectInputIssues(parsed.error.issues, options.parameters),
);
// Canonicalization is inside the translated region: a revoked permission
// keeps its reason and path.
@@ -105,7 +109,11 @@ export const traceDylibResolution = async (options: {
: options.enumerateRoots
? await executableRoots(root, view, options.signal)
: { roots: [target], unclassified: [] };
const roots = await requireMachoRoots(view, requested);
const roots = await requireMachoRoots(
view,
requested,
parsed.data.roots !== undefined,
);
const trace = await traceDylibLoading(view, {
roots,
unclassified,
@@ -203,29 +211,35 @@ const compare = (left: string, right: string): number =>
/**
* Resolve each root segment by segment, as dependency candidates are, so a
* symlink in an intermediate directory cannot lead outside the analyzed root.
* A root the caller selected that fails is an input error on that root; a
* root REA derived itself keeps reporting an artifact failure.
*/
const requireMachoRoots = async (
view: FilesystemTreeView,
roots: readonly string[],
callerSelected: boolean,
): Promise<string[]> => {
const resolved: string[] = [];
for (const path of roots) {
for (const [index, path] of roots.entries()) {
const reject = (
reason: "path" | "format",
message: string,
): AnalysisInputError | ArtifactReaderFailure =>
callerSelected
? new AnalysisInputError(OPERATION, undefined, [
{ path: ["roots", index], reason: "invalid_value", message },
])
: new ArtifactReaderFailure(reason, message);
const lookup = await resolveTreePath(view, path);
if (lookup.kind === "escapes")
throw new ArtifactReaderFailure(
"path",
`Root ${path} resolves outside the analyzed root`,
);
throw reject("path", `Root ${path} resolves outside the analyzed root`);
if (lookup.kind !== "file")
throw new ArtifactReaderFailure(
throw reject(
"path",
`Root ${path} is not a regular file in the analyzed root`,
);
if ((await view.image(lookup.path)).status === "not-mach-o")
throw new ArtifactReaderFailure(
"format",
`Root ${path} is not a Mach-O image`,
);
throw reject("format", `Root ${path} is not a Mach-O image`);
if (!resolved.includes(lookup.path)) resolved.push(lookup.path);
}
return resolved;
+7 -1
View File
@@ -22,7 +22,13 @@ import {
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
const ROOT_RELATIVE_PATH =
/^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
const rootRelativePathSchema = z
.string()
.min(1)
.regex(
ROOT_RELATIVE_PATH,
"Use a normalized path relative to the analyzed root, without a leading or trailing '/', '//', or '.' and '..' segments",
);
/** Caller selection of process roots and one CPU slice. */
export const dylibResolutionInputSchema = z.strictObject({
+46 -12
View File
@@ -15,7 +15,7 @@ import {
import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
const ENVIRONMENT = { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" };
@@ -29,6 +29,41 @@ const writeFiles = async (
}
};
/** A caller-selected root that cannot be traced is an input issue on that root. */
const expectRootInputError = async (
cli: TestCli,
{
app,
root,
reason,
message,
}: {
readonly app: string;
readonly root: string;
readonly reason: string;
readonly message: string;
},
): Promise<void> => {
const rejected = await cli.run({
arguments: ["trace-dylib-resolution", app, "--root", root, "--json"],
environment: ENVIRONMENT,
});
expect(rejected.exitCode).toBe(1);
expect(rejected.json).toMatchObject({
error: "Analysis failed",
code: "invalid_request",
details: {
issues: [
{
path: ["roots", 0],
reason,
message: expect.stringContaining(message),
},
],
},
});
};
const fixtureApp = async (): Promise<string> => {
const app = join(
await createTestTempDirectory("rea-dylib-cli-"),
@@ -141,17 +176,16 @@ describe("trace-dylib-resolution CLI", () => {
const outside = await createTestTempDirectory("rea-dylib-outside-");
await writeFiles(outside, { Tool: machoImage({}) });
await symlink(outside, join(app, "Contents/Linked"));
for (const root of [
"../outside",
"Contents/Info.plist",
"Contents/Linked/Tool",
]) {
const rejected = await cli.run({
arguments: ["trace-dylib-resolution", app, "--root", root, "--json"],
environment: ENVIRONMENT,
});
expect(rejected.exitCode).toBe(1);
expect(rejected.json).toMatchObject({ error: "Analysis failed" });
for (const [root, reason, message] of [
["../outside", "invalid_format", "Use a normalized path"],
["Contents/Info.plist", "invalid_value", "is not a Mach-O image"],
[
"Contents/Linked/Tool",
"invalid_value",
"resolves outside the analyzed root",
],
] as const) {
await expectRootInputError(cli, { app, root, reason, message });
}
},
);
+51 -1
View File
@@ -1,4 +1,4 @@
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -375,3 +375,53 @@ it.each([
});
},
);
it("reports caller-selected roots that cannot be traced as invalid input", async () => {
const app = join(
await createTestTempDirectory("rea-dylib-roots-"),
"Fixture.app",
);
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await writeFile(
join(app, "Contents/Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
);
await writeFile(
join(app, "Contents/MacOS/App"),
machoImage({ commands: [buildVersionCommand(1)] }),
);
await symlink("/bin/ls", join(app, "Contents/MacOS/outside"));
await withClient(async (client) => {
const opened = await client.callTool({
name: "open_binary",
arguments: { path: app },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
for (const [root, message] of [
["Contents/MacOS/Missing", "is not a regular file"],
["Contents/MacOS", "is not a regular file"],
["Contents/Info.plist", "is not a Mach-O image"],
["Contents/MacOS/outside", "resolves outside the analyzed root"],
] as const) {
const called = await client.callTool({
name: "trace_dylib_resolution",
arguments: { roots: ["Contents/MacOS/App", root] },
});
expect(called.isError, root).toBe(true);
expect(called.structuredContent, root).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [
{
path: ["roots", 1],
reason: "invalid_value",
message: expect.stringContaining(`Root ${root} ${message}`),
},
],
},
},
});
}
});
});