From 007f797b5aa02915dcb1fa400c54acacbfc27b22 Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Fri, 13 Nov 2026 17:55:04 -0300 Subject: [PATCH 1/5] fix: isolate PDF compression arguments and output paths --- .github/workflows/test.yml | 20 ++++++ README.md | 5 ++ package.json | 3 +- pdf-service.js | 30 ++++++-- test/request-safety.test.js | 137 ++++++++++++++++++++++++++++++++++++ 5 files changed, 187 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/test.yml create mode 100644 test/request-safety.test.js diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..72060c4 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,20 @@ +name: Request safety tests + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: '24' + # Route tests stub Chromium and external processes; no dependency install needed. + - run: npm test diff --git a/README.md b/README.md index 30666a9..80e262e 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,9 @@ file_put_contents('path/to/my/super-kool.pdf', $pdf); * You can see all these `options` in [puppeteer docs](https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pagepdfoptions) +* The output file path is generated by the service; an `options.path` value is ignored. +* `compressionResolution` accepts a positive integer (including a numeric form-field string), defaulting to `100`. Invalid HTML, JSON options, or compression resolution returns HTTP 400. + ## Getting started on developing locally this microservice To get started with development locally (using [`kool`](https://github.com/kool-dev/kool), of course!): @@ -52,6 +55,8 @@ To get started with development locally (using [`kool`](https://github.com/kool- In order to manage dependencies and run commands, please remind of using `kool run yarn` to stick with one single yarn version. +Run `npm test` with Node.js 24+ for offline request-safety regression tests. These exercise the real route with Chromium, filesystem writes, and external commands stubbed; they do not replace a real PDF-generation smoke test. + ## Roadmap Soon to be added wishes: diff --git a/package.json b/package.json index c4981eb..04ce087 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "scripts": { - "start": "node pdf-service.js" + "start": "node pdf-service.js", + "test": "node --test" }, "dependencies": { "body-parser": "^1.19.0", diff --git a/pdf-service.js b/pdf-service.js index 7107824..c09e87c 100644 --- a/pdf-service.js +++ b/pdf-service.js @@ -6,7 +6,7 @@ const crypto = require('crypto'); const app = express(); const bodyParser = require('body-parser'); const compression = require('compression'); -const { exec } = require('child_process'); +const { execFile } = require('child_process'); app.use(compression()); app.use(bodyParser.urlencoded({ @@ -46,9 +46,25 @@ app.post('/from-html', async (req, res) => { calls.fromHtml++; const html = req.body.html; + if (typeof html !== 'string') { + deliverJson(res, {msg: 'html must be a string'}, 400); + return; + } const disableCompression = req.body.disableCompression || false; - const compressionResolution = req.body.compressionResolution || 100; - const options = getPdfOptions(req.body.options); + const compressionResolution = req.body.compressionResolution ?? 100; + const resolution = Number(compressionResolution); + if (!['number', 'string'].includes(typeof compressionResolution) || + !Number.isInteger(resolution) || resolution <= 0) { + deliverJson(res, {msg: 'compressionResolution must be a positive integer'}, 400); + return; + } + let options; + try { + options = getPdfOptions(req.body.options); + } catch (err) { + deliverJson(res, {msg: 'options must be a JSON object'}, 400); + return; + } const htmlFile = generateFileName() + '.html'; const fullHtmlPath = path.join(storagePath, htmlFile); @@ -72,9 +88,7 @@ app.post('/from-html', async (req, res) => { deliverPdfFile(res, pdfFilePath); } else { // compress PDF outoput - const cmd = `shinkpdf -o ${compressedFilePath} -r ${compressionResolution} ${pdfFilePath}`; - - exec(cmd, (err, stdout, stderr) => { + execFile('shinkpdf', ['-o', compressedFilePath, '-r', String(resolution), pdfFilePath], (err, stdout, stderr) => { if (err) { console.log('Compressing - err:', err); } @@ -190,11 +204,13 @@ function getPdfOptions(options) { } const parsedOptions = JSON.parse(options); + if (parsedOptions === null || typeof parsedOptions !== 'object' || Array.isArray(parsedOptions)) { + throw new Error('options must be a JSON object'); + } let mappedOptions = {}; [ - 'path', 'scale', 'displayHeaderFooter', 'headerTemplate', diff --git a/test/request-safety.test.js b/test/request-safety.test.js new file mode 100644 index 0000000..20f968e --- /dev/null +++ b/test/request-safety.test.js @@ -0,0 +1,137 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const source = fs.readFileSync(path.join(__dirname, '../pdf-service.js'), 'utf8'); + +// Exercise the actual route without a network listener, Chromium, or filesystem writes. +async function service() { + const routes = {}; + const writes = []; + const pdfs = []; + const commands = []; + const removals = []; + const app = { + use() {}, + get(route, handler) { routes[route] = handler; }, + post(route, handler) { routes[route] = handler; }, + listen(port, callback) { callback(); }, + }; + const modules = { + express: () => app, + compression: () => () => {}, + 'body-parser': { urlencoded: () => () => {}, json: () => () => {} }, + puppeteer: { + launch: async () => ({ + newPage: async () => ({ + emulateMediaType: async () => {}, + setViewport: async () => {}, + goto: async () => {}, + pdf: async (options) => { pdfs.push(options); }, + close() {}, + }), + }), + }, + fs: { + existsSync: () => true, + writeFileSync: (...args) => { writes.push(args); }, + unlinkSync: (filename) => { removals.push(filename); }, + }, + child_process: { + execFile: (file, args, callback) => { + commands.push({ file, args: Array.from(args) }); + callback(null, '', ''); + }, + exec: () => { assert.fail('request must not invoke a shell'); }, + }, + }; + vm.runInNewContext(source, { + require: (name) => Object.hasOwn(modules, name) ? modules[name] : require(name), + __dirname: path.resolve(__dirname, '..'), + process: { env: {} }, + console: { log() {} }, + }); + await new Promise(setImmediate); + + async function request(body) { + const response = { + statusCode: 200, + status(code) { this.statusCode = code; return this; }, + contentType() { return this; }, + send(body) { this.body = body; return this; }, + sendFile(filename, options, callback) { + this.file = filename; + callback(); + }, + }; + await routes['/from-html']({ body, query: {} }, response); + return response; + } + return { request, writes, pdfs, commands, removals }; +} + +test('compression uses fixed executable and separate arguments', async () => { + for (const resolution of [undefined, 150, '150']) { + const app = await service(); + const response = await app.request({ html: '

PDF

', compressionResolution: resolution }); + assert.equal(response.statusCode, 200); + assert.equal(app.commands.length, 1); + const command = app.commands[0]; + assert.equal(command.file, 'shinkpdf'); + assert.deepEqual(command.args, [ + '-o', `${app.pdfs[0].path}_compressed.pdf`, + '-r', resolution === undefined ? '100' : '150', app.pdfs[0].path, + ]); + assert.equal(response.file, command.args[1]); + } +}); + +test('invalid compression input is rejected before files or commands', async () => { + for (const resolution of ['100; echo unexpected', '100 extra', '', 0, -1, 1.5, {}, [], true, 'Infinity']) { + const app = await service(); + const response = await app.request({ html: '

PDF

', compressionResolution: resolution }); + assert.equal(response.statusCode, 400); + assert.equal(app.writes.length, 0); + assert.equal(app.pdfs.length, 0); + assert.equal(app.commands.length, 0); + } +}); + +test('caller cannot override generated output path', async () => { + const app = await service(); + const response = await app.request({ + html: '

PDF

', + disableCompression: true, + options: JSON.stringify({ path: '/outside/storage.pdf', format: 'Letter', landscape: true }), + }); + assert.equal(response.statusCode, 200); + assert.equal(app.pdfs[0].format, 'Letter'); + assert.equal(app.pdfs[0].landscape, true); + assert.equal(path.dirname(app.pdfs[0].path), path.resolve(__dirname, '../storage')); + assert.equal(response.file, app.pdfs[0].path); + assert.equal(app.commands.length, 0); + assert.ok(app.removals.includes(app.pdfs[0].path)); +}); + +test('invalid options return a client error before side effects', async () => { + for (const options of ['{', 'null', 'true', '42', '[]']) { + const app = await service(); + const response = await app.request({ html: '

PDF

', options }); + assert.equal(response.statusCode, 400); + assert.equal(app.writes.length, 0); + assert.equal(app.commands.length, 0); + } +}); + +test('missing or non-string HTML returns a client error', async () => { + for (const html of [undefined, null, {}, [], 42]) { + const app = await service(); + const response = await app.request({ html }); + assert.equal(response.statusCode, 400); + assert.equal(app.writes.length, 0); + assert.equal(app.pdfs.length, 0); + assert.equal(app.commands.length, 0); + } +}); From 5f127cc08713ec3632fcb1294dbcadc082220639 Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Fri, 13 Nov 2026 17:57:26 -0300 Subject: [PATCH 2/5] docs: clarify PDF service deployment trust boundary --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 80e262e..d50e023 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,10 @@ PDF generation micro-service. Super easy to add on `kool` and `docker-compose` based environments, for generating PDFs from any URLs or given HTML content. +## Deployment security + +This service has no authentication and renders caller-provided URLs and active HTML. Keep it on a private network or behind an authenticated gateway, restrict outbound network access, and do not expose it directly to untrusted users. Chromium currently launches with `--no-sandbox`; request validation is not a substitute for process/network isolation or maintained browser dependencies. + ## Getting started using this microservice in your project If you use Docker Compose (hopefully with [`kool`](https://github.com/kool-dev/kool) to make things simpler) you can get PDF generation on your project with a few simple steps: From ab6dac888b9ba8c69fdb2b0e4b4c39c720d39144 Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Fri, 13 Nov 2026 17:58:35 -0300 Subject: [PATCH 3/5] fix: validate PDF resolution before numeric conversion --- pdf-service.js | 7 +++++-- test/request-safety.test.js | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/pdf-service.js b/pdf-service.js index c09e87c..eb00846 100644 --- a/pdf-service.js +++ b/pdf-service.js @@ -52,9 +52,12 @@ app.post('/from-html', async (req, res) => { } const disableCompression = req.body.disableCompression || false; const compressionResolution = req.body.compressionResolution ?? 100; + if (!['number', 'string'].includes(typeof compressionResolution)) { + deliverJson(res, {msg: 'compressionResolution must be a positive integer'}, 400); + return; + } const resolution = Number(compressionResolution); - if (!['number', 'string'].includes(typeof compressionResolution) || - !Number.isInteger(resolution) || resolution <= 0) { + if (!Number.isSafeInteger(resolution) || resolution <= 0) { deliverJson(res, {msg: 'compressionResolution must be a positive integer'}, 400); return; } diff --git a/test/request-safety.test.js b/test/request-safety.test.js index 20f968e..baf4508 100644 --- a/test/request-safety.test.js +++ b/test/request-safety.test.js @@ -89,7 +89,8 @@ test('compression uses fixed executable and separate arguments', async () => { }); test('invalid compression input is rejected before files or commands', async () => { - for (const resolution of ['100; echo unexpected', '100 extra', '', 0, -1, 1.5, {}, [], true, 'Infinity']) { + for (const resolution of ['100; echo unexpected', '100 extra', '', 0, -1, 1.5, + {}, { toString: null, valueOf: null }, [], true, 'Infinity', '9007199254740992']) { const app = await service(); const response = await app.request({ html: '

PDF

', compressionResolution: resolution }); assert.equal(response.statusCode, 400); From 8571f9551a6f494c2bd672507a6aae1fde73de5c Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Fri, 13 Nov 2026 18:02:47 -0300 Subject: [PATCH 4/5] test: cover asynchronous PDF compression fallback --- README.md | 2 +- test/request-safety.test.js | 39 ++++++++++++++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d50e023..e68089c 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ file_put_contents('path/to/my/super-kool.pdf', $pdf); * You can see all these `options` in [puppeteer docs](https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pagepdfoptions) * The output file path is generated by the service; an `options.path` value is ignored. -* `compressionResolution` accepts a positive integer (including a numeric form-field string), defaulting to `100`. Invalid HTML, JSON options, or compression resolution returns HTTP 400. +* `compressionResolution` accepts a positive safe integer (including a numeric form-field string), defaulting to `100`. Non-string HTML, malformed JSON option strings, parsed non-object JSON options, or invalid compression resolution returns HTTP 400. As before, non-string `options` values are ignored. ## Getting started on developing locally this microservice diff --git a/test/request-safety.test.js b/test/request-safety.test.js index baf4508..a0b4d92 100644 --- a/test/request-safety.test.js +++ b/test/request-safety.test.js @@ -7,7 +7,7 @@ const vm = require('node:vm'); const source = fs.readFileSync(path.join(__dirname, '../pdf-service.js'), 'utf8'); // Exercise the actual route without a network listener, Chromium, or filesystem writes. -async function service() { +async function service({ compressionError = null, asynchronousCompression = false } = {}) { const routes = {}; const writes = []; const pdfs = []; @@ -42,7 +42,11 @@ async function service() { child_process: { execFile: (file, args, callback) => { commands.push({ file, args: Array.from(args) }); - callback(null, '', ''); + if (asynchronousCompression) { + setImmediate(() => callback(compressionError, '', '')); + } else { + callback(compressionError, '', ''); + } }, exec: () => { assert.fail('request must not invoke a shell'); }, }, @@ -56,14 +60,18 @@ async function service() { await new Promise(setImmediate); async function request(body) { + let delivered; + const done = new Promise(resolve => { delivered = resolve; }); const response = { + done, statusCode: 200, status(code) { this.statusCode = code; return this; }, contentType() { return this; }, - send(body) { this.body = body; return this; }, + send(body) { this.body = body; delivered(); return this; }, sendFile(filename, options, callback) { this.file = filename; callback(); + delivered(); }, }; await routes['/from-html']({ body, query: {} }, response); @@ -136,3 +144,28 @@ test('missing or non-string HTML returns a client error', async () => { assert.equal(app.commands.length, 0); } }); + +test('asynchronous compression success and failure deliver and clean up', { timeout: 2000 }, async () => { + for (const compressionError of [null, new Error('compression failed')]) { + const app = await service({ compressionError, asynchronousCompression: true }); + const response = await app.request({ html: '

PDF

' }); + assert.equal(response.file, undefined); + await response.done; + const original = app.pdfs[0].path; + const compressed = `${original}_compressed.pdf`; + assert.equal(response.statusCode, 200); + assert.equal(response.file, compressionError ? original : compressed); + assert.equal(app.removals.filter(filename => filename === original).length, 1); + assert.equal(app.removals.includes(compressed), !compressionError); + assert.ok(app.removals.some(filename => filename.endsWith('.html'))); + } +}); + +test('non-string options retain the legacy ignored-options behavior', async () => { + for (const options of [{}, [], 42]) { + const app = await service(); + const response = await app.request({ html: '

PDF

', options }); + assert.equal(response.statusCode, 200); + assert.equal(app.pdfs[0].format, 'A4'); + } +}); From 20c966e8b5f6112c8b294c39c70371d3afd27de3 Mon Sep 17 00:00:00 2001 From: Daniel Polito Date: Fri, 13 Nov 2026 18:04:03 -0300 Subject: [PATCH 5/5] ci: avoid duplicate PDF test runs on pull requests --- .github/workflows/test.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 72060c4..6f31f64 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,6 +2,7 @@ name: Request safety tests on: push: + branches: [master] pull_request: workflow_dispatch: