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
21 changes: 21 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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!):
Expand All @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"scripts": {
"start": "node pdf-service.js"
"start": "node pdf-service.js",
"test": "node --test"
},
"dependencies": {
"body-parser": "^1.19.0",
Expand Down
33 changes: 26 additions & 7 deletions pdf-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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);

Expand All @@ -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);
}
Expand Down Expand Up @@ -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',
Expand Down
171 changes: 171 additions & 0 deletions test/request-safety.test.js
Original file line number Diff line number Diff line change
@@ -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: '<h1>PDF</h1>', 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,
{}, { toString: null, valueOf: null }, [], true, 'Infinity', '9007199254740992']) {
const app = await service();
const response = await app.request({ html: '<h1>PDF</h1>', 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: '<h1>PDF</h1>',
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: '<h1>PDF</h1>', 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);
}
});

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: '<h1>PDF</h1>' });
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: '<h1>PDF</h1>', options });
assert.equal(response.statusCode, 200);
assert.equal(app.pdfs[0].format, 'A4');
}
});
Loading