feat(native): read embedded cargo-auditable Rust dependency lists (#2456)

* feat(native): read embedded cargo-auditable Rust dependency lists

* fix(native): trim PE section padding and compute dependency cycles iteratively

* fix(native): ignore SHT_NOBITS sections and validate dependency edges linearly

* fix(native): bound compiler path scanning and retained hashes

* fix(rust): pass package arrays as named parameterized test cases

* fix(rust): admit graph expansion and preserve resource units

* fix(rust): reject malformed packages, false cycles, and hidden compiler paths

Fail the first malformed cargo-auditable package before Zod collects an
issue per field. Require cyclic dependency indices to match the cycles in
package dependencies. Keep read-only ELF ranges when a section name does
not fit the bounded name window, so a rustc path in that range is still
reported.

* fix(ci): repair integrated checks and Hopper test baseline

* fix(go): verify Mach-O sections against segments

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
Matt Van Horn
2026-10-14 02:50:30 +08:00
committed by GitHub
co-authored by Matt Van Horn morluto Cursor Agent
parent c7ceaadb70
commit 0e6eca4085
59 changed files with 2767 additions and 12 deletions
+1 -1
View File
@@ -343,7 +343,7 @@ const workflowAvailabilityFor = ({
kind,
policy,
}: AvailabilityContext): Availability | null => {
if (name === "inspect_go_binary")
if (name === "inspect_go_binary" || name === "inspect_rust_binary")
return { reason: "available", remediation: null };
if (name === "inspect_sqlite_database") {
const capability = sqliteDatabaseCapability(process.versions.node);
+19
View File
@@ -0,0 +1,19 @@
import type {
ExecutionOptions,
ProviderIdentity,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
InspectRustBinaryInput,
RustBinary,
} from "../../domain/rust/rustBinary.js";
import type { Result } from "../../domain/result.js";
/** Replaceable offline dependency reader with no target-execution authority. */
export interface RustBinaryPort {
readonly identity: ProviderIdentity;
inspect(
input: InspectRustBinaryInput,
options?: ExecutionOptions,
): Promise<Result<RustBinary, AnalysisError>>;
}
@@ -0,0 +1,132 @@
import { expect, it } from "vitest";
import {
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import type { RustBinary } from "../../domain/rust/rustBinary.js";
import { ok } from "../../domain/result.js";
import { RustBinaryService } from "./RustBinaryService.js";
const identity = {
id: "fixture-rust",
name: "Source-owned Rust reader seam",
version: "1",
};
const report: RustBinary = {
artifact: { path: "/artifacts/program", sha256: "a".repeat(64), bytes: 128 },
format: "elf",
architecture: "amd64",
bits: 64,
byte_order: "little",
auditable_metadata: {
section_name: ".dep-v0",
file_offset: 16,
section_bytes: 8,
compressed_bytes: 8,
uncompressed_bytes: 20,
format_version: 1,
packages: [
{
name: "sample",
version: "0.1.0",
source: "local",
kind: null,
dependencies: [],
root: true,
},
],
root_package_index: 0,
dependency_edges: [],
cyclic_dependency_indices: [],
},
rustc_commit: null,
limitations: [
"No /rustc/<40-hex>/ path was found in read-only data, so a rustc commit hash is unknown.",
],
};
it("rejects a relative path and extra arguments before reading", async () => {
let calls = 0;
const service = new RustBinaryService({
identity,
inspect: () => {
calls += 1;
return Promise.resolve(ok(report));
},
});
const relative = await service.inspect({ path: "program" });
const extra = await service.inspect({
path: report.artifact.path,
detail: "complete",
});
expect(relative.ok).toBe(false);
expect(extra.ok).toBe(false);
if (!relative.ok) expect(relative.error).toBeInstanceOf(AnalysisInputError);
if (!extra.ok) expect(extra.error).toBeInstanceOf(AnalysisInputError);
expect(calls).toBe(0);
});
it("records the selected artifact and the dependency section range", async () => {
const result = await new RustBinaryService({
identity,
inspect: () => Promise.resolve(ok(report)),
}).inspect({ path: report.artifact.path });
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
confidence: "observed",
subject: { format: "elf", architecture: "x86_64" },
normalized_result: report,
locations: [
{ kind: "artifact-path", path: report.artifact.path },
{ kind: "file-offset-range", start: 16, end: 24 },
],
});
const mismatched: RustBinary = {
...report,
artifact: { ...report.artifact, path: "/artifacts/other" },
};
const invalid = await new RustBinaryService({
identity,
inspect: () => Promise.resolve(ok(mismatched)),
}).inspect({ path: report.artifact.path });
expect(invalid.ok).toBe(false);
if (!invalid.ok) expect(invalid.error).toBeInstanceOf(AnalysisOutputError);
});
it("rejects a cycle claim the package dependencies do not contain", async () => {
if (report.auditable_metadata === null) throw new Error("expected metadata");
const invalidReport: RustBinary = {
...report,
auditable_metadata: {
...report.auditable_metadata,
cyclic_dependency_indices: [0],
},
};
const result = await new RustBinaryService({
identity,
inspect: () => Promise.resolve(ok(invalidReport)),
}).inspect({ path: report.artifact.path });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it.each([
{ from_index: 1, to_index: 0 },
{ from_index: 0, to_index: 1 },
])("rejects provider edges referencing missing packages: %j", async (edge) => {
if (report.auditable_metadata === null) throw new Error("expected metadata");
const invalidReport: RustBinary = {
...report,
auditable_metadata: {
...report.auditable_metadata,
dependency_edges: [edge],
},
};
const result = await new RustBinaryService({
identity,
inspect: () => Promise.resolve(ok(invalidReport)),
}).inspect({ path: report.artifact.path });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
+113
View File
@@ -0,0 +1,113 @@
import { isAbsolute } from "node:path";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { RustBinaryPort } from "./RustBinaryPort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { BINARY_ARCHITECTURES } from "../../domain/binaryTargetTypes.js";
import {
inspectRustBinaryInputSchema,
rustBinarySchema,
} from "../../domain/rust/rustBinary.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
const OPERATION = "inspect_rust_binary";
const architectureForSubject = (architecture: string) => {
switch (architecture) {
case "386":
return "x86";
case "amd64":
return "x86_64";
default:
return BINARY_ARCHITECTURES.find(
(supported) => supported === architecture,
);
}
};
/** Shared exact input validation and artifact-bound Evidence for CLI and MCP. */
export class RustBinaryService {
constructor(readonly provider: RustBinaryPort) {}
/** Inspect one explicitly selected file without acquiring a binary session. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const input = inspectRustBinaryInputSchema.safeParse(rawInput);
if (!input.success)
return err(
analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput, {
cause: input.error,
}),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute filesystem path on this host.",
},
]),
);
const inspected = await this.provider.inspect(input.data, options);
if (!inspected.ok) return inspected;
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const report = rustBinarySchema.safeParse(inspected.value);
if (!report.success || report.data.artifact.path !== input.data.path)
return err(
new AnalysisOutputError(
OPERATION,
"Rust dependency reader returned malformed metadata or changed the selected artifact identity.",
),
);
return ok(evidenceFor(this.provider.identity, input.data, report.data));
}
}
const evidenceFor = (
provider: RustBinaryPort["identity"],
parameters: { readonly path: string },
value: ReturnType<typeof rustBinarySchema.parse>,
): Evidence => {
const architecture = architectureForSubject(value.architecture);
const section = value.auditable_metadata;
return createEvidence(
{
path: value.artifact.path,
sha256: value.artifact.sha256,
format: value.format === "macho" ? "mach-o" : value.format,
...(architecture === undefined ? {} : { architecture }),
},
provider,
{
operation: OPERATION,
parameters,
result: value,
confidence: "observed",
limitations: value.limitations,
locations: [
{ kind: "artifact-path", path: value.artifact.path },
...(section === null
? []
: [
{
kind: "file-offset-range" as const,
start: section.file_offset,
end: section.file_offset + section.section_bytes,
},
]),
],
},
);
};
+2
View File
@@ -5,6 +5,7 @@ import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
import { createDirectAnalysis } from "./composition/directAnalysis.js";
import { registerEvmCommands } from "./cli/evmCommands.js";
import { registerGoCommands } from "./cli/goCommands.js";
import { registerRustCommands } from "./cli/rustCommands.js";
import { registerSqliteCommands } from "./cli/sqliteCommands.js";
import { registerAnalysisViewCommands } from "./cli/analysisViewCommands.js";
import { registerBinaryDiagnosticsCommands } from "./cli/binaryDiagnosticsCommands.js";
@@ -101,6 +102,7 @@ export const createCli = (
registerSignalCommands(cli, logger, environment);
registerEvmCommands(cli, logger, environment);
registerGoCommands(cli, logger);
registerRustCommands(cli, logger);
registerSqliteCommands(cli, logger, environment);
registerArtifactCommands(cli, logger, analysis.runProviderAnalysis);
registerManagedCommands(cli, logger, analysis.runProviderAnalysis);
+34
View File
@@ -0,0 +1,34 @@
import { z } from "incur";
import { resolve } from "node:path";
import { createRustBinaryService } from "../composition/rust.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
/** Resolve caller paths and inspect embedded Rust dependencies through the shared workflow. */
export const registerRustCommands = (
cli: CliInstance,
logger: Logger,
): void => {
const service = createRustBinaryService();
cli.command(CLI_COMMANDS.inspectRustBinary, {
description:
"Inspect an embedded cargo-auditable Rust dependency list without target execution",
args: z.object({
path: z.string().describe("Local ELF, PE or thin Mach-O image"),
}),
run: ({ args }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectRustBinary, async () => {
const result = await service.inspect(
{ path: resolve(args.path) },
{ signal },
);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
),
});
};
+1
View File
@@ -50,6 +50,7 @@ export const CLI_COMMANDS = Object.freeze({
inspectRecordedCrash: "inspect-recorded-crash",
inspectBinaryLayout: "inspect-binary-layout",
inspectGoBinary: "inspect-go-binary",
inspectRustBinary: "inspect-rust-binary",
inspectPeResources: "inspect-pe-resources",
inspectAnalysisView: "inspect-analysis-view",
listFridaDevices: "list-frida-devices",
+6
View File
@@ -0,0 +1,6 @@
import { RustBinaryService } from "../application/rust/RustBinaryService.js";
import { RustBinaryProvider } from "../rust/RustBinaryProvider.js";
/** Compose bundled offline inspection without a Rust toolchain or any child process. */
export const createRustBinaryService = (): RustBinaryService =>
new RustBinaryService(new RustBinaryProvider());
+26
View File
@@ -0,0 +1,26 @@
import {
inspectRustBinaryInputSchema,
rustBinarySchema,
} from "../../domain/rust/rustBinary.js";
import type { ToolContract } from "../toolContractTypes.js";
import { toolContractMetadata } from "../toolEffects.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
/** Static Rust dependency metadata is independent of active native-analysis providers. */
export const RUST_TOOL_CONTRACTS = [
{
name: "inspect_rust_binary",
...toolContractMetadata("inspect_rust_binary"),
kind: "artifact-provider",
description:
"Inspect the cargo-auditable crate dependency list embedded in an explicit local ELF, PE or thin Mach-O image. Returns the artifact SHA-256, the .dep-v0 section file offset and size, compressed and uncompressed sizes, format version, packages in their original order, the root package index, and dependency edges by index. Reads zlib-compressed JSON without installing Rust, opening a disassembler, executing the target, writing temporary files or accessing the network. A missing section is null metadata with a limitation and is not proof that the binary has no dependencies. A rustc commit hash is reported only as an inference when a /rustc/<40-hex>/ path is present in read-only data. Resource guards bound files to 256 MiB, dependency sections to 1 MiB, inflated JSON to the smaller of 8 MiB and 64 times the compressed size, and the complete report to 8 MiB. Malformed, unsupported and oversized inputs receive typed failures rather than partial success.",
inputSchema: inspectRustBinaryInputSchema,
outputSchema: evidenceResultOf(rustBinarySchema),
examples: [
{
title: "Inspect an embedded Rust dependency list",
input: { path: "/artifacts/application" },
},
],
},
] as const satisfies readonly ToolContract[];
+2
View File
@@ -3,6 +3,7 @@ import { SIGNAL_TOOL_CONTRACTS } from "./signals/signalToolContracts.js";
import { WASM_TOOL_CONTRACTS } from "./wasm/wasmToolContracts.js";
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
import { GO_TOOL_CONTRACTS } from "./go/goToolContracts.js";
import { RUST_TOOL_CONTRACTS } from "./rust/rustToolContracts.js";
import { SQLITE_TOOL_CONTRACTS } from "./sqlite/sqliteToolContracts.js";
import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "./analysisViewToolContracts.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
@@ -40,6 +41,7 @@ export const TOOL_CONTRACTS = [
...ARTIFACT_TOOL_CONTRACTS,
...EVM_TOOL_CONTRACTS,
...GO_TOOL_CONTRACTS,
...RUST_TOOL_CONTRACTS,
...WASM_TOOL_CONTRACTS,
...SQLITE_TOOL_CONTRACTS,
...CAPTURE_TOOL_CONTRACTS,
+2
View File
@@ -19,6 +19,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
resolve_native_call_targets: "states that it does not execute code",
inspect_pe_resources: "states that it does not execute the image",
inspect_go_binary: "reads embedded metadata without executing the target",
inspect_rust_binary:
"reads an embedded dependency list without executing the target",
inspect_sqlite_database:
"uses a trusted inspector worker without executing application code or caller SQL",
inspect_binary_layout:
+1
View File
@@ -54,6 +54,7 @@ const sessionEvidence = effects({ mutatesSession: true });
/** Explicit effect audit for every public tool. */
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
inspect_go_binary: evidence,
inspect_rust_binary: evidence,
inspect_sqlite_database: effects({
mutatesSession: true,
writesFilesystem: true,
+294
View File
@@ -0,0 +1,294 @@
import { z } from "zod";
import { digestSchema } from "../digests.js";
import { localPathStringSchema } from "../localPath.js";
export const RUST_AUDITABLE_FORMAT_VERSION = 1;
const index = z.number().int().nonnegative();
const rustcHash = z.string().regex(/^[0-9a-f]{40}$/u);
/** One embedded package, with omitted kind and root preserved as null and false. */
export const rustPackageSchema = z.strictObject({
name: z.string().min(1),
version: z.string().min(1),
source: z.string().min(1),
kind: z.enum(["runtime", "build"]).nullable(),
dependencies: z.array(index),
root: z.boolean(),
});
const dependencyEdgeSchema = z.strictObject({
from_index: index,
to_index: index,
});
/** zlib JSON from one `.dep-v0` section, in the section's package order. */
export const rustAuditableMetadataSchema = z.strictObject({
section_name: z.enum([".dep-v0", "__DATA,.dep-v0"]),
file_offset: index,
section_bytes: z.number().int().positive(),
compressed_bytes: z.number().int().positive(),
uncompressed_bytes: z.number().int().positive(),
format_version: z.literal(RUST_AUDITABLE_FORMAT_VERSION).nullable(),
packages: z.array(rustPackageSchema),
root_package_index: index.nullable(),
dependency_edges: z.array(dependencyEdgeSchema),
cyclic_dependency_indices: z.array(index),
});
/** Inferred compiler id from read-only `/rustc/<40-hex>/` paths. */
export const rustcCommitSchema = z.strictObject({
evidence_kind: z.literal("inferred"),
hashes: z
.array(
z.strictObject({
hash: rustcHash,
file_offset: index,
}),
)
.min(1),
});
/** One explicit local executable or library, independent of a disassembler target. */
export const inspectRustBinaryInputSchema = z.strictObject({
path: localPathStringSchema.describe(
"Absolute filesystem path to the selected executable or library",
),
});
/** Bounded cargo-auditable observation. A missing section is null, not an empty dependency list. */
export const rustBinarySchema = z
.strictObject({
artifact: z.strictObject({
path: localPathStringSchema,
sha256: digestSchema,
bytes: index,
}),
format: z.enum(["elf", "pe", "macho"]),
architecture: z.string(),
bits: z.union([z.literal(32), z.literal(64)]),
byte_order: z.enum(["little", "big"]),
auditable_metadata: rustAuditableMetadataSchema.nullable(),
rustc_commit: rustcCommitSchema.nullable(),
limitations: z.array(z.string()),
})
.superRefine((report, context) => {
const metadata = report.auditable_metadata;
if (metadata !== null) {
checkSection(report.artifact.bytes, metadata, context);
checkPackages(metadata, context);
}
checkRustc(report.artifact.bytes, report.rustc_commit, context);
});
export type RustPackage = z.infer<typeof rustPackageSchema>;
export type RustAuditableMetadata = z.infer<typeof rustAuditableMetadataSchema>;
export type RustBinary = z.infer<typeof rustBinarySchema>;
export type InspectRustBinaryInput = z.infer<
typeof inspectRustBinaryInputSchema
>;
const issue = (
context: z.RefinementCtx,
path: (string | number)[],
message: string,
): void => {
context.addIssue({ code: "custom", path, message });
};
const inside = (fileBytes: number, offset: number, size: number): boolean =>
offset <= fileBytes && size <= fileBytes - offset;
const checkSection = (
fileBytes: number,
metadata: RustAuditableMetadata,
context: z.RefinementCtx,
): void => {
if (
!inside(fileBytes, metadata.file_offset, metadata.section_bytes) ||
metadata.compressed_bytes !== metadata.section_bytes
)
issue(
context,
["auditable_metadata", "file_offset"],
"Dependency section range is outside the selected artifact or disagrees with its compressed size.",
);
};
const checkPackages = (
metadata: RustAuditableMetadata,
context: z.RefinementCtx,
): void => {
const roots: number[] = [];
const edgesByPackage = new Map<
number,
z.infer<typeof dependencyEdgeSchema>[]
>();
for (const [position, edge] of metadata.dependency_edges.entries()) {
if (
edge.from_index >= metadata.packages.length ||
edge.to_index >= metadata.packages.length
) {
issue(
context,
["auditable_metadata", "dependency_edges", position],
"Dependency edge index is outside the package list.",
);
continue;
}
const grouped = edgesByPackage.get(edge.from_index);
if (grouped === undefined) edgesByPackage.set(edge.from_index, [edge]);
else grouped.push(edge);
}
for (const [packageIndex, pkg] of metadata.packages.entries()) {
if (pkg.root) roots.push(packageIndex);
const edges = edgesByPackage.get(packageIndex) ?? [];
if (
edges.length !== pkg.dependencies.length ||
edges.some((edge, index) => edge.to_index !== pkg.dependencies[index])
)
issue(
context,
["auditable_metadata", "dependency_edges"],
"Dependency edges do not match package dependency indices.",
);
if (pkg.dependencies.some((target) => target >= metadata.packages.length))
issue(
context,
["auditable_metadata", "packages", packageIndex, "dependencies"],
"Dependency index is outside the package list.",
);
}
const root = metadata.root_package_index;
if (
root === null ? roots.length !== 0 : roots.length !== 1 || roots[0] !== root
)
issue(
context,
["auditable_metadata", "root_package_index"],
"Root package index does not match packages marked root.",
);
const cycles = cyclicDependencyIndices(metadata.packages);
if (
cycles.length !== metadata.cyclic_dependency_indices.length ||
cycles.some(
(index, position) =>
metadata.cyclic_dependency_indices[position] !== index,
)
)
issue(
context,
["auditable_metadata", "cyclic_dependency_indices"],
"Cyclic dependency indices do not match the cycles in package dependencies.",
);
};
/** Package indices that participate in a dependency cycle, in ascending order. */
export const cyclicDependencyIndices = (
packages: readonly { readonly dependencies: readonly number[] }[],
): number[] => {
const edges = packages.map((pkg) => pkg.dependencies);
const order = dependencyPostorder(edges);
const reversed = reversedDependencyEdges(edges);
const seen = new Uint8Array(edges.length);
const cyclic = new Set<number>();
for (let cursor = order.length - 1; cursor >= 0; cursor -= 1) {
const start = order[cursor];
if (start === undefined || seen[start] === 1) continue;
const component = dependencyComponent(start, reversed, seen);
if (dependencyComponentInCycle(component, edges))
for (const index of component) cyclic.add(index);
}
return [...cyclic].sort((left, right) => left - right);
};
interface DependencyWalkFrame {
readonly index: number;
edge: number;
}
const dependencyPostorder = (
edges: readonly (readonly number[])[],
): number[] => {
const seen = new Uint8Array(edges.length);
const order: number[] = [];
for (let start = 0; start < edges.length; start += 1) {
if (seen[start] === 1) continue;
const stack: DependencyWalkFrame[] = [{ index: start, edge: 0 }];
seen[start] = 1;
while (stack.length > 0) {
const frame = stack[stack.length - 1];
if (frame === undefined) break;
const next = edges[frame.index]?.[frame.edge];
if (next === undefined) {
stack.pop();
order.push(frame.index);
continue;
}
frame.edge += 1;
if (seen[next] === 0) {
seen[next] = 1;
stack.push({ index: next, edge: 0 });
}
}
}
return order;
};
const reversedDependencyEdges = (
edges: readonly (readonly number[])[],
): number[][] => {
const reversed = Array.from({ length: edges.length }, () => [] as number[]);
for (let from = 0; from < edges.length; from += 1)
for (const to of edges[from] ?? []) reversed[to]?.push(from);
return reversed;
};
const dependencyComponent = (
start: number,
reversed: readonly (readonly number[])[],
seen: Uint8Array,
): number[] => {
const component: number[] = [];
const stack = [start];
seen[start] = 1;
while (stack.length > 0) {
const index = stack.pop();
if (index === undefined) break;
component.push(index);
for (const next of reversed[index] ?? []) {
if (seen[next] === 0) {
seen[next] = 1;
stack.push(next);
}
}
}
return component;
};
const dependencyComponentInCycle = (
component: readonly number[],
edges: readonly (readonly number[])[],
): boolean => {
if (component.length > 1) return true;
const only = component[0];
return only !== undefined && (edges[only]?.includes(only) ?? false);
};
const checkRustc = (
fileBytes: number,
commit: RustBinary["rustc_commit"],
context: z.RefinementCtx,
): void => {
if (commit === null) return;
const seen = new Set<string>();
for (const [position, entry] of commit.hashes.entries()) {
if (seen.has(entry.hash) || !inside(fileBytes, entry.file_offset, 48))
issue(
context,
["rustc_commit", "hashes", position],
"rustc path hash is duplicated or its file offset is outside the artifact.",
);
seen.add(entry.hash);
}
};
+37
View File
@@ -34,6 +34,16 @@ export interface GoZeroFillMapping {
readonly size: bigint;
}
/** One named file section. Invalid declared ranges stay visible with `file_backed: false`. */
export interface GoImageSection {
readonly name: string;
readonly offset: number;
readonly size: number;
readonly file_backed: boolean;
readonly read_only: boolean;
readonly compressed: boolean;
}
/** Native container facts and its producer-defined build-info search area. */
export interface GoBinaryContainer {
readonly format: "elf" | "pe" | "macho";
@@ -42,6 +52,7 @@ export interface GoBinaryContainer {
readonly byte_order: "little" | "big";
readonly mappings: readonly GoFileMapping[];
readonly zero_fills: readonly GoZeroFillMapping[];
readonly sections: readonly GoImageSection[];
readonly search: GoFileMapping | null;
}
@@ -110,6 +121,32 @@ export class GoBinaryReader {
}
}
/** Admit a declared file span, or mark it unbacked when it leaves the file. */
export const declaredFileRange = (
fileBytes: number,
offset: bigint,
size: bigint,
): {
readonly offset: number;
readonly size: number;
readonly file_backed: boolean;
} => {
if (
offset < 0n ||
size < 0n ||
offset > BigInt(Number.MAX_SAFE_INTEGER) ||
size > BigInt(Number.MAX_SAFE_INTEGER) ||
offset > BigInt(fileBytes) ||
size > BigInt(fileBytes) - offset
)
return { offset: 0, size: 0, file_backed: false };
return {
offset: Number(offset),
size: Number(size),
file_backed: size > 0n,
};
};
/** Map a virtual span without losing precision or selecting an ambiguous alias. */
export const mappedFileOffset = (
mappings: readonly GoFileMapping[],
+3 -2
View File
@@ -55,7 +55,7 @@ export interface GoBinaryImage {
/** Inspect bounded executable bytes using native mappings, without loading or executing code. */
export const readGoBinaryImage = (bytes: Buffer): GoBinaryImage => {
const container = readContainer(bytes);
const container = readGoBinaryContainer(bytes);
const { format, architecture, bits, byte_order } = container;
const search = container.search;
const header = findHeader(bytes, search);
@@ -184,7 +184,8 @@ interface LocatedString {
readonly location: GoStringLocation;
}
const readContainer = (bytes: Buffer): GoBinaryContainer => {
/** Identify an ELF, PE, or thin Mach-O image and its named file sections. */
export const readGoBinaryContainer = (bytes: Buffer): GoBinaryContainer => {
if (bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
return readGoElfImage(bytes);
if (bytes.subarray(0, 2).equals(Buffer.from("MZ")))
+107
View File
@@ -1,9 +1,11 @@
import {
declaredFileRange,
GoBinaryFormatFailure,
GoBinaryReader,
mappedFileOffset,
type GoBinaryContainer,
type GoFileMapping,
type GoImageSection,
type GoZeroFillMapping,
} from "./GoBinaryContainer.js";
import { readElfFixedHeader } from "../domain/elfFixedHeader.js";
@@ -100,6 +102,7 @@ export const readGoElfImage = (bytes: Buffer): GoBinaryContainer => {
);
const mappings: GoFileMapping[] = [];
const zeroFills: GoZeroFillMapping[] = [];
const sections: GoImageSection[] = [];
let fallback: GoFileMapping | null = null;
for (let index = 0; index < phCount; index++) {
const offset = phStart + index * phWidth;
@@ -158,6 +161,15 @@ export const readGoElfImage = (bytes: Buffer): GoBinaryContainer => {
"malformed",
"ELF section name offset is outside its string table",
);
recordElfSection(sections, {
bytes,
names,
nameOffset,
reader,
bits,
wide,
header: offset,
});
// Comparing the complete fixed name avoids quadratic scans through malicious string tables.
const expectedName = Buffer.from(".go.buildinfo\0");
if (
@@ -213,10 +225,105 @@ export const readGoElfImage = (bytes: Buffer): GoBinaryContainer => {
byte_order: reader.little ? "little" : "big",
mappings,
zero_fills: zeroFills,
sections,
search: search ?? fallback,
};
};
const recordElfSection = (
sections: GoImageSection[],
input: {
readonly bytes: Buffer;
readonly names: { readonly offset: number; readonly size: number };
readonly nameOffset: number;
readonly reader: GoBinaryReader;
readonly bits: 32 | 64;
readonly wide: boolean;
readonly header: number;
},
): void => {
const decoded = elfSectionName(input.bytes, input.names, input.nameOffset);
const header = {
reader: input.reader,
bits: input.bits,
wide: input.wide,
header: input.header,
};
switch (decoded.status) {
case "named":
sections.push(elfImageSection({ ...header, name: decoded.name }));
return;
case "truncated": {
// Names past this window stay out of .dep-v0 matching. Read-only
// bytes can still hold the only compiler path.
const section = elfImageSection({ ...header, name: "" });
if (section.read_only) sections.push(section);
return;
}
case "unnamed":
return;
default: {
const unreachable: never = decoded;
return unreachable;
}
}
};
const elfSectionName = (
bytes: Buffer,
names: { readonly offset: number; readonly size: number },
nameOffset: number,
):
| { readonly status: "named"; readonly name: string }
| { readonly status: "unnamed" }
| { readonly status: "truncated" } => {
const start = names.offset + nameOffset;
const limit = Math.min(start + 64, names.offset + names.size);
const nul = bytes.subarray(start, limit).indexOf(0);
if (nul === 0) return { status: "unnamed" };
if (nul < 0) return { status: "truncated" };
return {
status: "named",
name: bytes.toString("latin1", start, start + nul),
};
};
const elfImageSection = ({
reader,
bits,
wide,
header,
name,
}: {
readonly reader: GoBinaryReader;
readonly bits: 32 | 64;
readonly wide: boolean;
readonly header: number;
readonly name: string;
}): GoImageSection => {
const type = reader.u32(header + 4);
const flags = reader.word(header + 8, bits);
const declared = declaredFileRange(
reader.bytes.length,
reader.word(header + (wide ? 24 : 16), bits),
reader.word(header + (wide ? 32 : 20), bits),
);
// SHT_NOBITS offsets and sizes do not describe stored bytes.
const range =
type === SHT_NOBITS ? { ...declared, file_backed: false } : declared;
const compressed = (flags & 0x800n) !== 0n;
const readOnly =
type === 1 &&
range.file_backed &&
!compressed &&
(flags & 1n) === 0n &&
(flags & 4n) === 0n &&
(flags & 2n) !== 0n;
return { name, ...range, read_only: readOnly, compressed };
};
const SHT_NOBITS = 8;
const elfArchitecture = (machine: number): string => {
const names = new Map([
[3, "386"],
+86 -5
View File
@@ -1,9 +1,11 @@
import {
declaredFileRange,
GoBinaryFormatFailure,
GoBinaryReader,
mappedFileOffset,
type GoBinaryContainer,
type GoFileMapping,
type GoImageSection,
type GoZeroFillMapping,
} from "./GoBinaryContainer.js";
@@ -30,6 +32,7 @@ export const readGoMachoImage = (bytes: Buffer): GoBinaryContainer => {
);
const mappings: GoFileMapping[] = [];
const zeroFills: GoZeroFillMapping[] = [];
const sections: GoImageSection[] = [];
const named: GoFileMapping[] = [];
let fallback: GoFileMapping | null = null;
let offset = commandStart;
@@ -105,11 +108,25 @@ export const readGoMachoImage = (bytes: Buffer): GoBinaryContainer => {
fallback = mapping;
for (let sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++) {
const section = offset + segmentHeader + sectionIndex * sectionWidth;
if (
fixedName(reader.range(section, 16, "Mach-O section name")) !==
"__go_buildinfo"
)
continue;
const sectionName = fixedName(
reader.range(section, 16, "Mach-O section name"),
);
sections.push(
machoImageSection({
reader,
bits,
wide,
header: section,
name: `${fixedName(reader.range(section + 16, 16, "Mach-O section segment"))},${sectionName}`,
protection,
unmapped: unmapped || mapping === undefined,
segmentAddress: address,
segmentMemorySize: memorySize,
segmentFileOffset: fileOffset,
segmentFileSize: fileSize,
}),
);
if (sectionName !== "__go_buildinfo") continue;
if (unmapped)
throw new GoBinaryFormatFailure(
"malformed",
@@ -175,10 +192,74 @@ export const readGoMachoImage = (bytes: Buffer): GoBinaryContainer => {
byte_order: little ? "little" : "big",
mappings,
zero_fills: zeroFills,
sections,
search: named[0] ?? fallback,
};
};
const machoImageSection = ({
reader,
bits,
wide,
header,
name,
protection,
unmapped,
segmentAddress,
segmentMemorySize,
segmentFileOffset,
segmentFileSize,
}: {
readonly reader: GoBinaryReader;
readonly bits: 32 | 64;
readonly wide: boolean;
readonly header: number;
readonly name: string;
readonly protection: number;
readonly unmapped: boolean;
readonly segmentAddress: bigint;
readonly segmentMemorySize: bigint;
readonly segmentFileOffset: bigint;
readonly segmentFileSize: bigint;
}): GoImageSection => {
const flags = reader.u32(header + (wide ? 64 : 56));
const zeroFill = [1, 0xc, 0x12].includes(flags & 0xff);
const sectionAddress = reader.word(header + 32, bits);
const sectionSize = reader.word(header + (wide ? 40 : 36), bits);
const sectionOffset = BigInt(reader.u32(header + (wide ? 48 : 40)));
const addressDelta = sectionAddress - segmentAddress;
const fileDelta = sectionOffset - segmentFileOffset;
const inSegmentMemory =
addressDelta >= 0n &&
addressDelta <= segmentMemorySize &&
sectionSize <= segmentMemorySize - addressDelta;
const inSegmentFile =
fileDelta >= 0n &&
fileDelta <= segmentFileSize &&
sectionSize <= segmentFileSize - fileDelta;
const range = unmapped
? { offset: 0, size: 0, file_backed: false }
: declaredFileRange(
reader.bytes.length,
BigInt(reader.u32(header + (wide ? 48 : 40))),
reader.word(header + (wide ? 40 : 36), bits),
);
const fileBacked =
range.file_backed && !zeroFill && inSegmentMemory && inSegmentFile;
const readOnly =
fileBacked &&
(protection & 1) !== 0 &&
(protection & 2) === 0 &&
(flags & 0x80000400) === 0;
return {
name,
...range,
file_backed: fileBacked,
read_only: readOnly,
compressed: false,
};
};
const fixedName = (bytes: Buffer): string => {
const nul = bytes.indexOf(0);
return bytes.subarray(0, nul < 0 ? bytes.length : nul).toString("latin1");
+51
View File
@@ -1,9 +1,11 @@
import { observeMzWindowsHeader, parseDosMzHeader } from "../domain/dosMz.js";
import {
declaredFileRange,
GoBinaryFormatFailure,
GoBinaryReader,
type GoBinaryContainer,
type GoFileMapping,
type GoImageSection,
type GoZeroFillMapping,
} from "./GoBinaryContainer.js";
@@ -86,14 +88,30 @@ export const readGoPeImage = (bytes: Buffer): GoBinaryContainer => {
);
const mappings: GoFileMapping[] = [];
const zeroFills: GoZeroFillMapping[] = [];
const sections: GoImageSection[] = [];
let search: GoFileMapping | null = null;
for (let index = 0; index < count; index++) {
const entry = start + index * 40;
const sectionName = peSectionName(
reader.range(entry, 8, "PE section name"),
);
const virtualSize = reader.u32(entry + 8);
const virtualAddress = reader.u32(entry + 12);
const size = reader.u32(entry + 16);
const offset = reader.u32(entry + 20);
const characteristics = reader.u32(entry + 36);
// SizeOfRawData includes file-alignment padding. VirtualSize is the content.
const contentSize = virtualSize === 0 ? size : Math.min(virtualSize, size);
if (sectionName.length > 0)
sections.push(
peImageSection({
reader,
name: sectionName,
size: contentSize,
offset,
characteristics,
}),
);
const address = imageBase + BigInt(virtualAddress);
if (address + BigInt(Math.max(size, virtualSize)) > 1n << BigInt(bits))
throw new GoBinaryFormatFailure(
@@ -138,6 +156,39 @@ export const readGoPeImage = (bytes: Buffer): GoBinaryContainer => {
byte_order: "little",
mappings,
zero_fills: zeroFills,
sections,
search,
};
};
const peSectionName = (bytes: Buffer): string => {
const nul = bytes.indexOf(0);
return bytes.toString("latin1", 0, nul < 0 ? bytes.length : nul);
};
const peImageSection = ({
reader,
name,
size,
offset,
characteristics,
}: {
readonly reader: GoBinaryReader;
readonly name: string;
readonly size: number;
readonly offset: number;
readonly characteristics: number;
}): GoImageSection => {
const range = declaredFileRange(
reader.bytes.length,
BigInt(offset),
BigInt(size),
);
const readOnly =
range.file_backed &&
(characteristics & 0x40000000) !== 0 &&
(characteristics & 0x80000000) === 0 &&
(characteristics & 0x20000000) === 0 &&
(characteristics & 0x40) !== 0;
return { name, ...range, read_only: readOnly, compressed: false };
};
+221
View File
@@ -0,0 +1,221 @@
import { deflateSync } from "node:zlib";
import { expect, it } from "vitest";
import {
RUST_SECTION_BYTES,
readAuditableSection,
RustAuditableFormatFailure,
RustAuditableResourceFailure,
} from "./RustAuditableReader.js";
const section = (document: unknown) =>
readAuditableSection(
".dep-v0",
0,
deflateSync(Buffer.from(JSON.stringify(document))),
);
it("preserves package order, omitted kind, and the root index", () => {
const parsed = section({
packages: [
{ name: "itoa", version: "1.0.18", source: "crates.io" },
{
name: "sample",
version: "0.1.0",
source: "local",
dependencies: [0],
root: true,
kind: "runtime",
},
],
format: 1,
});
expect(parsed).toMatchObject({
section_name: ".dep-v0",
format_version: 1,
root_package_index: 1,
compressed_bytes: parsed.section_bytes,
packages: [
{
name: "itoa",
version: "1.0.18",
source: "crates.io",
kind: null,
dependencies: [],
root: false,
},
{
name: "sample",
version: "0.1.0",
kind: "runtime",
dependencies: [0],
root: true,
},
],
dependency_edges: [{ from_index: 1, to_index: 0 }],
cyclic_dependency_indices: [],
});
expect(parsed.uncompressed_bytes).toBeGreaterThan(parsed.compressed_bytes);
});
it("reports dependency cycles and keeps an omitted format version unknown", () => {
const parsed = section({
packages: [
{ name: "a", version: "1", source: "local", dependencies: [1] },
{ name: "b", version: "1", source: "local", dependencies: [0] },
],
});
expect(parsed.cyclic_dependency_indices).toEqual([0, 1]);
expect(parsed.format_version).toBeNull();
expect(parsed.root_package_index).toBeNull();
});
it("includes every package that participates in a dependency cycle", () => {
const parsed = section({
packages: [
{ name: "a", version: "1", source: "local", dependencies: [1, 2] },
{ name: "b", version: "1", source: "local", dependencies: [0] },
{ name: "c", version: "1", source: "local", dependencies: [1] },
],
});
expect(parsed.cyclic_dependency_indices).toEqual([0, 1, 2]);
const self = section({
packages: [{ name: "a", version: "1", source: "local", dependencies: [0] }],
});
expect(self.cyclic_dependency_indices).toEqual([0]);
});
it("finishes a long acyclic dependency chain", () => {
const count = 20_000;
const parsed = section({
packages: Array.from({ length: count }, (_, index) => ({
name: `p${index.toString(36)}`,
version: "1",
source: "local",
...(index + 1 < count ? { dependencies: [index + 1] } : {}),
})),
});
expect(parsed.packages).toHaveLength(count);
expect(parsed.cyclic_dependency_indices).toEqual([]);
});
it("rejects out-of-range indices, multiple roots, and schema drift", () => {
expect(() =>
section({
packages: [
{ name: "a", version: "1", source: "local", dependencies: [2] },
],
}),
).toThrow(RustAuditableFormatFailure);
expect(() =>
section({
packages: [
{ name: "a", version: "1", source: "local", root: true },
{ name: "b", version: "1", source: "local", root: true },
],
}),
).toThrow(/more than one root/);
expect(() =>
section({
packages: [{ name: "a", version: "1", source: "local" }],
extra: true,
}),
).toThrow(/package schema/);
});
it("rejects invalid JSON, trailing zlib bytes, and an empty section", () => {
expect(() =>
readAuditableSection(".dep-v0", 0, deflateSync(Buffer.from("{"))),
).toThrow(/JSON is invalid/);
const trailed = Buffer.concat([
deflateSync(Buffer.from('{"packages":[]}')),
Buffer.from([0]),
]);
expect(() => readAuditableSection(".dep-v0", 0, trailed)).toThrow(
/zlib stream/,
);
expect(() => readAuditableSection(".dep-v0", 0, Buffer.alloc(0))).toThrow(
/empty/,
);
expect(() =>
readAuditableSection(".dep-v0", 0, Buffer.from([1, 2, 3])),
).toThrow(RustAuditableFormatFailure);
});
it("stops an inflate that exceeds the section ratio", () => {
const raw = Buffer.alloc(8000);
const compressed = deflateSync(raw);
expect(compressed.length * 64).toBeLessThan(raw.length);
expect(() => readAuditableSection(".dep-v0", 0, compressed)).toThrow(
RustAuditableResourceFailure,
);
expect(() =>
readAuditableSection(".dep-v0", 0, Buffer.alloc(RUST_SECTION_BYTES + 1)),
).toThrow(/1 MiB/);
});
it.each([{ packages: [] }, { packages: [{ future_package_field: true }] }])(
"rejects an unknown format before interpreting its packages: %j",
({ packages }) => {
expect(() => section({ format: 99, packages })).toThrow(
expect.objectContaining({
name: "RustAuditableFormatFailure",
kind: "unsupported",
message: "Unsupported cargo-auditable format version 99",
}),
);
},
);
it("rejects the first malformed package before schema issues accumulate", () => {
const stored = (document: unknown) =>
deflateSync(Buffer.from(JSON.stringify(document)), { level: 0 });
const emptyPackages = stored({
format: 1,
packages: Array.from({ length: 80_000 }, () => ({})),
});
expect(emptyPackages.length).toBeLessThan(RUST_SECTION_BYTES);
expect(() => readAuditableSection(".dep-v0", 0, emptyPackages)).toThrow(
/Dependency package 0 does not match the package schema/,
);
const invalidDependencies = stored({
format: 1,
packages: [
{
name: "a",
version: "1",
source: "local",
dependencies: Array.from({ length: 1_000 }, () => null),
},
],
});
expect(() => readAuditableSection(".dep-v0", 0, invalidDependencies)).toThrow(
/Dependency package 0 does not match the package schema/,
);
});
it("admits dependency expansion before allocating normalized or reverse edges", () => {
const document = {
packages: [
{
name: "a",
version: "1",
source: "local",
dependencies: Array<number>(400_000).fill(0),
},
],
};
// An uncompressed zlib stream clears the ratio guard while remaining below
// the one-MiB section limit, isolating the graph representation admission.
const payload = deflateSync(Buffer.from(JSON.stringify(document)), {
level: 0,
});
expect(payload.length).toBeLessThan(RUST_SECTION_BYTES);
expect(() => readAuditableSection(".dep-v0", 0, payload)).toThrow(
expect.objectContaining({
constraint: {
resource: "transport",
reported_limits: { maximum_output_bytes: 8 * 1024 * 1024 },
},
}),
);
});
+440
View File
@@ -0,0 +1,440 @@
import { deflateSync, inflateSync } from "node:zlib";
import { z } from "zod";
import {
RUST_AUDITABLE_FORMAT_VERSION,
cyclicDependencyIndices,
type RustAuditableMetadata,
type RustPackage,
} from "../domain/rust/rustBinary.js";
/** Selected-file admission limit shared with the stable artifact reader. */
export const RUST_BINARY_INPUT_BYTES = 256 * 1024 * 1024;
/** Compressed `.dep-v0` section limit. */
export const RUST_SECTION_BYTES = 1024 * 1024;
/** Inflated JSON may grow by at most this multiple of the section size. */
export const RUST_INFLATE_RATIO = 64;
/** Absolute inflated JSON limit, applied together with the ratio. */
export const RUST_UNCOMPRESSED_BYTES = 8 * 1024 * 1024;
/** Complete normalized report limit. */
export const RUST_OUTPUT_BYTES = 8 * 1024 * 1024;
const JSON_DEPTH = 32;
const packageSchema = z.strictObject({
name: z.string().min(1),
version: z.string().min(1),
source: z.string().min(1),
kind: z.enum(["runtime", "build"]).optional(),
dependencies: z.array(z.number().int().nonnegative()).optional(),
root: z.boolean().optional(),
});
const documentVersionSchema = z.object({
format: z.number().int().nonnegative().optional(),
});
const documentSchema = documentVersionSchema
.extend({
format: z.literal(RUST_AUDITABLE_FORMAT_VERSION).optional(),
packages: z.array(packageSchema),
})
.strict();
/** Malformed or unsupported dependency-section bytes. */
export class RustAuditableFormatFailure extends Error {
constructor(
readonly kind: "malformed" | "unsupported",
message: string,
options?: ErrorOptions,
) {
super(message, options);
this.name = "RustAuditableFormatFailure";
}
}
/** A resource admission limit with explicit semantic units. */
export type RustAuditableConstraint =
| {
readonly resource: "memory";
readonly reported_limits: { readonly maximum_bytes: number };
}
| {
readonly resource: "transport";
readonly reported_limits: { readonly maximum_output_bytes: number };
}
| {
readonly resource: "capacity";
readonly reported_limits: { readonly maximum_rustc_hashes: number };
};
/** Admission refused before retained output or graph expansion. */
export class RustAuditableResourceFailure extends Error {
constructor(
readonly constraint: RustAuditableConstraint,
message: string,
options?: ErrorOptions,
) {
super(message, options);
this.name = "RustAuditableResourceFailure";
}
}
/** Parsed section payload. Cycles are listed and are not walked. */
export const readAuditableSection = (
sectionName: RustAuditableMetadata["section_name"],
fileOffset: number,
bytes: Buffer,
): RustAuditableMetadata => {
if (bytes.length === 0)
throw new RustAuditableFormatFailure(
"malformed",
"Dependency section is empty",
);
if (bytes.length > RUST_SECTION_BYTES)
throw new RustAuditableResourceFailure(
{
resource: "memory",
reported_limits: { maximum_bytes: RUST_SECTION_BYTES },
},
"Dependency section exceeds the 1 MiB compressed limit",
);
const inflated = inflateSection(bytes);
const document = parseDocument(inflated);
const packages = normalizePackages(document.packages);
const root = rootIndex(packages);
return {
section_name: sectionName,
file_offset: fileOffset,
section_bytes: bytes.length,
compressed_bytes: bytes.length,
uncompressed_bytes: inflated.length,
format_version: document.format ?? null,
packages,
root_package_index: root,
dependency_edges: packages.flatMap((pkg, fromIndex) =>
pkg.dependencies.map((toIndex) => ({
from_index: fromIndex,
to_index: toIndex,
})),
),
cyclic_dependency_indices: cyclicDependencyIndices(packages),
};
};
const inflateSection = (bytes: Buffer): Buffer => {
const maximum = Math.min(
RUST_UNCOMPRESSED_BYTES,
bytes.length * RUST_INFLATE_RATIO,
);
try {
const inflated = inflateSync(bytes, {
maxOutputLength: maximum,
...(rejectsTrailingJunk() ? { rejectGarbageAfterEnd: true } : {}),
});
if (
!rejectsTrailingJunk() &&
shortestPrefix(bytes, inflated, maximum) !== bytes.length
)
throw new RustAuditableFormatFailure(
"malformed",
"Dependency section has bytes after the zlib stream",
);
return inflated;
} catch (cause) {
if (cause instanceof RustAuditableFormatFailure) throw cause;
throw inflateFailure(cause, maximum);
}
};
let trailingJunkRejected: boolean | undefined;
const rejectsTrailingJunk = (): boolean => {
if (trailingJunkRejected !== undefined) return trailingJunkRejected;
const trailed = Buffer.concat([
deflateSync(Buffer.from("a")),
Buffer.from([0]),
]);
try {
inflateSync(trailed, { rejectGarbageAfterEnd: true });
trailingJunkRejected = false;
} catch (cause) {
trailingJunkRejected =
cause instanceof Error &&
"code" in cause &&
cause.code === "ERR_TRAILING_JUNK_AFTER_STREAM_END";
}
return trailingJunkRejected;
};
const shortestPrefix = (
input: Buffer,
output: Buffer,
maximum: number,
): number => {
let low = 0;
let high = input.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (prefixMatches(input.subarray(0, mid), output, maximum)) high = mid;
else low = mid + 1;
}
return high;
};
const prefixMatches = (
prefix: Buffer,
output: Buffer,
maximum: number,
): boolean => {
try {
return inflateSync(prefix, { maxOutputLength: maximum }).equals(output);
} catch {
return false;
}
};
const inflateFailure = (cause: unknown, maximum: number): Error => {
const code =
cause instanceof Error && "code" in cause ? String(cause.code) : "";
if (code === "ERR_BUFFER_TOO_LARGE")
return new RustAuditableResourceFailure(
{ resource: "memory", reported_limits: { maximum_bytes: maximum } },
"Inflated dependency JSON exceeds the size limit",
);
if (
code === "ERR_TRAILING_JUNK_AFTER_STREAM_END" ||
code.startsWith("Z_") ||
code === "ERR_INVALID_ARG_TYPE"
)
return new RustAuditableFormatFailure(
"malformed",
"Dependency section is not a complete zlib stream",
);
return cause instanceof Error ? cause : new Error(String(cause));
};
const parseDocument = (bytes: Buffer): z.infer<typeof documentSchema> => {
let text: string;
try {
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch (cause) {
throw new RustAuditableFormatFailure(
"malformed",
"Dependency JSON is not valid UTF-8",
{ cause },
);
}
assertDepth(text);
let value: unknown;
try {
value = JSON.parse(text);
} catch (cause) {
throw new RustAuditableFormatFailure(
"malformed",
"Dependency section JSON is invalid",
{ cause },
);
}
const version = documentVersionSchema.safeParse(value);
if (!version.success)
throw new RustAuditableFormatFailure(
"malformed",
"Dependency JSON does not match the format schema",
{ cause: version.error },
);
if (
version.data.format !== undefined &&
version.data.format !== RUST_AUDITABLE_FORMAT_VERSION
)
throw new RustAuditableFormatFailure(
"unsupported",
`Unsupported cargo-auditable format version ${version.data.format}`,
);
admitGraphExpansion(value);
// One malformed package must fail before Zod retains an issue for every field.
rejectMalformedPackages(value);
const parsed = documentSchema.safeParse(value);
if (!parsed.success)
throw new RustAuditableFormatFailure(
"malformed",
"Dependency JSON does not match the package schema",
{ cause: parsed.error },
);
return parsed.data;
};
// These are lower bounds on the required normalized representation, not
// guessed per-object heap sizes. Count source arrays before Zod clones them,
// normalization builds edge objects, or SCC analysis creates reverse edges.
const MIN_PACKAGE_OUTPUT_BYTES = JSON.stringify({
name: "a",
version: "a",
source: "a",
kind: null,
dependencies: [],
root: true,
}).length;
const MIN_EDGE_OUTPUT_BYTES = JSON.stringify({
from_index: 0,
to_index: 0,
}).length;
const admitGraphExpansion = (value: unknown): void => {
if (
typeof value !== "object" ||
value === null ||
!("packages" in value) ||
!Array.isArray(value.packages)
)
return;
const packages: readonly unknown[] = value.packages;
let minimumBytes =
packages.length * MIN_PACKAGE_OUTPUT_BYTES +
Math.max(0, packages.length - 1);
let edges = 0;
const admit = () => {
const edgeBytes = edges * MIN_EDGE_OUTPUT_BYTES + Math.max(0, edges - 1);
if (minimumBytes + edgeBytes > RUST_OUTPUT_BYTES)
throw new RustAuditableResourceFailure(
{
resource: "transport",
reported_limits: { maximum_output_bytes: RUST_OUTPUT_BYTES },
},
"Dependency graph exceeds the complete report byte budget before expansion",
);
};
admit();
for (const pkg of packages) {
// Shape and index validity remain owned by documentSchema/rootIndex.
if (
typeof pkg !== "object" ||
pkg === null ||
!("dependencies" in pkg) ||
!Array.isArray(pkg.dependencies)
)
continue;
const count = pkg.dependencies.length;
edges += count;
minimumBytes += Math.max(0, count * 2 - 1);
admit();
}
};
const PACKAGE_FIELDS = new Set([
"name",
"version",
"source",
"kind",
"dependencies",
"root",
]);
const rejectMalformedPackages = (value: unknown): void => {
if (
typeof value !== "object" ||
value === null ||
!("packages" in value) ||
!Array.isArray(value.packages)
)
return;
for (const [index, pkg] of value.packages.entries()) {
if (!packageRecord(pkg))
throw new RustAuditableFormatFailure(
"malformed",
`Dependency package ${String(index)} does not match the package schema`,
);
}
};
const packageRecord = (
pkg: unknown,
): pkg is {
readonly dependencies?: readonly unknown[];
} => {
if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg))
return false;
const record = pkg as Record<string, unknown>;
for (const key of Object.keys(record)) {
if (!PACKAGE_FIELDS.has(key)) return false;
}
if (
!nonEmptyString(record.name) ||
!nonEmptyString(record.version) ||
!nonEmptyString(record.source)
)
return false;
if (
record.kind !== undefined &&
record.kind !== "runtime" &&
record.kind !== "build"
)
return false;
if (record.root !== undefined && typeof record.root !== "boolean")
return false;
const dependencies = record.dependencies;
if (dependencies === undefined) return true;
return (
Array.isArray(dependencies) &&
dependencies.every(
(entry) =>
typeof entry === "number" && Number.isInteger(entry) && entry >= 0,
)
);
};
const nonEmptyString = (value: unknown): value is string =>
typeof value === "string" && value.length > 0;
const assertDepth = (text: string): void => {
let depth = 0;
let quoted = false;
let escaped = false;
for (const char of text) {
if (quoted) {
if (escaped) escaped = false;
else if (char === "\\") escaped = true;
else if (char === '"') quoted = false;
continue;
}
if (char === '"') {
quoted = true;
continue;
}
if (char === "{" || char === "[") {
depth += 1;
if (depth > JSON_DEPTH)
throw new RustAuditableFormatFailure(
"malformed",
"Dependency JSON nesting exceeds 32 levels",
);
} else if ((char === "}" || char === "]") && depth > 0) depth -= 1;
}
};
const normalizePackages = (
packages: z.infer<typeof documentSchema>["packages"],
): RustPackage[] =>
packages.map((pkg) => ({
name: pkg.name,
version: pkg.version,
source: pkg.source,
kind: pkg.kind ?? null,
dependencies: pkg.dependencies ?? [],
root: pkg.root ?? false,
}));
const rootIndex = (packages: readonly RustPackage[]): number | null => {
const roots = packages.flatMap((pkg, index) => (pkg.root ? [index] : []));
if (roots.length > 1)
throw new RustAuditableFormatFailure(
"malformed",
"Dependency JSON declares more than one root package",
);
for (const [index, pkg] of packages.entries()) {
const outside = pkg.dependencies.find(
(target) => target >= packages.length,
);
if (outside !== undefined)
throw new RustAuditableFormatFailure(
"malformed",
`Dependency index ${String(outside)} from package ${String(index)} is outside the package list`,
);
}
return roots[0] ?? null;
};
+181
View File
@@ -0,0 +1,181 @@
import {
GoBinaryFormatFailure,
GoBinaryResourceFailure,
type GoImageSection,
} from "../go/GoBinaryContainer.js";
import { readGoBinaryContainer } from "../go/GoBinaryImage.js";
import type {
RustAuditableMetadata,
RustBinary,
} from "../domain/rust/rustBinary.js";
import {
readAuditableSection,
RustAuditableFormatFailure,
RustAuditableResourceFailure,
} from "./RustAuditableReader.js";
const RUSTC_PREFIX = Buffer.from("/rustc/");
const HASH_BYTES = 40;
/** One toolchain normally leaves one hash; a small cap bounds retained output. */
const MAX_RUSTC_HASHES = 64;
/** Container identity plus optional dependency metadata and inferred rustc commits. */
export interface RustBinaryImage {
readonly format: RustBinary["format"];
readonly architecture: string;
readonly bits: 32 | 64;
readonly byte_order: RustBinary["byte_order"];
readonly auditable_metadata: RustAuditableMetadata | null;
readonly rustc_commit: RustBinary["rustc_commit"];
}
/** Read dependency metadata from container sections without executing the image. */
export const readRustBinaryImage = (bytes: Buffer): RustBinaryImage => {
const container = readContainer(bytes);
const dependency = dependencySection(container.format, container.sections);
return {
format: container.format,
architecture: container.architecture,
bits: container.bits,
byte_order: container.byte_order,
auditable_metadata:
dependency === null
? null
: readDependency(bytes, container.format, dependency),
rustc_commit: rustcCommit(bytes, container.sections),
};
};
const readContainer = (bytes: Buffer) => {
try {
return readGoBinaryContainer(bytes);
} catch (cause) {
if (cause instanceof GoBinaryFormatFailure)
throw new RustAuditableFormatFailure(cause.kind, cause.message, {
cause,
});
if (cause instanceof GoBinaryResourceFailure)
throw new RustAuditableResourceFailure(
{
resource: "memory",
reported_limits: { maximum_bytes: cause.maximum_bytes },
},
cause.message,
{
cause,
},
);
throw cause;
}
};
const dependencySection = (
format: RustBinaryImage["format"],
sections: readonly GoImageSection[],
): GoImageSection | null => {
const expected = format === "macho" ? "__DATA,.dep-v0" : ".dep-v0";
const matches = sections.filter((section) => section.name === expected);
if (matches.length > 1)
throw new RustAuditableFormatFailure(
"malformed",
"Image contains more than one dependency section",
);
const section = matches[0];
if (section === undefined) return null;
if (section.compressed)
throw new RustAuditableFormatFailure(
"unsupported",
"Compressed dependency sections are unsupported",
);
if (!section.file_backed)
throw new RustAuditableFormatFailure(
"malformed",
"Dependency section is not file-backed",
);
return section;
};
const readDependency = (
bytes: Buffer,
format: RustBinaryImage["format"],
section: GoImageSection,
): RustAuditableMetadata =>
readAuditableSection(
format === "macho" ? "__DATA,.dep-v0" : ".dep-v0",
section.offset,
bytes.subarray(section.offset, section.offset + section.size),
);
const rustcCommit = (
bytes: Buffer,
sections: readonly GoImageSection[],
): RustBinaryImage["rustc_commit"] => {
const hashes: { hash: string; file_offset: number }[] = [];
const seen = new Set<string>();
// Overlapping declared sections are scanned once, so total work stays
// bounded by the file size however many sections reference a range.
for (const range of mergedReadOnlyRanges(sections))
collectHashes(bytes, range, seen, hashes);
return hashes.length === 0 ? null : { evidence_kind: "inferred", hashes };
};
const mergedReadOnlyRanges = (
sections: readonly GoImageSection[],
): { readonly offset: number; readonly end: number }[] => {
const ranges = sections
.filter((section) => section.read_only && section.size > 0)
.map((section) => ({
offset: section.offset,
end: section.offset + section.size,
}))
.sort((left, right) => left.offset - right.offset);
const merged: { offset: number; end: number }[] = [];
for (const range of ranges) {
const last = merged.at(-1);
if (last !== undefined && range.offset <= last.end)
last.end = Math.max(last.end, range.end);
else merged.push({ ...range });
}
return merged;
};
const collectHashes = (
bytes: Buffer,
range: { readonly offset: number; readonly end: number },
seen: Set<string>,
hashes: { hash: string; file_offset: number }[],
): void => {
const region = bytes.subarray(range.offset, range.end);
let cursor = 0;
while (cursor < region.length) {
const at = region.indexOf(RUSTC_PREFIX, cursor);
if (at < 0) return;
const start = at + RUSTC_PREFIX.length;
const hash = hashAt(region, start);
if (hash !== null && !seen.has(hash)) {
if (seen.size >= MAX_RUSTC_HASHES)
throw new RustAuditableResourceFailure(
{
resource: "capacity",
reported_limits: { maximum_rustc_hashes: MAX_RUSTC_HASHES },
},
`Read-only data contains more than ${MAX_RUSTC_HASHES} distinct rustc commit paths.`,
);
seen.add(hash);
hashes.push({ hash, file_offset: range.offset + at });
}
cursor = at + 1;
}
};
const hashAt = (region: Buffer, start: number): string | null => {
const end = start + HASH_BYTES;
if (end >= region.length || region[end] !== 0x2f) return null;
for (let index = start; index < end; index += 1) {
const byte = region[index] ?? 0;
const hex =
(byte >= 0x30 && byte <= 0x39) || (byte >= 0x61 && byte <= 0x66);
if (!hex) return null;
}
return region.toString("latin1", start, end);
};
+216
View File
@@ -0,0 +1,216 @@
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
import type { RustBinaryPort } from "../application/rust/RustBinaryPort.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisUnsupportedTargetError,
} from "../domain/analysisErrorCore.js";
import {
rustBinarySchema,
type InspectRustBinaryInput,
type RustBinary,
} from "../domain/rust/rustBinary.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
import { readRustBinaryImage } from "./RustBinaryImage.js";
import {
RUST_BINARY_INPUT_BYTES,
RUST_OUTPUT_BYTES,
RustAuditableFormatFailure,
RustAuditableResourceFailure,
} from "./RustAuditableReader.js";
/** Bundled reader identity. Embedded package versions are separate observed facts. */
export const RUST_BINARY_PROVIDER_IDENTITY = {
id: "rust-auditable",
name: "REA Rust dependency reader",
version: "1",
} as const;
const OPERATION = "inspect_rust_binary";
/** Stable in-process dependency inspection without subprocesses, temporary files, or a Rust toolchain. */
export class RustBinaryProvider implements RustBinaryPort {
readonly identity = RUST_BINARY_PROVIDER_IDENTITY;
/** Read one dependency section and any inferred rustc commit from the selected file. */
async inspect(
input: InspectRustBinaryInput,
options?: ExecutionOptions,
): Promise<Result<RustBinary, AnalysisError>> {
try {
const snapshot = await readStableArtifact(
input.path,
RUST_BINARY_INPUT_BYTES,
options?.signal,
);
options?.signal?.throwIfAborted();
const image = readRustBinaryImage(snapshot.bytes);
const report = {
...image,
artifact: {
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
limitations: limitationsFor(image),
};
if (Buffer.byteLength(JSON.stringify(report), "utf8") > RUST_OUTPUT_BYTES)
throw outputLimit(input.path);
const parsed = rustBinarySchema.safeParse(report);
if (!parsed.success)
throw new AnalysisOutputError(
OPERATION,
"Rust reader produced an invalid dependency report.",
{ cause: parsed.error },
);
options?.signal?.throwIfAborted();
return ok(parsed.data);
} catch (cause: unknown) {
return err(failureFor(cause, input.path, options?.signal));
}
}
}
const outputLimit = (path: string) =>
new AnalysisResourceConstraintError(
OPERATION,
"transport",
`Complete Rust metadata for ${path} exceeds the inline output budget; no partial success is returned.`,
{ maximum_output_bytes: RUST_OUTPUT_BYTES },
);
const limitationsFor = (
image: ReturnType<typeof readRustBinaryImage>,
): string[] => [
"Embedded dependency metadata is file content. It does not authenticate package names, versions, sources, or the compiler that produced the binary.",
"Only the .dep-v0 dependency section and read-only compiler path strings are inspected. Functions, types, and runtime behavior are not recovered.",
"Resource guards bound the selected file to 256 MiB, a dependency section to 1 MiB, inflated JSON to the smaller of 8 MiB and 64 times the section size, and the complete report to 8 MiB. Package and dependency counts are admitted against that output budget before schema cloning, graph objects, or reverse-edge allocation.",
...(image.auditable_metadata === null
? [
"No .dep-v0 section was found. Absence of .dep-v0 does not mean the binary has no dependencies.",
]
: []),
...(image.auditable_metadata?.packages.some((pkg) => pkg.kind === null)
? [
"An omitted package kind is left null. The embedded format treats an omitted kind as runtime, and that default was not stored in the section.",
]
: []),
...(image.auditable_metadata !== null &&
image.auditable_metadata.cyclic_dependency_indices.length > 0
? [
"Dependency indices contain a cycle. The cycle is reported and was not traversed.",
]
: []),
...rustcLimitation(image.rustc_commit),
];
const rustcLimitation = (
commit: ReturnType<typeof readRustBinaryImage>["rustc_commit"],
): string[] => {
if (commit === null)
return [
"No /rustc/<40-hex>/ path was found in read-only data, so a rustc commit hash is unknown.",
];
if (commit.hashes.length === 1)
return [
"The rustc commit hash is inferred from a /rustc/<40-hex>/ path in read-only data. It does not by itself prove which compiler produced the binary.",
];
return [
"Read-only data contains more than one /rustc/<40-hex>/ path, so a single rustc commit is unknown.",
];
};
const failureFor = (
cause: unknown,
path: string,
signal?: AbortSignal,
): AnalysisError => {
if (cause instanceof AnalysisError) return cause;
if (signal?.aborted) return new AnalysisCancelledError(OPERATION);
if (cause instanceof RustAuditableResourceFailure)
return new AnalysisResourceConstraintError(
OPERATION,
cause.constraint.resource,
`Selected artifact ${path}: ${cause.message}`,
cause.constraint.reported_limits,
{ cause },
);
if (cause instanceof RustAuditableFormatFailure)
return cause.kind === "unsupported"
? new AnalysisUnsupportedTargetError(OPERATION, path, cause.message, {
cause,
})
: new AnalysisInputError(OPERATION, { cause }, [
{
path: ["path"],
reason: "invalid_format",
message: `Selected artifact ${path}: ${cause.message}`,
},
]);
return artifactFailure(cause, path);
};
const artifactFailure = (cause: unknown, path: string): AnalysisError => {
if (cause instanceof ArtifactReaderFailure)
return artifactReaderFailure(cause, path);
if (cause instanceof Error && "code" in cause) {
if (cause.code === "EACCES" || cause.code === "EPERM")
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
cause,
});
if (
["ENOENT", "ENOTDIR", "ELOOP", "ENAMETOOLONG"].includes(
String(cause.code),
)
)
return new AnalysisInputError(OPERATION, { cause }, [
{
path: ["path"],
reason: "invalid_value",
message: `Selected artifact could not be read (${String(cause.code)}): ${path}.`,
},
]);
}
return new ProviderAdapterError(RUST_BINARY_PROVIDER_IDENTITY.id, OPERATION, {
cause,
diagnostics: {
path,
reason: cause instanceof Error ? cause.message : String(cause),
},
});
};
const artifactReaderFailure = (
cause: ArtifactReaderFailure,
path: string,
): AnalysisError => {
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(OPERATION, path, cause.message, {
cause,
});
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION);
if (cause.reason === "limit")
return new AnalysisResourceConstraintError(
OPERATION,
"file-size",
cause.message,
{ maximum_input_bytes: RUST_BINARY_INPUT_BYTES },
{ cause },
);
if (cause.reason === "path")
return new AnalysisInputError(OPERATION, { cause }, [
{ path: ["path"], reason: "invalid_format", message: cause.message },
]);
return new ProviderAdapterError(RUST_BINARY_PROVIDER_IDENTITY.id, OPERATION, {
cause,
diagnostics: { path, reason: cause.message },
});
};
+11
View File
@@ -22,6 +22,9 @@ import { createRecordedCrashService } from "../composition/binaryDiagnostics.js"
import { createGoBinaryService } from "../composition/go.js";
import type { GoBinaryService } from "../application/go/GoBinaryService.js";
import { registerGoTools } from "./registerGoTools.js";
import { createRustBinaryService } from "../composition/rust.js";
import type { RustBinaryService } from "../application/rust/RustBinaryService.js";
import { registerRustTools } from "./registerRustTools.js";
import type { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
import { registerAnalysisViewTool } from "./registerAnalysisViewTool.js";
import { registerBinaryDiagnosticsTools } from "./registerBinaryDiagnosticsTools.js";
@@ -141,6 +144,7 @@ export interface CreateServerOptions {
readonly logger?: Logger;
readonly binaryLayout?: BinaryLayoutService;
readonly goBinary?: GoBinaryService;
readonly rustBinary?: RustBinaryService;
readonly recordedCrash?: RecordedCrashService;
readonly firmwareAnalysis?: FirmwareAnalysisPort;
readonly javascriptRecovery?: JavaScriptRecoveryPort;
@@ -582,6 +586,13 @@ const registerConfiguredAnalysisTools = (
recordEvidence,
withAdmittedAnalysis,
);
registerRustTools(
server,
options.rustBinary ?? createRustBinaryService(),
toolLogger,
recordEvidence,
withAdmittedAnalysis,
);
registerWasmTools(
server,
wasmArtifact,
+31
View File
@@ -0,0 +1,31 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { RustBinaryService } from "../application/rust/RustBinaryService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "pino";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { createEvidenceToolHandler } from "./contractToolHandler.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Bind the exact Rust contract to its shared workflow and owning session Evidence ledger. */
export const registerRustTools = (
server: EvidenceMcpServer,
service: RustBinaryService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
): void => {
const contract = toolContract("inspect_rust_binary");
const handler = createEvidenceToolHandler(
server,
(input, options) => service.inspect(input, options),
logger,
recordEvidence,
withAdmittedAnalysis,
);
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
handler(contract),
);
};