-
Notifications
You must be signed in to change notification settings - Fork 542
feat(runtime): preflight native PDF inputs against provider document constraints #5754
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jhaabhijeet864
wants to merge
9
commits into
apache:main
Choose a base branch
from
jhaabhijeet864:feat/3284-pdf-preflight-validation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d43dca7
feat(runtime): preflight native PDF inputs against provider document …
jhaabhijeet864 fca8a97
feat(runtime): preflight native PDF inputs against provider document …
jhaabhijeet864 ed752dc
fix(runtime): improve PDF preflight heuristics and resolve CI vulnera…
jhaabhijeet864 cfdcea5
chore: refresh package-lock.json to resolve GitHub merge conflicts
jhaabhijeet864 b4bcfb8
chore: resolve package-lock.json conflicts by regenerating from main
jhaabhijeet864 0fbf03c
fix(runtime): refine PDF preflight and resolve ACP upload rejections
jhaabhijeet864 fcdba11
fix: address P2 and P3 review comments
jhaabhijeet864 2dfaadc
fix: use declared mimeType in acp prompt content to fix CI
jhaabhijeet864 f63f07f
fix: resolve Biome formatting and correct pdf encryption inline comments
jhaabhijeet864 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| import { describe, test } from 'node:test'; | ||
| import assert from 'node:assert/strict'; | ||
| import { Buffer } from 'node:buffer'; | ||
| import { validatePdfBytes } from '../pdf-preflight.js'; | ||
|
|
||
| describe('pdf-preflight', () => { | ||
| test('rejects files without %PDF- magic bytes', () => { | ||
| const bytes = Buffer.from('just a random string without magic bytes'); | ||
| const result = validatePdfBytes(bytes); | ||
| assert.deepEqual(result, { ok: false, reason: 'not_a_pdf' }); | ||
| }); | ||
|
|
||
| test('accepts files with %PDF- magic bytes', () => { | ||
| const bytes = Buffer.from('%PDF-1.4\n%EOF'); | ||
| const result = validatePdfBytes(bytes); | ||
| assert.deepEqual(result, { ok: true, pages: undefined }); | ||
| }); | ||
|
|
||
| test('rejects encrypted PDFs with indirect object reference', () => { | ||
| const bytes = Buffer.from('%PDF-1.4\n/Encrypt 1 0 R\n%EOF'); | ||
| const result = validatePdfBytes(bytes); | ||
| assert.deepEqual(result, { ok: false, reason: 'encrypted' }); | ||
| }); | ||
|
|
||
| test('rejects encrypted PDFs with inline dictionary', () => { | ||
| const bytes = Buffer.from('%PDF-1.4\n/Encrypt <<\n/Filter /Standard\n>>\n%EOF'); | ||
| const result = validatePdfBytes(bytes); | ||
| assert.deepEqual(result, { ok: false, reason: 'encrypted' }); | ||
| }); | ||
|
|
||
| test('does not false-positive on a document that merely mentions /Encrypt in text', () => { | ||
| const bytes = Buffer.from( | ||
| '%PDF-1.4\nstream\nThis paper discusses /Encrypt ion in PDF files\nendstream\n%EOF', | ||
| ); | ||
| const result = validatePdfBytes(bytes); | ||
| assert.deepEqual(result, { ok: true, pages: undefined }); | ||
| }); | ||
|
|
||
| test('extracts page count as advisory hint (never rejects)', () => { | ||
| const bytes = Buffer.from('%PDF-1.4\n<< /Type /Pages /Count 150 >>\n%EOF'); | ||
| const result = validatePdfBytes(bytes); | ||
| // Page count is reported but never used for rejection — callers decide policy. | ||
| assert.deepEqual(result, { ok: true, pages: 150 }); | ||
| }); | ||
|
|
||
| test('does not reject a valid one-page PDF with /Count mentioned in content stream', () => { | ||
| // Counterexample from review: a valid 1-page PDF whose content stream has a | ||
| // comment that contains /Type /Pages /Count 101 before the real page-tree object. | ||
| // The validator must NOT reject this document. | ||
| const bytes = Buffer.from( | ||
| '%PDF-1.4\n' + | ||
| 'stream\n% /Type /Pages /Count 101\nendstream\n' + | ||
| '<< /Type /Pages /Count 1 >>\n' + | ||
| '%EOF', | ||
| ); | ||
| const result = validatePdfBytes(bytes); | ||
| // The regex may capture either 101 or 1 depending on match order, but | ||
| // critically: the result must be ok:true — no rejection on page count. | ||
| assert.equal(result.ok, true); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| import { PDF_HEADER_SCAN_BYTES } from '@maka/core/attachments'; | ||
| import { Buffer } from 'node:buffer'; | ||
|
|
||
| export type PdfPreflightResult = | ||
| | { ok: true; pages?: number } | ||
| | { ok: false; reason: 'encrypted' | 'not_a_pdf' | 'malformed' }; | ||
|
|
||
| /** | ||
| * Deterministic, bounded, best-effort PDF preflight validator. | ||
| * | ||
| * Designed to filter out incompatible documents before LLM provider dispatch | ||
| * without the CPU, memory, and security overhead of full PDF object-graph | ||
| * evaluation, rendering, or OCR. | ||
| * | ||
| * **Fast-path heuristics**: | ||
| * | ||
| * - **Header**: Verifies presence of `%PDF-` within the canonical | ||
| * {@link PDF_HEADER_SCAN_BYTES} window defined in `@maka/core/attachments`. | ||
| * | ||
| * - **Encryption**: Searches for an active `/Encrypt` dictionary definition | ||
| * (`/Encrypt <<` or `/Encrypt N N R`). This is a best-effort text-level scan | ||
| * and may falsely match uncompressed stream content containing those exact | ||
| * sequences. | ||
| * | ||
| * - **Page count**: Best-effort bounded regex scan for | ||
| * `/Type /Pages ... /Count N`. The regex only matches outside of stream | ||
| * content by requiring the `/Type /Pages` dictionary key context, but it | ||
| * does not decompress object streams so the result is advisory. On success | ||
| * the `pages` field is populated for informational use by callers; the | ||
| * validator itself does **not** reject based on page count because a | ||
| * text-level scan cannot authoritatively distinguish a root page-tree | ||
| * `/Count` from an intermediate node or a content-stream comment. | ||
| * | ||
| * **Non-goals**: Does not parse fonts, decompress streams, render raster | ||
| * content, or extract text. | ||
| */ | ||
| export function validatePdfBytes(bytes: Uint8Array): PdfPreflightResult { | ||
| // 1. Structural check — reuse the canonical scan window from @maka/core. | ||
| const scanWindow = Math.min(bytes.length, PDF_HEADER_SCAN_BYTES); | ||
| const prefix = bytes.subarray(0, scanWindow); | ||
| const prefixStr = Buffer.from(prefix).toString('ascii'); | ||
| if (!prefixStr.includes('%PDF-')) { | ||
| return { ok: false, reason: 'not_a_pdf' }; | ||
| } | ||
|
|
||
| // 2. Build a bounded ASCII view for dictionary scanning. | ||
| // For files ≤ 5 MB convert the whole buffer; for larger files inspect only | ||
| // the first and last 1 MB where PDF trailers and catalog roots reside. | ||
| const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); | ||
|
|
||
| const scanBuffers: string[] = []; | ||
| if (buffer.length <= 5 * 1024 * 1024) { | ||
| scanBuffers.push(buffer.toString('ascii')); | ||
| } else { | ||
| // Scan head and tail independently to avoid synthetic matches across a concatenated seam. | ||
| scanBuffers.push(buffer.subarray(0, 1024 * 1024).toString('ascii')); | ||
| scanBuffers.push(buffer.subarray(buffer.length - 1024 * 1024).toString('ascii')); | ||
| } | ||
|
|
||
| // 3. Encryption check — match an active /Encrypt dictionary definition. | ||
| // Note: This is a best-effort text-level scan. Because it searches the entire | ||
| // extracted text buffer(s) rather than parsing the PDF object graph, it may | ||
| // falsely match uncompressed stream content containing the exact /Encrypt sequence. | ||
| const encryptRegex = /\/Encrypt\s*(?:<<|\d+\s+\d+\s+R)/; | ||
|
jhaabhijeet864 marked this conversation as resolved.
|
||
|
|
||
| const isEncrypted = scanBuffers.some((buf) => encryptRegex.test(buf)); | ||
|
|
||
| if (isEncrypted) { | ||
| return { ok: false, reason: 'encrypted' }; | ||
| } | ||
|
|
||
| // 4. Page count extraction (advisory, never used as a rejection gate). | ||
| // A text-level scan cannot reliably distinguish the root /Pages /Count from | ||
| // an intermediate page-tree node or a content-stream comment, so we report | ||
| // the value but leave enforcement to the caller's discretion. | ||
| // Note: The captured count may be any page-tree node's count, not necessarily the root. | ||
| const pagesRegex = /\/Type\s*\/Pages[\s\S]{0,100}?\/Count\s+(\d+)/; | ||
| const alternatePagesRegex = /\/Count\s+(\d+)[\s\S]{0,100}?\/Type\s*\/Pages/; | ||
| let pages: number | undefined = undefined; | ||
|
|
||
| for (const buf of scanBuffers) { | ||
| const match = buf.match(pagesRegex); | ||
| if (match && match[1]) { | ||
| pages = parseInt(match[1], 10); | ||
| if (isNaN(pages)) pages = undefined; | ||
| break; | ||
| } | ||
| const alternateMatch = buf.match(alternatePagesRegex); | ||
| if (alternateMatch && alternateMatch[1]) { | ||
| pages = parseInt(alternateMatch[1], 10); | ||
| if (isNaN(pages)) pages = undefined; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| return { ok: true, pages }; | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.