diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..6f31f64 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,21 @@ +name: Request safety tests + +on: + push: + branches: [master] + 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..e68089c 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: @@ -40,6 +44,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 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 To get started with development locally (using [`kool`](https://github.com/kool-dev/kool), of course!): @@ -52,6 +59,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..eb00846 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,28 @@ 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; + if (!['number', 'string'].includes(typeof compressionResolution)) { + deliverJson(res, {msg: 'compressionResolution must be a positive integer'}, 400); + return; + } + const resolution = Number(compressionResolution); + if (!Number.isSafeInteger(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 +91,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 +207,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..a0b4d92 --- /dev/null +++ b/test/request-safety.test.js @@ -0,0 +1,171 @@ +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({ compressionError = null, asynchronousCompression = false } = {}) { + 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) }); + if (asynchronousCompression) { + setImmediate(() => callback(compressionError, '', '')); + } else { + callback(compressionError, '', ''); + } + }, + 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) { + 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; delivered(); return this; }, + sendFile(filename, options, callback) { + this.file = filename; + callback(); + delivered(); + }, + }; + 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: '