feat(flutter)!: give Flutter APK admission per-call apk_limits (#14623)

* feat(flutter)!: give Flutter APK admission per-call apk_limits

identify_flutter_build and inspect_dart_aot refused a large but ordinary
APK at seven fixed allowances (APK snapshot, ZIP metadata, library read,
cumulative extraction, ABI count, library path and snapshot-hash
candidates) with no recovery. They now accept apk_limits (CLI
--apk-limits JSON) with today's values as defaults. Each refusal reports
details.limit naming the apk_limits field, its effective value and range.

The domain owns one bounds object that feeds both the schema and the
reported limit. library_path_bytes is capped by the 16-bit ZIP name
field, and the inspect_dart_aot ABI selector length now follows that
maximum instead of the old 1 KiB default.

BREAKING CHANGE: Flutter size, inventory and candidate refusals report
details.limit instead of a fixed_ceiling refusal, and the inspect_dart_aot
abi selector admits labels up to 65,521 characters.

* fix(flutter): bound library_path_bytes by the decoded ZIP name size

Inventory counts a library path's decoded UTF-8 bytes, and one stored
byte decodes to at most three (a CP437 box-drawing character), so the
maximum is three times the 16-bit stored name length rather than the
stored length itself. The ABI selector keeps its character bound from
the stored name. Recovery tests now assert the reported facts after
raising a limit.
This commit is contained in:
morluto authored and GitHub committed 2026-11-25 21:46:58 -05:00
1 parent 3dae567185
commit 49e2eca4f9
12 files changed
+404 -209

No files matched your search

+19 -12
View File
@@ -149,13 +149,18 @@ server; older servers keep the complete request after schema discovery.
`artifact_changed`. Provider-owned storage failures report a
`resource_constraint` with their native I/O cause. Cancellation is checked
during copying, metadata/symbol walks, string scanning, and after cleanup.
- **Bounded reads.** APK snapshots are bounded at 2 GiB, including while
copying. Identification permits 768 MiB of cumulative library extraction;
declared sizes are checked before extraction. Library reads are bounded at 256 MiB each and ZIP
metadata at 8 MiB. Before reading, the AOT image buffer reserves the
admitted declared size plus one byte; the reported byte count is the number
actually read. Exceeded budgets report
`resource_constraint`.
- **Bounded reads.** Both operations accept `apk_limits` (CLI
`--apk-limits` JSON) with these defaults: `apk_bytes` 2 GiB for the APK
snapshot, including while copying; `extraction_bytes` 768 MiB of cumulative
library extraction during identification, with declared sizes checked before
extraction; `library_bytes` 256 MiB per library read; and
`metadata_read_bytes` 8 MiB of ZIP metadata. Before reading, the AOT image
buffer reserves the admitted declared size plus one byte; the reported byte
count is the number actually read. An exceeded budget reports
`resource_constraint` with `details.limit` naming the `apk_limits` field, its
effective value and range; raise it on the next call for the same APK. Byte
fields accept any positive safe integer; libraries and metadata are held in
memory, so host heap remains an independent constraint.
- **Engine notes.** Engine libraries are spooled into the owned root. ELF
headers, note tables and note payloads share an 8 MiB metadata budget;
up to 64 distinct build IDs and 1024 distinct nonempty note ranges are retained.
@@ -164,10 +169,12 @@ server; older servers keep the complete request after schema discovery.
consume no inventory slots. Exceeding a bound preserves the candidates examined
from retained ranges and reports partial coverage with `build_id: null`.
- **Metadata and candidate capacity.** Both operations refuse duplicate
relevant library paths. Inventory is limited to 32 ABIs and 1024 bytes per
relevant library path, independently of compressed size. Identification
refuses more than 64 distinct snapshot hashes with `resource_constraint`
rather than silently dropping conflicting evidence.
relevant library paths. Inventory admits `apk_limits.abi_count` (32) ABIs
and `apk_limits.library_path_bytes` (1024; at most 196,605, the decoded UTF-8
size of the largest 65,535-byte stored ZIP name) bytes per relevant library path, independently of compressed size.
Identification refuses more than `apk_limits.snapshot_hash_candidates` (64)
distinct snapshot hashes with `resource_constraint` rather than silently
dropping conflicting evidence.
- **Selected ABI.** AOT inspection applies the library budget to the selected
ABI after selection; an oversized unselected library does not block it.
Undefined dynamic-symbol imports are not treated as snapshot exports.
@@ -250,7 +257,7 @@ layouts remain separate limitations. The default is 500; raising it can deliver
more strings than a complete overview needs. Use `detail: "summary"` for the MCP
identity/count task described above.
These controls do not raise APK, ELF, library or response budgets, deserialize
These controls do not raise `apk_limits`, ELF or response budgets, deserialize
Dart objects, or establish typed class/function semantics. Retained
`inspect_analysis_view` pages cover the returned selection; exhausting those
pages does not recover facts that the producing pool scan omitted. Re-run the
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "18d266261424a97c",
"input compact": "b0b894f04ba77b8d",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "43545508189c0e49",
"input compact": "2476699dc41f6dc7",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -70,7 +70,7 @@
"src/firmware/FirmwareFailures.ts": 1,
"src/firmware/FirmwareFiles.ts": 2,
"src/firmware/devicetree/DevicetreeProvider.ts": 1,
"src/flutter/FlutterBuildProvider.ts": 12,
"src/flutter/FlutterBuildProvider.ts": 4,
"src/ghidra/GhidraExecutableHeader.ts": 1,
"src/ghidra/GhidraFileArtifacts.ts": 1,
"src/ghidra/GhidraInstallationProperties.ts": 1,
@@ -186,44 +186,9 @@
}
},
"src/flutter/FlutterBuildProvider.ts": {
"\"The Flutter ABI inventory allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies."
},
"\"The Flutter APK expansion allowance (derived from the APK size)\"": {
"class": "derived",
"reason": "Expansion work is derived from the admitted APK's own size."
},
"\"The Flutter APK metadata read allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies."
},
"\"The Flutter library path allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies."
},
"\"The Flutter snapshot-hash candidate allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies."
},
"\"the Flutter APK snapshot allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies."
},
"\"the Flutter cumulative extraction allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies."
},
"\"the Flutter library read allowance\"": {
"class": "pending",
"issue": 14236,
"reason": "Flutter APK, library, extraction, ABI, path and snapshot-hash allowances are resource policies."
}
},
"src/ghidra/GhidraExecutableHeader.ts": {
+6 -3
View File
@@ -1,12 +1,14 @@
import type { RequestAnalysisPort } from "../ports/AnalysisProvider.js";
import type { FlutterRequest } from "../domain/flutter/flutterBuildAnalysis.js";
import type {
FlutterRequest,
FlutterOperation,
} from "../domain/flutter/flutterBuildAnalysis.js";
import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js";
import { withEvidenceCallerInputPath } from "../domain/evidence.js";
import { recognizeEvidence } from "../domain/evidenceValidation.js";
import { createFlutterBuildAnalysisService } from "../application/ProviderOperationServices.js";
import { createFlutterBuildAnalysisProvider } from "../composition/flutter.js";
import { FLUTTER_TOOL_CONTRACTS } from "../contracts/flutter/flutterToolContracts.js";
import type { FlutterOperation } from "../domain/flutter/flutterBuildAnalysis.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { contractNamed } from "./contractCliDescription.js";
@@ -66,6 +68,7 @@ export const registerFlutterCommands = (
description:
"Identify a Flutter build's Dart snapshot hash and engine facts by pure APK parsing",
positionals: ["path"],
jsonText: ["apk_limits"],
},
run("identify_flutter_build"),
);
@@ -77,7 +80,7 @@ export const registerFlutterCommands = (
description:
"Inspect one ABI's Dart AOT snapshot: sections, headers, and the string pool",
positionals: ["path"],
jsonText: ["pool_policy"],
jsonText: ["pool_policy", "apk_limits"],
omit: {
detail:
"The CLI returns complete Evidence; a summary needs a session that retains it for inspect_analysis_view",
+109 -3
View File
@@ -6,8 +6,108 @@ import { digestSchema } from "../digests.js";
import type { AnalysisParameterLimit } from "../analysisSettings.js";
import { analysisParameterLimitSchema } from "../analysisSettingDefinitions.js";
/** Full logical ZIP path budget, enforced by Flutter library inventory. */
export const MAX_FLUTTER_LIBRARY_PATH_BYTES = 1024;
/** ZIP stores a member name length in a 16-bit field. */
const ZIP_NAME_MAX_BYTES = 0xffff;
/**
* Inventory counts the decoded UTF-8 path. A stored byte decodes to at most
* three UTF-8 bytes (a CP437 box-drawing character is U+25xx), so a valid
* stored name needs at most three times its stored length.
*/
const ZIP_NAME_MAX_DECODED_BYTES = 3 * ZIP_NAME_MAX_BYTES;
const COUNT_MAXIMUM = 0x7fffffff;
/**
* Per-call APK admission for both Flutter operations: the bounds the schema
* enforces and the omitted value of each `apk_limits` field. Byte budgets are
* exact up to the safe-integer range; libraries and metadata are held in
* memory, so host heap is an independent constraint.
*/
export const FLUTTER_APK_LIMIT_BOUNDS = {
apk_bytes: {
default_value: 2 * 1024 * 1024 * 1024,
maximum: Number.MAX_SAFE_INTEGER,
unit: "bytes",
},
metadata_read_bytes: {
default_value: 8 * 1024 * 1024,
maximum: Number.MAX_SAFE_INTEGER,
unit: "bytes",
},
library_bytes: {
default_value: 256 * 1024 * 1024,
maximum: Number.MAX_SAFE_INTEGER,
unit: "bytes",
},
extraction_bytes: {
default_value: 768 * 1024 * 1024,
maximum: Number.MAX_SAFE_INTEGER,
unit: "bytes",
},
abi_count: { default_value: 32, maximum: COUNT_MAXIMUM, unit: "count" },
library_path_bytes: {
default_value: 1024,
maximum: ZIP_NAME_MAX_DECODED_BYTES,
unit: "bytes",
},
snapshot_hash_candidates: {
default_value: 64,
maximum: COUNT_MAXIMUM,
unit: "count",
},
} as const;
export type FlutterApkLimitField = keyof typeof FLUTTER_APK_LIMIT_BOUNDS;
export type FlutterApkLimits = Readonly<Record<FlutterApkLimitField, number>>;
const apkLimitField = (field: FlutterApkLimitField) =>
z.int().min(1).max(FLUTTER_APK_LIMIT_BOUNDS[field].maximum).optional();
export const flutterApkLimitsSchema = z.strictObject({
apk_bytes: apkLimitField("apk_bytes"),
metadata_read_bytes: apkLimitField("metadata_read_bytes"),
library_bytes: apkLimitField("library_bytes"),
extraction_bytes: apkLimitField("extraction_bytes"),
abi_count: apkLimitField("abi_count"),
library_path_bytes: apkLimitField("library_path_bytes"),
snapshot_hash_candidates: apkLimitField("snapshot_hash_candidates"),
});
/** Omitted fields resolve to their defaults; explicit values are kept. */
export const flutterApkLimits = (
selected?: z.infer<typeof flutterApkLimitsSchema>,
): FlutterApkLimits => {
const resolved: Record<string, number> = {};
for (const field of Object.keys(
FLUTTER_APK_LIMIT_BOUNDS,
) as FlutterApkLimitField[])
resolved[field] =
selected?.[field] ?? FLUTTER_APK_LIMIT_BOUNDS[field].default_value;
return resolved as FlutterApkLimits;
};
/** The per-call control that stopped an APK admission. */
export const flutterApkLimit = (
field: FlutterApkLimitField,
limits: FlutterApkLimits,
): AnalysisParameterLimit => ({
control_kind: "parameter",
parameter: `apk_limits.${field}`,
effective_value: limits[field],
unit: FLUTTER_APK_LIMIT_BOUNDS[field].unit,
minimum: 1,
maximum: FLUTTER_APK_LIMIT_BOUNDS[field].maximum,
default_value: FLUTTER_APK_LIMIT_BOUNDS[field].default_value,
applies_at: "next_call",
});
/** Recovery for an exhausted `apk_limits` field. */
export const flutterApkLimitRecovery = (
field: FlutterApkLimitField,
limits: FlutterApkLimits,
): string =>
limits[field] < FLUTTER_APK_LIMIT_BOUNDS[field].maximum
? `Pass a larger apk_limits.${field} (up to ${String(FLUTTER_APK_LIMIT_BOUNDS[field].maximum)}) on the next call for the same APK; no restart is required.`
: `apk_limits.${field} is at its maximum of ${String(limits[field])}; the APK cannot be admitted by raising it.`;
const APK_LIMITS_DESCRIPTION = `APK admission for this call; omitted fields use ${JSON.stringify(Object.fromEntries(Object.entries(FLUTTER_APK_LIMIT_BOUNDS).map(([field, bounds]) => [field, bounds.default_value])))}. apk_bytes bounds the private snapshot copy, metadata_read_bytes the ZIP directory reads, library_bytes each libapp.so/libflutter.so, extraction_bytes their total, abi_count and library_path_bytes the library inventory, and snapshot_hash_candidates distinct Dart snapshot hashes retained per libapp.so. A refusal reports the field in details.limit.`;
/** Retained GNU build-ID descriptor budget, in bytes. */
export const MAX_FLUTTER_BUILD_ID_BYTES = 64;
@@ -23,7 +123,7 @@ const gnuBuildIdSchema = z
* unmatched labels; inventory owns the exact UTF-8 byte check on real paths.
*/
const ABI_SELECTOR_MAX_CHARACTERS =
MAX_FLUTTER_LIBRARY_PATH_BYTES - "lib/".length - "/libapp.so".length;
ZIP_NAME_MAX_BYTES - "lib/".length - "/libapp.so".length;
/**
* ZIP labels are literal names, including backslashes and controls. They are
@@ -111,6 +211,9 @@ export const dartPoolPolicy = (
export const flutterInputSchemas = {
identify_flutter_build: z.strictObject({
path: localPathStringSchema.describe("Local APK file to inspect"),
apk_limits: flutterApkLimitsSchema
.optional()
.describe(APK_LIMITS_DESCRIPTION),
}),
inspect_dart_aot: z.strictObject({
pool_policy: dartPoolPolicySchema
@@ -121,6 +224,9 @@ export const flutterInputSchemas = {
path: localPathStringSchema.describe(
"Local APK file carrying a Flutter AOT payload",
),
apk_limits: flutterApkLimitsSchema
.optional()
.describe(APK_LIMITS_DESCRIPTION),
abi: abiSelectorSchema
.optional()
.describe(
+150 -117
View File
@@ -30,8 +30,12 @@ import {
} from "../ports/AnalysisProvider.js";
import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js";
import {
MAX_FLUTTER_LIBRARY_PATH_BYTES,
dartPoolBudgetLimit,
flutterApkLimit,
flutterApkLimitRecovery,
flutterApkLimits,
type FlutterApkLimitField,
type FlutterApkLimits,
dartPoolPolicy,
type DartPoolBudget,
type DartPoolPolicy,
@@ -65,7 +69,6 @@ import {
sameRegularFileState,
} from "../filesystem/RegularFile.js";
import {
MAX_SNAPSHOT_HASH_CANDIDATES,
LabeledStringScanner,
SnapshotHashScanner,
} from "./FlutterPayloadScan.js";
@@ -75,56 +78,26 @@ import { readElfBuildIds } from "./ElfBuildId.js";
import { privateWorkspaceFailure } from "../process/privateWorkspaceFailure.js";
import { errorMessage } from "../kernel/errorMessage.js";
const APK_METADATA_READ_MAX_BYTES = 8 * 1024 * 1024;
const LIBRARY_MAX_BYTES = 256 * 1024 * 1024;
/** Cumulative cap across every library entry in one identification. */
const TOTAL_EXTRACTION_MAX_BYTES = 768 * 1024 * 1024;
/** The APK itself must fit within this budget before any copy. */
const APK_MAX_BYTES = 2 * 1024 * 1024 * 1024;
// At most 32 ABI projections (two libraries each). With bounded hashes and
// engine labels this keeps expanded result metadata below 512 KiB for ordinary
// ABI names, independently of the archive's compressed-byte budget.
const MAX_FLUTTER_ABIS = 32;
const IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/u;
/** Each release-fixed Flutter ceiling with the value that refused the input. */
const FLUTTER_ALLOWANCES = {
apkMetadataRead: fixedAllowanceOptions(
"The Flutter APK metadata read allowance",
"parser",
{ limit: APK_METADATA_READ_MAX_BYTES, unit: "bytes" },
),
abiInventory: fixedAllowanceOptions(
"The Flutter ABI inventory allowance",
"parser",
{ limit: MAX_FLUTTER_ABIS, unit: "ABIs" },
),
libraryPath: fixedAllowanceOptions(
"The Flutter library path allowance",
"parser",
{ limit: MAX_FLUTTER_LIBRARY_PATH_BYTES, unit: "bytes" },
),
apkSnapshot: fixedAllowanceOptions(
"the Flutter APK snapshot allowance",
"input",
{ limit: APK_MAX_BYTES, unit: "bytes" },
),
libraryRead: fixedAllowanceOptions(
"the Flutter library read allowance",
"input",
{ limit: LIBRARY_MAX_BYTES, unit: "bytes" },
),
cumulativeExtraction: fixedAllowanceOptions(
"the Flutter cumulative extraction allowance",
"input",
{ limit: TOTAL_EXTRACTION_MAX_BYTES, unit: "bytes" },
),
snapshotHashCandidates: fixedAllowanceOptions(
"The Flutter snapshot-hash candidate allowance",
"parser",
{ limit: MAX_SNAPSHOT_HASH_CANDIDATES, unit: "candidates" },
),
} as const;
/**
* Refuse an APK admission at its `apk_limits` field. ABI projections are
* bounded (two libraries each, with bounded hashes and engine labels), so the
* defaults keep expanded result metadata small for ordinary ABI names.
*/
const apkLimitRefusal = (
operation: string,
field: FlutterApkLimitField,
limits: FlutterApkLimits,
boundary: "file-size" | "memory",
message: string,
reported: Record<string, number | string>,
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(operation, boundary, message, reported, {
retryable: false,
limit: flutterApkLimit(field, limits),
remediationAction: flutterApkLimitRecovery(field, limits),
});
/**
* Stream a local file digest without retaining large files in memory.
@@ -226,6 +199,7 @@ const mapInputFailure = (
operation: string,
path: string,
cause: unknown,
limits: FlutterApkLimits,
): AnalysisError => {
if (cause instanceof AnalysisError) return cause;
const cancellation = observedCancellation(cause);
@@ -240,7 +214,7 @@ const mapInputFailure = (
cause,
});
if (cause instanceof ArtifactReaderFailure && cause.reason === "limit")
return readerLimitFailure(operation, cause);
return readerLimitFailure(operation, cause, limits);
return new AnalysisInputError(operation, { cause }, [
{
path: ["path"],
@@ -260,6 +234,7 @@ const mapInputFailure = (
const readerLimitFailure = (
operation: string,
cause: ArtifactReaderFailure,
limits: FlutterApkLimits,
): AnalysisError => {
if (cause.fixedAllowance !== undefined)
return new AnalysisResourceConstraintError(
@@ -291,8 +266,13 @@ const readerLimitFailure = (
operation,
"memory",
cause.message,
{ max_metadata_read_bytes: APK_METADATA_READ_MAX_BYTES },
{ cause, ...FLUTTER_ALLOWANCES.apkMetadataRead },
{ max_metadata_read_bytes: limits.metadata_read_bytes },
{
cause,
retryable: false,
limit: flutterApkLimit("metadata_read_bytes", limits),
remediationAction: flutterApkLimitRecovery("metadata_read_bytes", limits),
},
);
};
@@ -347,10 +327,11 @@ const mapPackageFailure = (
operation: string,
path: string,
cause: unknown,
limits: FlutterApkLimits,
): unknown =>
cause instanceof Error && "code" in cause && typeof cause.code === "string"
? cause
: mapInputFailure(operation, path, cause);
: mapInputFailure(operation, path, cause, limits);
interface FlutterLibrary {
readonly entry: ArtifactEntry;
@@ -364,6 +345,7 @@ const collectFlutterLibraries = async (
operation: string,
path: string,
signal: AbortSignal | undefined,
limits: FlutterApkLimits,
): Promise<FlutterLibrary[]> => {
const libraries: FlutterLibrary[] = [];
const paths = new Set<string>();
@@ -383,21 +365,27 @@ const collectFlutterLibraries = async (
]);
paths.add(entry.path);
abis.add(match[1]!);
if (
abis.size > MAX_FLUTTER_ABIS ||
Buffer.byteLength(entry.path) > MAX_FLUTTER_LIBRARY_PATH_BYTES
)
throw new AnalysisResourceConstraintError(
if (abis.size > limits.abi_count)
throw apkLimitRefusal(
operation,
"abi_count",
limits,
"memory",
"Flutter library inventory exceeds the bounded ABI projection budget",
`Flutter library inventory names more than ${String(limits.abi_count)} ABIs`,
{ max_flutter_abis: limits.abi_count, observed_abis: abis.size },
);
const pathBytes = Buffer.byteLength(entry.path);
if (pathBytes > limits.library_path_bytes)
throw apkLimitRefusal(
operation,
"library_path_bytes",
limits,
"memory",
`A Flutter library path has ${String(pathBytes)} bytes, above ${String(limits.library_path_bytes)}`,
{
max_flutter_abis: MAX_FLUTTER_ABIS,
max_library_path_bytes: MAX_FLUTTER_LIBRARY_PATH_BYTES,
max_library_path_bytes: limits.library_path_bytes,
observed_path_bytes: pathBytes,
},
abis.size > MAX_FLUTTER_ABIS
? FLUTTER_ALLOWANCES.abiInventory
: FLUTTER_ALLOWANCES.libraryPath,
);
libraries.push({
entry,
@@ -407,7 +395,7 @@ const collectFlutterLibraries = async (
}
return libraries;
} catch (cause) {
throw mapPackageFailure(operation, path, cause);
throw mapPackageFailure(operation, path, cause, limits);
}
};
@@ -418,22 +406,28 @@ async function* openEntrySafely(
operation: string,
path: string,
signal: AbortSignal | undefined,
limits: FlutterApkLimits,
): AsyncGenerator<Buffer> {
try {
yield* await reader.open(entry, signal);
} catch (cause) {
throw mapPackageFailure(operation, path, cause);
throw mapPackageFailure(operation, path, cause, limits);
}
}
const checkApkSize = (operation: string, bytes: number): void => {
if (bytes > APK_MAX_BYTES)
throw new AnalysisResourceConstraintError(
const checkApkSize = (
operation: string,
bytes: number,
limits: FlutterApkLimits,
): void => {
if (bytes > limits.apk_bytes)
throw apkLimitRefusal(
operation,
"apk_bytes",
limits,
"file-size",
`The selected APK exceeds the ${String(APK_MAX_BYTES)}-byte snapshot budget`,
{ max_apk_bytes: APK_MAX_BYTES, observed_bytes: bytes },
FLUTTER_ALLOWANCES.apkSnapshot,
`The selected APK exceeds the ${String(limits.apk_bytes)}-byte snapshot budget`,
{ max_apk_bytes: limits.apk_bytes, observed_bytes: bytes },
);
};
@@ -466,6 +460,7 @@ export class FlutterBuildProvider {
operation: string,
path: string,
signal: AbortSignal | undefined,
limits: FlutterApkLimits,
): Promise<OwnedSnapshot> {
let root: string;
try {
@@ -487,7 +482,7 @@ export class FlutterBuildProvider {
try {
return await read();
} catch (cause) {
throw mapInputFailure(operation, path, cause);
throw mapInputFailure(operation, path, cause, limits);
}
};
try {
@@ -506,14 +501,14 @@ export class FlutterBuildProvider {
} catch (cause) {
if (cause instanceof RegularFileAdmissionFailure) {
this.ownResource(root, cause.owner);
throw mapInputFailure(operation, path, cause.cause);
throw mapInputFailure(operation, path, cause.cause, limits);
}
throw mapInputFailure(operation, path, cause);
throw mapInputFailure(operation, path, cause, limits);
}
const before = await readSource(() =>
source.handle.stat({ bigint: true }),
);
checkApkSize(operation, Number(before.size));
checkApkSize(operation, Number(before.size), limits);
const output = this.ownResource(
root,
new OwnedFileHandle(await openFile(snapshotPath, "wx")),
@@ -550,7 +545,7 @@ export class FlutterBuildProvider {
"code" in cause &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
throw mapInputFailure(operation, path, cause);
throw mapInputFailure(operation, path, cause, limits);
throw new AnalysisArtifactChangedError(
operation,
path,
@@ -587,10 +582,13 @@ export class FlutterBuildProvider {
}
}
private readerFor(snapshot: OwnedSnapshot): ZipArtifactReader {
private readerFor(
snapshot: OwnedSnapshot,
limits: FlutterApkLimits,
): ZipArtifactReader {
return this.ownResource(
snapshot.root,
new ZipArtifactReader(snapshot.path, "apk", APK_METADATA_READ_MAX_BYTES),
new ZipArtifactReader(snapshot.path, "apk", limits.metadata_read_bytes),
);
}
@@ -772,13 +770,20 @@ export class FlutterBuildProvider {
let snapshot: OwnedSnapshot | undefined;
let result: Result<AnalysisExecution, AnalysisError>;
try {
snapshot = await this.ownSnapshot(request.operation, path, signal);
const reader = this.readerFor(snapshot);
const limits = flutterApkLimits(request.input.apk_limits);
snapshot = await this.ownSnapshot(
request.operation,
path,
signal,
limits,
);
const reader = this.readerFor(snapshot, limits);
const libraries = await collectFlutterLibraries(
reader,
request.operation,
path,
signal,
limits,
);
result =
request.operation === "inspect_dart_aot"
@@ -790,6 +795,7 @@ export class FlutterBuildProvider {
reader,
libraries,
dartPoolPolicy(request.input.pool_policy),
limits,
)
: await this.identifyFlutterBuild(
path,
@@ -797,6 +803,7 @@ export class FlutterBuildProvider {
snapshot,
reader,
libraries,
limits,
);
} catch (cause) {
result = err(
@@ -867,17 +874,26 @@ export class FlutterBuildProvider {
snapshot: OwnedSnapshot,
reader: ZipArtifactReader,
flutterEntries: readonly FlutterLibrary[],
limits: FlutterApkLimits,
): Promise<Result<AnalysisExecution, AnalysisError>> {
const operation = "identify_flutter_build";
for (const { entry } of flutterEntries) {
if (entry.declaredSize !== null && entry.declaredSize > LIBRARY_MAX_BYTES)
if (
entry.declaredSize !== null &&
entry.declaredSize > limits.library_bytes
)
return err(
new AnalysisResourceConstraintError(
apkLimitRefusal(
operation,
"library_bytes",
limits,
"file-size",
`${entry.path} exceeds the library read budget`,
{ max_library_bytes: LIBRARY_MAX_BYTES, entry_path: entry.path },
FLUTTER_ALLOWANCES.libraryRead,
{
max_library_bytes: limits.library_bytes,
entry_path: entry.path,
declared_bytes: entry.declaredSize,
},
),
);
}
@@ -888,17 +904,18 @@ export class FlutterBuildProvider {
(total, { entry }) => total + (entry.declaredSize ?? 0),
0,
);
if (declaredTotal > TOTAL_EXTRACTION_MAX_BYTES)
if (declaredTotal > limits.extraction_bytes)
return err(
new AnalysisResourceConstraintError(
apkLimitRefusal(
operation,
"extraction_bytes",
limits,
"file-size",
`declared library sizes total ${String(declaredTotal)} bytes, exceeding the ${String(TOTAL_EXTRACTION_MAX_BYTES)}-byte cumulative budget before any extraction`,
`declared library sizes total ${String(declaredTotal)} bytes, exceeding the ${String(limits.extraction_bytes)}-byte cumulative budget before any extraction`,
{
max_total_bytes: TOTAL_EXTRACTION_MAX_BYTES,
max_total_bytes: limits.extraction_bytes,
declared_total: declaredTotal,
},
FLUTTER_ALLOWANCES.cumulativeExtraction,
),
);
@@ -906,9 +923,18 @@ export class FlutterBuildProvider {
let extractedTotal = 0;
let libraryIndex = 0;
for (const { entry, abi, kind } of flutterEntries) {
const stream = openEntrySafely(reader, entry, operation, path, signal);
const stream = openEntrySafely(
reader,
entry,
operation,
path,
signal,
limits,
);
const hash = createHash("sha256");
const snapshotScanner = new SnapshotHashScanner();
const snapshotScanner = new SnapshotHashScanner(
limits.snapshot_hash_candidates,
);
const labeledScanner = new LabeledStringScanner();
const engineFile =
kind === "libflutter"
@@ -936,17 +962,18 @@ export class FlutterBuildProvider {
Math.min(view.length, headerPrefix.length - headerBytes),
);
bytes += view.byteLength;
if (bytes > LIBRARY_MAX_BYTES)
if (bytes > limits.library_bytes)
return err(
new AnalysisResourceConstraintError(
apkLimitRefusal(
operation,
"library_bytes",
limits,
"file-size",
`${entry.path} exceeds the ${String(LIBRARY_MAX_BYTES)}-byte read budget while streaming`,
`${entry.path} exceeds the ${String(limits.library_bytes)}-byte read budget while streaming`,
{
max_library_bytes: LIBRARY_MAX_BYTES,
max_library_bytes: limits.library_bytes,
entry_path: entry.path,
},
FLUTTER_ALLOWANCES.libraryRead,
),
);
hash.update(view);
@@ -957,14 +984,15 @@ export class FlutterBuildProvider {
}
// Enforce the cumulative cap inside the chunk loop so refusal
// happens before the remaining bytes are streamed and hashed.
if (extractedTotal + bytes > TOTAL_EXTRACTION_MAX_BYTES)
if (extractedTotal + bytes > limits.extraction_bytes)
return err(
new AnalysisResourceConstraintError(
apkLimitRefusal(
operation,
"extraction_bytes",
limits,
"file-size",
`cumulative library extraction across ${String(flutterEntries.length)} entries exceeds the ${String(TOTAL_EXTRACTION_MAX_BYTES)}-byte budget`,
{ max_total_bytes: TOTAL_EXTRACTION_MAX_BYTES },
FLUTTER_ALLOWANCES.cumulativeExtraction,
`cumulative library extraction across ${String(flutterEntries.length)} entries exceeds the ${String(limits.extraction_bytes)}-byte budget`,
{ max_total_bytes: limits.extraction_bytes },
),
);
}
@@ -975,15 +1003,16 @@ export class FlutterBuildProvider {
const scan = snapshotScanner.result();
if (scan.capped)
return err(
new AnalysisResourceConstraintError(
apkLimitRefusal(
operation,
"snapshot_hash_candidates",
limits,
"memory",
"Snapshot hash candidates exceed the retained evidence budget",
{
max_snapshot_hash_candidates: MAX_SNAPSHOT_HASH_CANDIDATES,
max_snapshot_hash_candidates: limits.snapshot_hash_candidates,
entry_path: entry.path,
},
FLUTTER_ALLOWANCES.snapshotHashCandidates,
),
);
facts.set(abi, {
@@ -1147,6 +1176,7 @@ export class FlutterBuildProvider {
reader: ZipArtifactReader,
libraries: readonly FlutterLibrary[],
poolPolicy: DartPoolPolicy,
limits: FlutterApkLimits,
): Promise<Result<AnalysisExecution, AnalysisError>> {
const candidates = libraries.filter((library) => library.kind === "libapp");
if (candidates.length === 0)
@@ -1179,15 +1209,16 @@ export class FlutterBuildProvider {
.join(", ")}`,
),
);
const declared = selected.entry.declaredSize ?? LIBRARY_MAX_BYTES + 1;
if (declared > LIBRARY_MAX_BYTES)
const declared = selected.entry.declaredSize ?? limits.library_bytes + 1;
if (declared > limits.library_bytes)
return err(
new AnalysisResourceConstraintError(
apkLimitRefusal(
"inspect_dart_aot",
"library_bytes",
limits,
"file-size",
`lib/${selected.abi}/libapp.so declares ${String(declared)} bytes, exceeding the ${String(LIBRARY_MAX_BYTES)}-byte read budget`,
{ max_library_bytes: LIBRARY_MAX_BYTES },
FLUTTER_ALLOWANCES.libraryRead,
`lib/${selected.abi}/libapp.so declares ${String(declared)} bytes, exceeding the ${String(limits.library_bytes)}-byte read budget`,
{ max_library_bytes: limits.library_bytes },
),
);
const imagePath = join(snapshot.root, "libapp.so");
@@ -1203,6 +1234,7 @@ export class FlutterBuildProvider {
"inspect_dart_aot",
path,
signal,
limits,
);
let total = 0;
for await (const chunk of stream) {
@@ -1210,14 +1242,15 @@ export class FlutterBuildProvider {
return err(cancelledBy("inspect_dart_aot", signal));
const view = chunk as Buffer;
total += view.byteLength;
if (total > LIBRARY_MAX_BYTES)
if (total > limits.library_bytes)
return err(
new AnalysisResourceConstraintError(
apkLimitRefusal(
"inspect_dart_aot",
"library_bytes",
limits,
"file-size",
`lib/${selected.abi}/libapp.so exceeds the ${String(LIBRARY_MAX_BYTES)}-byte read budget while streaming`,
{ max_library_bytes: LIBRARY_MAX_BYTES },
FLUTTER_ALLOWANCES.libraryRead,
`lib/${selected.abi}/libapp.so exceeds the ${String(limits.library_bytes)}-byte read budget while streaming`,
{ max_library_bytes: limits.library_bytes },
),
);
imageHash.update(view);
+4 -4
View File
@@ -48,10 +48,10 @@ export interface SnapshotHashScan {
* Feed chunks in order; a trailing carry keeps a magic-to-hash span that a
* chunk boundary would otherwise split.
*/
/** Hard cap on distinct hashes retained before partial coverage reports. */
export const MAX_SNAPSHOT_HASH_CANDIDATES = 64;
export class SnapshotHashScanner {
/** Distinct hashes retained before the scan reports itself capped. */
constructor(private readonly maximumCandidates = 64) {}
#sources = 0;
#capped = false;
private readonly candidates: string[] = [];
@@ -61,7 +61,7 @@ export class SnapshotHashScanner {
#recordCandidate(candidate: string | null): void {
if (candidate === null) return;
if (!this.candidateSet.has(candidate)) {
if (this.candidates.length === MAX_SNAPSHOT_HASH_CANDIDATES)
if (this.candidates.length === this.maximumCandidates)
this.#capped = true;
else {
this.candidateSet.add(candidate);
+46 -5
View File
@@ -57,8 +57,8 @@ it("advertises and validates one ABI selector grammar with field correction guid
"a",
"abi\\label",
"abi\nlabel",
"l".repeat(1010),
"😀".repeat(1010),
"l".repeat(65_521),
"😀".repeat(65_521),
]) {
expect(accepts({ abi })).toBe(true);
expect(abiSchema.safeParse(abi).success).toBe(true);
@@ -66,9 +66,9 @@ it("advertises and validates one ABI selector grammar with field correction guid
for (const abi of [
"",
"lib/x86_64",
"l".repeat(1011),
"😀".repeat(1011),
"l".repeat(1010) + "\n",
"l".repeat(65_522),
"😀".repeat(65_522),
"l".repeat(65_521) + "\n",
]) {
expect(accepts({ abi })).toBe(false);
expect(abiSchema.safeParse(abi).success).toBe(false);
@@ -132,3 +132,44 @@ it("inspects the caller-selected nonstandard ABI through the public CLI", async
]);
expect(JSON.parse(invalid.stdout).code).toBe("VALIDATION_ERROR");
});
it("refuses at apk_limits.abi_count and recovers the same APK through the public CLI", async () => {
const path = await createFlutterApk("two-abis.apk", [
{ path: "lib/arm64-v8a/libapp.so", bytes: aotFixtureImage("a".repeat(32)) },
{ path: "lib/x86_64/libapp.so", bytes: aotFixtureImage("b".repeat(32)) },
]);
const refused = await serveCli([
"identify-flutter-build",
path,
"--apk-limits",
'{"abi_count":1}',
"--json",
]);
expect(JSON.parse(refused.stdout)).toMatchObject({
code: "resource_constraint",
retryable: false,
details: {
limit: {
control_kind: "parameter",
parameter: "apk_limits.abi_count",
effective_value: 1,
unit: "count",
minimum: 1,
maximum: 0x7fffffff,
default_value: 32,
applies_at: "next_call",
},
},
});
const recovered = await serveCli([
"identify-flutter-build",
path,
"--apk-limits",
'{"abi_count":2}',
"--json",
]);
expect(recovered.exitCode, recovered.stdout).toBe(0);
expect(JSON.parse(recovered.stdout)).toMatchObject({
parameters: { path, apk_limits: { abi_count: 2 } },
});
});
@@ -938,11 +938,16 @@ it.each(["identify_flutter_build", "inspect_dart_aot"] as const)(
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("resource_constraint");
expect(projected.retryable).toBe(false);
expect(projected.details?.refusal).toMatchObject({
kind: "fixed_ceiling",
allowance_kind: "input",
limit: 2 * 1024 ** 3,
expect(projected.details?.refusal).toBeUndefined();
expect(projected.details?.limit).toEqual({
control_kind: "parameter",
parameter: "apk_limits.apk_bytes",
effective_value: 2 * 1024 ** 3,
unit: "bytes",
minimum: 1,
maximum: Number.MAX_SAFE_INTEGER,
default_value: 2 * 1024 ** 3,
applies_at: "next_call",
});
expect(projected.remediation.action).not.toMatch(/evidence reply/u);
expect(result.error).toMatchObject({
@@ -1110,11 +1115,31 @@ it.each(["identify_flutter_build", "inspect_dart_aot"] as const)(
reportedLimits: { max_metadata_read_bytes: 8 * 1024 ** 2 },
});
expect(result.error.message).toContain("ZIP metadata read requires");
expect(projectAnalysisError(result.error).details?.refusal).toMatchObject({
kind: "fixed_ceiling",
limit: 8 * 1024 ** 2,
expect(projectAnalysisError(result.error).details?.limit).toMatchObject({
control_kind: "parameter",
parameter: "apk_limits.metadata_read_bytes",
effective_value: 8 * 1024 ** 2,
unit: "bytes",
});
// The same APK passes metadata admission when the caller raises it; it
// carries no Flutter libraries, which each operation then reports.
const raised = await provider.execute({
operation,
input: { path, apk_limits: { metadata_read_bytes: 16 * 1024 ** 2 } },
});
if (operation === "identify_flutter_build") {
if (!raised.ok) throw raised.error;
expect(
flutterResultSchemas.identify_flutter_build.parse(raised.value.result)
.abis,
).toEqual([]);
} else {
if (raised.ok) throw new Error("Expected the no-payload refusal");
expect(projectAnalysisError(raised.error)).toMatchObject({
code: "unsupported_target",
message: expect.stringContaining("No lib/<abi>/libapp.so was found"),
});
}
},
);
@@ -1388,12 +1413,12 @@ it.each(["identify_flutter_build", "inspect_dart_aot"] as const)(
);
it.each([
["identify_flutter_build", "ABI", 32, "ABIs"],
["inspect_dart_aot", "ABI", 32, "ABIs"],
["identify_flutter_build", "path", 1024, "bytes"],
["identify_flutter_build", "ABI", 32, "apk_limits.abi_count"],
["inspect_dart_aot", "ABI", 32, "apk_limits.abi_count"],
["identify_flutter_build", "path", 1024, "apk_limits.library_path_bytes"],
] as const)(
"%s refuses %s metadata expansion before opening empty libraries",
async (operation, shape, limit, unit) => {
async (operation, shape, limit, parameter) => {
const path = await buildApk(
"many-abis.apk",
shape === "ABI"
@@ -1416,11 +1441,10 @@ it.each([
if (result.ok) throw new Error("ABI expansion must be refused");
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("resource_constraint");
expect(projected.details?.refusal).toMatchObject({
kind: "fixed_ceiling",
allowance_kind: "parser",
limit,
unit,
expect(projected.details?.limit).toMatchObject({
control_kind: "parameter",
parameter,
effective_value: limit,
});
expect(extract).not.toHaveBeenCalled();
},
@@ -1637,11 +1661,26 @@ it("refuses truncated hash-candidate evidence and includes five-character tokens
if (result.ok) throw new Error("Incomplete candidate set must be explicit");
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("resource_constraint");
expect(projected.details?.refusal).toMatchObject({
kind: "fixed_ceiling",
limit: 64,
unit: "candidates",
expect(projected.details?.limit).toMatchObject({
control_kind: "parameter",
parameter: "apk_limits.snapshot_hash_candidates",
effective_value: 64,
unit: "count",
});
// Raising the control retains every distinct candidate of the same APK.
const raised = await provider.execute({
operation: "identify_flutter_build",
input: { path, apk_limits: { snapshot_hash_candidates: 65 } },
});
if (!raised.ok) throw raised.error;
expect(
flutterResultSchemas.identify_flutter_build.parse(raised.value.result)
.abis[0]?.libapp.snapshot_hash_candidates,
).toEqual(
Array.from({ length: 65 }, (_, index) =>
index.toString(16).padStart(32, "0"),
),
);
});
it.each([
+8 -7
View File
@@ -228,11 +228,11 @@ it("advertises and enforces the same Unicode selector grammar through MCP", asyn
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(canonicalInputSchema(tool.name))).toBe(true);
for (const abi of [
"😀".repeat(1010),
"l".repeat(1010),
"😀".repeat(1009) + "\n",
"😀".repeat(65_521),
"l".repeat(65_521),
"😀".repeat(65_520) + "\n",
...["\n", "\r", "\u2028", "\u2029"].map(
(terminator) => "l".repeat(1009) + terminator,
(terminator) => "l".repeat(65_520) + terminator,
),
]) {
const arguments_ = { path: "/fixture.apk", abi };
@@ -251,9 +251,10 @@ it("advertises and enforces the same Unicode selector grammar through MCP", asyn
for (const [abi, reason] of [
["", "out_of_range"],
["lib/x86_64", "invalid_format"],
["😀".repeat(1011), "invalid_value"],
["😀".repeat(65_522), "invalid_value"],
...["\n", "\r", "\u2028", "\u2029"].map(
(terminator) => ["l".repeat(1010) + terminator, "invalid_value"] as const,
(terminator) =>
["l".repeat(65_521) + terminator, "invalid_value"] as const,
),
] as const) {
const arguments_ = { path: "/fixture.apk", abi };
@@ -274,7 +275,7 @@ it("advertises and enforces the same Unicode selector grammar through MCP", asyn
path: ["abi"],
reason,
message: expect.stringMatching(
/exact lib\/ directory label.*1–1010 Unicode characters.*without '\/'/iu,
/exact lib\/ directory label.*1–65521 Unicode characters.*without '\/'/iu,
),
}),
],