Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(native): report PE input byte budgets as file-size limits (#4290)

Henglie467f5572ac06
diff --git a/src/artifacts/ArtifactReader.ts b/src/artifacts/ArtifactReader.ts
index ad40de57d..417fa5474 100644
--- a/src/artifacts/ArtifactReader.ts
+++ b/src/artifacts/ArtifactReader.ts
@@ -9,9 +9,17 @@ import type {
AnalysisPartialObservation,
} from "../domain/analysisErrorBase.js";
+/** Which bound a `limit` failure hit, so callers need not infer it. */
+export type ArtifactReaderBoundary = "file-size" | "capacity" | "memory";
+
export interface ArtifactReaderFailureOptions extends ErrorOptions {
readonly cleanup?: AnalysisCleanupObservation;
readonly partialObservation?: AnalysisPartialObservation;
+ /**
+ * The constrained bound for a `limit` reason. Callers report the resource
+ * from this instead of assuming every budget is memory.
+ */
+ readonly boundary?: ArtifactReaderBoundary;
}
/** Archive-neutral entry metadata. Reader adapters never choose output paths. */
@@ -132,6 +140,8 @@ export interface ArtifactReader {
export class ArtifactReaderFailure extends Error {
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly partialObservation: AnalysisPartialObservation | undefined;
+ /** The constrained bound for a `limit` reason, when the reader knows it. */
+ readonly boundary: ArtifactReaderBoundary | undefined;
constructor(
readonly reason:
@@ -155,6 +165,7 @@ export class ArtifactReaderFailure extends Error {
this.name = "ArtifactReaderFailure";
this.cleanup = options?.cleanup;
this.partialObservation = options?.partialObservation;
+ this.boundary = options?.boundary;
}
/** Preserve the primary failure while attaching cleanup and any complete observation. */
@@ -174,6 +185,11 @@ export class ArtifactReaderFailure extends Error {
{
cause: primary,
cleanup: combineCleanup(primary.cleanup, cleanup),
+ // The constrained bound survives cleanup wrapping, or a file-size
+ // refusal would be reported as a memory constraint once a close fails.
+ ...(primary.boundary === undefined
+ ? {}
+ : { boundary: primary.boundary }),
...(mergedObservation === undefined
? {}
: { partialObservation: mergedObservation }),
diff --git a/src/artifacts/readStableArtifact.ts b/src/artifacts/readStableArtifact.ts
index 808133d89..d42af37c2 100644
--- a/src/artifacts/readStableArtifact.ts
+++ b/src/artifacts/readStableArtifact.ts
@@ -64,6 +64,7 @@ export const readStableArtifact = async (
throw new ArtifactReaderFailure(
"limit",
`Selected artifact exceeds ${String(maximumBytes)} bytes: ${path}`,
+ { boundary: "file-size" },
);
const file = await afterValidation(path, "before open", () =>
fileSystem.open(
@@ -104,6 +105,7 @@ export const readStableArtifact = async (
throw new ArtifactReaderFailure(
"limit",
`Selected artifact grew beyond its byte limit: ${path}`,
+ { boundary: "file-size" },
);
chunks.push(bytes);
}
diff --git a/src/domain/analysisErrorCore.ts b/src/domain/analysisErrorCore.ts
index 71a77a647..50b5f1af1 100644
--- a/src/domain/analysisErrorCore.ts
+++ b/src/domain/analysisErrorCore.ts
@@ -33,16 +33,26 @@ export const ANALYSIS_RESOURCE_KINDS = [
export class AnalysisResourceConstraintError extends AnalysisError {
readonly _tag = "AnalysisResourceConstraintError";
readonly remediationAction: string | undefined;
+ /**
+ * Whether retrying the same request can succeed. A caller-selected bound is
+ * deterministic for the same input, so it is not retryable even when its
+ * resource kind would otherwise be treated as admission capacity.
+ */
+ readonly retryable: boolean | undefined;
constructor(
readonly operation: string,
readonly resource: (typeof ANALYSIS_RESOURCE_KINDS)[number],
readonly reason: string,
readonly reportedLimits: Readonly<Record<string, JsonValue>> | null,
- options?: AnalysisErrorOptions & { readonly remediationAction?: string },
+ options?: AnalysisErrorOptions & {
+ readonly remediationAction?: string;
+ readonly retryable?: boolean;
+ },
) {
super(`Resource constraint during ${operation}: ${reason}`, options);
this.remediationAction = options?.remediationAction;
+ this.retryable = options?.retryable;
}
}
diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts
index 026886ed5..a89f1b413 100644
--- a/src/domain/analysisErrorProjection.ts
+++ b/src/domain/analysisErrorProjection.ts
@@ -87,7 +87,7 @@ export const projectAnalysisError = (
error.retryable) ||
(code === "resource_constraint" &&
error instanceof AnalysisResourceConstraintError &&
- error.resource === "capacity"),
+ (error.retryable ?? error.resource === "capacity")),
remediation: {
action: analysisErrorRemediationAction(error),
},
diff --git a/src/domain/explicitSensitiveFailure.ts b/src/domain/explicitSensitiveFailure.ts
index 8a0fac095..7bb7c6170 100644
--- a/src/domain/explicitSensitiveFailure.ts
+++ b/src/domain/explicitSensitiveFailure.ts
@@ -168,6 +168,9 @@ export const redactExplicitFailure = (
...(error.remediationAction === undefined
? {}
: { remediationAction: text(error.remediationAction) }),
+ ...(error.retryable === undefined
+ ? {}
+ : { retryable: error.retryable }),
},
);
if (error instanceof ProviderCleanupError)
diff --git a/src/domain/native/peResources.ts b/src/domain/native/peResources.ts
index 9ed9c3552..f214bc772 100644
--- a/src/domain/native/peResources.ts
+++ b/src/domain/native/peResources.ts
@@ -14,6 +14,11 @@ const identity = z.discriminatedUnion("kind", [
}),
]);
+/** Hard ceiling on the caller-selected input read budget. */
+export const MAX_INSPECT_PE_FILE_BYTES = 536870912;
+/** Hard ceiling on the caller-selected resource-directory-entry budget. */
+export const MAX_INSPECT_PE_DIRECTORY_ENTRIES = 65536;
+
/** Complete bounded inspection of a caller-selected PE image, without execution. */
export const inspectPeResourcesInputSchema = z.strictObject({
path: localPathStringSchema.describe(
@@ -23,7 +28,7 @@ export const inspectPeResourcesInputSchema = z.strictObject({
.number()
.int()
.min(64)
- .max(536870912)
+ .max(MAX_INSPECT_PE_FILE_BYTES)
.default(67108864)
.describe("Maximum stable artifact bytes to read (default 64 MiB)"),
// Windows resource images carry thousands of entries: Windows 11 25H2
@@ -35,7 +40,7 @@ export const inspectPeResourcesInputSchema = z.strictObject({
.number()
.int()
.min(1)
- .max(65536)
+ .max(MAX_INSPECT_PE_DIRECTORY_ENTRIES)
.default(16384)
.describe(
"Maximum resource directory entries to examine; exceeding the budget fails without partial success",
diff --git a/src/kuna/KunaQueryErrors.ts b/src/kuna/KunaQueryErrors.ts
index c038eb6b2..536aef6a8 100644
--- a/src/kuna/KunaQueryErrors.ts
+++ b/src/kuna/KunaQueryErrors.ts
@@ -71,7 +71,12 @@ export const kunaQueryFailureForCaller = (
source.resource,
source.reason,
source.reportedLimits,
- options,
+ {
+ ...options,
+ ...(source.retryable === undefined
+ ? {}
+ : { retryable: source.retryable }),
+ },
);
if (source instanceof AnalysisOutputError)
return new AnalysisOutputError(operation, source.reason, {
diff --git a/src/native/pe/PeResourceParser.ts b/src/native/pe/PeResourceParser.ts
index a72687fc0..56f812971 100644
--- a/src/native/pe/PeResourceParser.ts
+++ b/src/native/pe/PeResourceParser.ts
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { setImmediate } from "node:timers/promises";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
+import type { ArtifactReaderBoundary } from "../../artifacts/ArtifactReader.js";
import { jsonParts } from "../../domain/jsonSerialization.js";
import type {
InspectPeResourcesInput,
@@ -18,8 +19,8 @@ type OccupiedRange = Range & {
kind: "directory" | "name" | "data-entry" | "payload";
};
const METADATA_BYTES = 8 * 1024 * 1024;
-const limit = (message: string): never => {
- throw new ArtifactReaderFailure("limit", message);
+const limit = (message: string, boundary: ArtifactReaderBoundary): never => {
+ throw new ArtifactReaderFailure("limit", message, { boundary });
};
/** Count bytes through the canonical bounded JSON writer. */
const jsonBytes = (value: unknown, maximum: number): number => {
@@ -52,6 +53,7 @@ export const parsePeResources = async (
if (metadataBytes + projectedBytes > METADATA_BYTES)
limit(
"PE resource metadata exceeds the 8 MiB complete-result allocation budget.",
+ "memory",
);
};
const accountBytes = (projectedBytes: number): void => {
@@ -123,6 +125,7 @@ export const parsePeResources = async (
if (count > input.max_entries - examined)
limit(
"PE resource directory entry budget exceeded; no partial inventory was returned.",
+ "capacity",
);
examined += count;
relative(at, 16 + 8 * count);
@@ -251,7 +254,7 @@ export const parsePeResources = async (
};
signal?.throwIfAborted();
if (jsonBytes(report, METADATA_BYTES) > METADATA_BYTES)
- limit("PE resource result exceeds the 8 MiB allocation budget.");
+ limit("PE resource result exceeds the 8 MiB allocation budget.", "memory");
return report;
};
diff --git a/src/native/pe/PeResourcesProvider.test.ts b/src/native/pe/PeResourcesProvider.test.ts
new file mode 100644
index 000000000..f54100c22
--- /dev/null
+++ b/src/native/pe/PeResourcesProvider.test.ts
@@ -0,0 +1,174 @@
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
+import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
+import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js";
+import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
+import {
+ MAX_INSPECT_PE_DIRECTORY_ENTRIES,
+ MAX_INSPECT_PE_FILE_BYTES,
+ inspectPeResourcesInputSchema,
+} from "../../domain/native/peResources.js";
+import { kunaQueryFailureForCaller } from "../../kuna/KunaQueryErrors.js";
+import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
+import {
+ inputBudgetRemediation,
+ PeResourcesProvider,
+} from "./PeResourcesProvider.js";
+import { peResourceFixture } from "./PeResources.fixture.js";
+
+const inspect = async (
+ path: string,
+ input: {
+ readonly max_file_bytes?: number;
+ readonly max_entries?: number;
+ } = {},
+) => {
+ const provider = new PeResourcesProvider();
+ try {
+ return await provider.inspect(
+ inspectPeResourcesInputSchema.parse({ path, ...input }),
+ );
+ } finally {
+ await provider.close();
+ }
+};
+
+describe("PE resource provider budget reporting", () => {
+ it("reports an input byte budget as a file-size bound", async () => {
+ const root = await createTestTempDirectory("rea-pe-input-budget-");
+ const path = join(root, "resource.exe");
+ await writeFile(path, peResourceFixture().bytes);
+ const result = await inspect(path, { max_file_bytes: 64 });
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected a refusal");
+ expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
+ expect(result.error).toMatchObject({
+ _tag: "AnalysisResourceConstraintError",
+ resource: "file-size",
+ });
+ expect(result.error.message).toContain(
+ "Selected artifact exceeds 64 bytes",
+ );
+ expect(
+ (result.error as AnalysisResourceConstraintError).reportedLimits,
+ ).toMatchObject({ max_file_bytes: 64 });
+ });
+
+ it("reports an entry budget as a capacity bound", async () => {
+ const root = await createTestTempDirectory("rea-pe-entry-budget-");
+ const path = join(root, "resource.exe");
+ await writeFile(path, peResourceFixture().bytes);
+ const result = await inspect(path, { max_entries: 1 });
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected a refusal");
+ expect(result.error).toMatchObject({
+ _tag: "AnalysisResourceConstraintError",
+ resource: "capacity",
+ });
+ expect(result.error.message).toContain("entry budget exceeded");
+ });
+
+ it("reports a file-size budget without memory remediation advice", async () => {
+ const root = await createTestTempDirectory("rea-pe-budget-advice-");
+ const path = join(root, "resource.exe");
+ await writeFile(path, peResourceFixture().bytes);
+ const result = await inspect(path, { max_file_bytes: 64 });
+ if (result.ok) throw new Error("Expected a refusal");
+ const error = result.error as AnalysisResourceConstraintError;
+ expect(error.resource).toBe("file-size");
+ expect(error.remediationAction).toContain("max_file_bytes");
+ expect(error.retryable).toBe(false);
+ // The projected advice must not send the caller to worker write limits.
+ expect(projectAnalysisError(error)).toMatchObject({
+ retryable: false,
+ remediation: { action: expect.stringContaining("max_file_bytes") },
+ });
+ });
+
+ it("keeps an entry budget refusal non-retryable with its own advice", async () => {
+ const root = await createTestTempDirectory("rea-pe-entry-advice-");
+ const path = join(root, "resource.exe");
+ await writeFile(path, peResourceFixture().bytes);
+ const result = await inspect(path, { max_entries: 1 });
+ if (result.ok) throw new Error("Expected a refusal");
+ const error = result.error as AnalysisResourceConstraintError;
+ expect(error.resource).toBe("capacity");
+ expect(error.remediationAction).toContain("max_entries");
+ expect(projectAnalysisError(error)).toMatchObject({
+ retryable: false,
+ remediation: { action: expect.stringContaining("max_entries") },
+ });
+ });
+
+ it("keeps the boundary when a cleanup failure wraps the limit", () => {
+ // A file that grows past its byte limit while its handle also fails to
+ // close reaches the provider through withCleanup.
+ const wrapped = ArtifactReaderFailure.withCleanup(
+ new ArtifactReaderFailure("limit", "Selected artifact exceeds 64 bytes", {
+ boundary: "file-size",
+ }),
+ { reason: "close failed", resources: ["handle"] },
+ );
+ expect(wrapped.boundary).toBe("file-size");
+ });
+
+ it("names the ceiling instead of an impossible bound at the schema maxima", () => {
+ const base = { path: "/artifacts/application.exe" };
+ expect(
+ inputBudgetRemediation("file-size", {
+ ...base,
+ max_file_bytes: MAX_INSPECT_PE_FILE_BYTES,
+ max_entries: 16384,
+ }),
+ ).toContain("input ceiling");
+ expect(
+ inputBudgetRemediation("capacity", {
+ ...base,
+ max_file_bytes: 67108864,
+ max_entries: MAX_INSPECT_PE_DIRECTORY_ENTRIES,
+ }),
+ ).toContain("resource-directory ceiling");
+ // Below the ceiling the advice still names the bound the caller raises.
+ expect(
+ inputBudgetRemediation("file-size", {
+ ...base,
+ max_file_bytes: 64,
+ max_entries: 16384,
+ }),
+ ).toContain("Raise max_file_bytes above 64");
+ expect(
+ inputBudgetRemediation("capacity", {
+ ...base,
+ max_file_bytes: 67108864,
+ max_entries: 1,
+ }),
+ ).toContain("Raise max_entries above 1");
+ });
+
+ it("preserves retryability through failure redaction and caller copies", async () => {
+ const source = new AnalysisResourceConstraintError(
+ "inspect_pe_resources",
+ "file-size",
+ "Selected artifact exceeds 64 bytes",
+ { max_file_bytes: 64 },
+ { retryable: false },
+ );
+ const redacted = redactExplicitFailure(source, ["secret"]);
+ expect(redacted).toMatchObject({ retryable: false });
+ const copied = kunaQueryFailureForCaller(source, "other_operation");
+ expect(copied).toMatchObject({ retryable: false });
+ // An undeclared retryability stays undeclared, so the shared projection
+ // keeps its resource-kind default.
+ const undeclared = new AnalysisResourceConstraintError(
+ "inspect_pe_resources",
+ "memory",
+ "Result allocation exceeded the budget",
+ null,
+ );
+ expect(redactExplicitFailure(undeclared, ["secret"])).toMatchObject({
+ retryable: undefined,
+ });
+ });
+});
diff --git a/src/native/pe/PeResourcesProvider.ts b/src/native/pe/PeResourcesProvider.ts
index 4f31256d9..5e0e872a3 100644
--- a/src/native/pe/PeResourcesProvider.ts
+++ b/src/native/pe/PeResourcesProvider.ts
@@ -12,7 +12,11 @@ import {
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
-import type { InspectPeResourcesInput } from "../../domain/native/peResources.js";
+import {
+ MAX_INSPECT_PE_DIRECTORY_ENTRIES,
+ MAX_INSPECT_PE_FILE_BYTES,
+ type InspectPeResourcesInput,
+} from "../../domain/native/peResources.js";
import { err, ok } from "../../domain/result.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { PE_RESOURCES_PROVIDER } from "../../application/InvestigationProviders.js";
@@ -56,6 +60,23 @@ export class PeResourcesProvider implements PeResourcesPort {
}
}
+/**
+ * Remediation for a caller-selected budget refusal. At the schema ceiling
+ * there is no value left to raise the bound to, so the advice names the
+ * ceiling instead of an impossible raise.
+ */
+export const inputBudgetRemediation = (
+ boundary: "file-size" | "capacity",
+ input: InspectPeResourcesInput,
+): string =>
+ boundary === "file-size"
+ ? input.max_file_bytes >= MAX_INSPECT_PE_FILE_BYTES
+ ? `The image exceeds the ${String(MAX_INSPECT_PE_FILE_BYTES)}-byte input ceiling this operation accepts; select a smaller artifact.`
+ : `Raise max_file_bytes above ${String(input.max_file_bytes)} bytes or select a smaller artifact; the limit is the caller-selected input read budget.`
+ : input.max_entries >= MAX_INSPECT_PE_DIRECTORY_ENTRIES
+ ? `The image exceeds the ${String(MAX_INSPECT_PE_DIRECTORY_ENTRIES)}-entry resource-directory ceiling this operation accepts; select a smaller artifact.`
+ : `Raise max_entries above ${String(input.max_entries)} or select a smaller artifact; the limit is the caller-selected resource directory entry budget.`;
+
const peResourcesFailurePrimary = (
cause: unknown,
input: InspectPeResourcesInput,
@@ -74,16 +95,31 @@ const peResourcesFailurePrimary = (
if (signal?.aborted) return new AnalysisCancelledError(operation, { cause });
if (cause instanceof ArtifactReaderFailure) {
+ // An input byte budget is a file-size bound, not a memory constraint, and
+ // an entry budget is a capacity bound. Report what was actually exceeded.
if (cause.reason === "limit")
return new AnalysisResourceConstraintError(
operation,
- "memory",
+ cause.boundary ?? "memory",
cause.message,
{
max_file_bytes: input.max_file_bytes,
max_entries: input.max_entries,
},
- { cause },
+ {
+ cause,
+ // Both bounds are caller-selected and deterministic for the same
+ // input, so waiting for an active analysis cannot help.
+ ...(cause.boundary === undefined || cause.boundary === "memory"
+ ? {}
+ : {
+ retryable: false,
+ remediationAction: inputBudgetRemediation(
+ cause.boundary,
+ input,
+ ),
+ }),
+ },
);
if (cause.reason === "path" || cause.reason === "format")
return new AnalysisInputError(operation, { cause }, [