feat(artifacts)!: give Deno, wxapkg and tar readers artifact_limits controls (#14620)

* feat(artifacts)!: give Deno, wxapkg and tar readers artifact_limits controls

Deno compile, wxapkg and tar readers refused large ordinary inputs at
fixed allowances with no recovery. Their admission budgets are now
per-call artifact_limits.deno, .wxapkg and .tar fields with today's
values as defaults, and each refusal reports details.reader_limit.
artifact_limits.expanded_bytes now also applies to Deno and wxapkg.

The shared artifact path registry names its owning group's path_parts
and path_nodes controls instead of a fixed fallback.

audit_release_exposure max_file_bytes keeps its 256 MiB default but is
no longer capped there; its refusal reports details.limit.

The Deno VFS recursion depth is registered as a representation bound
and the wxapkg member-I/O allowance as derived from expanded_bytes.

BREAKING CHANGE: artifactReaderLimitsSchema now requires deno, wxapkg
and tar groups, so saved Evidence whose effective_limits predates them
fails validation and must be re-inspected. A release-exposure refusal
at max_file_bytes reports details.limit instead of a fixed_ceiling
refusal.

* fix(artifacts): keep Deno indexed paths representable and omit undercounted retained size

artifact_limits.deno.path_parts now has a minimum of 2: indexed fallbacks
live under a reserved top-level namespace directory, so a one-part
selection could only refuse the whole inspection. The retained-bytes
refusal no longer reports a required value, because the bounded byte
count stops at the allowance and understates it.
This commit is contained in:
morluto
2026-11-25 21:35:20 -05:00
committed by GitHub
parent 33e4e07dd0
commit 3dae567185
36 changed files with 690 additions and 461 deletions
+19 -15
View File
@@ -38,16 +38,19 @@ Layout reference: Deno `cli/lib/standalone/binary.rs` and `cli/lib/standalone/vi
## Deno compile sections
`MAX_DENO_METADATA_JSON_BYTES` admits at most 8 MiB of metadata JSON.
`MAX_DENO_VFS_HEADER_JSON_BYTES` admits at most 32 MiB of virtual-filesystem
header JSON. Specifier, redirect, and remote tables each admit at most 100,000
records. Specifier text admits at most 8 MiB, and remote module bodies admit at
most 256 MiB. The virtual filesystem admits at most 100,000 directory, file,
and symlink records and at most 512 nested levels (`MAX_DENO_VFS_DEPTH`). A
name longer than 4,096 UTF-16 code units is indexed and is not retained.
`MAX_DENO_VFS_RETAINED_UNITS` admits at most 32 million UTF-16 code units across
the source path built for every entry, directories included, and retained
symlink parts. A logical path deeper than 256 parts, a name that is not a safe
Admission budgets are per-call fields of `artifact_limits.deno` on
`inspect_artifact` and `extract_artifact`; a refusal reports the field in
`details.reader_limit` ([artifact reader admission](reference/limits-and-recovery.md#artifact-reader-admission)).
Defaults: `metadata_json_bytes` 8 MiB of metadata JSON, `vfs_header_json_bytes`
32 MiB of virtual-filesystem header JSON, `table_records` 100,000 records in
each specifier, redirect, and remote table, `specifier_text_bytes` 8 MiB,
`remote_body_bytes` 256 MiB of remote module bodies, `vfs_entries` 100,000
directory, file, and symlink records, and `vfs_name_units` 32 million UTF-16
code units across the source path built for every entry, directories
included, and retained symlink parts. The walk stops at 512 nested levels
(`MAX_DENO_VFS_DEPTH`), a fixed recursion bound that protects the call stack.
A name longer than 4,096 UTF-16 code units is indexed and is not retained. A
logical path deeper than `path_parts` (256), a name that is not a safe
relative path, a path component longer than 255 UTF-8 bytes
(`MAX_DENO_PATH_COMPONENT_BYTES`, POSIX `NAME_MAX`), or a logical path longer
than 512 UTF-8 bytes (`MAX_DENO_LOGICAL_PATH_BYTES`, half of the Darwin
@@ -56,11 +59,12 @@ spelling is within the name allowance. Component and path lengths include the
`.deno-*` suffix of the stored regions a member has. A descendant has no source
path when an ancestor spelling was not retained. Cancellation is checked before
the virtual-filesystem walk. The walk does not yield, so it does not observe a
cancellation that arrives while it is running; the retained allowance bounds its
work. The combined logical path tree admits at most 250,000 distinct prefixes.
`MAX_DENO_RETAINED_BYTES` admits at most 256 MiB of retained header and entry
metadata. The shared artifact expansion budget also bounds the sum of referenced
member lengths, with a 256 MiB floor.
cancellation that arrives while it is running; `vfs_name_units` bounds its
work. The combined logical path tree admits `path_nodes` (250,000) distinct
prefixes, and `retained_bytes` admits 256 MiB of retained header and entry
metadata. `artifact_limits.expanded_bytes` bounds the sum of referenced member
lengths; omitted, it is the shared artifact expansion budget with a 256 MiB
floor.
Carrier location claims a file only after it confirms the carrier name: a
Mach-O `__SUI` segment, a `SUI` ELF note descriptor named `d3n0l4nd`, a PE
+6 -4
View File
@@ -604,16 +604,18 @@ editable setting or active worker telemetry.
## Artifact reader admission
`inspect_artifact` and `extract_artifact` accept `dotnet_bundle`, `node_sea`
and `godot` groups in `artifact_limits`. Their controls apply when recognition
`inspect_artifact` and `extract_artifact` accept `bun`, `dotnet_bundle`,
`node_sea`, `godot`, `iso9660`, `deno`, `wxapkg` and `tar` groups in
`artifact_limits`. Their controls apply when recognition
or inventory encounters that format; supplying
a policy does not assert the format is present. Unsupported keys are rejected.
Each group follows one domain-owned default policy. See [.NET bundles](../dotnet-bundles.md),
[Node SEA](../node-sea.md), [Godot PCK](../godot-pck.md) and
[Bun standalone](../bun-standalone.md) for format semantics.
[Bun standalone](../bun-standalone.md), [Deno compile](../deno-standalone.md),
[wxapkg](../wxapkg.md) and [tar](../tar-archives.md) for format semantics.
`artifact_limits.expanded_bytes` selects aggregate plaintext work for ZIP, Bun,
SEA and PCK readers, including repeated readable logical occurrences. Omission
SEA, PCK, ISO 9660, Deno, wxapkg and tar readers, including repeated readable logical occurrences. Omission
retains each archive's encoded-size-derived default. The .NET bundle group's
own `expanded_bytes` controls its independently enforced bundle expansion.
+1 -1
View File
@@ -73,7 +73,7 @@ The report omits a check that cannot apply to the formats the audit detected, an
On a single Windows PE, for example, the Electron, JavaScript, Mach-O, and Android checks are omitted, and `native.hardening` keeps its `inspect_binary_hardening` probe.
Source map text is counted and then dropped. A selected file is read through the stable artifact reader. Text and source-map members stay inside the allowances listed under `coverage.allowances`, and each kind has its own allowance, so binary members cannot use up the read that a later source map needs. Native images on disk are registered from inventory classification and are not limited to those allowances. Other files and package members are identified from a bounded header. The bytes a package member's text or map read returns decide before its name does, so a PE called `payload.js.map` is read as a PE. A header with no NUL byte, or one that starts with a UTF-16 byte order mark, is scanned as text, so names such as `.env.production`, `server.key`, and `credentials` do not depend on an extension list. UTF-16 without a byte order mark has NUL bytes and is not recognized this way. A member already known to be text, such as a script, is also scanned when it is UTF-8 holding a stray NUL. One whose header is at least an eighth NUL bytes is taken to be wide text. It is not decoded and is counted as skipped, as is UTF-32. A binary plist is decoded, so its strings, dictionary keys and data are scanned in whichever encoding each object uses. One that cannot be decoded still has its bytes scanned and is counted as skipped. A file whose header could not be read leaves `text.credential_markers` undecided. A packaged ELF, Mach-O, or PE image is read in full and written to a temporary copy, removed afterward, so it can be probed for an embedded package. All packaged images share one `max_file_bytes` allowance. An image that does not fit, or whose bytes cannot be read, is not probed and leaves member coverage `unknown`. A packaged PE is also read for its debug records. An SVG file is read for its scripts as an HTML file is. A script that an HTML file loads, or a Node SEA main script, is examined as a script whatever it is called, so a name such as `boot.map` does not make it a map, and an HTML file loaded this way is still examined as HTML. Its bytes still decide over that role: a `.map` or loaded script whose text parses as a source map, a JSON object with `version` and `mappings`, `sources`, or `sections`, is read as a source map, so `<script src="main.map">` pointing at a map with `sourcesContent` still reports `javascript.source_map_sources` exposed. One read before that HTML file, one that is not found, one at a location the audit cannot place, or one past the 1 MiB of resolved script paths the audit keeps (`MAX_RELEASE_EXPOSURE_SCRIPT_TARGET_BYTES`) leaves `javascript.source_map_sources` undecided. A `.map` read before the HTML file that loads it is not reported as a linker map. Skipped members are listed under `coverage.omitted`. The report keeps the first eight scan limitations; a `limitations` entry under `coverage.omitted` counts the reports past them, including repeats. When the selection is a file, the parent directory is listed up to a fixed entry allowance for sibling `.pdb`, `.dSYM`, `.debug`, and linker `.map` debug companions. A sibling source map that the selected file declares, such as `app.js.map`, or a sibling script that a selected HTML file loads, such as `app.js`, is not read as part of the artifact, so it leaves `javascript.source_map_sources` undecided.
Source map text is counted and then dropped. A selected file is read through the stable artifact reader. Text and source-map members stay inside the allowances listed under `coverage.allowances`, and each kind has its own allowance, so binary members cannot use up the read that a later source map needs. Native images on disk are registered from inventory classification and are not limited to those allowances. Other files and package members are identified from a bounded header. The bytes a package member's text or map read returns decide before its name does, so a PE called `payload.js.map` is read as a PE. A header with no NUL byte, or one that starts with a UTF-16 byte order mark, is scanned as text, so names such as `.env.production`, `server.key`, and `credentials` do not depend on an extension list. UTF-16 without a byte order mark has NUL bytes and is not recognized this way. A member already known to be text, such as a script, is also scanned when it is UTF-8 holding a stray NUL. One whose header is at least an eighth NUL bytes is taken to be wide text. It is not decoded and is counted as skipped, as is UTF-32. A binary plist is decoded, so its strings, dictionary keys and data are scanned in whichever encoding each object uses. One that cannot be decoded still has its bytes scanned and is counted as skipped. A file whose header could not be read leaves `text.credential_markers` undecided. A packaged ELF, Mach-O, or PE image is read in full and written to a temporary copy, removed afterward, so it can be probed for an embedded package. All packaged images share one `max_file_bytes` allowance, a per-call budget of 256 MiB by default with no fixed ceiling below the safe-integer range; reads are held in memory. A selected file larger than it is refused with `details.limit` naming `max_file_bytes` and its range. An image that does not fit, or whose bytes cannot be read, is not probed and leaves member coverage `unknown`. A packaged PE is also read for its debug records. An SVG file is read for its scripts as an HTML file is. A script that an HTML file loads, or a Node SEA main script, is examined as a script whatever it is called, so a name such as `boot.map` does not make it a map, and an HTML file loaded this way is still examined as HTML. Its bytes still decide over that role: a `.map` or loaded script whose text parses as a source map, a JSON object with `version` and `mappings`, `sources`, or `sections`, is read as a source map, so `<script src="main.map">` pointing at a map with `sourcesContent` still reports `javascript.source_map_sources` exposed. One read before that HTML file, one that is not found, one at a location the audit cannot place, or one past the 1 MiB of resolved script paths the audit keeps (`MAX_RELEASE_EXPOSURE_SCRIPT_TARGET_BYTES`) leaves `javascript.source_map_sources` undecided. A `.map` read before the HTML file that loads it is not reported as a linker map. Skipped members are listed under `coverage.omitted`. The report keeps the first eight scan limitations; a `limitations` entry under `coverage.omitted` counts the reports past them, including repeats. When the selection is a file, the parent directory is listed up to a fixed entry allowance for sibling `.pdb`, `.dSYM`, `.debug`, and linker `.map` debug companions. A sibling source map that the selected file declares, such as `app.js.map`, or a sibling script that a selected HTML file loads, such as `app.js`, is not read as part of the artifact, so it leaves `javascript.source_map_sources` undecided.
Inline JavaScript maps use the data URL body. The audit ignores the URL
fragment and accepts omitted padding and ASCII whitespace in base64. Invalid
+2 -2
View File
@@ -68,8 +68,8 @@ extraction never writes outside its fresh output root.
- Gzip decompression, including the preparation pass, is charged to the archive plaintext-work allowance `artifact_limits.expanded_bytes`. Its default is the larger of 256 MiB and 500 times the file size.
- Members opened in archive order share one forward decompression. A member opened out of order starts a new decompression, which is charged again.
- A pax or GNU long-name record is limited to 1 MiB.
- Retained member metadata is limited to 64 MiB: a fixed 512 bytes per member plus its path and link bytes.
- `artifact_limits.tar.extended_header_bytes` (default 1 MiB) bounds one pax or GNU long-name record.
- `artifact_limits.tar.metadata_bytes` (default 64 MiB) bounds retained member metadata: a fixed 512 bytes per member plus its path and link bytes. A refusal reports either field in `details.reader_limit`.
- A reader serves at most four member streams at once.
## CLI
+14 -10
View File
@@ -29,16 +29,20 @@ fit the data region declared by one index-length convention.
## Resource bounds
These are resource policies, not format maxima. The encoded member table is
limited to 16 MiB and its buffer, parsed rows, retained entries and escaped
path projections share a conservative 64 MiB admission budget, reserved
before allocation; a declared member name is limited to 64 KiB. A reader
admits four active member streams. The shared archive plaintext-work ceiling
is the larger of 256 MiB and 500 times carrier size: every declared member
extent is charged, including aliases that overlap one stored range. A
separate member-I/O budget allows four times the larger of 1,024 and the sum
of the member count and declared 64 KiB plaintext chunks, bounding repeated
tiny-member reads independently of output bytes.
These are resource policies, not format maxima, and each is a per-call field
of `artifact_limits` on `inspect_artifact` and `extract_artifact`; a refusal
reports the field in `details.reader_limit`
([artifact reader admission](reference/limits-and-recovery.md#artifact-reader-admission)).
`wxapkg.table_bytes` (default 16 MiB) bounds the encoded member table, and its
buffer, parsed rows, retained entries and escaped path projections share
`wxapkg.directory_bytes` (default 64 MiB), reserved before allocation. A
declared member name is limited to 64 KiB. A reader admits four active member
streams. `artifact_limits.expanded_bytes` bounds archive plaintext work;
omitted, it is the larger of 256 MiB and 500 times carrier size. Every declared
member extent is charged, including aliases that overlap one stored range. A
separate member-I/O budget, derived from that admission, allows four times the
larger of 1,024 and the sum of the member count and declared 64 KiB plaintext
chunks, bounding repeated tiny-member reads independently of output bytes.
## CLI
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "d4ebd6a35bc062aa",
"input compact": "86bfdb6593ffe879",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "7ca5783e32c7fd0a",
"input compact": "190b002fc2ba8cd0",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "9402a1e3f66fd9f8",
"input compact": "5647cf3c21603dd5",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
+4 -78
View File
@@ -75,30 +75,10 @@
"reason": "Projects the boot-image parser's own named ceiling (`ceiling.name`); the value is declared by that parser."
}
},
"src/artifacts/DenoStandaloneArtifactReader.ts": {
"\"The Deno compile retained metadata allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Deno retained metadata bytes are a resource policy."
}
},
"src/artifacts/WxapkgArtifactReader.ts": {
"\"The wxapkg directory-and-chunk I/O work allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "wxapkg directory, member-table and I/O allowances are resource policies."
}
},
"src/artifacts/WxapkgStructures.ts": {
"\"The wxapkg directory representation allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "wxapkg directory, member-table and I/O allowances are resource policies."
},
"\"The wxapkg member table allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "wxapkg directory, member-table and I/O allowances are resource policies."
"class": "derived",
"reason": "Four times the admitted member count plus 64 KiB chunks of declared member bytes, which artifact_limits.expanded_bytes bounds; it grows with that admission."
}
},
"src/artifacts/apple/AppleAssetCatalogAnalysis.ts": {
@@ -108,18 +88,6 @@
"reason": "assetutil output capture is a producer budget without a per-call control."
}
},
"src/artifacts/deno/DenoSectionLayout.ts": {
"`The Deno compile ${scope} allowance`": {
"class": "pending",
"issue": 14236,
"reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima."
},
"`The Deno compile ${scope} record allowance`": {
"class": "pending",
"issue": 14236,
"reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima."
}
},
"src/artifacts/deno/DenoStandaloneLocation.ts": {
"parserLimit.name": {
"class": "forwarding",
@@ -128,19 +96,8 @@
},
"src/artifacts/deno/DenoVirtualFs.ts": {
"\"The Deno compile virtual filesystem depth allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima."
},
"\"The Deno compile virtual filesystem entry allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima."
},
"\"The Deno compile virtual filesystem retained name allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Deno compile table, VFS entry, depth and retained-name allowances are resource policies, not Deno format maxima."
"class": "representation",
"reason": "Bounds nested walkEntries recursion so a deeply nested VFS JSON cannot exhaust the call stack; entry, name and path budgets are per-call artifact_limits.deno controls."
}
},
"src/artifacts/dotnet/DotnetBundle.ts": {
@@ -155,25 +112,6 @@
"reason": "Duplicate-blob verification work is bounded by the carrier's own file size, so the bound grows with the admitted input."
}
},
"src/artifacts/releaseExposure/releaseExposureFailures.ts": {
"\"The release exposure input allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "The release exposure input allowance bounds bytes read, a resource policy."
}
},
"src/artifacts/tar/TarWalk.ts": {
"\"The tar extended-header allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "tar extended-header and retained member-metadata allowances are resource policies."
},
"\"The tar member metadata allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "tar extended-header and retained member-metadata allowances are resource policies."
}
},
"src/browser/WebBundleAnalysisWorker.ts": {
"\"The web-bundle worker transfer allowance\"": {
"class": "pending",
@@ -549,18 +487,6 @@
"reason": "Sensitive terminal redaction state is a resource policy."
}
},
"src/resources/ArtifactPaths.ts": {
"\"The artifact path depth allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Artifact path depth and tree-node allowances are resource policies."
},
"\"The artifact path tree allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Artifact path depth and tree-node allowances are resource policies."
}
},
"src/resources/artifactReadBudget.ts": {
"ceiling.name": {
"class": "forwarding",
@@ -17,7 +17,6 @@
"src/application/environment/environmentTools.ts": 1,
"src/application/investigation/InvestigationRetention.ts": 1,
"src/application/reverse/ReverseEngineeringService.ts": 1,
"src/artifacts/DesktopApplicationReader.ts": 1,
"src/browser/WebBundleAnalysisWorker.ts": 1,
"src/browser/history/playwrightTrace/PlaywrightTraceDecoder.ts": 1,
"src/browser/history/playwrightTrace/TraceFailure.ts": 1,
+1 -7
View File
@@ -146,15 +146,9 @@ export class BunStandaloneArtifactReader extends PositionalArtifactReader<
artifactExpansionBudgetBytes(located.graph.payloadLength),
);
const paths = new ArtifactPathRegistry({
group: "bun",
maxParts: this.limits.path_parts,
maxNodes: this.limits.path_nodes,
limitFailure: (field, maximum, required) =>
artifactReaderLimitFailure(
`artifact_limits.bun.${field}`,
maximum,
"count",
required,
),
});
for (const module of decoded.modules) {
assertArtifactReadActive(signal);
+45 -34
View File
@@ -6,11 +6,15 @@ import type {
DenoStandaloneMetadata,
} from "../domain/formatMetadata/packageAndGameMetadata.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
DEFAULT_DENO_READER_LIMITS,
type DenoReaderLimits,
} from "../domain/artifactReaderLimits.js";
import { jsonValueByteLength } from "../domain/jsonValueByteLength.js";
import {
assertArtifactReadActive,
ArtifactReaderFailure,
artifactFixedLimitFailure,
artifactReaderLimitFailure,
type ArtifactEntry,
ArtifactPathRegistry,
normalizeArtifactPath,
@@ -32,14 +36,12 @@ import { ArtifactEmbeddedFormatProbes } from "./ArtifactEmbeddedFormatProbes.js"
import {
DENO_CHILD_SUFFIXES,
DENO_PATH_LENGTH_LIMITATION,
DENO_PATH_PARTS_LIMITATION,
DENO_UNSAFE_PATH_LIMITATION,
denoLogicalPathFits,
MAX_DENO_LOGICAL_PATH_PARTS,
denoPathPartsLimitation,
type DenoVfsMember,
} from "./deno/DenoVirtualFs.js";
const MAX_DENO_LOGICAL_PATH_NODES = 250_000;
const UNLISTED_VFS_LIMITATION =
"The Deno compile virtual filesystem could not be listed, so its files are not inventoried.";
/**
@@ -49,7 +51,6 @@ const UNLISTED_VFS_LIMITATION =
const NON_PORTABLE_PATH_CHARACTERS = /[:\\*?"<>|\u0001-\u001f]/gu;
const percentEscape = (character: string): string =>
`%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
export const MAX_DENO_RETAINED_BYTES = 256 * 1024 * 1024;
interface RemoteDestination {
readonly path: string;
@@ -68,6 +69,8 @@ export class DenoStandaloneArtifactReader extends PositionalArtifactReader<
constructor(
private readonly path: string,
admitted?: StableRegularFileDescriptor | DenoStandaloneAdmission,
private readonly limits: DenoReaderLimits = DEFAULT_DENO_READER_LIMITS,
private readonly expandedBytes?: number,
) {
const descriptor =
admitted !== undefined && "kind" in admitted ? admitted.source : admitted;
@@ -125,40 +128,44 @@ export class DenoStandaloneArtifactReader extends PositionalArtifactReader<
return bytes;
},
signal,
this.limits,
);
const header = sectionHeader(location, section);
const retainedAllowance = this.limits.retained_bytes;
let retainedBytes = jsonValueByteLength(
header as JsonValue,
MAX_DENO_RETAINED_BYTES,
retainedAllowance,
);
if (retainedBytes > MAX_DENO_RETAINED_BYTES)
throw denoRetainedLimit(retainedBytes);
if (retainedBytes > retainedAllowance)
throw denoRetainedLimit(retainedAllowance);
let declaredPlaintext = 0n;
const expansionBudget = BigInt(
artifactExpansionBudgetBytes(location.length),
this.expandedBytes ?? artifactExpansionBudgetBytes(location.length),
);
const paths = new ArtifactPathRegistry({
maxParts: MAX_DENO_LOGICAL_PATH_PARTS,
maxNodes: MAX_DENO_LOGICAL_PATH_NODES,
group: "deno",
maxParts: this.limits.path_parts,
maxNodes: this.limits.path_nodes,
});
const entries = new Map<string, ArtifactEntry>();
const admit = (entry: ArtifactEntry): void => {
if (entry.declaredSize !== null) {
declaredPlaintext += BigInt(entry.declaredSize);
if (declaredPlaintext > expansionBudget)
throw new ArtifactReaderFailure(
"limit",
`Deno compile readable entries declare ${String(declaredPlaintext)} plaintext bytes, exceeding this section's ${String(expansionBudget)}-byte expansion budget. This release has no runtime override. Host memory and NODE_OPTIONS do not raise it.`,
{ boundary: "capacity" },
throw artifactReaderLimitFailure(
"artifact_limits.expanded_bytes",
Number(expansionBudget),
"bytes",
declaredPlaintext,
);
}
paths.reservePath(entry.path);
retainedBytes += jsonValueByteLength(
(entry.formatMetadata ?? null) as JsonValue,
Math.max(0, MAX_DENO_RETAINED_BYTES - retainedBytes),
Math.max(0, retainedAllowance - retainedBytes),
);
if (retainedBytes > MAX_DENO_RETAINED_BYTES)
throw denoRetainedLimit(retainedBytes);
if (retainedBytes > retainedAllowance)
throw denoRetainedLimit(retainedAllowance);
entries.set(entry.adapterKey, entry);
};
if (section.vfs.listing === "listed") {
@@ -167,7 +174,11 @@ export class DenoStandaloneArtifactReader extends PositionalArtifactReader<
admit(vfsEntry(location.offset, section, member));
}
}
const remotePlans = assignRemoteDestinations(section, paths);
const remotePlans = assignRemoteDestinations(
section,
paths,
this.limits.path_parts,
);
for (const module of section.remoteModules.modules) {
assertArtifactReadActive(signal);
const destination = remotePlans.get(module.index);
@@ -381,6 +392,7 @@ const remoteUrlSuffix = (url: URL): string => {
const remoteDestination = (
section: DenoParsedSection,
module: DenoRemoteModule,
maximumParts: number,
): RemoteDestination => {
const fallback = `deno-remote/${String(module.index)}`;
const text = section.specifierText.get(module.specifierId) ?? null;
@@ -409,14 +421,11 @@ const remoteDestination = (
}
let parts = 1;
for (let index = 0; index < candidate.length; index += 1)
if (
candidate.charCodeAt(index) === 47 &&
++parts > MAX_DENO_LOGICAL_PATH_PARTS
)
if (candidate.charCodeAt(index) === 47 && ++parts > maximumParts)
return {
path: fallback,
sourcePath: text,
limitations: [DENO_PATH_PARTS_LIMITATION],
limitations: [denoPathPartsLimitation(maximumParts)],
};
let normalized: string;
try {
@@ -480,6 +489,7 @@ const remoteConcretePaths = (
const assignRemoteDestinations = (
section: DenoParsedSection,
paths: ArtifactPathRegistry,
maximumParts: number,
): ReadonlyMap<number, RemoteDestination> => {
const modules = section.remoteModules.modules;
const assigned = new Map<number, RemoteDestination>();
@@ -493,7 +503,7 @@ const assignRemoteDestinations = (
paths.reservePath(concrete);
};
for (const module of modules) {
const natural = remoteDestination(section, module);
const natural = remoteDestination(section, module, maximumParts);
if (fits(module, natural.path)) {
assigned.set(module.index, natural);
take(module, natural.path);
@@ -522,14 +532,15 @@ const assignRemoteDestinations = (
return assigned;
};
const denoRetainedLimit = (claimed: number): ArtifactReaderFailure =>
artifactFixedLimitFailure(
{
name: "The Deno compile retained metadata allowance",
kind: "parser",
limit: MAX_DENO_RETAINED_BYTES,
unit: "bytes",
},
`The retained metadata claims ${String(claimed)} bytes, above ${String(MAX_DENO_RETAINED_BYTES)} bytes.`,
/**
* `jsonValueByteLength` stops counting once its budget is exceeded, so the
* counted size understates the requirement and is not reported as required.
*/
const denoRetainedLimit = (allowance: number): ArtifactReaderFailure =>
artifactReaderLimitFailure(
"artifact_limits.deno.retained_bytes",
allowance,
"bytes",
undefined,
"memory",
);
@@ -90,6 +90,8 @@ export class DesktopApplicationReader implements DesktopApplicationPort {
{ max_concurrent_inspections: 1 },
{
retryable: true,
// An occupied admission: the slot frees when the inspection ends.
measuredExhaustion: true,
remediationAction:
"Wait for this directory inspection to finish before submitting another.",
},
+2 -2
View File
@@ -118,7 +118,7 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import {
PACKAGED_NATIVE_IMAGES,
MAX_RELEASE_EXPOSURE_FILE_BYTES,
RELEASE_EXPOSURE_FILE_BYTES,
MAX_RELEASE_EXPOSURE_INVENTORY_BYTES,
MAX_RELEASE_EXPOSURE_INVENTORY_ENTRIES,
MAX_RELEASE_EXPOSURE_MEMBER_PROBE_BYTES,
@@ -255,7 +255,7 @@ export class ReleaseExposureReader implements ReleaseExposurePort {
visitInterruptedScan?: ReleaseExposureScanVisitor,
): Promise<Result<ReleaseExposureScan, AnalysisError>> {
const maxFileBytes =
input.max_file_bytes ?? MAX_RELEASE_EXPOSURE_FILE_BYTES;
input.max_file_bytes ?? RELEASE_EXPOSURE_FILE_BYTES.default_value;
const context: ScanContext = {
signal: options?.signal,
resources: this.#resources,
@@ -99,11 +99,12 @@ describe("wxapkg allocation and malformed-input boundaries", () => {
await expect(collectEntries(reader)).rejects.toMatchObject({
reason: "limit",
boundary: "capacity",
fixedAllowance: {
name: "The wxapkg member table allowance",
kind: "parser",
limit: 16 * 1024 * 1024,
unit: "bytes",
readerLimit: {
parameter: "artifact_limits.wxapkg.table_bytes",
effective_value: 16 * 1024 * 1024,
// The declared index length less its four-byte file count.
required_value: 17 * 1024 * 1024 - 4,
can_increase: true,
},
});
expect(reads).toHaveBeenCalledTimes(1); // bounded header only
@@ -140,8 +141,9 @@ describe("wxapkg allocation and malformed-input boundaries", () => {
await expect(collectEntries(reader)).rejects.toMatchObject({
reason: "limit",
boundary: "capacity",
fixedAllowance: {
name: "The wxapkg directory representation allowance",
readerLimit: {
parameter: "artifact_limits.wxapkg.directory_bytes",
effective_value: 64 * 1024 * 1024,
unit: "bytes",
},
});
@@ -163,7 +165,12 @@ describe("wxapkg allocation and malformed-input boundaries", () => {
try {
await expect(collectEntries(reader)).rejects.toMatchObject({
reason: "limit",
message: expect.stringContaining("wxapkg members declare"),
readerLimit: {
parameter: "artifact_limits.expanded_bytes",
// 500 times the encoded package size when no value is selected.
effective_value: expect.any(Number),
can_increase: true,
},
});
} finally {
await reader.close();
+20 -6
View File
@@ -6,6 +6,7 @@ import type { Readable } from "node:stream";
import {
ArtifactReaderFailure,
artifactFixedLimitFailure,
artifactReaderLimitFailure,
copyArtifactEntry,
assertProducedEntry,
type ArtifactEntry,
@@ -20,6 +21,10 @@ import { readArtifactFileBytes } from "./ArtifactFileRange.js";
import type { ArtifactFormatMetadata } from "../domain/artifactFormatMetadata.js";
import type { WxapkgMetadata } from "../domain/formatMetadata/packageAndGameMetadata.js";
import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
import {
DEFAULT_WXAPKG_READER_LIMITS,
type WxapkgReaderLimits,
} from "../domain/artifactReaderLimits.js";
import {
readWxapkgFileTable,
readWxapkgHeader,
@@ -59,7 +64,12 @@ export class WxapkgArtifactReader implements ArtifactReader {
#admittedReadOperations = 0;
#closing = false;
constructor(path: string, admitted?: StableRegularFileDescriptor) {
constructor(
path: string,
admitted?: StableRegularFileDescriptor,
private readonly limits: WxapkgReaderLimits = DEFAULT_WXAPKG_READER_LIMITS,
private readonly expandedBytes?: number,
) {
this.#source = new ArtifactFileSource(path, "wxapkg package", admitted);
}
@@ -177,9 +187,11 @@ export class WxapkgArtifactReader implements ArtifactReader {
handle,
header,
initial.size,
this.limits,
signal,
);
const budget = artifactExpansionBudgetBytes(initial.size);
const budget =
this.expandedBytes ?? artifactExpansionBudgetBytes(initial.size);
const entries = new Map<string, WxapkgEntryState>();
let declaredBytes = 0n;
for (let index = 0; index < members.length; index++) {
@@ -189,10 +201,12 @@ export class WxapkgArtifactReader implements ArtifactReader {
// Overlapping member ranges are valid; each declared path causes a read.
declaredBytes += BigInt(member.size);
if (declaredBytes > BigInt(budget))
throw new ArtifactReaderFailure(
"limit",
`wxapkg members declare ${String(declaredBytes)} bytes, exceeding the ${String(budget)}-byte plaintext-work budget`,
{ boundary: "memory" },
throw artifactReaderLimitFailure(
"artifact_limits.expanded_bytes",
budget,
"bytes",
declaredBytes,
"memory",
);
const adapterKey = `wxapkg-entry:${String(index)}`;
entries.set(adapterKey, {
+24 -27
View File
@@ -5,9 +5,10 @@ import {
ArtifactReaderFailure,
malformedArtifact,
truncatedArtifact,
artifactFixedLimitFailure,
artifactReaderLimitFailure,
assertArtifactReadActive,
} from "../resources/index.js";
import type { WxapkgReaderLimits } from "../domain/artifactReaderLimits.js";
import { readArtifactFileBytes } from "./ArtifactFileRange.js";
import { setImmediate } from "node:timers/promises";
import {
@@ -21,10 +22,12 @@ import {
} from "../domain/wxapkgFormat.js";
import { strictUtf8Decoder } from "../domain/strictUtf8.js";
/** The member table is a flat name/offset/size row list. */
const MAX_TABLE_BYTES = 16 * 1024 * 1024;
/** Encoded retained directory representation; paths are charged separately. */
const DIRECTORY_BUDGET_BYTES = 64 * 1024 * 1024;
/*
* The member table is a flat name/offset/size row list read under
* `artifact_limits.wxapkg.table_bytes`. Its retained representation (the
* table buffer, JS rows and escaped name projections) is reserved under
* `artifact_limits.wxapkg.directory_bytes` before allocating.
*/
/** Member names are relative package paths; larger claims are malformed. */
const MAX_MEMBER_NAME_BYTES = 64 * 1024;
/** Detecting prefix covers the fixed header, table head and encrypted magic. */
@@ -38,16 +41,11 @@ export const wxapkgFormatFailure = (detail: string): ArtifactReaderFailure =>
const wxapkgTruncatedFailure = (detail: string): ArtifactReaderFailure =>
truncatedArtifact("wxapkg", `wxapkg is malformed: ${detail}`);
/** Buffers, JS rows and escaped name projections, reserved before allocating. */
const directoryLimit = (): Error =>
artifactFixedLimitFailure(
{
name: "The wxapkg directory representation allowance",
kind: "parser",
limit: DIRECTORY_BUDGET_BYTES,
unit: "bytes",
},
`The wxapkg directory needs more than ${String(DIRECTORY_BUDGET_BYTES)} bytes to represent.`,
const directoryLimit = (limits: WxapkgReaderLimits) => (): Error =>
artifactReaderLimitFailure(
"artifact_limits.wxapkg.directory_bytes",
limits.directory_bytes,
"bytes",
);
export interface WxapkgHeader {
@@ -121,6 +119,7 @@ export const readWxapkgFileTable = async (
handle: FileHandle,
header: WxapkgHeader,
size: number,
limits: WxapkgReaderLimits,
signal?: AbortSignal,
): Promise<WxapkgFileTable> => {
const layout = header.layout;
@@ -138,18 +137,16 @@ export const readWxapkgFileTable = async (
}
if (tableStart === undefined)
throw wxapkgTruncatedFailure("declared member table exceeds the file");
if (readBytes > MAX_TABLE_BYTES)
throw artifactFixedLimitFailure(
{
name: "The wxapkg member table allowance",
kind: "parser",
limit: MAX_TABLE_BYTES,
unit: "bytes",
},
`The wxapkg member table declares ${String(readBytes)} bytes, above ${String(MAX_TABLE_BYTES)} bytes.`,
if (readBytes > limits.table_bytes)
throw artifactReaderLimitFailure(
"artifact_limits.wxapkg.table_bytes",
limits.table_bytes,
"bytes",
readBytes,
);
const budget = new Budget(DIRECTORY_BUDGET_BYTES);
budget.charge(readBytes, directoryLimit);
const budget = new Budget(limits.directory_bytes);
const exhausted = directoryLimit(limits);
budget.charge(readBytes, exhausted);
const table = await readArtifactFileBytes(
"wxapkg",
handle,
@@ -178,7 +175,7 @@ export const readWxapkgFileTable = async (
)
throw wxapkgFormatFailure("member row exceeds the table");
// Row storage plus the reader's owned entries/map; charge before decode.
budget.charge(512 + nameLength * 24, directoryLimit);
budget.charge(512 + nameLength * 24, exhausted);
let declaredPath: string;
try {
declaredPath = UTF8.decode(table.subarray(cursor, cursor + nameLength));
+9 -1
View File
@@ -291,6 +291,8 @@ const NON_ZIP_FORMATS = {
new DenoStandaloneArtifactReader(
path,
admittedAs("deno-standalone", options),
options.readerLimits?.deno,
options.readerLimits?.expanded_bytes,
),
}),
dmg: container("dmg", {
@@ -378,7 +380,12 @@ const NON_ZIP_FORMATS = {
readerLimitation:
"wxapkg inventory establishes packaged member names and stored bytes; wxml/wxss sources, compiled bundles and runtime behavior are not reconstructed. V1MMWX-encrypted packages are unsupported.",
createReader: (path, options) =>
new WxapkgArtifactReader(path, sourceOf(options)),
new WxapkgArtifactReader(
path,
sourceOf(options),
options.readerLimits?.wxapkg,
options.readerLimits?.expanded_bytes,
),
}),
tar: container("tar", {
roleContainer: true,
@@ -392,6 +399,7 @@ const NON_ZIP_FORMATS = {
path,
sourceOf(options),
options.readerLimits?.expanded_bytes,
options.readerLimits?.tar,
),
}),
dds: gpuAsset("dds"),
+20 -11
View File
@@ -1,10 +1,7 @@
import { expect, it } from "vitest";
import {
MAX_DENO_REMOTE_BODY_BYTES,
MAX_DENO_SPECIFIER_TEXT_BYTES,
parseDenoSection,
} from "./DenoSectionLayout.js";
import { DEFAULT_DENO_READER_LIMITS } from "../../domain/artifactReaderLimits.js";
import { parseDenoSection } from "./DenoSectionLayout.js";
import {
buildDenoSection,
defaultDenoMetadata,
@@ -147,7 +144,11 @@ it("refuses metadata JSON above the named allowance before reading it as JSON",
bytes.writeBigUInt64LE(BigInt(claimed), DENO_FIXTURE_SECTION_MAGIC.length);
await expect(parseDenoSectionBytes(bytes)).rejects.toMatchObject({
reason: "limit",
message: expect.stringContaining("metadata JSON"),
readerLimit: {
parameter: "artifact_limits.deno.metadata_json_bytes",
effective_value: 8 * 1024 * 1024,
required_value: claimed,
},
});
});
@@ -161,24 +162,28 @@ it("refuses a specifier table above the named record allowance", async () => {
),
).rejects.toMatchObject({
reason: "limit",
message: expect.stringContaining("specifier"),
readerLimit: {
parameter: "artifact_limits.deno.table_records",
effective_value: 100_000,
required_value: 100_001,
},
});
});
it.each([
{
text: "file:///wire-specifier.ts",
limit: MAX_DENO_SPECIFIER_TEXT_BYTES,
limit: DEFAULT_DENO_READER_LIMITS.specifier_text_bytes,
field: "specifier text",
},
{
text: "wire-module",
limit: MAX_DENO_REMOTE_BODY_BYTES,
limit: DEFAULT_DENO_READER_LIMITS.remote_body_bytes,
field: "remote module",
},
{
text: "wire-transpiled",
limit: MAX_DENO_REMOTE_BODY_BYTES,
limit: DEFAULT_DENO_READER_LIMITS.remote_body_bytes,
field: "remote transpiled",
},
])(
@@ -310,7 +315,11 @@ it("keeps the redirect count allowance and rejects duplicate IDs across batches"
overCount.writeUInt32LE(100_001, REDIRECT_ROWS - 4);
await expect(parseDenoSectionBytes(overCount)).rejects.toMatchObject({
reason: "limit",
fixedAllowance: { limit: 100_000, unit: "records" },
readerLimit: {
parameter: "artifact_limits.deno.table_records",
effective_value: 100_000,
unit: "count",
},
});
const sources = Array.from({ length: 1_024 }, (_, index) => index);
await expect(
+45 -49
View File
@@ -4,8 +4,12 @@ import {
ArtifactReaderFailure,
malformedArtifact,
abortIfNeeded,
artifactFixedLimitFailure,
artifactReaderLimitFailure,
} from "../../resources/index.js";
import {
DEFAULT_DENO_READER_LIMITS,
type DenoReaderLimits,
} from "../../domain/artifactReaderLimits.js";
import { walkDenoVirtualFs, type DenoVfsWalk } from "./DenoVirtualFs.js";
import { parseJsonWithDuplicatePolicy } from "../../domain/jsonDuplicateMember.js";
import { strictUtf8Decoder } from "../../domain/strictUtf8.js";
@@ -13,13 +17,8 @@ import { strictUtf8Decoder } from "../../domain/strictUtf8.js";
/** Opening and closing marker of a Deno compile data section. */
export const DENO_SECTION_MAGIC = Buffer.from("d3n0l4nd", "latin1");
const MAX_DENO_METADATA_JSON_BYTES = 8 * 1024 * 1024;
export const MAX_DENO_VFS_HEADER_JSON_BYTES = 32 * 1024 * 1024;
const MAX_DENO_TABLE_COUNT = 100_000;
const REDIRECT_ROW_BYTES = 8;
const REDIRECT_BATCH_ROWS = 1_024;
export const MAX_DENO_SPECIFIER_TEXT_BYTES = 8 * 1024 * 1024;
export const MAX_DENO_REMOTE_BODY_BYTES = 256 * 1024 * 1024;
const KNOWN_REMOTE_FLAGS = 0x0f;
const FLAG_TRANSPILED = 1 << 0;
@@ -134,6 +133,7 @@ export const parseDenoSection = async (
sectionLength: number,
read: DenoSectionRead,
signal?: AbortSignal,
limits: DenoReaderLimits = DEFAULT_DENO_READER_LIMITS,
): Promise<DenoParsedSection> => {
abortIfNeeded(signal);
if (
@@ -186,17 +186,18 @@ export const parseDenoSection = async (
new BinaryReader(await pull(8), true, "deno").word(0, 64);
const readBounded = async (
claimed: bigint,
max: number,
field: "metadata_json_bytes" | "vfs_header_json_bytes",
scope: string,
): Promise<Buffer> => {
const range = takeRange(claimed, scope);
if (claimed > BigInt(max)) throw denoByteLimit(scope, claimed, max);
if (claimed > BigInt(limits[field]))
throw denoByteLimit(field, claimed, limits);
return readExact(range.sectionOffset, range.length);
};
const metadataBytes = await readBounded(
await u64(),
MAX_DENO_METADATA_JSON_BYTES,
"metadata_json_bytes",
"metadata JSON",
);
const metadata = observeMetadata(decodeJson(metadataBytes, "metadata JSON"));
@@ -204,7 +205,7 @@ export const parseDenoSection = async (
const specifierStart = cursor;
const specifierCount = await u32();
assertTableCount(specifierCount, "specifier");
assertTableCount(specifierCount, limits);
const specifierText = new Map<number, string | null>();
let textBytes = 0;
let invalidUtf8 = false;
@@ -213,12 +214,8 @@ export const parseDenoSection = async (
const length = await u32();
const range = takeRange(BigInt(length), "specifier text");
textBytes += length;
if (textBytes > MAX_DENO_SPECIFIER_TEXT_BYTES)
throw denoByteLimit(
"specifier text",
textBytes,
MAX_DENO_SPECIFIER_TEXT_BYTES,
);
if (textBytes > limits.specifier_text_bytes)
throw denoByteLimit("specifier_text_bytes", textBytes, limits);
const bytes = await readExact(range.sectionOffset, range.length);
const id = await u32();
if (specifierText.has(id))
@@ -237,7 +234,7 @@ export const parseDenoSection = async (
const redirectStart = cursor;
const redirectCount = await u32();
assertTableCount(redirectCount, "redirect");
assertTableCount(redirectCount, limits);
const redirectIds = new Set<number>();
let redirectListing: DenoListing = "listed";
for (let index = 0; index < redirectCount;) {
@@ -283,13 +280,13 @@ export const parseDenoSection = async (
const remoteStart = cursor;
const remoteCount = await u32();
assertTableCount(remoteCount, "remote module");
assertTableCount(remoteCount, limits);
const remoteIds = new Set<number>();
const modules: DenoRemoteModule[] = [];
let remoteBodies = 0n;
const takeRemoteBody = (length: number, scope: string): DenoByteRange => {
const range = takeRange(BigInt(length), scope);
remoteBodies = addRemoteBody(remoteBodies, length);
remoteBodies = addRemoteBody(remoteBodies, length, limits);
return range;
};
let unresolvedRemote = false;
@@ -348,7 +345,7 @@ export const parseDenoSection = async (
const vfsHeader = await readBounded(
await u64(),
MAX_DENO_VFS_HEADER_JSON_BYTES,
"vfs_header_json_bytes",
"vfs header JSON",
);
const vfsJson = decodeJson(vfsHeader, "vfs header JSON");
@@ -368,32 +365,30 @@ export const parseDenoSection = async (
remoteModules,
vfsHeaderByteLength: vfsHeader.length,
vfsFileData,
vfs: walkDenoVirtualFs(vfsJson, vfsFileData.length, signal),
vfs: walkDenoVirtualFs(vfsJson, vfsFileData.length, signal, limits),
specifierText,
};
};
const addRemoteBody = (total: bigint, length: number): bigint => {
const addRemoteBody = (
total: bigint,
length: number,
limits: DenoReaderLimits,
): bigint => {
const next = total + BigInt(length);
if (next > BigInt(MAX_DENO_REMOTE_BODY_BYTES))
throw denoByteLimit(
"remote module bodies",
next,
MAX_DENO_REMOTE_BODY_BYTES,
);
if (next > BigInt(limits.remote_body_bytes))
throw denoByteLimit("remote_body_bytes", next, limits);
return next;
};
const assertTableCount = (count: number, scope: string): void => {
if (count > MAX_DENO_TABLE_COUNT)
throw artifactFixedLimitFailure(
{
name: `The Deno compile ${scope} record allowance`,
kind: "count",
limit: MAX_DENO_TABLE_COUNT,
unit: "records",
},
`Deno compile ${scope} table claims ${String(count)} records, exceeding MAX_DENO_TABLE_COUNT (${String(MAX_DENO_TABLE_COUNT)} records).`,
/** Each specifier, redirect and remote-module table shares one record budget. */
const assertTableCount = (count: number, limits: DenoReaderLimits): void => {
if (count > limits.table_records)
throw artifactReaderLimitFailure(
"artifact_limits.deno.table_records",
limits.table_records,
"count",
count,
);
};
@@ -539,18 +534,19 @@ export const denoUnsupported = (detail: string): ArtifactReaderFailure =>
`Deno compile section layout is unsupported: ${detail}`,
);
export const denoByteLimit = (
scope: string,
const denoByteLimit = (
field:
| "metadata_json_bytes"
| "vfs_header_json_bytes"
| "specifier_text_bytes"
| "remote_body_bytes",
claimed: number | bigint,
allowance: number,
limits: DenoReaderLimits,
): ArtifactReaderFailure =>
artifactFixedLimitFailure(
{
name: `The Deno compile ${scope} allowance`,
kind: "parser",
limit: allowance,
unit: "bytes",
},
`The ${scope} claims ${String(claimed)} bytes, above ${String(allowance)} bytes.`,
artifactReaderLimitFailure(
`artifact_limits.deno.${field}`,
limits[field],
"bytes",
claimed,
"memory",
);
+29 -22
View File
@@ -1,13 +1,11 @@
import { expect, it } from "vitest";
import { ArtifactReaderFailure } from "../../resources/ArtifactReader.js";
import {
MAX_DENO_LOGICAL_PATH_PARTS,
walkDenoVirtualFs,
} from "./DenoVirtualFs.js";
import { DEFAULT_DENO_READER_LIMITS } from "../../domain/artifactReaderLimits.js";
import { walkDenoVirtualFs } from "./DenoVirtualFs.js";
// Independent format and admission examples.
const MAX_DENO_VFS_ENTRIES = 100_000;
const MAX_DENO_LOGICAL_PATH_PARTS = 256;
const MAX_DENO_VFS_NAME_UNITS = 4_096;
const MAX_DENO_VFS_DEPTH = 512;
const MAX_DENO_PATH_COMPONENT_BYTES = 255;
@@ -171,26 +169,31 @@ it.each(["0", "0.deno-transpiled", "0/leaf"])(
},
);
it("refuses an entry count above the named allowance", () => {
const entries = Array.from({ length: MAX_DENO_VFS_ENTRIES + 1 }, () =>
file("a.ts", 0, 0),
);
it("refuses an entry count above the selected allowance", () => {
const entries = Array.from({ length: 3 }, () => file("a.ts", 0, 0));
const limits = { ...DEFAULT_DENO_READER_LIMITS, vfs_entries: 2 };
let failure: unknown;
try {
walkDenoVirtualFs(entries, 0);
walkDenoVirtualFs(entries, 0, undefined, limits);
} catch (cause) {
failure = cause;
expect(cause).toMatchObject({
reason: "limit",
fixedAllowance: {
name: "The Deno compile virtual filesystem entry allowance",
kind: "count",
limit: MAX_DENO_VFS_ENTRIES,
unit: "entries",
readerLimit: {
parameter: "artifact_limits.deno.vfs_entries",
effective_value: 2,
required_value: 3,
can_increase: true,
},
});
}
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(
walkDenoVirtualFs(entries, 0, undefined, {
...limits,
vfs_entries: 3,
}).members,
).toHaveLength(3);
});
it("does not publish a bare child name when an ancestor source was dropped", () => {
@@ -365,21 +368,25 @@ it("indexes a path over the logical byte allowance and its descendants", () => {
});
it("charges directory paths against the retained allowance", () => {
const name = "d".repeat(MAX_DENO_VFS_NAME_UNITS);
const emptySiblings = Array.from({ length: 99_000 }, (_, index): unknown => ({
const name = "d".repeat(64);
const emptySiblings = Array.from({ length: 4 }, (_, index): unknown => ({
Dir: { n: `s${String(index)}`, e: [] },
}));
const chain = (depth: number): unknown[] =>
depth === 0 ? emptySiblings : [{ Dir: { n: name, e: chain(depth - 1) } }];
// Directory sources alone (64 + 129 + 194 units) exceed the selection.
expect(() =>
walkDenoVirtualFs(chain(MAX_DENO_LOGICAL_PATH_PARTS), 0),
walkDenoVirtualFs(chain(3), 0, undefined, {
...DEFAULT_DENO_READER_LIMITS,
vfs_name_units: 300,
}),
).toThrow(
expect.objectContaining({
reason: "limit",
fixedAllowance: expect.objectContaining({
name: "The Deno compile virtual filesystem retained name allowance",
kind: "bytes",
unit: "UTF-16 code units",
readerLimit: expect.objectContaining({
parameter: "artifact_limits.deno.vfs_name_units",
effective_value: 300,
unit: "count",
}),
}),
);
+40 -38
View File
@@ -2,30 +2,29 @@ import {
ArtifactReaderFailure,
malformedArtifact,
artifactFixedLimitFailure,
artifactReaderLimitFailure,
normalizeArtifactPath,
abortIfNeeded,
} from "../../resources/index.js";
import {
DEFAULT_DENO_READER_LIMITS,
type DenoReaderLimits,
} from "../../domain/artifactReaderLimits.js";
/** Directory, file, and symlink records admitted from one virtual filesystem. */
const MAX_DENO_VFS_ENTRIES = 100_000;
/** Logical path parts admitted before an indexed fallback. */
export const MAX_DENO_LOGICAL_PATH_PARTS = 256;
/**
* UTF-16 code units retained for one virtual name. Longer names are indexed
* and the original spelling is not copied into members.
*/
const MAX_DENO_VFS_NAME_UNITS = 4_096;
/**
* Nested `walkEntries` calls. This is the recursion budget, separate from
* the logical-path part fallback.
* Nested `walkEntries` calls. This is the recursion budget that keeps a
* deeply nested VFS from exhausting the call stack, separate from the
* logical-path part fallback. `artifact_limits.deno.vfs_name_units` bounds the
* UTF-16 code units of the source path built for each entry, directories
* included, plus retained symlink parts; each path is rebuilt and normalized
* once, so that control also bounds the synchronous walk.
*/
const MAX_DENO_VFS_DEPTH = 512;
/**
* UTF-16 code units of the source path built for each entry, directories
* included, plus retained symlink parts. Each path is rebuilt and normalized
* once, so this also bounds the synchronous walk.
*/
const MAX_DENO_VFS_RETAINED_UNITS = 32 * 1024 * 1024;
/** POSIX NAME_MAX. A longer component makes extraction fail with ENAMETOOLONG. */
const MAX_DENO_PATH_COMPONENT_BYTES = 255;
/**
@@ -40,7 +39,9 @@ export const DENO_CHILD_SUFFIXES = {
sourceMap: ".deno-sourcemap",
} as const;
export const DENO_PATH_PARTS_LIMITATION = `The virtual name exceeds the fixed ${String(MAX_DENO_LOGICAL_PATH_PARTS)}-part logical path allowance; an indexed path is used and the original name is retained.`;
/** The indexed-fallback limitation for a name deeper than the selected path parts. */
export const denoPathPartsLimitation = (maximumParts: number): string =>
`The virtual name exceeds artifact_limits.deno.path_parts (${String(maximumParts)} parts); an indexed path is used and the original name is retained.`;
const NAME_LIMITATION = `The virtual name exceeds the fixed ${String(MAX_DENO_VFS_NAME_UNITS)}-unit name allowance; an indexed path is used and the original name is not retained.`;
export const DENO_PATH_LENGTH_LIMITATION = `The virtual name exceeds the fixed ${String(MAX_DENO_PATH_COMPONENT_BYTES)}-byte path component or ${String(MAX_DENO_LOGICAL_PATH_BYTES)}-byte logical path allowance; an indexed path is used and the original name is retained.`;
export const DENO_UNSAFE_PATH_LIMITATION =
@@ -79,6 +80,7 @@ class UnsupportedVfsShape {
}
interface WalkState {
readonly limits: DenoReaderLimits;
count: number;
retainedUnits: number;
readonly indexed: Set<number>;
@@ -133,11 +135,13 @@ export const walkDenoVirtualFs = (
value: unknown,
fileDataLength: number,
signal?: AbortSignal,
limits: DenoReaderLimits = DEFAULT_DENO_READER_LIMITS,
): DenoVfsWalk => {
abortIfNeeded(signal);
if (!Array.isArray(value)) return { listing: "unsupported", members: [] };
const members: DenoVfsMember[] = [];
const state: WalkState = {
limits,
count: 0,
retainedUnits: 0,
indexed: new Set(),
@@ -207,7 +211,8 @@ const walkEntries = (
const tagged = taggedEntry(entry);
if (tagged === undefined) throw new UnsupportedVfsShape();
const index = state.count;
if (index >= MAX_DENO_VFS_ENTRIES) throw denoVfsEntryLimit(index + 1);
if (index >= state.limits.vfs_entries)
throw denoVfsEntryLimit(state.limits, index + 1);
state.count += 1;
const name = tagged.body.n;
if (typeof name !== "string") throw new UnsupportedVfsShape();
@@ -222,6 +227,7 @@ const walkEntries = (
source,
index,
Math.max(0, ...(regions?.children ?? []).map((c) => c.suffix.length)),
state.limits.path_parts,
);
const childParent: Parent = {
path: destination.forceChildren ? null : destination.path,
@@ -373,6 +379,7 @@ const logicalDestination = (
source: string | null,
index: number,
reservedBytes: number,
maximumParts: number,
): Destination => {
const indexed = (
limitation: string,
@@ -389,8 +396,8 @@ const logicalDestination = (
return indexed(NAME_LIMITATION, null);
if (unsafeName(name)) return indexed(DENO_UNSAFE_PATH_LIMITATION, source);
const parts = parent.parts + 1;
if (parts > MAX_DENO_LOGICAL_PATH_PARTS)
return indexed(DENO_PATH_PARTS_LIMITATION, source);
if (parts > maximumParts)
return indexed(denoPathPartsLimitation(maximumParts), source);
const joined = parent.path === null ? name : `${parent.path}/${name}`;
try {
const path = normalizeArtifactPath(joined);
@@ -444,7 +451,14 @@ const boundedSymlinkParts = (
const retainText = (state: WalkState, text: string | null): string | null => {
if (text === null || text.length === 0) return text;
const next = state.retainedUnits + text.length;
if (next > MAX_DENO_VFS_RETAINED_UNITS) throw denoVfsRetainedLimit(next);
if (next > state.limits.vfs_name_units)
throw artifactReaderLimitFailure(
"artifact_limits.deno.vfs_name_units",
state.limits.vfs_name_units,
"count",
next,
"memory",
);
state.retainedUnits = next;
return text;
};
@@ -499,15 +513,15 @@ const asRecord = (value: unknown): Record<string, unknown> | undefined => {
return Object.fromEntries(Object.entries(value));
};
const denoVfsEntryLimit = (count: number): ArtifactReaderFailure =>
artifactFixedLimitFailure(
{
name: "The Deno compile virtual filesystem entry allowance",
kind: "count",
limit: MAX_DENO_VFS_ENTRIES,
unit: "entries",
},
`Deno compile virtual filesystem claims ${String(count)} entries, exceeding MAX_DENO_VFS_ENTRIES (${String(MAX_DENO_VFS_ENTRIES)} entries).`,
const denoVfsEntryLimit = (
limits: DenoReaderLimits,
count: number,
): ArtifactReaderFailure =>
artifactReaderLimitFailure(
"artifact_limits.deno.vfs_entries",
limits.vfs_entries,
"count",
count,
);
const denoVfsDepthLimit = (depth: number): ArtifactReaderFailure =>
@@ -520,15 +534,3 @@ const denoVfsDepthLimit = (depth: number): ArtifactReaderFailure =>
},
`Deno compile virtual filesystem nests ${String(depth)} levels, exceeding MAX_DENO_VFS_DEPTH (${String(MAX_DENO_VFS_DEPTH)} levels).`,
);
const denoVfsRetainedLimit = (units: number): ArtifactReaderFailure =>
artifactFixedLimitFailure(
{
name: "The Deno compile virtual filesystem retained name allowance",
kind: "bytes",
limit: MAX_DENO_VFS_RETAINED_UNITS,
unit: "UTF-16 code units",
},
`Deno compile virtual filesystem paths use ${String(units)} UTF-16 code units, exceeding MAX_DENO_VFS_RETAINED_UNITS (${String(MAX_DENO_VFS_RETAINED_UNITS)} units).`,
"memory",
);
+1 -7
View File
@@ -171,15 +171,9 @@ export const readDotnetBundle = async (
}
const files: DotnetBundleFile[] = [];
const paths = new ArtifactPathRegistry({
group: "dotnet_bundle",
maxParts: limits.path_parts,
maxNodes: limits.path_nodes,
limitFailure: (field, maximum, required) =>
artifactReaderLimitFailure(
`artifact_limits.dotnet_bundle.${field}`,
maximum,
"count",
required,
),
});
let expandedBytes = 0n;
for (let index = 0; index < count; index++) {
@@ -16,9 +16,11 @@ import {
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js";
import { RELEASE_EXPOSURE_PROVIDER } from "../../domain/investigationProviders.js";
import { MAX_RELEASE_EXPOSURE_FILE_BYTES } from "../../domain/releaseExposure.js";
import {
RELEASE_EXPOSURE_FILE_BYTES,
releaseExposureFileBytesLimit,
} from "../../domain/releaseExposure.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { isSelectedRegularFileError } from "../../filesystem/RegularFile.js";
import { errorMessage } from "../../kernel/errorMessage.js";
@@ -26,16 +28,14 @@ import { errorMessage } from "../../kernel/errorMessage.js";
export const RELEASE_EXPOSURE_AUDIT_OPERATION = "audit_release_exposure";
const PROVIDER_ID = RELEASE_EXPOSURE_PROVIDER.id;
export const fileSizeRecovery = (maxFileBytes: number) =>
maxFileBytes >= MAX_RELEASE_EXPOSURE_FILE_BYTES
? fixedAllowanceOptions("The release exposure input allowance", "input", {
limit: MAX_RELEASE_EXPOSURE_FILE_BYTES,
unit: "bytes",
})
: {
retryable: false as const,
remediationAction: `Raise max_file_bytes above ${String(maxFileBytes)} bytes or select a smaller artifact. The ceiling is ${String(MAX_RELEASE_EXPOSURE_FILE_BYTES)} bytes.`,
};
const fileSizeRecovery = (maxFileBytes: number) => ({
retryable: false as const,
limit: releaseExposureFileBytesLimit(maxFileBytes),
remediationAction:
maxFileBytes < RELEASE_EXPOSURE_FILE_BYTES.maximum
? `Raise max_file_bytes above ${String(maxFileBytes)} bytes (up to ${String(RELEASE_EXPOSURE_FILE_BYTES.maximum)}) on the next call for the same artifact, or select a smaller artifact. Reads are held in memory.`
: `max_file_bytes is at its maximum of ${String(maxFileBytes)} bytes; select a smaller artifact.`,
});
/**
* The header admission is its own bound, not the selected-file ceiling, so
+15 -6
View File
@@ -21,7 +21,8 @@ import type {
ArtifactTraversalOmission,
} from "../../resources/index.js";
import { TarArtifactReader } from "./TarArtifactReader.js";
import { TAR_RETAINED_METADATA_BYTES, walkTar } from "./TarWalk.js";
import { walkTar } from "./TarWalk.js";
import { DEFAULT_TAR_READER_LIMITS } from "../../domain/artifactReaderLimits.js";
import { GzipTarStream, TarStreamEnded } from "./TarByteStream.js";
import {
gzipTarFixture,
@@ -277,7 +278,9 @@ describe("truncated tar", () => {
trailingCarrierNonZero: () => Promise.reject(ended),
close: () => undefined,
};
await expect(walkTar(stream, undefined)).rejects.toMatchObject({
await expect(
walkTar(stream, undefined, DEFAULT_TAR_READER_LIMITS),
).rejects.toMatchObject({
reason: "truncated",
parseFailure: { kind: "truncated", format: "gzip" },
});
@@ -480,10 +483,11 @@ describe("tar header edge cases", () => {
});
it("refuses repeated global pax headers at the retained metadata allowance", async () => {
const value = "x".repeat(800_000);
const metadataBytes = 64 * 1024;
const value = "x".repeat(8_000);
const pieces: Buffer[] = [];
const perRecord = Buffer.byteLength("k000") + value.length + 64;
const count = Math.floor(TAR_RETAINED_METADATA_BYTES / perRecord) + 2;
const count = Math.floor(metadataBytes / perRecord) + 2;
for (let index = 0; index < count; index += 1) {
const key = `k${String(index).padStart(3, "0")}`;
const body = ` ${key}=${value}\n`;
@@ -499,6 +503,9 @@ describe("tar header edge cases", () => {
}
const reader = new TarArtifactReader(
await write("global-pax-budget.tar", Buffer.concat(pieces)),
undefined,
undefined,
{ ...DEFAULT_TAR_READER_LIMITS, metadata_bytes: metadataBytes },
);
try {
await expect(async () => {
@@ -506,9 +513,11 @@ describe("tar header edge cases", () => {
}).rejects.toMatchObject({
reason: "limit",
boundary: "memory",
fixedAllowance: {
limit: TAR_RETAINED_METADATA_BYTES,
readerLimit: {
parameter: "artifact_limits.tar.metadata_bytes",
effective_value: metadataBytes,
unit: "bytes",
can_increase: true,
},
});
} finally {
+6 -1
View File
@@ -1,3 +1,7 @@
import {
DEFAULT_TAR_READER_LIMITS,
type TarReaderLimits,
} from "../../domain/artifactReaderLimits.js";
import type { FileHandle } from "node:fs/promises";
import type { Readable } from "node:stream";
import { setImmediate } from "node:timers/promises";
@@ -84,6 +88,7 @@ export class TarArtifactReader implements ArtifactReader {
path: string,
admitted?: StableRegularFileDescriptor,
expandedBytes?: number,
private readonly limits: TarReaderLimits = DEFAULT_TAR_READER_LIMITS,
) {
this.#source = new ArtifactFileSource(path, "tar archive", admitted);
this.#expandedBytes = expandedBytes;
@@ -216,7 +221,7 @@ export class TarArtifactReader implements ArtifactReader {
: new PlainTarStream(handle, initial.size);
let walk;
try {
walk = await walkTar(stream, signal);
walk = await walkTar(stream, signal, this.limits);
} finally {
stream.close();
}
+29 -38
View File
@@ -13,25 +13,23 @@ import {
type TarPaxRecords,
} from "../../domain/tarFormat.js";
import type { ArtifactTraversalOmissionKind } from "../../domain/artifactGraph.js";
import type { TarReaderLimits } from "../../domain/artifactReaderLimits.js";
import {
artifactFixedLimitFailure,
artifactReaderLimitFailure,
artifactParseFailure,
assertArtifactReadActive,
} from "../../resources/index.js";
import { TarStreamEnded, type TarByteStream } from "./TarByteStream.js";
/**
* Largest pax extended header or GNU long-name record read into memory. Real
* records hold one path or a few attributes; the allowance only stops a
* declared size from forcing an arbitrary allocation.
/*
* `artifact_limits.tar.extended_header_bytes` bounds one pax extended header
* or GNU long-name record read into memory. Real records hold one path or a
* few attributes; the allowance only stops a declared size from forcing an
* arbitrary allocation. `artifact_limits.tar.metadata_bytes` bounds retained
* member metadata: a fixed per-member charge plus decoded path and link
* bytes, and the global pax map, for streams of many tiny members or repeated
* pax global headers.
*/
export const TAR_EXTENDED_HEADER_BYTES = 1024 * 1024;
/**
* Retained member metadata: a fixed per-member charge plus decoded path and
* link bytes, and the global pax map. It bounds memory for tar streams of
* many tiny members or repeated pax global headers.
*/
export const TAR_RETAINED_METADATA_BYTES = 64 * 1024 * 1024;
const MEMBER_OVERHEAD_BYTES = 512;
/** One map entry retained with a pax keyword, besides its key and value bytes. */
const PAX_ENTRY_OVERHEAD_BYTES = 64;
@@ -194,27 +192,21 @@ const typeflagText = (typeflag: number): string =>
const tarFormatFailure = (detail: string, offset: number): unknown =>
artifactParseFailure(malformedInput("tar", detail, { offset }), undefined);
const extendedHeaderLimit = (size: bigint): Error =>
artifactFixedLimitFailure(
{
name: "The tar extended-header allowance",
kind: "parser",
limit: TAR_EXTENDED_HEADER_BYTES,
unit: "bytes",
},
`A tar pax or GNU long-name record declares ${String(size)} bytes, more than the ${String(TAR_EXTENDED_HEADER_BYTES)}-byte extended-header allowance.`,
const extendedHeaderLimit = (limits: TarReaderLimits, size: bigint): Error =>
artifactReaderLimitFailure(
"artifact_limits.tar.extended_header_bytes",
limits.extended_header_bytes,
"bytes",
size,
"memory",
);
const retainedMetadataLimit = (): Error =>
artifactFixedLimitFailure(
{
name: "The tar member metadata allowance",
kind: "parser",
limit: TAR_RETAINED_METADATA_BYTES,
unit: "bytes",
},
`The tar members need more than ${String(TAR_RETAINED_METADATA_BYTES)} bytes of retained metadata.`,
const retainedMetadataLimit = (limits: TarReaderLimits) => (): Error =>
artifactReaderLimitFailure(
"artifact_limits.tar.metadata_bytes",
limits.metadata_bytes,
"bytes",
undefined,
"memory",
);
@@ -248,13 +240,15 @@ const countTrailingNonZero = async (
export const walkTar = async (
stream: TarByteStream,
signal: AbortSignal | undefined,
limits: TarReaderLimits,
): Promise<TarWalk> => {
const members: TarMember[] = [];
const omissions: { path: string; kind: ArtifactTraversalOmissionKind }[] = [];
const limitations: string[] = [];
const dialects = new Set<TarHeaderDialect>();
let paxHeaders = 0;
const retained = new Budget(TAR_RETAINED_METADATA_BYTES);
const retained = new Budget(limits.metadata_bytes);
const metadataLimit = retainedMetadataLimit(limits);
const global = new Map<string, string>();
let chargedGlobalPax = 0;
let local: TarPaxRecords | undefined;
@@ -366,8 +360,8 @@ export const walkTar = async (
}
const dataOffset = stream.position;
if (extension) {
if (declaredSize > BigInt(TAR_EXTENDED_HEADER_BYTES))
throw extendedHeaderLimit(declaredSize);
if (declaredSize > BigInt(limits.extended_header_bytes))
throw extendedHeaderLimit(limits, declaredSize);
const data = await stream.read(size, signal);
const padding = await stream.skip(tarPaddedSize(size) - size, signal);
if (data.length < size || padding < tarPaddedSize(size) - size) {
@@ -400,10 +394,7 @@ export const walkTar = async (
chargedGlobalPax + mergedPaxBytesDelta(global, pax.records),
);
if (nextBytes > chargedGlobalPax)
retained.charge(
nextBytes - chargedGlobalPax,
retainedMetadataLimit,
);
retained.charge(nextBytes - chargedGlobalPax, metadataLimit);
else if (nextBytes < chargedGlobalPax)
retained.refund(chargedGlobalPax - nextBytes);
chargedGlobalPax = nextBytes;
@@ -460,7 +451,7 @@ export const walkTar = async (
retained.charge(
MEMBER_OVERHEAD_BYTES +
2 * (Buffer.byteLength(path) + Buffer.byteLength(linkTarget ?? "")),
retainedMetadataLimit,
metadataLimit,
);
if ("omit" in role)
omissions.push({ path: path.replace(/\/+$/u, ""), kind: role.omit });
+144 -13
View File
@@ -93,6 +93,57 @@ export const iso9660ReaderLimitsSchema = z.strictObject({
});
export type Iso9660ReaderLimits = z.output<typeof iso9660ReaderLimitsSchema>;
export const DEFAULT_DENO_READER_LIMITS = {
metadata_json_bytes: 8 * 1024 * 1024,
vfs_header_json_bytes: 32 * 1024 * 1024,
table_records: 100_000,
specifier_text_bytes: 8 * 1024 * 1024,
remote_body_bytes: 256 * 1024 * 1024,
vfs_entries: 100_000,
vfs_name_units: 32 * 1024 * 1024,
retained_bytes: 256 * 1024 * 1024,
path_parts: 256,
path_nodes: 250_000,
};
export const denoReaderLimitsSchema = z.strictObject({
metadata_json_bytes: representedBytes,
vfs_header_json_bytes: representedBytes,
table_records: count,
specifier_text_bytes: bytes,
remote_body_bytes: bytes,
vfs_entries: count,
vfs_name_units: count,
retained_bytes: bytes,
/**
* Indexed fallbacks live under a reserved top-level namespace directory
* (`deno-vfs/<index>`, `deno-remote/<index>`) that keeps them collision-free,
* so the smallest representable logical path has two parts.
*/
path_parts: count.min(2),
path_nodes: count,
});
export type DenoReaderLimits = z.output<typeof denoReaderLimitsSchema>;
export const DEFAULT_WXAPKG_READER_LIMITS = {
table_bytes: 16 * 1024 * 1024,
directory_bytes: 64 * 1024 * 1024,
};
export const wxapkgReaderLimitsSchema = z.strictObject({
table_bytes: bytes,
directory_bytes: bytes,
});
export type WxapkgReaderLimits = z.output<typeof wxapkgReaderLimitsSchema>;
export const DEFAULT_TAR_READER_LIMITS = {
extended_header_bytes: 1024 * 1024,
metadata_bytes: 64 * 1024 * 1024,
};
export const tarReaderLimitsSchema = z.strictObject({
extended_header_bytes: representedBytes,
metadata_bytes: bytes,
});
export type TarReaderLimits = z.output<typeof tarReaderLimitsSchema>;
/** Input selections preserve omission; only the producing operation resolves defaults. */
export const artifactReaderLimitsInputSchema = z.strictObject({
bun: z
@@ -179,6 +230,50 @@ export const artifactReaderLimitsInputSchema = z.strictObject({
.describe(
`ISO 9660 admission; omitted fields use ${JSON.stringify(DEFAULT_ISO9660_READER_LIMITS)}. Descriptor count bounds the volume descriptor set; directory depth, record count, directory bytes and path bytes bound directory-tree traversal.`,
),
deno: z
.strictObject({
metadata_json_bytes:
denoReaderLimitsSchema.shape.metadata_json_bytes.exactOptional(),
vfs_header_json_bytes:
denoReaderLimitsSchema.shape.vfs_header_json_bytes.exactOptional(),
table_records: denoReaderLimitsSchema.shape.table_records.exactOptional(),
specifier_text_bytes:
denoReaderLimitsSchema.shape.specifier_text_bytes.exactOptional(),
remote_body_bytes:
denoReaderLimitsSchema.shape.remote_body_bytes.exactOptional(),
vfs_entries: denoReaderLimitsSchema.shape.vfs_entries.exactOptional(),
vfs_name_units:
denoReaderLimitsSchema.shape.vfs_name_units.exactOptional(),
retained_bytes:
denoReaderLimitsSchema.shape.retained_bytes.exactOptional(),
path_parts: denoReaderLimitsSchema.shape.path_parts.exactOptional(),
path_nodes: denoReaderLimitsSchema.shape.path_nodes.exactOptional(),
})
.exactOptional()
.describe(
`Deno compile admission; omitted fields use ${JSON.stringify(DEFAULT_DENO_READER_LIMITS)}. Table records apply to each specifier, redirect and remote-module table; VFS name units are retained UTF-16 path units; path parts (at least 2, the depth of an indexed fallback path) also select indexed fallback paths.`,
),
wxapkg: z
.strictObject({
table_bytes: wxapkgReaderLimitsSchema.shape.table_bytes.exactOptional(),
directory_bytes:
wxapkgReaderLimitsSchema.shape.directory_bytes.exactOptional(),
})
.exactOptional()
.describe(
`wxapkg admission; omitted fields use ${JSON.stringify(DEFAULT_WXAPKG_READER_LIMITS)}. Table bytes bound the member table read; directory bytes bound its retained representation.`,
),
tar: z
.strictObject({
extended_header_bytes:
tarReaderLimitsSchema.shape.extended_header_bytes.exactOptional(),
metadata_bytes:
tarReaderLimitsSchema.shape.metadata_bytes.exactOptional(),
})
.exactOptional()
.describe(
`tar admission; omitted fields use ${JSON.stringify(DEFAULT_TAR_READER_LIMITS)}. Extended-header bytes bound one pax or GNU long-name record; metadata bytes bound retained member metadata.`,
),
expanded_bytes: bytes
.exactOptional()
.describe(
@@ -194,6 +289,9 @@ export const artifactReaderLimitsSchema = z.strictObject({
node_sea: nodeSeaReaderLimitsSchema,
godot: godotReaderLimitsSchema,
iso9660: iso9660ReaderLimitsSchema,
deno: denoReaderLimitsSchema,
wxapkg: wxapkgReaderLimitsSchema,
tar: tarReaderLimitsSchema,
expanded_bytes: bytes.exactOptional(),
});
export type ArtifactReaderLimits = z.output<typeof artifactReaderLimitsSchema>;
@@ -209,11 +307,36 @@ export const resolveArtifactReaderLimits = (
node_sea: { ...DEFAULT_NODE_SEA_READER_LIMITS, ...selected?.node_sea },
godot: { ...DEFAULT_GODOT_READER_LIMITS, ...selected?.godot },
iso9660: { ...DEFAULT_ISO9660_READER_LIMITS, ...selected?.iso9660 },
deno: { ...DEFAULT_DENO_READER_LIMITS, ...selected?.deno },
wxapkg: { ...DEFAULT_WXAPKG_READER_LIMITS, ...selected?.wxapkg },
tar: { ...DEFAULT_TAR_READER_LIMITS, ...selected?.tar },
...(selected?.expanded_bytes === undefined
? {}
: { expanded_bytes: selected.expanded_bytes }),
});
/** Every group's resolved schema; the source of each field's supported range. */
const READER_LIMIT_GROUPS = {
bun: bunReaderLimitsSchema,
dotnet_bundle: dotnetBundleReaderLimitsSchema,
node_sea: nodeSeaReaderLimitsSchema,
godot: godotReaderLimitsSchema,
iso9660: iso9660ReaderLimitsSchema,
deno: denoReaderLimitsSchema,
wxapkg: wxapkgReaderLimitsSchema,
tar: tarReaderLimitsSchema,
} as const;
type ReaderLimitGroup = keyof typeof READER_LIMIT_GROUPS;
/** The exact contract field a reader admission names on refusal. */
export type ArtifactReaderLimitParameter =
| {
[
Group in ReaderLimitGroup
]: `artifact_limits.${Group}.${keyof z.output<(typeof READER_LIMIT_GROUPS)[Group]> & string}`;
}[ReaderLimitGroup]
| "artifact_limits.expanded_bytes";
/** A per-call reader admission, independent of runtime-setting registry membership. */
export interface ArtifactReaderLimitFact {
readonly parameter: string;
@@ -229,17 +352,25 @@ export interface ArtifactReaderLimitFact {
readonly pending_restart: false;
}
/** Runtime representation ceilings differ from aggregate plaintext-work budgets. */
/**
* The supported maximum of a reader admission, read from the schema the next
* call is validated against, so the reported range cannot drift from it.
*/
export const artifactReaderLimitMaximum = (
parameter: string,
unit: ArtifactReaderLimitFact["unit"],
): number =>
unit === "count"
? 0x7fffffff
: [
"artifact_limits.bun.representation_bytes",
"artifact_limits.dotnet_bundle.string_bytes",
"artifact_limits.godot.directory_bytes",
].includes(parameter)
? bufferConstants.MAX_STRING_LENGTH
: Number.MAX_SAFE_INTEGER;
parameter: ArtifactReaderLimitParameter,
): number => {
const [, group, field] = parameter.split(".");
const schema =
field === undefined
? bytes
: (
READER_LIMIT_GROUPS[group as ReaderLimitGroup].shape as Record<
string,
typeof bytes
>
)[field];
const maximum = schema?.maxValue;
if (maximum === undefined || maximum === null || !Number.isFinite(maximum))
throw new TypeError(`${parameter} names no bounded reader admission`);
return maximum;
};
+5 -2
View File
@@ -1,5 +1,8 @@
import { BinaryReader } from "../binaryContainer.js";
import { DEFAULT_ISO9660_READER_LIMITS } from "../artifactReaderLimits.js";
import {
DEFAULT_ISO9660_READER_LIMITS,
type ArtifactReaderLimitParameter,
} from "../artifactReaderLimits.js";
import { decodeIso9660RecordDate } from "./iso9660Dates.js";
import { err, ok, type Result } from "../result.js";
import {
@@ -39,7 +42,7 @@ export const ISO9660_FLAG_DIRECTORY = 0x02;
export const ISO9660_FLAG_MULTI_EXTENT = 0x80;
type Iso9660LimitSpec = LimitRef & {
readonly parameter: string;
readonly parameter: ArtifactReaderLimitParameter;
readonly maximum: number;
readonly unit: "bytes" | "count";
};
+29 -7
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { PE_CODEVIEW_PREFIX_BYTES } from "./binaryTargetTypes.js";
import type { AnalysisParameterLimit } from "./analysisSettings.js";
import { digestSchema } from "./digests.js";
import { evidenceLocationSchema, type EvidenceLocation } from "./evidence.js";
import {
@@ -8,8 +9,29 @@ import {
localPathStringSchema,
} from "./localPath.js";
/** Selected-file ceiling for one release-exposure audit. */
export const MAX_RELEASE_EXPOSURE_FILE_BYTES = 256 * 1024 * 1024;
/**
* `max_file_bytes`: the per-call selected-file, on-disk PE and shared
* packaged-image read budget. Reads are held in memory, so the host heap is
* an independent constraint; the accounting is exact up to the safe-integer
* range.
*/
export const RELEASE_EXPOSURE_FILE_BYTES = {
minimum: 1,
maximum: Number.MAX_SAFE_INTEGER,
default_value: 256 * 1024 * 1024,
} as const;
/** The per-call control that stopped a release-exposure read. */
export const releaseExposureFileBytesLimit = (
effectiveValue: number,
): AnalysisParameterLimit => ({
control_kind: "parameter",
parameter: "max_file_bytes",
effective_value: effectiveValue,
unit: "bytes",
...RELEASE_EXPOSURE_FILE_BYTES,
applies_at: "next_call",
});
/** Members inventoried from one installation or package. */
export const MAX_RELEASE_EXPOSURE_INVENTORY_ENTRIES = 65_536;
/** Bytes hashed while inventorying one installation or package. */
@@ -43,7 +65,7 @@ const RELEASE_EXPOSURE_LIMITATION =
"This report states what static analysis of the selected artifact recovered. It does not establish that the application is secure.";
export const RELEASE_EXPOSURE_ALLOWANCES = [
`Selected file reads stop at ${String(MAX_RELEASE_EXPOSURE_FILE_BYTES)} bytes.`,
`Selected file reads stop at max_file_bytes (${String(RELEASE_EXPOSURE_FILE_BYTES.default_value)} bytes by default).`,
`Text member scans read at most ${String(MAX_RELEASE_EXPOSURE_TEXT_MEMBER_BYTES)} bytes each and ${String(MAX_RELEASE_EXPOSURE_TEXT_BYTES)} bytes in total.`,
`HTML script targets keep at most ${String(MAX_RELEASE_EXPOSURE_SCRIPT_TARGET_BYTES)} bytes of resolved paths. Later targets stay unassessed.`,
`Local source map targets keep at most ${String(MAX_RELEASE_EXPOSURE_MAP_TARGET_BYTES)} bytes of resolved paths. Later targets stay unassessed.`,
@@ -339,11 +361,11 @@ export const auditReleaseExposureInputSchema = z.strictObject({
),
max_file_bytes: z
.int()
.positive()
.max(MAX_RELEASE_EXPOSURE_FILE_BYTES)
.default(MAX_RELEASE_EXPOSURE_FILE_BYTES)
.min(RELEASE_EXPOSURE_FILE_BYTES.minimum)
.max(RELEASE_EXPOSURE_FILE_BYTES.maximum)
.default(RELEASE_EXPOSURE_FILE_BYTES.default_value)
.describe(
"Selected-file, on-disk PE, and shared packaged-image read ceiling. Text, source-map, and other package members use the smaller allowances in coverage.allowances.",
`Selected-file, on-disk PE, and shared packaged-image read budget (default ${String(RELEASE_EXPOSURE_FILE_BYTES.default_value)} bytes); reads are held in memory. Text, source-map, and other package members use the smaller allowances in coverage.allowances.`,
),
});
+19 -3
View File
@@ -192,9 +192,21 @@ it.each([["app.js", "App.js"], ["other.js"]])(
);
it("reserves prefix capacity atomically without declaring destination kinds", () => {
const registry = new ArtifactPathRegistry({ maxParts: 4, maxNodes: 3 });
const registry = new ArtifactPathRegistry({
group: "deno",
maxParts: 4,
maxNodes: 3,
});
registry.reservePath("a/b");
expect(() => registry.reservePath("a/c/d")).toThrow();
expect(() => registry.reservePath("a/c/d")).toThrow(
expect.objectContaining({
readerLimit: expect.objectContaining({
parameter: "artifact_limits.deno.path_nodes",
effective_value: 3,
required_value: 4,
}),
}),
);
expect(() => registry.reservePath("z")).not.toThrow();
expect(() => registry.reservePath("a/b")).not.toThrow();
registry.add("a/b", "file");
@@ -202,7 +214,11 @@ it("reserves prefix capacity atomically without declaring destination kinds", ()
});
it("reports a file prefix conflict without inserting the candidate", () => {
const registry = new ArtifactPathRegistry({ maxParts: 4, maxNodes: 2 });
const registry = new ArtifactPathRegistry({
group: "deno",
maxParts: 4,
maxNodes: 2,
});
registry.reservePath("a/b");
expect(registry.conflicts("a/b")).toBe(true);
expect(registry.conflicts("a")).toBe(true);
+21 -43
View File
@@ -4,11 +4,8 @@ import { posix } from "node:path";
import { logicalPathNfc } from "../domain/artifactIdentity.js";
import { quotedExcerpt } from "../domain/excerpt.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import {
ArtifactReaderFailure,
artifactFixedLimitFailure,
type ArtifactEntry,
} from "./ArtifactReader.js";
import { ArtifactReaderFailure, type ArtifactEntry } from "./ArtifactReader.js";
import { artifactReaderLimitFailure } from "./ArtifactReaderLimits.js";
const ABSOLUTE_DRIVE_PATH = /^[A-Za-z]:[\\/]/u;
@@ -100,15 +97,15 @@ export class ArtifactPathRegistry {
};
#nodeCount = 0;
/**
* A budgeted registry belongs to one reader's `artifact_limits` group; its
* refusals name that group's `path_parts` and `path_nodes` controls.
*/
constructor(
private readonly budget?: {
readonly group: "bun" | "dotnet_bundle" | "deno";
readonly maxParts: number;
readonly maxNodes: number;
readonly limitFailure?: (
resource: "path_parts" | "path_nodes",
effectiveValue: number,
requiredValue: number,
) => ArtifactReaderFailure;
},
) {}
@@ -140,44 +137,25 @@ export class ArtifactPathRegistry {
#visit(path: string, kind?: DestinationEntryKind): void {
const parts = path.split("/");
if (this.budget !== undefined && parts.length > this.budget.maxParts)
throw (
this.budget.limitFailure?.(
"path_parts",
this.budget.maxParts,
parts.length,
) ??
artifactFixedLimitFailure(
{
name: "The artifact path depth allowance",
kind: "parser",
limit: this.budget.maxParts,
unit: "path parts",
},
`An artifact path has ${String(parts.length)} parts, above ${String(this.budget.maxParts)}.`,
)
const budget = this.budget;
if (budget !== undefined && parts.length > budget.maxParts)
throw artifactReaderLimitFailure(
`artifact_limits.${budget.group}.path_parts`,
budget.maxParts,
"count",
parts.length,
);
if (this.budget !== undefined) {
if (budget !== undefined) {
let observed = this.#root;
for (const [index, part] of parts.entries()) {
const existing = observed.children.get(part);
if (existing === undefined) {
if (parts.length - index > this.budget.maxNodes - this.#nodeCount)
throw (
this.budget.limitFailure?.(
"path_nodes",
this.budget.maxNodes,
this.#nodeCount + parts.length - index,
) ??
artifactFixedLimitFailure(
{
name: "The artifact path tree allowance",
kind: "parser",
limit: this.budget.maxNodes,
unit: "path nodes",
},
`The artifact paths need ${String(this.#nodeCount + parts.length - index)} path nodes, above ${String(this.budget.maxNodes)}.`,
)
if (parts.length - index > budget.maxNodes - this.#nodeCount)
throw artifactReaderLimitFailure(
`artifact_limits.${budget.group}.path_nodes`,
budget.maxNodes,
"count",
this.#nodeCount + parts.length - index,
);
break;
}
+6 -3
View File
@@ -1,10 +1,13 @@
import type { ArtifactLimitBoundary } from "../domain/artifactOperationError.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import { artifactReaderLimitMaximum } from "../domain/artifactReaderLimits.js";
import {
artifactReaderLimitMaximum,
type ArtifactReaderLimitParameter,
} from "../domain/artifactReaderLimits.js";
/** Construct exact next-call recovery at the enforcing resource owner. */
export const artifactReaderLimitFailure = (
parameter: string,
parameter: ArtifactReaderLimitParameter,
effectiveValue: number,
unit: "bytes" | "count",
requiredValue?: number | bigint,
@@ -16,7 +19,7 @@ export const artifactReaderLimitFailure = (
? Number(requiredValue)
: requiredValue.toString()
: requiredValue;
const maximum = artifactReaderLimitMaximum(parameter, unit);
const maximum = artifactReaderLimitMaximum(parameter);
const canIncrease =
effectiveValue < maximum &&
(requiredValue === undefined ||
@@ -9,7 +9,12 @@ import {
bunModuleGraphPayload,
elfAppendedBunPayload,
} from "../../src/artifacts/bun/BunStandalone.fixture.js";
import {
buildDenoSection,
denoElf,
} from "../../src/artifacts/deno/DenoStandalone.fixture.js";
import { dotnetBundleFixture } from "../../src/artifacts/dotnet/DotnetBundle.fixture.js";
import { tarFixture } from "../../src/artifacts/tar/tar.fixture.js";
import { nodeSeaElf } from "../../src/artifacts/nodeSea/NodeSea.fixture.js";
import type { ArtifactReaderLimitsInput } from "../../src/domain/artifactReaderLimits.js";
import {
@@ -19,6 +24,7 @@ import {
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import { buildGodotPck } from "../fixtures/godotPck.js";
import { buildWxapkg } from "../fixtures/wxapkg.js";
import { workspaceCliTest as test } from "../support/cli/workspaceCliFixture.js";
const readInspection = (value: unknown) => {
@@ -98,6 +104,47 @@ const readers: readonly ReaderCase[] = [
parameter: "artifact_limits.godot.directory_bytes",
value: 1,
},
{
format: "deno-standalone",
create: () =>
denoElf(
buildDenoSection({
vfs: [
{ File: { n: "main.ts", o: [0, 4], u: true } },
{ File: { n: "other.ts", o: [0, 4], u: true } },
],
vfsFileData: Buffer.from("main"),
}),
),
lower: { deno: { vfs_entries: 1 } },
raised: { deno: { vfs_entries: 2 } },
parameter: "artifact_limits.deno.vfs_entries",
value: 1,
},
{
format: "wxapkg",
create: () =>
buildWxapkg([
{ path: "/app.js", data: "app" },
{ path: "/page.wxml", data: "page" },
]),
lower: { wxapkg: { table_bytes: 1 } },
raised: { wxapkg: { table_bytes: 4096 } },
parameter: "artifact_limits.wxapkg.table_bytes",
value: 1,
},
{
format: "tar",
create: () =>
tarFixture([
{ name: "first.txt", data: "first" },
{ name: "second.txt", data: "second" },
]),
lower: { tar: { metadata_bytes: 1 } },
raised: { tar: { metadata_bytes: 4096 } },
parameter: "artifact_limits.tar.metadata_bytes",
value: 1,
},
{
format: "zip",
create: async () => {
@@ -311,6 +358,8 @@ test("rejects unknown reader-policy fields before opening the selected artifact"
for (const policy of [
{ unknown: 1 },
{ node_sea: { argument_count: 1, unknown: 1 } },
// An indexed Deno fallback path has two parts, so one is unrepresentable.
{ deno: { path_parts: 1 } },
]) {
const invalid = await cli.run({
arguments: [
@@ -322,3 +322,39 @@ cliTest(
expectCliMcpEvidenceParity(evidence, response.structuredContent, image);
},
);
cliTest(
"names max_file_bytes and its range when a selected file exceeds it",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-release-exposure-budget-");
const path = join(root, "blob.bin");
await writeFile(path, Buffer.alloc(128, 1));
const command = ["audit-release-exposure", path, "--json"];
const refused = await cli.run({
arguments: [...command, "--max-file-bytes", "64"],
});
expect(refused.exitCode).toBe(1);
expect(refused.json).toMatchObject({
retryable: false,
details: {
limit: {
control_kind: "parameter",
parameter: "max_file_bytes",
effective_value: 64,
unit: "bytes",
minimum: 1,
maximum: Number.MAX_SAFE_INTEGER,
default_value: 256 * 1024 * 1024,
applies_at: "next_call",
},
},
});
const admitted = await cli.run({
arguments: [...command, "--max-file-bytes", "128"],
});
expect(admitted.exitCode, admitted.stderr).toBe(0);
expect(outputSchema.parse(admitted.json).parameters).toMatchObject({
max_file_bytes: 128,
});
},
);
+17 -7
View File
@@ -86,7 +86,7 @@ it.each(["compact"] as const)(
},
);
it("refuses a wxapkg member table above its fixed allowance with a typed refusal through compiled MCP", async () => {
it("refuses a wxapkg member table above artifact_limits.wxapkg.table_bytes and admits it when raised through compiled MCP", async () => {
const root = await createTestTempDirectory("rea-wxapkg-mcp-table-");
const path = join(root, "package.wxapkg");
const declaredTableBytes = 17 * 1024 * 1024;
@@ -101,15 +101,25 @@ it("refuses a wxapkg member table above its fixed allowance with a typed refusal
expect(reply.isError, JSON.stringify(reply)).toBe(true);
const { error } = parseMcpToolError(reply);
expect(error).toMatchObject({
retryable: false,
retryable: true,
details: {
refusal: {
kind: "fixed_ceiling",
allowance_kind: "parser",
limit: 16 * 1024 * 1024,
unit: "bytes",
reader_limit: {
parameter: "artifact_limits.wxapkg.table_bytes",
effective_value: 16 * 1024 * 1024,
required_value: declaredTableBytes - 4,
can_increase: true,
update_mode: "parameter",
},
},
});
// Raising the control admits the table; its zero-filled rows are then
// reported as malformed rather than as an admission limit.
const raised = await call("extract_artifact", {
artifact_limits: { wxapkg: { table_bytes: declaredTableBytes } },
});
expect(raised.isError, JSON.stringify(raised)).toBe(true);
expect(parseMcpToolError(raised).error.details).not.toHaveProperty(
"reader_limit",
);
await call("close_binary", {});
});