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:
@@ -3,6 +3,7 @@ import { constants } from "node:fs";
|
|||||||
import { lstat, open, readlink, realpath } from "node:fs/promises";
|
import { lstat, open, readlink, realpath } from "node:fs/promises";
|
||||||
import { join, relative, sep } from "node:path";
|
import { join, relative, sep } from "node:path";
|
||||||
|
|
||||||
|
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
|
||||||
import { resolveTreePath } from "../../domain/apple/dyldPaths.js";
|
import { resolveTreePath } from "../../domain/apple/dyldPaths.js";
|
||||||
import {
|
import {
|
||||||
dylibResolutionInputSchema,
|
dylibResolutionInputSchema,
|
||||||
@@ -13,10 +14,12 @@ import {
|
|||||||
type DylibTreeView,
|
type DylibTreeView,
|
||||||
type MachoImageFacts,
|
type MachoImageFacts,
|
||||||
} from "../../domain/apple/dylibResolution.js";
|
} from "../../domain/apple/dylibResolution.js";
|
||||||
|
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
|
||||||
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
import { ArtifactReaderFailure } from "../ArtifactReader.js";
|
||||||
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||||
import { hasMachoMagic, readMachoImage } from "./MachoLoadCommandReader.js";
|
import { hasMachoMagic, readMachoImage } from "./MachoLoadCommandReader.js";
|
||||||
|
|
||||||
|
const OPERATION = "trace_dylib_resolution";
|
||||||
const HASH_CHUNK_BYTES = 1024 * 1024;
|
const HASH_CHUNK_BYTES = 1024 * 1024;
|
||||||
|
|
||||||
/** Device, inode, size and change times of the file whose bytes were parsed. */
|
/** Device, inode, size and change times of the file whose bytes were parsed. */
|
||||||
@@ -86,9 +89,10 @@ export const traceDylibResolution = async (options: {
|
|||||||
}): Promise<DylibResolutionResult> => {
|
}): Promise<DylibResolutionResult> => {
|
||||||
const parsed = dylibResolutionInputSchema.safeParse(options.parameters);
|
const parsed = dylibResolutionInputSchema.safeParse(options.parameters);
|
||||||
if (!parsed.success)
|
if (!parsed.success)
|
||||||
throw new ArtifactReaderFailure(
|
throw new AnalysisInputError(
|
||||||
"path",
|
OPERATION,
|
||||||
"roots must be normalized paths relative to the analyzed root",
|
{ cause: parsed.error },
|
||||||
|
projectInputIssues(parsed.error.issues, options.parameters),
|
||||||
);
|
);
|
||||||
// Canonicalization is inside the translated region: a revoked permission
|
// Canonicalization is inside the translated region: a revoked permission
|
||||||
// keeps its reason and path.
|
// keeps its reason and path.
|
||||||
@@ -105,7 +109,11 @@ export const traceDylibResolution = async (options: {
|
|||||||
: options.enumerateRoots
|
: options.enumerateRoots
|
||||||
? await executableRoots(root, view, options.signal)
|
? await executableRoots(root, view, options.signal)
|
||||||
: { roots: [target], unclassified: [] };
|
: { roots: [target], unclassified: [] };
|
||||||
const roots = await requireMachoRoots(view, requested);
|
const roots = await requireMachoRoots(
|
||||||
|
view,
|
||||||
|
requested,
|
||||||
|
parsed.data.roots !== undefined,
|
||||||
|
);
|
||||||
const trace = await traceDylibLoading(view, {
|
const trace = await traceDylibLoading(view, {
|
||||||
roots,
|
roots,
|
||||||
unclassified,
|
unclassified,
|
||||||
@@ -203,29 +211,35 @@ const compare = (left: string, right: string): number =>
|
|||||||
/**
|
/**
|
||||||
* Resolve each root segment by segment, as dependency candidates are, so a
|
* Resolve each root segment by segment, as dependency candidates are, so a
|
||||||
* symlink in an intermediate directory cannot lead outside the analyzed root.
|
* 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 (
|
const requireMachoRoots = async (
|
||||||
view: FilesystemTreeView,
|
view: FilesystemTreeView,
|
||||||
roots: readonly string[],
|
roots: readonly string[],
|
||||||
|
callerSelected: boolean,
|
||||||
): Promise<string[]> => {
|
): Promise<string[]> => {
|
||||||
const resolved: 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);
|
const lookup = await resolveTreePath(view, path);
|
||||||
if (lookup.kind === "escapes")
|
if (lookup.kind === "escapes")
|
||||||
throw new ArtifactReaderFailure(
|
throw reject("path", `Root ${path} resolves outside the analyzed root`);
|
||||||
"path",
|
|
||||||
`Root ${path} resolves outside the analyzed root`,
|
|
||||||
);
|
|
||||||
if (lookup.kind !== "file")
|
if (lookup.kind !== "file")
|
||||||
throw new ArtifactReaderFailure(
|
throw reject(
|
||||||
"path",
|
"path",
|
||||||
`Root ${path} is not a regular file in the analyzed root`,
|
`Root ${path} is not a regular file in the analyzed root`,
|
||||||
);
|
);
|
||||||
if ((await view.image(lookup.path)).status === "not-mach-o")
|
if ((await view.image(lookup.path)).status === "not-mach-o")
|
||||||
throw new ArtifactReaderFailure(
|
throw reject("format", `Root ${path} is not a Mach-O image`);
|
||||||
"format",
|
|
||||||
`Root ${path} is not a Mach-O image`,
|
|
||||||
);
|
|
||||||
if (!resolved.includes(lookup.path)) resolved.push(lookup.path);
|
if (!resolved.includes(lookup.path)) resolved.push(lookup.path);
|
||||||
}
|
}
|
||||||
return resolved;
|
return resolved;
|
||||||
|
|||||||
@@ -22,7 +22,13 @@ import {
|
|||||||
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
|
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
|
||||||
const ROOT_RELATIVE_PATH =
|
const ROOT_RELATIVE_PATH =
|
||||||
/^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
|
/^(?!\/)(?!(?:.*\/)?\.{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. */
|
/** Caller selection of process roots and one CPU slice. */
|
||||||
export const dylibResolutionInputSchema = z.strictObject({
|
export const dylibResolutionInputSchema = z.strictObject({
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import {
|
|||||||
import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
|
import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
|
||||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.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" };
|
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 fixtureApp = async (): Promise<string> => {
|
||||||
const app = join(
|
const app = join(
|
||||||
await createTestTempDirectory("rea-dylib-cli-"),
|
await createTestTempDirectory("rea-dylib-cli-"),
|
||||||
@@ -141,17 +176,16 @@ describe("trace-dylib-resolution CLI", () => {
|
|||||||
const outside = await createTestTempDirectory("rea-dylib-outside-");
|
const outside = await createTestTempDirectory("rea-dylib-outside-");
|
||||||
await writeFiles(outside, { Tool: machoImage({}) });
|
await writeFiles(outside, { Tool: machoImage({}) });
|
||||||
await symlink(outside, join(app, "Contents/Linked"));
|
await symlink(outside, join(app, "Contents/Linked"));
|
||||||
for (const root of [
|
for (const [root, reason, message] of [
|
||||||
"../outside",
|
["../outside", "invalid_format", "Use a normalized path"],
|
||||||
"Contents/Info.plist",
|
["Contents/Info.plist", "invalid_value", "is not a Mach-O image"],
|
||||||
"Contents/Linked/Tool",
|
[
|
||||||
]) {
|
"Contents/Linked/Tool",
|
||||||
const rejected = await cli.run({
|
"invalid_value",
|
||||||
arguments: ["trace-dylib-resolution", app, "--root", root, "--json"],
|
"resolves outside the analyzed root",
|
||||||
environment: ENVIRONMENT,
|
],
|
||||||
});
|
] as const) {
|
||||||
expect(rejected.exitCode).toBe(1);
|
await expectRootInputError(cli, { app, root, reason, message });
|
||||||
expect(rejected.json).toMatchObject({ error: "Analysis failed" });
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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 { join } from "node:path";
|
||||||
|
|
||||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
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}`),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user