Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
30 changes: 19 additions & 11 deletions packages/extraction/src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ import { spawn } from 'node:child_process';
import { constants } from 'node:fs';
import { mkdtemp, open, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { ExtractionError, policy, validateResult } from './protocol.js';
import {
ExtractionError,
pdfPageCount,
policy,
validatePdfPageCount,
validateResult,
} from './protocol.js';
import type { Format } from './protocol.js';

export interface Backend {
Expand All @@ -12,7 +18,8 @@ export interface Backend {
job: string,
format: Format,
digest: string,
signal: AbortSignal
signal: AbortSignal,
countPages?: boolean
): Promise<Buffer>;
cleanup(job: string): Promise<void>;
}
Expand Down Expand Up @@ -138,29 +145,30 @@ export class RestrictedBackend implements Backend {
job: string,
format: Format,
digest: string,
signal: AbortSignal
signal: AbortSignal,
countPages = false
): Promise<Buffer> {
await this.execute(job, format, signal);
await this.execute(job, countPages ? 'pdf-page-count' : format, signal);
const resultBytes = countPages
? pdfPageCount.resultBytes
: policy.resultBytes;
const file = await open(
join(job, 'result'),
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
);
try {
const stat = await file.stat();
if (
!stat.isFile() ||
stat.nlink !== 1 ||
stat.size > policy.resultBytes
) {
if (!stat.isFile() || stat.nlink !== 1 || stat.size > resultBytes) {
throw new ExtractionError('OUTPUT_LIMIT');
}
const buffer = Buffer.alloc(stat.size + 1);
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
if (bytesRead > policy.resultBytes)
if (bytesRead > resultBytes)
throw new ExtractionError('OUTPUT_LIMIT');
const bytes = buffer.subarray(0, bytesRead);
signal.throwIfAborted();
validateResult(bytes, format, digest);
if (countPages) validatePdfPageCount(bytes, digest);
else validateResult(bytes, format, digest);
return bytes;
} finally {
await file.close();
Expand Down
27 changes: 26 additions & 1 deletion packages/extraction/src/protocol.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { policy, validateResult } from './protocol.js';
import {
pdfPageCount,
policy,
validatePdfPageCount,
validateResult,
} from './protocol.js';
const digest = 'a'.repeat(64);
const value = (text = 'hello') => ({
version: 1,
Expand Down Expand Up @@ -66,3 +71,23 @@ test('rejects excess pages and does not accept PDF pages as DOCX structure', ()
validateResult(encode({ ...value(), format: 'docx' }), 'docx', digest)
);
});

test('validates a count-only PDF result independently of the extraction segment limit', () => {
const result = {
version: 1,
operation: pdfPageCount.operation,
inputSha256: digest,
pages: 601,
};
assert.doesNotThrow(() => validatePdfPageCount(encode(result), digest));
for (const changed of [
{ ...result, pages: 0 },
{ ...result, pages: 1.5 },
{ ...result, inputSha256: 'b'.repeat(64) },
{ ...result, extra: true },
])
assert.throws(() => validatePdfPageCount(encode(changed), digest));
assert.throws(() =>
validatePdfPageCount(Buffer.alloc(pdfPageCount.resultBytes + 1), digest)
);
});
29 changes: 29 additions & 0 deletions packages/extraction/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export const policy = Object.freeze({
deadlineMs: 10_000,
maxSegments: 128,
});
export const pdfPageCount = Object.freeze({
operation: 'document.pdf-page-count',
inputBytes: 32 * 1024 * 1024,
resultBytes: 256,
});
export type Format = 'pdf' | 'docx';
export type ErrorCode =
| 'INVALID_REQUEST'
Expand Down Expand Up @@ -102,6 +107,30 @@ export function validateResult(
throw new ExtractionError('INVALID_DOCUMENT');
return result;
}
export function validatePdfPageCount(bytes: Buffer, digest: string): void {
if (bytes.length > pdfPageCount.resultBytes)
throw new ExtractionError('OUTPUT_LIMIT');
let result;
try {
result = JSON.parse(
new TextDecoder('utf-8', { fatal: true }).decode(bytes)
);
} catch {
throw new ExtractionError('INVALID_DOCUMENT');
}
if (
!result ||
typeof result !== 'object' ||
!keys(result, ['version', 'operation', 'inputSha256', 'pages']) ||
result.version !== 1 ||
result.operation !== pdfPageCount.operation ||
result.inputSha256 !== digest ||
!Number.isSafeInteger(result.pages) ||
result.pages < 1
)
throw new ExtractionError('INVALID_DOCUMENT');
}

export function sha256(bytes: Buffer): string {
return createHash('sha256').update(bytes).digest('hex');
}
46 changes: 45 additions & 1 deletion packages/extraction/src/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async function send(port: number, overrides = {}, path = '/v1/extract-text') {
host: '127.0.0.1',
port,
path,
method: path === '/v1/capabilities' ? 'GET' : 'POST',
method: path.endsWith('/capabilities') ? 'GET' : 'POST',
headers: Object.fromEntries(
Object.entries({ ...headers, ...overrides }).filter(
([, value]) => value !== undefined
Expand Down Expand Up @@ -351,3 +351,47 @@ test('unauthenticated expectations and stalled bodies close without admission',
await f.close();
}
});

test('uses the guarded backend counting mode only for authenticated PDF requests', async () => {
const f = await fixture();
try {
const path = '/v1/pdf-page-count';
const legacyCaps = await send(f.port, {}, '/v1/capabilities');
const countCaps = await send(f.port, {}, `${path}/capabilities`);
assert.equal(legacyCaps.status, 200);
assert.deepEqual(Object.keys(JSON.parse(legacyCaps.body)).sort(), [
'formats',
'limitations',
'limits',
'operation',
'structure',
'version',
]);
assert.equal(countCaps.status, 200);
assert.equal(
JSON.parse(countCaps.body).operation,
'document.pdf-page-count'
);
assert.equal(
(await send(f.port, { Authorization: undefined }, path)).status,
401
);
assert.equal(
(await send(f.port, { 'X-Extraction-Format': 'docx' }, path))
.status,
400
);
assert.deepEqual(f.events, []);
f.backend.run = async (_job, format, _digest, _signal, countPages) => {
assert.equal(format, 'pdf');
assert.equal(countPages, true);
f.events.push('count');
return Buffer.from('{"pages":601}');
};
assert.equal((await send(f.port, {}, path)).status, 200);
assert.deepEqual(f.events, ['create', 'count', 'cleanup']);
assert.deepEqual(await readdir(f.root), []);
} finally {
await f.close();
}
});
55 changes: 37 additions & 18 deletions packages/extraction/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createHash, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
import { open } from 'node:fs/promises';
import { join } from 'node:path';
import { ExtractionError, policy } from './protocol.js';
import { ExtractionError, pdfPageCount, policy } from './protocol.js';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { Backend } from './backend.js';
import type { Format } from './protocol.js';
Expand Down Expand Up @@ -51,7 +51,11 @@ function reply(res: ServerResponse, code: number, bytes: Buffer): void {
});
res.end(bytes);
}
function requestFormat(req: IncomingMessage): Format {
function requestFormat(
req: IncomingMessage,
maxBytes: number,
countPages: boolean
): Format {
const seen = new Set<string>();
for (let i = 0; i < req.rawHeaders.length; i += 2) {
const name = req.rawHeaders[i]!.toLowerCase();
Expand Down Expand Up @@ -81,15 +85,12 @@ function requestFormat(req: IncomingMessage): Format {
throw new ExtractionError('INVALID_REQUEST');
}
const format = req.headers['x-extraction-format'];
if (format !== 'pdf' && format !== 'docx')
if (format !== 'pdf' && (countPages || format !== 'docx'))
throw new ExtractionError('INVALID_REQUEST');
const length = req.headers['content-length'];
if (typeof length !== 'string' || !/^[1-9]\d*$/.test(length))
throw new ExtractionError('INVALID_REQUEST');
if (
!Number.isSafeInteger(Number(length)) ||
Number(length) > policy.inputBytes
)
if (!Number.isSafeInteger(Number(length)) || Number(length) > maxBytes)
throw new ExtractionError('INPUT_LIMIT');
return format;
}
Expand Down Expand Up @@ -155,25 +156,42 @@ export function extractionServer(
res: ServerResponse
): Promise<void> {
if (!authorized(req)) return unauthorized(res);
if (req.method === 'GET' && req.url === '/v1/capabilities') {
reply(
res,
backend.healthy ? 200 : 503,
Buffer.from(JSON.stringify(capabilities))
);
return;
if (req.method === 'GET') {
if (req.url === '/v1/capabilities') {
reply(
res,
backend.healthy ? 200 : 503,
Buffer.from(JSON.stringify(capabilities))
);
return;
}
if (req.url === '/v1/pdf-page-count/capabilities') {
reply(
res,
backend.healthy ? 200 : 503,
Buffer.from(JSON.stringify({ version: 1, ...pdfPageCount }))
);
return;
}
}
if (req.method !== 'POST' || req.url !== '/v1/extract-text') {
const countPages = req.url === '/v1/pdf-page-count';
if (
req.method !== 'POST' ||
(!countPages && req.url !== '/v1/extract-text')
) {
reply(
res,
404,
Buffer.from('{"error":{"code":"INVALID_REQUEST"}}')
);
return;
}
const maxBytes = countPages
? pdfPageCount.inputBytes
: policy.inputBytes;
let format: Format;
try {
format = requestFormat(req);
format = requestFormat(req, maxBytes, countPages);
} catch (error) {
const code =
error instanceof ExtractionError
Expand Down Expand Up @@ -232,7 +250,7 @@ export function extractionServer(
for await (const chunk of req) {
controller.signal.throwIfAborted();
size += chunk.length;
if (size > policy.inputBytes)
if (size > maxBytes)
throw new ExtractionError('INPUT_LIMIT');
digest.update(chunk);
await file.writeFile(chunk);
Expand All @@ -247,7 +265,8 @@ export function extractionServer(
job,
format,
digest.digest('hex'),
controller.signal
controller.signal,
countPages
);
} catch (error) {
failure = error;
Expand Down
2 changes: 1 addition & 1 deletion packages/extraction/tests/adversarial.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
writer.encrypt('private-test-password')
writer.write(root / 'encrypted.pdf')
writer = PdfWriter()
for index in range(129):
for index in range(601):
writer.add_blank_page(width=10, height=10)
writer.write(root / 'too-many-pages.pdf')
print('Adversarial documents generated')
Expand Down
12 changes: 12 additions & 0 deletions packages/extraction/tests/container-client.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ for (const Authorization of [undefined, `Bearer ${'0'.repeat(64)}`]) {
}
const fixtures = '/tests/fixtures';
const pages = readFileSync(`${fixtures}/pages.pdf`);
const count = await send('pdf', pages, '/v1/pdf-page-count');
assert.equal(count.status, 200);
assert.deepEqual(count.value, {
version: 1,
operation: 'document.pdf-page-count',
inputSha256: createHash('sha256').update(pages).digest('hex'),
pages: 2,
});
const longPdf = readFileSync(`${fixtures}/too-many-pages.pdf`);
const longCount = await send('pdf', longPdf, '/v1/pdf-page-count');
assert.equal(longCount.status, 200);
assert.equal(longCount.value.pages, 601);
const result = await send('pdf', pages);
assert.equal(result.status, 200);
assert.deepEqual(
Expand Down
24 changes: 21 additions & 3 deletions packages/extraction/worker/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import zlib

INPUT_BYTES = 10 * 1024 * 1024
PDF_COUNT_INPUT_BYTES = 32 * 1024 * 1024
TEXT_BYTES = 1024 * 1024
RESULT_BYTES = 3 * 1024 * 1024
EXPANDED_BYTES = 32 * 1024 * 1024
Expand Down Expand Up @@ -472,10 +473,27 @@ def main():
if sys.argv[1] == "probe":
probe()
return
data = open("input", "rb").read(INPUT_BYTES + 1)
if not data or len(data) > INPUT_BYTES:
raise Rejected("INPUT_LIMIT")
mode = sys.argv[1]
limit = PDF_COUNT_INPUT_BYTES if mode == "pdf-page-count" else INPUT_BYTES
with open("input", "rb") as source:
data = source.read(limit + 1)
if not data or len(data) > limit:
raise Rejected("INPUT_LIMIT")
if mode == "pdf-page-count":
from pypdf import PdfReader
if not data.startswith(b"%PDF-"):
raise Rejected("INVALID_DOCUMENT")
reader = PdfReader(io.BytesIO(data), strict=True)
if reader.is_encrypted:
raise Rejected("ENCRYPTED_DOCUMENT")
pages = len(reader.pages)
if pages < 1:
raise Rejected("INVALID_DOCUMENT")
result = {"version": 1, "operation": "document.pdf-page-count",
"inputSha256": hashlib.sha256(data).hexdigest(), "pages": pages}
with open("result", "x", encoding="utf-8") as target:
json.dump(result, target, separators=(",", ":"))
return
if mode == "pdf":
if not data.startswith(b"%PDF-"):
raise Rejected("INVALID_DOCUMENT")
Expand Down
Loading