From 6a1d150ede495c7d3ee5e7ca56260b867a5e938a Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 30 Oct 2026 07:31:36 +0000 Subject: [PATCH 1/3] fix(apple): charge the XML plist decoder's DOM before decoding The XML preflight charged 4 bytes per character and 256 bytes per start or end tag. The decoder builds an @xmldom/xmldom DOM that measured 1,000-1,160 bytes per element and up to 240 bytes per text, comment or CDATA node, which were not charged at all. A 1.75 MB plist of 230,000 lines was admitted under the 64 MiB decode budget and peaked at 249 MiB of heap; shipped Apple plists peaked at 80-104 MiB. Charge each element and each text, comment, CDATA or DOCTYPE node at a measured upper bound, keeping the character and number-projection terms. The binary estimator already bounds its decoder and is unchanged. Fixes #8113 Co-Authored-By: Claude Opus 5.5 --- docs/native-investigation.md | 6 +- .../apple/PropertyListDecodeBudget.test.ts | 57 +++++++++++++++ .../apple/PropertyListDecodeBudget.ts | 69 +++++++++++++------ 3 files changed, 109 insertions(+), 23 deletions(-) create mode 100644 src/artifacts/apple/PropertyListDecodeBudget.test.ts diff --git a/docs/native-investigation.md b/docs/native-investigation.md index 89d4bf811c9..3962b7cefda 100644 --- a/docs/native-investigation.md +++ b/docs/native-investigation.md @@ -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 diff --git a/src/artifacts/apple/PropertyListDecodeBudget.test.ts b/src/artifacts/apple/PropertyListDecodeBudget.test.ts new file mode 100644 index 00000000000..2bc3f33c627 --- /dev/null +++ b/src/artifacts/apple/PropertyListDecodeBudget.test.ts @@ -0,0 +1,57 @@ +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( + `\n\n${body}\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(`\n${"\n".repeat(100_000)}\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"); +}); + +it("admits an ordinary pretty-printed XML plist", () => { + const entry = (index: number) => + `\t\n${Array.from( + { length: 5 }, + (_, key) => + `\t\tKey${String(key)}\n\t\t${String(index)}.5\n`, + ).join("")}\t\n`; + const parsed = parsePlistXmlSource( + xmlPlist( + `\n${Array.from({ length: 2000 }, (_, index) => entry(index)).join("")}\n`, + ), + ); + if (!parsed.ok) throw parsed.error; + expect(parsed.value.value).toHaveLength(2000); +}); + +it.each([ + ["elements", "", 1280], + ["text after elements", "\n", 1280 + 384], + ["comments", "", 384], + ["CDATA sections", "", 1280 + 384], +])( + "charges %s for the DOM nodes the decoder builds", + (_name, item, perItem) => { + const count = 1000; + const bytes = xmlPlist(`${item.repeat(count)}`); + const { estimatedBytes } = preflightPropertyListDecode( + bytes, + Number.MAX_SAFE_INTEGER, + ); + expect(estimatedBytes).toBeGreaterThanOrEqual( + bytes.length * 4 + count * perItem, + ); + }, +); diff --git a/src/artifacts/apple/PropertyListDecodeBudget.ts b/src/artifacts/apple/PropertyListDecodeBudget.ts index 1f499510ac1..329c6f5ac92 100644 --- a/src/artifacts/apple/PropertyListDecodeBudget.ts +++ b/src/artifacts/apple/PropertyListDecodeBudget.ts @@ -60,6 +60,15 @@ export const preflightPropertyListDecode = ( return expansion; }; +/** + * Peak heap of the XML decoder's DOM: each element measured 1,000–1,160 + * bytes, and each text, comment or CDATA node up to 240 bytes, 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 estimateXmlPlistExpansion = ( bytes: Buffer, maxBytes: number, @@ -72,36 +81,47 @@ 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. + let estimate = xml.length * 4; + 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; + 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; + 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, internalSubset: false }; + return; + } + const text = start > cursor; const opaqueEnd = xml.startsWith("" : xml.startsWith(" Date: Fri, 30 Oct 2026 07:46:00 +0000 Subject: [PATCH 2/3] fix(apple): charge every XML element, attribute and reference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The XML preflight recognized only element names starting with an ASCII letter, so names such as é, _, a CJK or astral character escaped the element charge: 100,000 <é/> elements (0.5 MB) built an 84 MiB DOM before the plist decoder rejected the tag. Attributes and entity or character references were also uncharged; 20 attributes per element measured about 210 bytes each, and each reference about 26 bytes beyond its characters. Classify markup by the character after "<" instead of a name pattern, so anything other than an end tag, comment, CDATA, PI or declaration counts as an element (saxes rejects malformed markup before the DOM is built). Charge each unquoted "=" in a start tag as an attribute node and every "&" as a reference. Co-Authored-By: Claude Opus 5.5 --- .../apple/PropertyListDecodeBudget.test.ts | 17 +++++++ .../apple/PropertyListDecodeBudget.ts | 48 +++++++++++++------ 2 files changed, 51 insertions(+), 14 deletions(-) diff --git a/src/artifacts/apple/PropertyListDecodeBudget.test.ts b/src/artifacts/apple/PropertyListDecodeBudget.test.ts index 2bc3f33c627..f86507e8fad 100644 --- a/src/artifacts/apple/PropertyListDecodeBudget.test.ts +++ b/src/artifacts/apple/PropertyListDecodeBudget.test.ts @@ -20,6 +20,20 @@ it("refuses an XML plist whose DOM exceeds the native decode budget", () => { 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(`${`<${name}/>`.repeat(100_000)}`), + ); + 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\n${Array.from( @@ -41,6 +55,9 @@ it.each([ ["text after elements", "\n", 1280 + 384], ["comments", "", 384], ["CDATA sections", "", 1280 + 384], + ["non-ASCII elements", "<é/>", 1280], + ["attributes", '', 1280 + 2 * 384], + ["references", "&A", 1280 + 384 + 2 * 64], ])( "charges %s for the DOM nodes the decoder builds", (_name, item, perItem) => { diff --git a/src/artifacts/apple/PropertyListDecodeBudget.ts b/src/artifacts/apple/PropertyListDecodeBudget.ts index 329c6f5ac92..81b53866188 100644 --- a/src/artifacts/apple/PropertyListDecodeBudget.ts +++ b/src/artifacts/apple/PropertyListDecodeBudget.ts @@ -62,12 +62,14 @@ export const preflightPropertyListDecode = ( /** * Peak heap of the XML decoder's DOM: each element measured 1,000–1,160 - * bytes, and each text, comment or CDATA node up to 240 bytes, with - * @xmldom/xmldom on 64-bit Node. Number projection adds literal metadata. + * 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, @@ -81,8 +83,17 @@ const estimateXmlPlistExpansion = ( ) => Error = propertyListDecodeBudgetFailure, ): number => { const xml = xmlText ?? decodeXmlPlistText(bytes); - // The decoded text and the DOM's copies of its character data. + // 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; + } const elementBytes = XML_ELEMENT_BYTES + (numberProjection ? XML_NUMBER_PROJECTION_ELEMENT_BYTES : 0); @@ -97,7 +108,8 @@ const estimateXmlPlistExpansion = ( `XML plist internal entity expansion exceeds ${budget}`, ); if (token.text) estimate += XML_NODE_BYTES; - if (token.kind === "element") estimate += elementBytes; + 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; } @@ -112,13 +124,15 @@ const estimateXmlPlistExpansion = ( 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) { - yield { kind: "none", text: true, internalSubset: false }; + yield { kind: "none", text: true, attributes: 0, internalSubset: false }; return; } const text = start > cursor; @@ -133,14 +147,19 @@ function* xmlPreflightTokens(xml: string): Generator<{ const end = xml.indexOf(opaqueEnd, start + 2); if (end < 0) return; cursor = end + opaqueEnd.length; - yield { kind: "node", text, internalSubset: false }; + 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 = /^") break; + else if (character === "=") attributes += 1; else if (doctype && character === "[") internalSubset = true; } if (end === xml.length) return; cursor = end + 1; - if (doctype || element || endTag) - yield { - kind: element ? "element" : doctype ? "node" : "none", - text, - internalSubset, - }; + yield { + kind: endTag ? "none" : declaration ? "node" : "element", + text, + attributes, + internalSubset, + }; } } From 0be3ca3115ad84f0571d1daa4dee01d086b55466 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Fri, 30 Oct 2026 07:55:49 +0000 Subject: [PATCH 3/3] fix(apple): charge XML references only where the parser expands them The previous commit charged every "&" in the document as a reference, including literal ampersands inside CDATA sections and comments. A valid plist with one CDATA string of 1,000,000 ampersands was refused although it is a single node the decoder holds as one string. Count "&" during the existing token walk, only in text runs and in the attribute values of start tags, so comments, CDATA, PIs and declarations add no reference charge and the scan stays a single pass. Co-Authored-By: Claude Opus 5.5 --- .../apple/PropertyListDecodeBudget.test.ts | 31 ++++++++++++ .../apple/PropertyListDecodeBudget.ts | 49 +++++++++++++------ 2 files changed, 65 insertions(+), 15 deletions(-) diff --git a/src/artifacts/apple/PropertyListDecodeBudget.test.ts b/src/artifacts/apple/PropertyListDecodeBudget.test.ts index f86507e8fad..e39b88868c6 100644 --- a/src/artifacts/apple/PropertyListDecodeBudget.test.ts +++ b/src/artifacts/apple/PropertyListDecodeBudget.test.ts @@ -34,6 +34,37 @@ it.each(["é", "_", ":", "雪", "\u{1d4b3}"])( }, ); +it("refuses text whose entity references exceed the decode budget", () => { + const parsed = parsePlistXmlSource( + xmlPlist(`${"&".repeat(1_000_000)}`), + ); + expect(parsed.ok).toBe(false); + if (parsed.ok) throw new Error("Expected a decode budget refusal"); + expect(parsed.error).toBeInstanceOf(AnalysisResourceConstraintError); +}); + +// Opaque sections hold literal ampersands, not references the parser expands. +it.each([ + ["a CDATA string", ``], + ["a comment", ``], +])("admits literal ampersands in %s", (_name, value) => { + const parsed = parsePlistXmlSource(xmlPlist(`${value}`)); + if (!parsed.ok) throw parsed.error; + expect(parsed.value.value).toEqual([ + value.startsWith("") ? "&".repeat(1_000_000) : true, + ]); +}); + +it("charges references only in text and attribute values", () => { + const mixed = + '<>'; + const estimate = (body: string) => + preflightPropertyListDecode(xmlPlist(body), Number.MAX_SAFE_INTEGER) + .estimatedBytes; + // Same length and nodes without any "&": only the three references differ. + expect(estimate(mixed) - estimate(mixed.replaceAll("&", "x"))).toBe(3 * 64); +}); + it("admits an ordinary pretty-printed XML plist", () => { const entry = (index: number) => `\t\n${Array.from( diff --git a/src/artifacts/apple/PropertyListDecodeBudget.ts b/src/artifacts/apple/PropertyListDecodeBudget.ts index 81b53866188..fc5b201b64a 100644 --- a/src/artifacts/apple/PropertyListDecodeBudget.ts +++ b/src/artifacts/apple/PropertyListDecodeBudget.ts @@ -83,17 +83,8 @@ const estimateXmlPlistExpansion = ( ) => Error = propertyListDecodeBudgetFailure, ): number => { const xml = xmlText ?? decodeXmlPlistText(bytes); - // 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. + // The decoded text and the DOM's copies of its character data. 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; - } const elementBytes = XML_ELEMENT_BYTES + (numberProjection ? XML_NUMBER_PROJECTION_ELEMENT_BYTES : 0); @@ -108,6 +99,7 @@ const estimateXmlPlistExpansion = ( `XML plist internal entity expansion exceeds ${budget}`, ); if (token.text) estimate += XML_NODE_BYTES; + estimate += token.references * XML_REFERENCE_BYTES; if (token.kind === "element") estimate += elementBytes + token.attributes * XML_NODE_BYTES; else if (token.kind === "node") estimate += XML_NODE_BYTES; @@ -118,24 +110,41 @@ const estimateXmlPlistExpansion = ( /** * 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. + * Each token reports the DOM node it creates (none for an end tag), whether + * character data, which becomes a text node, precedes it, and the references + * the parser expands in that text and in the tag's attribute values. Opaque + * comment, CDATA, PI and declaration content holds no references. */ 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; + /** "&" in the preceding text and in this start tag's attribute values. */ + readonly references: number; readonly internalSubset: boolean; }> { + const textReferences = (from: number, to: number): number => { + let count = 0; + for (let index = from; index < to; index += 1) + if (xml.charCodeAt(index) === 0x26) count += 1; + return count; + }; let cursor = 0; while (cursor < xml.length) { const start = xml.indexOf("<", cursor); if (start < 0) { - yield { kind: "none", text: true, attributes: 0, internalSubset: false }; + yield { + kind: "none", + text: true, + attributes: 0, + references: textReferences(cursor, xml.length), + internalSubset: false, + }; return; } const text = start > cursor; + const references = textReferences(cursor, start); const opaqueEnd = xml.startsWith("" : xml.startsWith("") break; else if (character === "=") attributes += 1; @@ -173,9 +191,10 @@ function* xmlPreflightTokens(xml: string): Generator<{ if (end === xml.length) return; cursor = end + 1; yield { - kind: endTag ? "none" : declaration ? "node" : "element", + kind: element ? "element" : declaration ? "node" : "none", text, attributes, + references: references + attributeReferences, internalSubset, }; }