Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/native-investigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -512,8 +512,10 @@ output-budget omissions remain omissions.

Source input is limited to 64 MiB. Binary and direct XML decoding reserve an
estimated 64 MiB decode budget before parsing; this is not a hard process-memory
bound. JSON decode memory has not been measured and has no equivalent decode
estimate. A refused input reports non-retryable `resource_constraint` with
bound. The XML estimate charges every element and every text, comment or CDATA
node of the decoder's DOM at a measured upper bound, so a plist made of many
small elements reaches it at a few MiB of source. JSON decode memory has not
been measured and has no equivalent decode estimate. A refused input reports non-retryable `resource_constraint` with
`reported_limits.maximum_input_bytes` or `maximum_decoded_bytes` as applicable.
Ordinary direct-source decoding has a ceiling of 998 source nesting levels,
derived from the existing 1000-level JSON result capacity by reserving one level
Expand Down
74 changes: 74 additions & 0 deletions src/artifacts/apple/PropertyListDecodeBudget.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { expect, it } from "vitest";

import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
import { parsePlistXmlSource } from "../../native/parsers/plist.js";
import { preflightPropertyListDecode } from "./PropertyListDecodeBudget.js";

const xmlPlist = (body: string): Buffer =>
Buffer.from(
`<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0">\n${body}</plist>\n`,
);

it("refuses an XML plist whose DOM exceeds the native decode budget", () => {
// Real decode peaks near 110 MiB: about 1,100 bytes per element and text node.
const parsed = parsePlistXmlSource(
xmlPlist(`<array>\n${"<true/>\n".repeat(100_000)}</array>\n`),
);
expect(parsed.ok).toBe(false);
if (parsed.ok) throw new Error("Expected a decode budget refusal");
expect(parsed.error).toBeInstanceOf(AnalysisResourceConstraintError);
expect(parsed.error.message).toContain("native plist decode budget");
});

// Saxes accepts any XML NameStartChar, and the DOM holds every element
// before the plist decoder rejects an unknown tag.
it.each(["é", "_", ":", "雪", "\u{1d4b3}"])(
"refuses 100,000 elements whose names start with %s before building the DOM",
(name) => {
const parsed = parsePlistXmlSource(
xmlPlist(`<array>${`<${name}/>`.repeat(100_000)}</array>`),
);
expect(parsed.ok).toBe(false);
if (parsed.ok) throw new Error("Expected a decode budget refusal");
expect(parsed.error).toBeInstanceOf(AnalysisResourceConstraintError);
},
);

it("admits an ordinary pretty-printed XML plist", () => {
const entry = (index: number) =>
`\t<dict>\n${Array.from(
{ length: 5 },
(_, key) =>
`\t\t<key>Key${String(key)}</key>\n\t\t<real>${String(index)}.5</real>\n`,
).join("")}\t</dict>\n`;
const parsed = parsePlistXmlSource(
xmlPlist(
`<array>\n${Array.from({ length: 2000 }, (_, index) => entry(index)).join("")}</array>\n`,
),
);
if (!parsed.ok) throw parsed.error;
expect(parsed.value.value).toHaveLength(2000);
});

it.each([
["elements", "<true/>", 1280],
["text after elements", "<true/>\n", 1280 + 384],
["comments", "<!---->", 384],
["CDATA sections", "<string><![CDATA[a]]></string>", 1280 + 384],
["non-ASCII elements", "<é/>", 1280],
["attributes", '<true a="x>y" b="z"/>', 1280 + 2 * 384],
["references", "<string>&amp;&#x41;</string>", 1280 + 384 + 2 * 64],
])(
"charges %s for the DOM nodes the decoder builds",
(_name, item, perItem) => {
const count = 1000;
const bytes = xmlPlist(`<array>${item.repeat(count)}</array>`);
const { estimatedBytes } = preflightPropertyListDecode(
bytes,
Number.MAX_SAFE_INTEGER,
);
expect(estimatedBytes).toBeGreaterThanOrEqual(
bytes.length * 4 + count * perItem,
);
},
);
89 changes: 68 additions & 21 deletions src/artifacts/apple/PropertyListDecodeBudget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,17 @@ export const preflightPropertyListDecode = (
return expansion;
};

/**
* Peak heap of the XML decoder's DOM: each element measured 1,000–1,160
* bytes, each text, comment, CDATA or attribute node up to 240 bytes, and
* each entity or character reference about 26 bytes beyond its characters,
* with @xmldom/xmldom on 64-bit Node. Number projection adds literal metadata.
*/
const XML_ELEMENT_BYTES = 1280;
const XML_NUMBER_PROJECTION_ELEMENT_BYTES = 256;
const XML_NODE_BYTES = 384;
const XML_REFERENCE_BYTES = 64;

const estimateXmlPlistExpansion = (
bytes: Buffer,
maxBytes: number,
Expand All @@ -72,36 +83,59 @@ const estimateXmlPlistExpansion = (
) => Error = propertyListDecodeBudgetFailure,
): number => {
const xml = xmlText ?? decodeXmlPlistText(bytes);
const decodedSourceBytes = xml.length * 2;
let elementCount = 0;
// Reserve room for numeric source metadata and the projected attribute copy.
const elementBytes = numberProjection ? 256 : 128;
// The decoded text and the DOM's copies of its character data. Every "&"
// outside opaque sections starts a reference; counting all is an upper bound.
let estimate = xml.length * 4;
for (
let reference = xml.indexOf("&");
reference >= 0;
reference = xml.indexOf("&", reference + 1)
) {
estimate += XML_REFERENCE_BYTES;
if (estimate > maxBytes) return maxBytes + 1;
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}
const elementBytes =
XML_ELEMENT_BYTES +
(numberProjection ? XML_NUMBER_PROJECTION_ELEMENT_BYTES : 0);
// Value nesting is bounded by the shared plist parser, which counts plist
// value depth; raw element depth would also count the envelope and keys.
for (const token of xmlPreflightTokens(xml)) {
if (token.doctype) {
if (token.internalSubset)
// Only a declaration outside opaque text can introduce an internal
// subset. Brackets in quoted external identifiers are literal text.
if (token.internalSubset)
throw fail(
"expansion",
`XML plist internal entity expansion exceeds ${budget}`,
);
continue;
}
elementCount += 1;
if (decodedSourceBytes * 2 + elementCount * elementBytes > maxBytes)
return maxBytes + 1;
throw fail(
"expansion",
`XML plist internal entity expansion exceeds ${budget}`,
);
if (token.text) estimate += XML_NODE_BYTES;
if (token.kind === "element")
estimate += elementBytes + token.attributes * XML_NODE_BYTES;
else if (token.kind === "node") estimate += XML_NODE_BYTES;
if (estimate > maxBytes) return maxBytes + 1;
}
return decodedSourceBytes * 2 + elementCount * elementBytes;
return estimate;
};

/** Consume each XML span once; malformed tokens cannot restart suffix scans. */
function* xmlPreflightTokens(xml: string) {
/**
* Consume each XML span once; malformed tokens cannot restart suffix scans.
* Each token reports the DOM node it creates (none for an end tag) and
* whether character data, which becomes a text node, precedes it.
*/
function* xmlPreflightTokens(xml: string): Generator<{
readonly kind: "element" | "node" | "none";
readonly text: boolean;
/** Unquoted "=" signs; each attribute of a well-formed tag has one. */
readonly attributes: number;
readonly internalSubset: boolean;
}> {
let cursor = 0;
while (cursor < xml.length) {
const start = xml.indexOf("<", cursor);
if (start < 0) return;
if (start < 0) {
yield { kind: "none", text: true, attributes: 0, internalSubset: false };
return;
}
const text = start > cursor;
const opaqueEnd = xml.startsWith("<!--", start)
? "-->"
: xml.startsWith("<![CDATA[", start)
Expand All @@ -113,24 +147,37 @@ function* xmlPreflightTokens(xml: string) {
const end = xml.indexOf(opaqueEnd, start + 2);
if (end < 0) return;
cursor = end + opaqueEnd.length;
yield { kind: "node", text, attributes: 0, internalSubset: false };
continue;
}
// Classify by the character after "<" rather than a name pattern: any
// other markup starts an element, whatever its name's script. Saxes
// rejects malformed markup before the DOM is built, so over-counting it
// is harmless.
const doctype = /^<!DOCTYPE\b/iu.test(xml.slice(start, start + 10));
const element = /^<\/?[A-Za-z]/u.test(xml.slice(start, start + 4));
const declaration = xml[start + 1] === "!";
const endTag = xml[start + 1] === "/";
let quote: string | undefined;
let internalSubset = false;
let attributes = 0;
let end = start + 1;
for (; end < xml.length; end += 1) {
const character = xml[end];
if (quote !== undefined) {
if (character === quote) quote = undefined;
} else if (character === '"' || character === "'") quote = character;
else if (character === ">") break;
else if (character === "=") attributes += 1;
else if (doctype && character === "[") internalSubset = true;
}
if (end === xml.length) return;
cursor = end + 1;
if (doctype || element) yield { doctype, internalSubset };
yield {
kind: endTag ? "none" : declaration ? "node" : "element",
text,
attributes,
internalSubset,
};
}
}

Expand Down
Loading