Skip to content

Commit 716e33f

Browse files
authored
fix(file-search): reject docx markup bombs before parsing and stop requeueing killed builds (#10616)
A small .docx can hold tens of MB of one-character elements or attribute-heavy elements: it passes the zip guard's byte and ratio ceilings, but mammoth expands objects per XML node and attribute before any of our budgets run, so one such file takes an indexing worker past its memory limit. The kill skips every failure hook, so Trigger.dev retries and then the stale-claim reaper requeued the same file forever. - zip guard: optional parsed-markup budget, estimated from the bytes the verification pass already inflates (every `<` and every `=`, calibrated against mammoth under Bun); docx, doc, live file text and the Word empty-package check use a 2 GiB word-processing budget - revision stamps build_started_at while a run is inside a build; the run clears it however it leaves and publishing clears it, so the next run to begin a build counts a stamp it finds as a killed predecessor and marks the revision failed (build_abandoned) at two - a render keeps a killed run's stamp and count for the same artifact, clears the stamp of a live build it supersedes, never requeues a revision stopped for that artifact, and gives changed inputs a fresh count - migration 0485 adds the three columns with IF NOT EXISTS
1 parent f1a0ea4 commit 716e33f

21 files changed

Lines changed: 35065 additions & 24 deletions

‎apps/sim/lib/file-parsers/doc-parser.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@ import { parseOfficeText } from '@/lib/file-parsers/officeparser-module'
77
import { sniffFileKind } from '@/lib/file-parsers/sniff'
88
import type { FileParseOptions, FileParseResult, FileParser } from '@/lib/file-parsers/types'
99
import { decodeTextBuffer, sanitizeTextForUTF8 } from '@/lib/file-parsers/utils'
10-
import { assertOoxmlArchiveWithinLimits, isZipShaped } from '@/lib/file-parsers/zip-guard'
10+
import {
11+
assertOoxmlArchiveWithinLimits,
12+
isZipShaped,
13+
WORDPROCESSING_OOXML_LIMITS,
14+
} from '@/lib/file-parsers/zip-guard'
1115

1216
const logger = createLogger('DocParser')
1317

@@ -69,7 +73,7 @@ export class DocParser implements FileParser {
6973
throw new FileParserError('empty_input', 'Empty buffer provided')
7074
}
7175

72-
assertOoxmlArchiveWithinLimits(buffer)
76+
assertOoxmlArchiveWithinLimits(buffer, WORDPROCESSING_OOXML_LIMITS)
7377

7478
if (isZipShaped(buffer)) {
7579
return await this.parseOoxmlContainer(buffer, options)
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import JSZip from 'jszip'
2+
import { describe, expect, it, vi } from 'vitest'
3+
import { ZipBombError } from '@/lib/file-parsers/ooxml-limits'
4+
5+
const { mockConvertToHtml, mockExtractRawText, mockParseOfficeText } = vi.hoisted(() => ({
6+
mockConvertToHtml: vi.fn(),
7+
mockExtractRawText: vi.fn(),
8+
mockParseOfficeText: vi.fn(),
9+
}))
10+
11+
vi.mock('mammoth', () => ({
12+
default: {
13+
convertToHtml: mockConvertToHtml,
14+
extractRawText: mockExtractRawText,
15+
images: { imgElement: vi.fn() },
16+
},
17+
}))
18+
vi.mock('@/lib/file-parsers/officeparser-module', () => ({
19+
parseOfficeText: mockParseOfficeText,
20+
}))
21+
22+
import { DocxParser } from '@/lib/file-parsers/docx-parser'
23+
import {
24+
assertOoxmlArchiveWithinLimits,
25+
WORDPROCESSING_OOXML_LIMITS,
26+
} from '@/lib/file-parsers/zip-guard'
27+
28+
describe('DocxParser.parseBuffer', () => {
29+
it('rejects a document of one-character elements before any parser expands it', async () => {
30+
const budget = WORDPROCESSING_OOXML_LIMITS.maxParsedMarkupBytes
31+
const zip = new JSZip()
32+
// One `<` per 3 KiB of budget: the wrapper's two tags put it just over.
33+
zip.file(
34+
'word/document.xml',
35+
`<w:document>${'<a/>'.repeat(Math.ceil(budget / 3072))}</w:document>`
36+
)
37+
const bomb = await zip.generateAsync({
38+
type: 'nodebuffer',
39+
compression: 'DEFLATE',
40+
compressionOptions: { level: 1 },
41+
})
42+
// Within every byte and ratio ceiling, so only the markup budget can reject it.
43+
expect(() => assertOoxmlArchiveWithinLimits(bomb)).not.toThrow()
44+
45+
await expect(new DocxParser().parseBuffer(bomb)).rejects.toBeInstanceOf(ZipBombError)
46+
expect(mockConvertToHtml).not.toHaveBeenCalled()
47+
expect(mockExtractRawText).not.toHaveBeenCalled()
48+
expect(mockParseOfficeText).not.toHaveBeenCalled()
49+
})
50+
})

‎apps/sim/lib/file-parsers/docx-parser.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ import { parseOfficeText } from '@/lib/file-parsers/officeparser-module'
1616
import { isEncryptedOoxmlContainer } from '@/lib/file-parsers/ooxml-encryption'
1717
import type { FileParseOptions, FileParseResult, FileParser } from '@/lib/file-parsers/types'
1818
import { sanitizeTextForUTF8 } from '@/lib/file-parsers/utils'
19-
import { assertOoxmlArchiveWithinLimits } from '@/lib/file-parsers/zip-guard'
19+
import {
20+
assertOoxmlArchiveWithinLimits,
21+
WORDPROCESSING_OOXML_LIMITS,
22+
} from '@/lib/file-parsers/zip-guard'
2023

2124
const logger = createLogger('DocxParser')
2225

@@ -118,7 +121,7 @@ export class DocxParser implements FileParser {
118121
throw new FileParserError('empty_input', 'Empty buffer provided')
119122
}
120123

121-
assertOoxmlArchiveWithinLimits(buffer)
124+
assertOoxmlArchiveWithinLimits(buffer, WORDPROCESSING_OOXML_LIMITS)
122125
const maxTextBytes =
123126
options.docxTextMode === 'complete'
124127
? (options.maxTextBytes ?? MAX_DOCX_CONVERSION_BYTES)

‎apps/sim/lib/file-parsers/zip-guard.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,43 @@ describe('assertOoxmlArchiveWithinLimits', () => {
318318
).toThrow(/exceeds the maximum allowed/)
319319
})
320320

321+
describe('parsed markup budget', () => {
322+
const budget = (maxParsedMarkupBytes: number): OoxmlSizeLimits => ({
323+
...HIGH_LIMITS,
324+
maxParsedMarkupBytes,
325+
})
326+
const NODE = 3072
327+
const ATTRIBUTE = 512
328+
329+
it('charges every node and attribute across deflated and stored entries, up to the budget', async () => {
330+
const zip = new JSZip()
331+
// Four `<` and one `=` deflated, six `<` stored.
332+
zip.file('word/document.xml', '<w:p w:a="1"><w:r>a</w:r></w:p>', { compression: 'DEFLATE' })
333+
zip.file('word/styles.xml', '<s><t/><u/><v/><w/></s>', { compression: 'STORE' })
334+
const buffer = await zip.generateAsync({ type: 'nodebuffer' })
335+
const estimate = 10 * NODE + ATTRIBUTE
336+
337+
expect(() => assertOoxmlArchiveWithinLimits(buffer, budget(estimate))).not.toThrow()
338+
expect(() => assertOoxmlArchiveWithinLimits(buffer, budget(estimate - 1))).toThrow(
339+
ZipBombError
340+
)
341+
})
342+
343+
it('charges a part whose markup hides behind a binary signature', async () => {
344+
const zip = new JSZip()
345+
zip.file(
346+
'word/document.xml',
347+
Buffer.concat([
348+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
349+
Buffer.from('<a/>'.repeat(20)),
350+
])
351+
)
352+
const buffer = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' })
353+
354+
expect(() => assertOoxmlArchiveWithinLimits(buffer, budget(10 * NODE))).toThrow(ZipBombError)
355+
})
356+
})
357+
321358
it('no-ops for buffers that are not ZIP archives', () => {
322359
const plaintext = Buffer.from('this is just plain text, not a zip archive at all')
323360
expect(() => assertOoxmlArchiveWithinLimits(plaintext)).not.toThrow()

‎apps/sim/lib/file-parsers/zip-guard.ts‎

Lines changed: 88 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ export interface OoxmlSizeLimits {
5555
maxCompressionRatio: number
5656
/** The ratio check only applies once the expanded size exceeds this floor, so small files are never flagged. */
5757
ratioCheckFloorBytes: number
58+
/**
59+
* Ceiling on the heap a DOM parser is estimated to hold for the markup of every entry (see
60+
* {@link estimateMarkupBytes}); absent means no ceiling. That heap tracks the number of XML nodes
61+
* and attributes, not bytes, so an entry well inside the size ceilings can still hold millions
62+
* of one-character elements.
63+
*/
64+
maxParsedMarkupBytes?: number
5865
}
5966

6067
const ONE_HUNDRED_MEBIBYTES = 100 * 1024 * 1024
@@ -70,13 +77,65 @@ const ONE_HUNDRED_MEBIBYTES = 100 * 1024 * 1024
7077
* shared with the browser preview guard via {@link ./ooxml-limits}; the ratio
7178
* heuristic is server-only.
7279
*/
73-
export const DEFAULT_OOXML_SIZE_LIMITS: OoxmlSizeLimits = {
80+
const DEFAULT_OOXML_SIZE_LIMITS: OoxmlSizeLimits = {
7481
maxTotalUncompressedBytes: MAX_OOXML_TOTAL_UNCOMPRESSED_BYTES,
7582
maxEntryUncompressedBytes: MAX_OOXML_ENTRY_UNCOMPRESSED_BYTES,
7683
maxCompressionRatio: 150,
7784
ratioCheckFloorBytes: ONE_HUNDRED_MEBIBYTES,
7885
}
7986

87+
/**
88+
* Limits for word-processing archives, which mammoth and officeparser expand into objects per XML
89+
* node and attribute before any caller's budget runs. Every markup shape measured at this budget
90+
* peaked under 1.7 GB, leaving the 4 GB indexing worker its headroom. Real Word XML carries one `<`
91+
* per 12 to 24 bytes, so the budget admits roughly 12 MB of it, well over a thousand pages.
92+
*
93+
* Every entry is charged, media included: mammoth parses a part as XML whatever bytes precede its
94+
* root element (a PNG signature included), so no sniff of an entry's content or name can tell which
95+
* parts it will expand. Compressed media holds about one `<` and one `=` per 256 bytes, so media
96+
* alone fills the budget only near the 150 MiB total ceiling.
97+
*/
98+
export const WORDPROCESSING_OOXML_LIMITS = {
99+
...DEFAULT_OOXML_SIZE_LIMITS,
100+
maxParsedMarkupBytes: 2 * 1024 * 1024 * 1024,
101+
} satisfies OoxmlSizeLimits
102+
103+
/**
104+
* Upper bounds on mammoth's resident cost under Bun, per markup delimiter. Every `<` is charged,
105+
* closing tags included, because each text node lies between two of them; the costliest shape
106+
* (self-closing paragraphs) grew past 3 KiB per `<` at a million of them. Every attribute needs an
107+
* `=`; attribute-heavy elements held under 0.4 KiB per `=`.
108+
*/
109+
const MARKUP_BYTES_PER_NODE = 3072
110+
const MARKUP_BYTES_PER_ATTRIBUTE = 512
111+
const NODE_DELIMITER = 0x3c
112+
const ATTRIBUTE_DELIMITER = 0x3d
113+
114+
/** Estimated parse heap charged so far against a budget; charging stops once it is exceeded. */
115+
interface MarkupTally {
116+
budget: number
117+
bytes: number
118+
}
119+
120+
function chargeDelimiters(
121+
tally: MarkupTally,
122+
content: Buffer,
123+
delimiter: number,
124+
costPerDelimiter: number
125+
): void {
126+
let index = content.indexOf(delimiter)
127+
while (index !== -1 && tally.bytes <= tally.budget) {
128+
tally.bytes += costPerDelimiter
129+
index = content.indexOf(delimiter, index + 1)
130+
}
131+
}
132+
133+
/** Adds an entry's estimated parse heap to the tally, stopping once it passes its budget. */
134+
function estimateMarkupBytes(tally: MarkupTally, content: Buffer): void {
135+
chargeDelimiters(tally, content, NODE_DELIMITER, MARKUP_BYTES_PER_NODE)
136+
chargeDelimiters(tally, content, ATTRIBUTE_DELIMITER, MARKUP_BYTES_PER_ATTRIBUTE)
137+
}
138+
80139
/**
81140
* Whether the buffer is shaped like a ZIP archive — i.e. begins with a local
82141
* file header (the leading signature of every non-empty ZIP, and thus every
@@ -451,10 +510,17 @@ function sumDeclaredUncompressedSize(
451510
* that reads as STORED here but DEFLATE downstream would skip inflation
452511
* verification entirely.
453512
*
513+
* When `markup` is given, every entry's estimated parse heap is added to it
514+
* from the bytes this pass already holds, until the tally passes its `budget`.
515+
*
454516
* Returns an error message when the archive is lying or is shaped in a way that
455517
* cannot be verified, and `null` when every entry checks out.
456518
*/
457-
function findInflationMismatch(buffer: Buffer, location: CentralDirectoryLocation): string | null {
519+
function findInflationMismatch(
520+
buffer: Buffer,
521+
location: CentralDirectoryLocation,
522+
markup?: MarkupTally
523+
): string | null {
458524
let cursor = location.offset
459525
let verified = 0
460526

@@ -517,14 +583,17 @@ function findInflationMismatch(buffer: Buffer, location: CentralDirectoryLocatio
517583
if (uncompressedSize !== compressedSize) {
518584
return `stored entry declares ${uncompressedSize} bytes but holds ${compressedSize}`
519585
}
586+
if (markup)
587+
estimateMarkupBytes(markup, buffer.subarray(dataStart, dataStart + compressedSize))
520588
} else if (compressionMethod === COMPRESSION_METHOD_DEFLATE) {
521589
// The declared compressed size is untrusted too; clamp it to the buffer
522590
// and let the deflate stream's own end marker terminate the read.
523591
const dataEnd = Math.min(dataStart + compressedSize, buffer.length)
524592
try {
525-
inflateRawSync(buffer.subarray(dataStart, dataEnd), {
593+
const content = inflateRawSync(buffer.subarray(dataStart, dataEnd), {
526594
maxOutputLength: Math.max(uncompressedSize, 1),
527595
})
596+
if (markup) estimateMarkupBytes(markup, content)
528597
} catch (error) {
529598
const code = (error as NodeJS.ErrnoException).code
530599
if (code === 'ERR_BUFFER_TOO_LARGE') {
@@ -724,7 +793,11 @@ export function assertOoxmlArchiveWithinLimits(
724793
)
725794
}
726795

727-
const mismatch = findInflationMismatch(buffer, location)
796+
const markup =
797+
limits.maxParsedMarkupBytes === undefined
798+
? undefined
799+
: { budget: limits.maxParsedMarkupBytes, bytes: 0 }
800+
const mismatch = findInflationMismatch(buffer, location, markup)
728801
if (mismatch) {
729802
logger.warn('Rejected OOXML archive: declared sizes do not match actual contents', {
730803
reason: mismatch,
@@ -733,4 +806,15 @@ export function assertOoxmlArchiveWithinLimits(
733806
})
734807
throw new ArchiveIntegrityError(`Archive contents do not match declared sizes: ${mismatch}`)
735808
}
809+
810+
if (markup && markup.bytes > markup.budget) {
811+
logger.warn('Rejected OOXML archive: markup exceeds the parse budget', {
812+
maxParsedMarkupBytes: markup.budget,
813+
declaredTotalUncompressed: totalUncompressed,
814+
compressedBytes: buffer.length,
815+
})
816+
throw new ZipBombError(
817+
`Archive markup would take more than the maximum allowed ${markup.budget} bytes to parse`
818+
)
819+
}
736820
}

‎apps/sim/lib/microsoft-word/document.server.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ import { escapeRegExp } from '@sim/utils/string'
22
import { Document, HeadingLevel, Packer, Paragraph, TextRun } from 'docx'
33
import JSZip from 'jszip'
44
import { DocxParser } from '@/lib/file-parsers/docx-parser'
5-
import { assertOoxmlArchiveWithinLimits } from '@/lib/file-parsers/zip-guard'
5+
import {
6+
assertOoxmlArchiveWithinLimits,
7+
WORDPROCESSING_OOXML_LIMITS,
8+
} from '@/lib/file-parsers/zip-guard'
69

710
/** MIME type Microsoft Graph reports for `.docx` drive items. */
811
export const DOCX_MIME_TYPE =
@@ -253,7 +256,7 @@ async function isEmptyWordPackage(buffer: Buffer): Promise<boolean> {
253256
// rejected it as a zip bomb. Without this the rescue reads `word/document.xml`
254257
// into a string with no size cap, making the guard the trigger for the expansion
255258
// it prevents. Kept outside the catch so the rejection propagates.
256-
assertOoxmlArchiveWithinLimits(buffer)
259+
assertOoxmlArchiveWithinLimits(buffer, WORDPROCESSING_OOXML_LIMITS)
257260

258261
try {
259262
const zip = await JSZip.loadAsync(buffer)

‎apps/sim/lib/sim-search/live/file-text.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@ import { sniffFileKind } from '@/lib/file-parsers/sniff'
33
import type { FileParseResult } from '@/lib/file-parsers/types'
44
import {
55
assertOoxmlArchiveWithinLimits,
6-
DEFAULT_OOXML_SIZE_LIMITS,
6+
WORDPROCESSING_OOXML_LIMITS,
77
} from '@/lib/file-parsers/zip-guard'
88
import { NATIVE_RESPONSE_MAX_BYTES, NativeSearchError } from '@/lib/sim-search/live/http'
99

1010
/** Extracted text one live file read may return. */
1111
export const MAX_FILE_TEXT_BYTES = 1024 * 1024
1212
const MAX_FILE_PDF_PAGES = 100
1313
const FILE_DOCX_LIMITS = {
14-
...DEFAULT_OOXML_SIZE_LIMITS,
14+
...WORDPROCESSING_OOXML_LIMITS,
1515
maxTotalUncompressedBytes: 10 * 1024 * 1024,
1616
maxEntryUncompressedBytes: 4 * 1024 * 1024,
1717
}

0 commit comments

Comments
 (0)