diff --git a/docs/guides/native/ntfs-metadata.md b/docs/guides/native/ntfs-metadata.md index b6712a568f..00c3808f56 100644 --- a/docs/guides/native/ntfs-metadata.md +++ b/docs/guides/native/ntfs-metadata.md @@ -23,7 +23,7 @@ MCP accepts absolute local paths: } ``` -The paired workflow admits at most 64 MiB per acquisition. Its Evidence records +The paired workflow reads each acquisition into memory up to `max_file_bytes` (64 MiB by default; CLI `--max-file-bytes`). A larger acquisition, including one retained from an earlier call, is refused with `details.limit` naming `max_file_bytes`. Its Evidence records both paths, lengths and SHA-256 digests. Keep the acquisitions and compare both digests between pages. Offsets refer to those original files, whose bytes remain unchanged; sector fixups are restored only in a scratch record before attribute diff --git a/docs/maven-gradle-metadata.md b/docs/maven-gradle-metadata.md index eb24b28261..65c6fbabf8 100644 --- a/docs/maven-gradle-metadata.md +++ b/docs/maven-gradle-metadata.md @@ -101,19 +101,20 @@ well-formed document that is not a Maven project or Gradle module metadata file is `unsupported_target` with `details.failure_kind` set to `unsupported`. Document type declarations are unsupported. External entities are not resolved. -A POM is counted as a stream before its document tree is built, and one with -more than 1,048,576 XML nodes (elements, attributes, text, CDATA, comments and -processing instructions) is refused as a resource limit, as is a report above -65,536 dependency and constraint rows, 4,096 Gradle variants, or 65,536 -dependency exclusions summed over every row. Each collection is counted before -its report records are built. -Unresolved property-reference and coordinate-gap records share a 65,536-record -allowance. Repeated references within one field are deduplicated in source -order; the same spelling in different fields or rows remains separate evidence. -Variant names repeated across dependency and constraint rows are also limited -to 4,194,304 UTF-16 code units. These fixed parser and report allowances are -separate from the selected file-read budget; raising `max_file_bytes` does not -raise them. +A POM is counted as a stream before its document tree is built. Report +expansion is bounded by `report_limits` fields (CLI `--report-limits` JSON), +each counted before its report records are built: `xml_nodes` (1,048,576 XML +nodes: elements, attributes, text, CDATA, comments and processing +instructions), `dependency_rows` (65,536 dependency and constraint rows), +`variants` (4,096 Gradle variants), `exclusions` (65,536 dependency exclusions +summed over every row), `unresolved_records` (65,536 property-reference and +coordinate-gap records) and `repeated_variant_name_chars` (4,194,304 UTF-16 +code units of variant names repeated across dependency and constraint rows). +A refusal reports the field, its effective value and range in `details.limit`; +raise it on the next call. Repeated references within one field are +deduplicated in source order; the same spelling in different fields or rows +remains separate evidence. These report allowances are separate from the +selected file-read budget; raising `max_file_bytes` does not raise them. POM profiles, when present, stay unread and unactivated. Declared repositories stay unread and are not contacted. Packaging is not defaulted to `jar` when diff --git a/scripts/verify/advertised-schemas/tools/inspect_maven_gradle_metadata.json b/scripts/verify/advertised-schemas/tools/inspect_maven_gradle_metadata.json index c6fcb641f5..5aad7d2eec 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_maven_gradle_metadata.json +++ b/scripts/verify/advertised-schemas/tools/inspect_maven_gradle_metadata.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "14d15ae0b2da05c0", + "input compact": "53d3b80917065967", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_ntfs_journal.json b/scripts/verify/advertised-schemas/tools/inspect_ntfs_journal.json index a77fe0c5a1..06df3adf1e 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_ntfs_journal.json +++ b/scripts/verify/advertised-schemas/tools/inspect_ntfs_journal.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "8828739c3844ee36", + "input compact": "8d1d2e2907a828da", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/fixed-ceiling-registry.json b/scripts/verify/fixed-ceiling-registry.json index 958e02ec8a..a7592276ec 100644 --- a/scripts/verify/fixed-ceiling-registry.json +++ b/scripts/verify/fixed-ceiling-registry.json @@ -62,13 +62,6 @@ "reason": "apktool output capture is a producer budget without a per-call control." } }, - "src/application/ntfs/NtfsJournalService.ts": { - "\"The NTFS journal file allowance\"": { - "class": "pending", - "issue": 14236, - "reason": "The NTFS journal file allowance bounds bytes read, a resource policy." - } - }, "src/artifacts/AndroidBootImageArtifactReader.ts": { "ceiling.name": { "class": "forwarding", @@ -199,9 +192,8 @@ }, "src/ghidra/GhidraInstallationProperties.ts": { "\"The Ghidra installation-properties read allowance\"": { - "class": "pending", - "issue": 14236, - "reason": "Bounds the read of an installation's properties file; a resource policy on an operator-owned file." + "class": "protocol", + "reason": "Bounds Ghidra's own Ghidra/application.properties, a short key=value installation descriptor of the bring-your-own provider (about 1 KiB); no analysis input passes through it, and a larger file is not a Ghidra installation REA can drive." } }, "src/go/GoBinaryProvider.ts": { @@ -236,13 +228,6 @@ "reason": "IL2CPP metadata input, native-link candidate and Ghidra seed allowances are resource policies; the ELF pointer index became max_native_index_bytes." } }, - "src/java/MavenGradleMetadataProvider.ts": { - "Object.entries(REPORT_ALLOWANCE_SUBJECTS).find( ([key]) => key === name, )?.[1](maximum) ?? name": { - "class": "pending", - "issue": 14236, - "reason": "Maven and Gradle XML node and report allowances are resource policies." - } - }, "src/kuna/KunaProjectReader.ts": { "`Kuna's buffered function-text allowance of ${String(KUNA_FUNCTION_TEXT_BYTES)} bytes`": { "class": "pending", diff --git a/scripts/verify/untyped-budget-refusal-baseline.json b/scripts/verify/untyped-budget-refusal-baseline.json index be38b150fa..ac509a7d2d 100644 --- a/scripts/verify/untyped-budget-refusal-baseline.json +++ b/scripts/verify/untyped-budget-refusal-baseline.json @@ -44,7 +44,6 @@ "src/gpu/GpuCodeObjectsProvider.ts": 2, "src/hopper/HopperCallerReconciliation.ts": 1, "src/il2cpp/Il2cppMetadataProvider.ts": 2, - "src/java/MavenGradleMetadataProvider.ts": 1, "src/javascript/analysis/JavaScriptAnalysisTransfer.ts": 1, "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 8, "src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts": 1, @@ -66,7 +65,6 @@ "src/native/pe/PeResourcesProvider.ts": 1, "src/native/pwntools/PwntoolsDecoder.ts": 1, "src/native/windows/WindowsShortcutProvider.ts": 2, - "src/nuget/NugetNupkgProvider.ts": 1, "src/process/capture/ProcessNormalization.ts": 1, "src/server/ErrorEvidenceTransport.ts": 2, "src/server/ProgressiveToolCatalog.ts": 1, diff --git a/src/application/ntfs/NtfsJournalService.test.ts b/src/application/ntfs/NtfsJournalService.test.ts index 78eeeff9c6..c7cca83d84 100644 --- a/src/application/ntfs/NtfsJournalService.test.ts +++ b/src/application/ntfs/NtfsJournalService.test.ts @@ -1,4 +1,3 @@ -import { fixedAllowanceRemediation } from "../../domain/fixedAllowanceRemediation.js"; import { createHash } from "node:crypto"; import { lstat, open, realpath, writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -74,7 +73,7 @@ it("preserves the completed file identity when MFT interpretation fails", async } }); -it("refuses an oversized acquisition as a fixed ceiling, not host memory", async () => { +it("refuses an oversized acquisition at max_file_bytes, not host memory", async () => { const resources = new ArtifactResourceScope(); const directory = await createTestTempDirectory("rea-ntfs-oversized-"); const mftPath = join(directory, "mft"); @@ -92,18 +91,17 @@ it("refuses an oversized acquisition as a fixed ceiling, not host memory", async code: "resource_constraint", retryable: false, details: { - refusal: { - kind: "fixed_ceiling", - allowance: "The NTFS journal file allowance", - limit: 64 * 1024 * 1024, + limit: { + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: 64 * 1024 * 1024, unit: "bytes", }, }, }); - // Recovery comes from the fixed-allowance owner, not host-memory advice. - expect(projected.remediation.action).toContain( - fixedAllowanceRemediation("The NTFS journal file allowance", "input"), - ); + expect(projected.details).not.toHaveProperty("refusal"); + // Recovery names the per-call control, not host-memory advice. + expect(projected.remediation.action).toContain("max_file_bytes"); } finally { await resources.close(); } diff --git a/src/application/ntfs/NtfsJournalService.ts b/src/application/ntfs/NtfsJournalService.ts index 4b002aa31c..4a714edaa8 100644 --- a/src/application/ntfs/NtfsJournalService.ts +++ b/src/application/ntfs/NtfsJournalService.ts @@ -1,4 +1,4 @@ -import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; +import { isHostLimitFailure } from "../../domain/parseFailure.js"; import type { BigIntStats } from "node:fs"; import { ntfsJournalCacheFor, @@ -33,6 +33,7 @@ import { createEvidence, type Evidence } from "../../domain/evidence.js"; import { err, ok, type Result } from "../../domain/result.js"; import { NTFS_JOURNAL_FILE_BYTES, + ntfsJournalFileBytesLimit, NTFS_JOURNAL_OPERATION as operation, NTFS_JOURNAL_PROVIDER, ntfsJournalInputSchema, @@ -52,7 +53,7 @@ type PathParameter = "mft_path" | "journal_path"; const inputFailure = ( parameter: PathParameter, message: string, - cause?: unknown, + cause?: Error, ) => new AnalysisInputError( operation, @@ -65,32 +66,67 @@ const inputFailure = ( [{ path: [parameter], reason: "invalid_format", message }], ); +/** + * An acquisition the call could not hold: above the caller's + * `max_file_bytes`, or (measured) beyond what the host could allocate. + */ +const acquisitionConstraint = ( + kind: "budget" | "host", + message: string, + maxFileBytes: number, + cause?: Error, +): AnalysisError => + new AnalysisResourceConstraintError( + operation, + kind === "budget" ? "file-size" : "memory", + message, + { maximum_file_bytes: maxFileBytes }, + { + ...(cause === undefined ? {} : { cause }), + ...(kind === "host" + ? { + measuredExhaustion: true, + remediationAction: + "Run on a host with more available memory, or select a smaller acquisition. A larger max_file_bytes does not help.", + } + : { + retryable: false, + limit: ntfsJournalFileBytesLimit(maxFileBytes), + remediationAction: + maxFileBytes < NTFS_JOURNAL_FILE_BYTES.maximum + ? `Raise max_file_bytes above ${String(maxFileBytes)} bytes on the next call for the same acquisitions; both are read into memory.` + : "max_file_bytes is at its maximum; select a smaller acquisition.", + }), + }, + ); + const readFailure = ( failure: unknown, path: string, parameter: PathParameter, + maxFileBytes: number, ): AnalysisError => { const { cause } = artifactFilePrimaryFacts(failure); + // The host could not hold an admitted acquisition in memory; this is + // measured capacity, not file I/O or the caller's byte budget. + if (cause instanceof Error && isHostLimitFailure(cause)) + return acquisitionConstraint( + "host", + `The host could not hold the ${parameter} acquisition in memory.`, + maxFileBytes, + cause, + ); if (cause instanceof ArtifactReaderFailure) { if (cause.reason === "cancelled") return artifactFileCancellationError(operation, cause); if (cause.reason === "integrity") return readerIntegrityFailure(operation, path, cause); if (cause.reason === "limit") - return new AnalysisResourceConstraintError( - operation, - "file-size", + return acquisitionConstraint( + "budget", cause.message, - { - maximum_file_bytes: NTFS_JOURNAL_FILE_BYTES, - }, - { - cause, - ...fixedAllowanceOptions("The NTFS journal file allowance", "input", { - limit: NTFS_JOURNAL_FILE_BYTES, - unit: "bytes", - }), - }, + maxFileBytes, + cause, ); } if ( @@ -126,19 +162,29 @@ const readFailure = ( const readAcquisition = async ( path: string, parameter: PathParameter, + maxFileBytes: number, resources: ArtifactResourceScope, signal?: AbortSignal, cached?: NtfsAcquisition, ): Promise> => { try { if (cached !== undefined) { + // A retained acquisition is admitted again under this call's budget. + if (cached.snapshot.bytes.length > maxFileBytes) + return err( + acquisitionConstraint( + "budget", + `The retained ${parameter} acquisition has ${String(cached.snapshot.bytes.length)} bytes, above max_file_bytes (${String(maxFileBytes)}).`, + maxFileBytes, + ), + ); await assertStableArtifactState(path, cached.state, signal); return ok(cached); } let state: BigIntStats | undefined; const snapshot = await readStableArtifact( path, - NTFS_JOURNAL_FILE_BYTES, + maxFileBytes, signal, undefined, resources, @@ -156,7 +202,7 @@ const readAcquisition = async ( return err( projectStableArtifactFailure( cause, - readFailure(cause, path, parameter), + readFailure(cause, path, parameter, maxFileBytes), path, NTFS_JOURNAL_PROVIDER.id, operation, @@ -246,7 +292,12 @@ export const inspectNtfsJournalEvidence = async ( return err( projectStableArtifactFailure( cause, - readFailure(cause, input.mft_path, "mft_path"), + readFailure( + cause, + input.mft_path, + "mft_path", + input.max_file_bytes ?? NTFS_JOURNAL_FILE_BYTES.default_value, + ), input.mft_path, NTFS_JOURNAL_PROVIDER.id, operation, @@ -263,10 +314,14 @@ const inspectAdmittedJournal = async ( cache: NtfsJournalCache, signal?: AbortSignal, ): Promise> => { + // Evidence records the caller's input; execution uses the resolved budget. + const maxFileBytes = + input.max_file_bytes ?? NTFS_JOURNAL_FILE_BYTES.default_value; const retained = cache.select(input.mft_path, input.journal_path); const mft = await readAcquisition( input.mft_path, "mft_path", + maxFileBytes, resources, signal, retained?.mft, @@ -298,6 +353,7 @@ const inspectAdmittedJournal = async ( const journal = await readAcquisition( input.journal_path, "journal_path", + maxFileBytes, resources, signal, retained?.journal, diff --git a/src/cli/mavenGradleMetadataCommands.ts b/src/cli/mavenGradleMetadataCommands.ts index 6ea28b4254..8eb8d512a6 100644 --- a/src/cli/mavenGradleMetadataCommands.ts +++ b/src/cli/mavenGradleMetadataCommands.ts @@ -24,6 +24,7 @@ export const registerMavenGradleMetadataCommands = ( "Inspect a Maven POM or Gradle module-metadata document without running Maven or Gradle", positionals: ["path"], callerPaths: ["path"], + jsonText: ["report_limits"], fields: { path: { description: "Local Maven pom.xml or Gradle .module metadata file", diff --git a/src/domain/java/mavenGradleMetadata.ts b/src/domain/java/mavenGradleMetadata.ts index 56baff83b9..6617f30eaf 100644 --- a/src/domain/java/mavenGradleMetadata.ts +++ b/src/domain/java/mavenGradleMetadata.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import type { AnalysisParameterLimit } from "../analysisSettings.js"; import { digestSchema } from "../digests.js"; import { absoluteLocalPathStringSchema } from "../localPath.js"; @@ -9,47 +10,108 @@ const uint = z.number().int().min(0).max(0xffffffff); export const MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES = 16 * 1024 * 1024; /** - * Fixed allowance for variant-name characters repeated across Gradle dependency - * and constraint rows (name length times rows, summed over variants). + * Per-call report allowances (`report_limits`): each field's omitted value and + * the maximum the schema accepts. Each bounds a collection that expands a few + * input bytes into a much larger report: + * + * - `dependency_rows`: dependency plus constraint rows. A row spelled in two + * or three input bytes (`{}` or ``) becomes a full row and up + * to three unresolved records; the largest published BOMs declare a few + * thousand rows. + * - `variants`: Gradle variants in one module file; published modules, + * including Kotlin Multiplatform roots, declare at most a few hundred. + * - `exclusions`: dependency exclusions summed over every row. + * - `unresolved_records`: expanded property-reference and coordinate-gap + * records. + * - `xml_nodes`: XML nodes in one Maven POM, counted as a stream before the + * document tree is built; each costs hundreds of bytes of tree. + * - `repeated_variant_name_chars`: variant-name characters repeated across + * Gradle dependency and constraint rows (name length times rows). */ -export const MAVEN_GRADLE_METADATA_REPEATED_VARIANT_NAME_CHARS = - 4 * 1024 * 1024; +export const MAVEN_GRADLE_REPORT_LIMIT_BOUNDS = { + dependency_rows: { default_value: 65_536, unit: "count" }, + variants: { default_value: 4_096, unit: "count" }, + exclusions: { default_value: 65_536, unit: "count" }, + unresolved_records: { default_value: 65_536, unit: "count" }, + xml_nodes: { default_value: 1_048_576, unit: "count" }, + repeated_variant_name_chars: { + default_value: 4 * 1024 * 1024, + unit: "count", + }, +} as const; +/** Every allowance counts records or UTF-16 units held in 32-bit indices. */ +const MAVEN_GRADLE_REPORT_LIMIT_MAXIMUM = 0x7fffffff; +export type MavenGradleReportLimitField = + keyof typeof MAVEN_GRADLE_REPORT_LIMIT_BOUNDS; +export type MavenGradleReportLimits = Readonly< + Record +>; -/** - * Fixed allowance for dependency plus constraint rows in one report. A row - * spelled in two or three input bytes (`{}` or ``) becomes a full - * row and up to three unresolved records, a few hundred bytes of report; the - * largest published BOMs declare a few thousand rows. - */ -export const MAVEN_GRADLE_METADATA_DEPENDENCY_ROWS = 65_536; +const reportLimitField = (field: MavenGradleReportLimitField) => + z + .int() + .min(1) + .max(MAVEN_GRADLE_REPORT_LIMIT_MAXIMUM) + .optional() + .describe( + `Default ${String(MAVEN_GRADLE_REPORT_LIMIT_BOUNDS[field].default_value)}`, + ); +export const mavenGradleReportLimitsSchema = z.strictObject({ + dependency_rows: reportLimitField("dependency_rows"), + variants: reportLimitField("variants"), + exclusions: reportLimitField("exclusions"), + unresolved_records: reportLimitField("unresolved_records"), + xml_nodes: reportLimitField("xml_nodes"), + repeated_variant_name_chars: reportLimitField("repeated_variant_name_chars"), +}); -/** - * Fixed allowance for Gradle variants in one module file. An empty variant - * (`{}`) becomes a full variant record; published modules, including Kotlin - * Multiplatform roots with one variant per target and usage, declare at most a - * few hundred. - */ -export const MAVEN_GRADLE_METADATA_VARIANTS = 4_096; +/** Omitted fields resolve to their defaults; explicit values are kept. */ +export const mavenGradleReportLimits = ( + selected?: z.infer, +): MavenGradleReportLimits => { + const resolved: Record = {}; + for (const field of Object.keys( + MAVEN_GRADLE_REPORT_LIMIT_BOUNDS, + ) as MavenGradleReportLimitField[]) + resolved[field] = + selected?.[field] ?? + MAVEN_GRADLE_REPORT_LIMIT_BOUNDS[field].default_value; + return resolved as MavenGradleReportLimits; +}; -/** - * Fixed allowance for dependency exclusions summed over every row in one - * report. An empty exclusion (`{}` or ``) becomes a full exclusion - * record; real rows exclude a handful of modules each. - */ -export const MAVEN_GRADLE_METADATA_EXCLUSIONS = 65_536; +/** The per-call control that stopped a report, from the schema's bounds. */ +export const mavenGradleReportLimit = ( + field: MavenGradleReportLimitField, + effectiveValue: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter: `report_limits.${field}`, + effective_value: effectiveValue, + unit: MAVEN_GRADLE_REPORT_LIMIT_BOUNDS[field].unit, + minimum: 1, + maximum: MAVEN_GRADLE_REPORT_LIMIT_MAXIMUM, + default_value: MAVEN_GRADLE_REPORT_LIMIT_BOUNDS[field].default_value, + applies_at: "next_call", +}); -/** Fixed allowance for expanded property-reference and coordinate-gap records. */ -export const MAVEN_GRADLE_METADATA_UNRESOLVED_RECORDS = 65_536; +/** `max_file_bytes`: the schema's bounds and omitted value. */ +export const MAVEN_GRADLE_FILE_BYTES = { + minimum: 1, + maximum: MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES, + default_value: 1024 * 1024, +} as const; -/** - * Fixed allowance for XML nodes (elements, attributes, text, CDATA, comments - * and processing instructions) in one Maven POM, counted as a stream before - * the document tree is built. Each node costs hundreds of bytes of tree, so a - * 16 MiB POM of tiny elements could otherwise allocate gigabytes; the - * allowance still admits a POM at the dependency-row allowance with a dozen - * nodes per row. - */ -export const MAVEN_GRADLE_METADATA_XML_NODES = 1_048_576; +/** The per-call control that stopped the input read. */ +export const mavenGradleFileBytesLimit = ( + effectiveValue: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: effectiveValue, + unit: "bytes", + ...MAVEN_GRADLE_FILE_BYTES, + applies_at: "next_call", +}); const nullableText = z.string().min(1).nullable(); @@ -126,12 +188,17 @@ export const inspectMavenGradleMetadataInputSchema = z.strictObject({ max_file_bytes: z .number() .int() - .min(1) - .max(MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES) - .default(1024 * 1024) + .min(MAVEN_GRADLE_FILE_BYTES.minimum) + .max(MAVEN_GRADLE_FILE_BYTES.maximum) + .default(MAVEN_GRADLE_FILE_BYTES.default_value) .describe( "Maximum stable artifact bytes to read; exceeding the budget fails without partial success", ), + report_limits: mavenGradleReportLimitsSchema + .optional() + .describe( + "Report expansion allowances for this call (positive counts): dependency_rows (dependency plus constraint rows), variants (Gradle variants), exclusions, unresolved_records (property-reference and coordinate-gap records), xml_nodes (POM XML nodes), repeated_variant_name_chars (variant-name characters repeated across rows). A refusal reports the field in details.limit.", + ), }); const coordinateSchema = z.strictObject({ diff --git a/src/domain/nuget/nupkg.ts b/src/domain/nuget/nupkg.ts index 211ed4644f..72d5dff872 100644 --- a/src/domain/nuget/nupkg.ts +++ b/src/domain/nuget/nupkg.ts @@ -1,3 +1,4 @@ +import type { AnalysisParameterLimit } from "../analysisSettings.js"; import { z } from "zod"; import { digestSchema } from "../digests.js"; @@ -16,11 +17,38 @@ export const MAX_INSPECT_NUGET_NUPKG_ENTRIES = 65536; /** Hard ceiling on decoded .nuspec bytes. */ export const MAX_INSPECT_NUGET_NUPKG_NUSPEC_BYTES = 16 * 1024 * 1024; -export const NUGET_NUPKG_LIMIT_MAXIMA = { - max_file_bytes: MAX_INSPECT_NUGET_NUPKG_FILE_BYTES, - max_entries: MAX_INSPECT_NUGET_NUPKG_ENTRIES, - max_nuspec_bytes: MAX_INSPECT_NUGET_NUPKG_NUSPEC_BYTES, +/** Each per-call budget's schema bounds and omitted value. */ +export const NUGET_NUPKG_BUDGETS = { + max_file_bytes: { + minimum: 16, + maximum: MAX_INSPECT_NUGET_NUPKG_FILE_BYTES, + default_value: 64 * 1024 * 1024, + }, + max_entries: { + minimum: 1, + maximum: MAX_INSPECT_NUGET_NUPKG_ENTRIES, + default_value: 4096, + }, + max_nuspec_bytes: { + minimum: 1, + maximum: MAX_INSPECT_NUGET_NUPKG_NUSPEC_BYTES, + default_value: 1024 * 1024, + }, } as const; +export type NugetNupkgBudget = keyof typeof NUGET_NUPKG_BUDGETS; + +/** The per-call control that stopped a package read, from the schema's bounds. */ +export const nugetNupkgBudgetLimit = ( + parameter: NugetNupkgBudget, + effectiveValue: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter, + effective_value: effectiveValue, + unit: parameter === "max_entries" ? "count" : "bytes", + ...NUGET_NUPKG_BUDGETS[parameter], + applies_at: "next_call", +}); /** Path-derived NuGet folder roles; restore-time asset selection is not observed. */ export const NUGET_NUPKG_ENTRY_ROLES = [ @@ -88,25 +116,25 @@ export const inspectNugetNupkgInputSchema = z.strictObject({ max_file_bytes: z .number() .int() - .min(16) - .max(MAX_INSPECT_NUGET_NUPKG_FILE_BYTES) - .default(67108864) + .min(NUGET_NUPKG_BUDGETS.max_file_bytes.minimum) + .max(NUGET_NUPKG_BUDGETS.max_file_bytes.maximum) + .default(NUGET_NUPKG_BUDGETS.max_file_bytes.default_value) .describe("Maximum stable artifact bytes to read (default 64 MiB)"), max_entries: z .number() .int() - .min(1) - .max(MAX_INSPECT_NUGET_NUPKG_ENTRIES) - .default(4096) + .min(NUGET_NUPKG_BUDGETS.max_entries.minimum) + .max(NUGET_NUPKG_BUDGETS.max_entries.maximum) + .default(NUGET_NUPKG_BUDGETS.max_entries.default_value) .describe( "Maximum ZIP entries to inventory; exceeding the budget fails without partial success", ), max_nuspec_bytes: z .number() .int() - .min(1) - .max(MAX_INSPECT_NUGET_NUPKG_NUSPEC_BYTES) - .default(1048576) + .min(NUGET_NUPKG_BUDGETS.max_nuspec_bytes.minimum) + .max(NUGET_NUPKG_BUDGETS.max_nuspec_bytes.maximum) + .default(NUGET_NUPKG_BUDGETS.max_nuspec_bytes.default_value) .describe( "Maximum expanded bytes to decode for the .nuspec and the OPC _rels/.rels member; exceeding the budget fails without partial success", ), diff --git a/src/domain/windows/ntfsJournalQuery.ts b/src/domain/windows/ntfsJournalQuery.ts index b57205adb0..4ec466d91e 100644 --- a/src/domain/windows/ntfsJournalQuery.ts +++ b/src/domain/windows/ntfsJournalQuery.ts @@ -2,6 +2,7 @@ import { MFT_INLINE_HEADER_LIMIT } from "./ntfsMft.js"; import { ntfsMftMetadataSchema } from "../formatMetadata/androidAndSystemMetadata.js"; import { USN_INLINE_EXTENT_LIMIT } from "./ntfsUsnJournal.js"; import { z } from "zod"; +import type { AnalysisParameterLimit } from "../analysisSettings.js"; import { digestSchema } from "../digests.js"; import { absoluteLocalPathStringSchema } from "../localPath.js"; @@ -13,8 +14,28 @@ export const NTFS_JOURNAL_PROVIDER = { version: "1", } as const; -/** Working-set allowance for each in-memory acquisition, independent of page size. */ -export const NTFS_JOURNAL_FILE_BYTES = 64 * 1024 * 1024; +/** + * `max_file_bytes`: the per-call working-set allowance for each in-memory + * acquisition (MFT and journal), independent of page size. Acquisitions are + * held in memory, so host heap is an independent constraint. + */ +export const NTFS_JOURNAL_FILE_BYTES = { + minimum: 1, + maximum: Number.MAX_SAFE_INTEGER, + default_value: 64 * 1024 * 1024, +} as const; + +/** The per-call control that stopped an acquisition read. */ +export const ntfsJournalFileBytesLimit = ( + effectiveValue: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: effectiveValue, + unit: "bytes", + ...NTFS_JOURNAL_FILE_BYTES, + applies_at: "next_call", +}); const offset = z.int().nonnegative(); export const ntfsJournalRowLimitSchema = z .int() @@ -27,6 +48,14 @@ export const ntfsJournalRowLimitSchema = z export const ntfsJournalInputSchema = z.strictObject({ mft_path: absoluteLocalPathStringSchema, journal_path: absoluteLocalPathStringSchema, + max_file_bytes: z + .int() + .min(NTFS_JOURNAL_FILE_BYTES.minimum) + .max(NTFS_JOURNAL_FILE_BYTES.maximum) + .optional() + .describe( + `Bytes read into memory from each of the MFT and journal acquisitions (default ${String(NTFS_JOURNAL_FILE_BYTES.default_value)}); the whole acquisition is read, independent of page size.`, + ), start_file_offset: offset .default(0) .describe( diff --git a/src/java/MavenGradleMetadata.errors.ts b/src/java/MavenGradleMetadata.errors.ts index 06b394c43e..45c6d33f19 100644 --- a/src/java/MavenGradleMetadata.errors.ts +++ b/src/java/MavenGradleMetadata.errors.ts @@ -1,19 +1,11 @@ import { decodeLimit } from "../domain/parseFailure.js"; +import type { MavenGradleReportLimitField } from "../domain/java/mavenGradleMetadata.js"; /** The ParseFailure format of a Maven POM or Gradle module metadata file. */ export const MAVEN_GRADLE_METADATA_FORMAT = "maven-gradle-metadata"; -/** Fixed report allowances; each names the representation it bounds. */ -export type MavenGradleReportAllowance = - | "repeated_variant_name_chars" - | "dependency_rows" - | "variants" - | "exclusions" - | "unresolved_records" - | "xml_nodes"; - const REPORT_REFUSALS: Readonly< Record< - MavenGradleReportAllowance, + MavenGradleReportLimitField, (required: number, limit: number) => string > > = { @@ -37,7 +29,7 @@ const REPORT_REFUSALS: Readonly< * repeated variant name expands a few input bytes into a much larger report. */ export const metadataReportLimit = ( - allowance: MavenGradleReportAllowance, + allowance: MavenGradleReportLimitField, maximum: number, required: number, ) => diff --git a/src/java/MavenGradleMetadataParser.test.ts b/src/java/MavenGradleMetadataParser.test.ts index 856d9cbc21..fcedab4f97 100644 --- a/src/java/MavenGradleMetadataParser.test.ts +++ b/src/java/MavenGradleMetadataParser.test.ts @@ -771,18 +771,16 @@ it.each([ source: repeatedVariantModule(), maximum: 4_194_304, required: 5_000_000, - recovery: "character allowance for variant names", }, { boundary: "variants", source: `{"formatVersion":"1.1","variants":[${Array(4_097).fill("{}").join(",")}]}`, maximum: 4_096, required: 4_097, - recovery: "4096-variant allowance", }, -])( - "reports the measured $boundary fixed allowance", - async ({ boundary, source, maximum, required, recovery }) => { +] as const)( + "reports the measured $boundary allowance as its report_limits control", + async ({ boundary, source, maximum, required }) => { const root = await createTestTempDirectory("rea-gradle-report-"); const path = join(root, "demo.module"); await writeFile(path, source); @@ -792,17 +790,31 @@ it.each([ path, max_file_bytes: 1024 * 1024, }); - if (result.ok) - throw new Error(`Expected a fixed allowance for ${boundary}`); + if (result.ok) throw new Error(`Expected a report limit for ${boundary}`); expect(projectAnalysisError(result.error)).toMatchObject({ code: "resource_constraint", retryable: false, details: { reported_limits: { boundary, maximum, required }, - refusal: { kind: "fixed_ceiling", allowance_kind: "report" }, + limit: { + control_kind: "parameter", + parameter: `report_limits.${boundary}`, + effective_value: maximum, + default_value: maximum, + applies_at: "next_call", + }, + }, + remediation: { + action: expect.stringContaining(`report_limits.${boundary}`), }, - remediation: { action: expect.stringContaining(recovery) }, }); + // The same document is reported once the caller raises the control. + const raised = await provider.inspect({ + path, + max_file_bytes: 1024 * 1024, + report_limits: { [boundary]: required }, + }); + if (!raised.ok) throw raised.error; } finally { await provider.close(); } diff --git a/src/java/MavenGradleMetadataParser.ts b/src/java/MavenGradleMetadataParser.ts index 7c90df180a..c5e2057a29 100644 --- a/src/java/MavenGradleMetadataParser.ts +++ b/src/java/MavenGradleMetadataParser.ts @@ -15,11 +15,9 @@ import { xmlFirstChildNamed, } from "../domain/xmlDocument.js"; import { - MAVEN_GRADLE_METADATA_DEPENDENCY_ROWS, - MAVEN_GRADLE_METADATA_EXCLUSIONS, - MAVEN_GRADLE_METADATA_REPEATED_VARIANT_NAME_CHARS, - MAVEN_GRADLE_METADATA_VARIANTS, - MAVEN_GRADLE_METADATA_XML_NODES, + mavenGradleReportLimits, + type MavenGradleReportLimitField, + type MavenGradleReportLimits, requestedVersionKind, type MavenGradleDependency, type MavenGradleMetadata, @@ -28,7 +26,6 @@ import { redactRecordedTransportUrl } from "../domain/recordedTransportUrl.js"; import { MAVEN_GRADLE_METADATA_FORMAT, metadataReportLimit, - type MavenGradleReportAllowance, } from "./MavenGradleMetadata.errors.js"; const BASE_LIMITATIONS = [ @@ -81,7 +78,7 @@ const isMavenProjectRoot = (root: Node | null): root is Element => { /** Refuse a report whose expanded collection would outgrow its fixed allowance. */ const admit = ( - allowance: MavenGradleReportAllowance, + allowance: MavenGradleReportLimitField, limit: number, required: number, ): void => { @@ -288,12 +285,13 @@ const parseMavenDependency = < const parsePom = ( xml: string, artifact: { path: string; sha256: string; bytes: number }, + limits: MavenGradleReportLimits, ): MavenGradleMetadata => { const limitations: string[] = [...BASE_LIMITATIONS]; // Maven applies XML 1.0 end-of-line handling to property and coordinate text. const parsed = parseXmlDocumentWithinNodeLimit(xml, { lineEndings: "normalize", - maximumNodes: MAVEN_GRADLE_METADATA_XML_NODES, + maximumNodes: limits.xml_nodes, }); if (!parsed.ok && parsed.error.kind === "node-limit") throw metadataReportLimit( @@ -317,7 +315,9 @@ const parsePom = ( MAVEN_GRADLE_METADATA_FORMAT, "Selected XML document is not a Maven project POM.", ); - const unresolved = new MavenGradleUnresolvedCollector(); + const unresolved = new MavenGradleUnresolvedCollector( + limits.unresolved_records, + ); const parentElement = soleNamed(root, "parent"); const parent = parentElement === undefined @@ -381,12 +381,12 @@ const parsePom = ( ); admit( "dependency_rows", - MAVEN_GRADLE_METADATA_DEPENDENCY_ROWS, + limits.dependency_rows, managedElements.length + dependencyElements.length, ); admit( "exclusions", - MAVEN_GRADLE_METADATA_EXCLUSIONS, + limits.exclusions, [...managedElements, ...dependencyElements].reduce( (count, element) => count + mavenExclusionElements(element).length, 0, @@ -485,6 +485,7 @@ const parseGradleDependency = < const parseGradle = ( source: string, artifact: { path: string; sha256: string; bytes: number }, + limits: MavenGradleReportLimits, ): MavenGradleMetadata => { const json = parseJsonWithDuplicatePolicy(source, "reject"); if (!json.ok) { @@ -534,7 +535,9 @@ const parseGradle = ( limitations.push( `Recognized fields in this unfamiliar format version were interpreted using Gradle module metadata ${GRADLE_MODULE_METADATA_VERSION}. Version-specific declarations may be unreported.`, ); - const unresolved = new MavenGradleUnresolvedCollector(); + const unresolved = new MavenGradleUnresolvedCollector( + limits.unresolved_records, + ); const coordinates = { group_id: component === null ? null : gradleText(component.group), artifact_id: component === null ? null : gradleText(component.module), @@ -547,7 +550,7 @@ const parseGradle = ( // Count each expanded collection before any report record is built. admit( "variants", - MAVEN_GRADLE_METADATA_VARIANTS, + limits.variants, gradleArray(variantsValue, "variants").length, ); const variants = gradleObjects(variantsValue, "variants"); @@ -557,7 +560,7 @@ const parseGradle = ( ]); admit( "dependency_rows", - MAVEN_GRADLE_METADATA_DEPENDENCY_ROWS, + limits.dependency_rows, rowLists.reduce((count, rows) => count + rows.length, 0), ); let exclusions = 0; @@ -565,16 +568,14 @@ const parseGradle = ( for (const row of rows) if (isRecord(row)) exclusions += gradleArray(row.excludes, "excludes").length; - admit("exclusions", MAVEN_GRADLE_METADATA_EXCLUSIONS, exclusions); + admit("exclusions", limits.exclusions, exclusions); const dependencies: MavenGradleDependency<"variant-dependencies">[] = []; const dependency_management: MavenGradleDependency<"variant-constraints">[] = []; const gradleVariants: NonNullable["variants"] = []; let nextIndex = 0; - const repeatedVariantNames = new Budget( - MAVEN_GRADLE_METADATA_REPEATED_VARIANT_NAME_CHARS, - ); + const repeatedVariantNames = new Budget(limits.repeated_variant_name_chars); const variantNameIndices = new Map(); for (const [index, variant] of variants.entries()) { const declaredName = variant.name; @@ -686,6 +687,7 @@ const parseGradle = ( export const parseMavenGradleMetadata = ( bytes: Uint8Array, artifact: { path: string; sha256: string; bytes: number }, + limits: MavenGradleReportLimits = mavenGradleReportLimits(), ): MavenGradleMetadata => { if (bytes.length !== artifact.bytes) throw malformedInput( @@ -708,9 +710,9 @@ export const parseMavenGradleMetadata = ( } const trimmed = source.trimStart(); if (trimmed.startsWith("{") || trimmed.startsWith("[")) - return parseGradle(source, artifact); + return parseGradle(source, artifact, limits); if (opensLikeXml(trimmed) || trimmed.startsWith("<")) - return parsePom(source, artifact); + return parsePom(source, artifact, limits); throw unsupportedInput( MAVEN_GRADLE_METADATA_FORMAT, "Selected file is not a Maven POM or Gradle module-metadata document.", diff --git a/src/java/MavenGradleMetadataProvider.ts b/src/java/MavenGradleMetadataProvider.ts index 679978341d..c2813545b3 100644 --- a/src/java/MavenGradleMetadataProvider.ts +++ b/src/java/MavenGradleMetadataProvider.ts @@ -16,15 +16,16 @@ import { decodeLimit } from "../domain/parseFailure.js"; import { errorMessage } from "../kernel/errorMessage.js"; import { ArtifactOperationError } from "../domain/artifactOperationError.js"; import { - MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES, + MAVEN_GRADLE_FILE_BYTES, + mavenGradleFileBytesLimit, + mavenGradleReportLimit, + mavenGradleReportLimits, + MAVEN_GRADLE_REPORT_LIMIT_BOUNDS, + type MavenGradleReportLimitField, type InspectMavenGradleMetadataInput, } from "../domain/java/mavenGradleMetadata.js"; import { err, ok } from "../domain/result.js"; -import { - MAVEN_GRADLE_METADATA_FORMAT, - type MavenGradleReportAllowance, -} from "./MavenGradleMetadata.errors.js"; -import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; +import { MAVEN_GRADLE_METADATA_FORMAT } from "./MavenGradleMetadata.errors.js"; import { MAVEN_GRADLE_METADATA_PROVIDER_IDENTITY } from "./MavenGradleMetadataProviderIdentity.js"; import { parseMavenGradleMetadata } from "./MavenGradleMetadataParser.js"; import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; @@ -65,11 +66,15 @@ export class MavenGradleMetadataProvider { this.#resources, ); return ok( - parseMavenGradleMetadata(snapshot.bytes, { - path: input.path, - sha256: snapshot.sha256, - bytes: snapshot.bytes.length, - }), + parseMavenGradleMetadata( + snapshot.bytes, + { + path: input.path, + sha256: snapshot.sha256, + bytes: snapshot.bytes.length, + }, + mavenGradleReportLimits(input.report_limits), + ), ); }); } catch (cause) { @@ -81,27 +86,13 @@ export class MavenGradleMetadataProvider { const inputBudgetRemediation = ( input: InspectMavenGradleMetadataInput, ): string => - input.max_file_bytes >= MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES - ? `The file exceeds the ${String(MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES)}-byte input ceiling this operation accepts; select a smaller artifact.` - : `Raise max_file_bytes above ${String(input.max_file_bytes)} bytes, up to ${String(MAX_INSPECT_MAVEN_GRADLE_METADATA_FILE_BYTES)}, or select a smaller artifact; this is the caller-selected input read budget.`; + input.max_file_bytes >= MAVEN_GRADLE_FILE_BYTES.maximum + ? `The file exceeds the ${String(MAVEN_GRADLE_FILE_BYTES.maximum)}-byte input ceiling this operation accepts; select a smaller artifact.` + : `Raise max_file_bytes above ${String(input.max_file_bytes)} bytes, up to ${String(MAVEN_GRADLE_FILE_BYTES.maximum)}, or select a smaller artifact; this is the caller-selected input read budget.`; -/** The subject a fixed-allowance remediation names for each report allowance. */ -const REPORT_ALLOWANCE_SUBJECTS: Readonly< - Record string> -> = { - dependency_rows: (limit) => - `The ${String(limit)}-row allowance for dependency and constraint rows`, - variants: (limit) => - `The ${String(limit)}-variant allowance for Gradle module variants`, - exclusions: (limit) => - `The ${String(limit)}-exclusion allowance for dependency exclusions`, - unresolved_records: (limit) => - `The ${String(limit)}-record allowance for unresolved references and coordinates`, - xml_nodes: (limit) => - `The ${String(limit)}-node allowance for a Maven POM document tree`, - repeated_variant_name_chars: (limit) => - `The ${String(limit)}-character allowance for variant names repeated across Gradle dependency rows`, -}; +const REPORT_LIMIT_FIELDS = Object.keys( + MAVEN_GRADLE_REPORT_LIMIT_BOUNDS, +) as MavenGradleReportLimitField[]; const mavenGradleMetadataFailure = ( cause: unknown, @@ -121,28 +112,25 @@ const mavenGradleMetadataFailure = ( recognise: (failure) => { if (!isParseLimit(failure, MAVEN_GRADLE_METADATA_FORMAT)) return undefined; - const { name, maximum } = failure.failure.limit; + const { name, maximum, required } = failure.failure.limit; + const field = REPORT_LIMIT_FIELDS.find((field) => field === name); + const limit = + field === undefined + ? undefined + : mavenGradleReportLimit(field, maximum); return parseLimitConstraint(OPERATION, "memory", failure, { path: input.path, - ...fixedAllowanceOptions( - Object.entries(REPORT_ALLOWANCE_SUBJECTS).find( - ([key]) => key === name, - )?.[1](maximum) ?? name, - name === "xml_nodes" ? "parser" : "report", - { - limit: maximum, - unit: - name === "repeated_variant_name_chars" - ? "UTF-16 code units" - : name === "unresolved_records" - ? "records" - : name === "dependency_rows" - ? "rows" - : name === "xml_nodes" - ? "nodes" - : name, - }, - ), + retryable: false, + ...(limit === undefined + ? {} + : { + limit, + remediationAction: + maximum < limit.maximum && + (required === undefined || required <= limit.maximum) + ? `Pass a larger ${limit.parameter}${required === undefined ? "" : ` (at least ${String(required)})`} on the next call for the same document; no restart is required.` + : `${limit.parameter} cannot exceed ${String(limit.maximum)}, which does not admit this document; select a document within that bound.`, + }), }); }, fileSize: (failure) => @@ -157,6 +145,7 @@ const mavenGradleMetadataFailure = ( ), { retryable: false, + limit: mavenGradleFileBytesLimit(input.max_file_bytes), remediationAction: inputBudgetRemediation(input), }, ), diff --git a/src/java/MavenGradleUnresolvedCollector.ts b/src/java/MavenGradleUnresolvedCollector.ts index e0302e3f69..90bf17aa49 100644 --- a/src/java/MavenGradleUnresolvedCollector.ts +++ b/src/java/MavenGradleUnresolvedCollector.ts @@ -1,6 +1,6 @@ import { Budget } from "../domain/budget.js"; import { - MAVEN_GRADLE_METADATA_UNRESOLVED_RECORDS, + MAVEN_GRADLE_REPORT_LIMIT_BOUNDS, mavenPropertyOccurrences, type MavenGradleUnresolved, } from "../domain/java/mavenGradleMetadata.js"; @@ -13,7 +13,10 @@ export class MavenGradleUnresolvedCollector { readonly #records: MavenGradleUnresolved[] = []; readonly #budget: Budget; - constructor(maximum = MAVEN_GRADLE_METADATA_UNRESOLVED_RECORDS) { + constructor( + maximum: number = MAVEN_GRADLE_REPORT_LIMIT_BOUNDS.unresolved_records + .default_value, + ) { this.#budget = new Budget(maximum); } diff --git a/src/nuget/NugetNupkgProvider.ts b/src/nuget/NugetNupkgProvider.ts index e0549cf39a..064ca7e824 100644 --- a/src/nuget/NugetNupkgProvider.ts +++ b/src/nuget/NugetNupkgProvider.ts @@ -16,9 +16,11 @@ import { decodeLimit } from "../domain/parseFailure.js"; import { fixedCeilingConstraint } from "../domain/analysisErrorCore.js"; import { ArtifactOperationError } from "../domain/artifactOperationError.js"; import { + NUGET_NUPKG_BUDGETS, NUGET_NUPKG_FORMAT, - NUGET_NUPKG_LIMIT_MAXIMA, + nugetNupkgBudgetLimit, type InspectNugetNupkgInput, + type NugetNupkgBudget, } from "../domain/nuget/nupkg.js"; import { err, ok } from "../domain/result.js"; import { errorMessage } from "../kernel/errorMessage.js"; @@ -28,13 +30,14 @@ import { parseNugetNupkg } from "./NugetNupkgParser.js"; const OPERATION = "inspect_nuget_nupkg"; -const budgetRecovery = ( - parameter: keyof typeof NUGET_NUPKG_LIMIT_MAXIMA, - selected: number, -): string => - selected >= NUGET_NUPKG_LIMIT_MAXIMA[parameter] - ? `${parameter} is at this operation's maximum of ${String(NUGET_NUPKG_LIMIT_MAXIMA[parameter])}; select a complete artifact within that bound.` - : `Raise ${parameter} above ${String(selected)}, up to ${String(NUGET_NUPKG_LIMIT_MAXIMA[parameter])}, or select a smaller artifact. The budget applies on the next call; repeating the unchanged request does not raise it.`; +/** The refusal options for an exhausted per-call budget. */ +const budgetRecovery = (parameter: NugetNupkgBudget, selected: number) => ({ + limit: nugetNupkgBudgetLimit(parameter, selected), + remediationAction: + selected >= NUGET_NUPKG_BUDGETS[parameter].maximum + ? `${parameter} is at this operation's maximum of ${String(NUGET_NUPKG_BUDGETS[parameter].maximum)}; select a complete artifact within that bound.` + : `Raise ${parameter} above ${String(selected)}, up to ${String(NUGET_NUPKG_BUDGETS[parameter].maximum)}, or select a smaller artifact. The budget applies on the next call; repeating the unchanged request does not raise it.`, +}); const nupkgFailure = ( cause: unknown, @@ -52,9 +55,7 @@ const nupkgFailure = ( recognise: (failure, origin) => { if (isParseLimit(failure, NUGET_NUPKG_FORMAT)) { const parameter = ( - Object.keys( - NUGET_NUPKG_LIMIT_MAXIMA, - ) as (keyof typeof NUGET_NUPKG_LIMIT_MAXIMA)[] + Object.keys(NUGET_NUPKG_BUDGETS) as NugetNupkgBudget[] ).find((name) => name === failure.failure.limit.name); return parseLimitConstraint( OPERATION, @@ -67,12 +68,7 @@ const nupkgFailure = ( retryable: false, ...(parameter === undefined ? {} - : { - remediationAction: budgetRecovery( - parameter, - failure.failure.limit.maximum, - ), - }), + : budgetRecovery(parameter, failure.failure.limit.maximum)), }, ); } @@ -114,10 +110,7 @@ const nupkgFailure = ( ), { retryable: false, - remediationAction: budgetRecovery( - "max_file_bytes", - input.max_file_bytes, - ), + ...budgetRecovery("max_file_bytes", input.max_file_bytes), }, ), unclassified: (failure) => diff --git a/tests/acceptance/mavenGradleMetadataCli.test.ts b/tests/acceptance/mavenGradleMetadataCli.test.ts index 90aefbb29e..6e1a2fdba1 100644 --- a/tests/acceptance/mavenGradleMetadataCli.test.ts +++ b/tests/acceptance/mavenGradleMetadataCli.test.ts @@ -29,6 +29,58 @@ const bundleOutputSchema = contractNamed( "get_evidence_bundle", ).outputSchema; +cliTest( + "refuses a POM at report_limits.xml_nodes and reports it when raised through CLI and MCP", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-maven-report-limits-"); + const path = join(root, "pom.xml"); + await writeFile(path, mavenPomFixture); + const command = ["inspect-maven-gradle-metadata", path, "--json"]; + const limit = { + control_kind: "parameter", + parameter: "report_limits.xml_nodes", + effective_value: 8, + unit: "count", + minimum: 1, + default_value: 1_048_576, + applies_at: "next_call", + }; + const refused = await cli.run({ + arguments: [...command, "--report-limits", '{"xml_nodes":8}'], + }); + expect(refused.exitCode).toBe(1); + expect(refused.json).toMatchObject({ + code: "resource_constraint", + retryable: false, + details: { limit }, + remediation: { + action: expect.stringContaining("report_limits.xml_nodes"), + }, + }); + const raised = await cli.run({ + arguments: [...command, "--report-limits", '{"xml_nodes":100000}'], + }); + expect(raised.exitCode, raised.stderr).toBe(0); + expect(outputSchema.parse(raised.json).parameters).toMatchObject({ + report_limits: { xml_nodes: 100_000 }, + }); + const { call } = await connectLocalToolsMcp(); + const mcpRefused = await call("inspect_maven_gradle_metadata", { + path, + report_limits: { xml_nodes: 8 }, + }); + expect(mcpRefused.isError).toBe(true); + expect(parseMcpToolError(mcpRefused).error).toMatchObject({ + details: { limit }, + }); + const mcpRaised = await call("inspect_maven_gradle_metadata", { + path, + report_limits: { xml_nodes: 100_000 }, + }); + expect(mcpRaised.isError, JSON.stringify(mcpRaised)).not.toBe(true); + }, +); + cliTest( "preserves Maven property value characters through CLI, MCP and retained Evidence", async ({ cli }) => { diff --git a/tests/acceptance/nugetNupkgCli.test.ts b/tests/acceptance/nugetNupkgCli.test.ts index 5fe36f6a45..e15135cf70 100644 --- a/tests/acceptance/nugetNupkgCli.test.ts +++ b/tests/acceptance/nugetNupkgCli.test.ts @@ -186,6 +186,38 @@ cliTest( }, ); +cliTest( + "names max_entries and its range when a package has more members", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-nupkg-entry-budget-"); + const path = join(root, "demo.nupkg"); + await writeFile(path, await nugetNupkgFixture()); + const command = ["inspect-nuget-nupkg", path, "--json"]; + const refused = await cli.run({ + arguments: [...command, "--max-entries", "1"], + }); + expect(refused.exitCode).toBe(1); + expect(refused.json).toMatchObject({ + code: "resource_constraint", + retryable: false, + details: { + limit: { + control_kind: "parameter", + parameter: "max_entries", + effective_value: 1, + unit: "count", + minimum: 1, + maximum: 65_536, + default_value: 4096, + applies_at: "next_call", + }, + }, + }); + const admitted = await cli.run({ arguments: command }); + expect(admitted.exitCode, admitted.stderr).toBe(0); + }, +); + cliTest("refuses a non-ZIP file through the public CLI", async ({ cli }) => { const root = await createTestTempDirectory("rea-nupkg-cli-invalid-"); const path = join(root, "not-a-package.nupkg"); diff --git a/tests/boundary/filesystem/mavenGradleMetadata.test.ts b/tests/boundary/filesystem/mavenGradleMetadata.test.ts index 526ff1c69a..e25dc76f8f 100644 --- a/tests/boundary/filesystem/mavenGradleMetadata.test.ts +++ b/tests/boundary/filesystem/mavenGradleMetadata.test.ts @@ -135,6 +135,13 @@ describe("Maven POM and Gradle module metadata stable filesystem boundary", () = const tooSmall = await service.inspect({ path, max_file_bytes: 16 }); if (tooSmall.ok) throw new Error("Expected resource budget failure"); expect(tooSmall.error._tag).toBe("AnalysisResourceConstraintError"); + expect(tooSmall.error.limit).toMatchObject({ + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: 16, + maximum: 16 * 1024 * 1024, + default_value: 1024 * 1024, + }); const cancelled = await service.inspect( { path }, { signal: AbortSignal.abort() }, diff --git a/tests/boundary/mcp/ntfsJournal.test.ts b/tests/boundary/mcp/ntfsJournal.test.ts index f6a2e10870..ac4c24eb47 100644 --- a/tests/boundary/mcp/ntfsJournal.test.ts +++ b/tests/boundary/mcp/ntfsJournal.test.ts @@ -223,6 +223,75 @@ mcpTest( }, ); +mcpTest( + "CLI and MCP name max_file_bytes and re-admit a retained acquisition under it", + async ({ mcp, onTestFinished }) => { + const directory = await createTestTempDirectory("rea-ntfs-budget-"); + const { mftPath, journalPath } = await createAcquisitions(directory); + const limit = { + control_kind: "parameter", + parameter: "max_file_bytes", + effective_value: 1024, + unit: "bytes", + minimum: 1, + maximum: Number.MAX_SAFE_INTEGER, + default_value: 64 * 1024 * 1024, + applies_at: "next_call", + }; + const cli = await serveCli([ + "inspect-ntfs-journal", + mftPath, + journalPath, + "--max-file-bytes=1024", + "--json", + ]); + expect(JSON.parse(cli.stdout)).toMatchObject({ + code: "resource_constraint", + retryable: false, + details: { limit }, + }); + + const config = parseConfig({}); + if (!config.ok) throw config.error; + const session = createBinarySession(config.value, silentLogger, {}); + onTestFinished(async () => { + const closed = await session.close(); + if (!closed.ok) throw closed.error; + }); + const client = await mcp.connect( + createServer({ kind: "session", session }), + ); + const admitted = await client.callTool({ + name: "inspect_ntfs_journal", + arguments: { mft_path: mftPath, journal_path: journalPath }, + }); + expect(admitted.isError, JSON.stringify(admitted.content)).not.toBe(true); + // The retained 33,792-byte MFT is admitted again under the lower budget. + const lowered = await client.callTool({ + name: "inspect_ntfs_journal", + arguments: { + mft_path: mftPath, + journal_path: journalPath, + max_file_bytes: 1024, + }, + }); + expect(lowered.isError).toBe(true); + expect(parseMcpToolError(lowered).error).toMatchObject({ + code: "resource_constraint", + details: { limit }, + }); + const raised = await client.callTool({ + name: "inspect_ntfs_journal", + arguments: { + mft_path: mftPath, + journal_path: journalPath, + max_file_bytes: 33792, + }, + }); + expect(raised.isError, JSON.stringify(raised.content)).not.toBe(true); + }, +); + mcpTest( "CLI/MCP retain extension facts through independent detail pages and later journal failure", async ({ mcp, onTestFinished }) => {