From ff816d21ebeb370d96ed9ca522cf2dbfa9c8a5cf Mon Sep 17 00:00:00 2001 From: Anders Evenrud Date: Thu, 28 Dec 2023 21:34:51 +0100 Subject: [PATCH] fix(vfs): race condition on temp file cleanup There was a race condition relating to streams in the VFS pipeline that could lead to unhandled rejection whenever a cleanup is performed on an endpoint with pre-check errors (like readonly). --- src/vfs.js | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/vfs.js b/src/vfs.js index a0c4b5b..98f9a1c 100644 --- a/src/vfs.js +++ b/src/vfs.js @@ -64,7 +64,11 @@ const parseRangeHeader = (range, size) => { const onDone = (req, res) => { if (req.files) { for (let fieldname in req.files) { - fs.unlink(req.files[fieldname].path, () => ({})); + try { + fs.removeSync(req.files[fieldname].path); + } catch (e) { + console.warn('Failed to unlink temporary file', e); + } } } }; @@ -75,16 +79,21 @@ const onDone = (req, res) => { const wrapper = fn => (req, res, next) => fn(req, res) .then(result => { if (result instanceof Stream) { + result.on('error', error => { + next(error); + }); + + result.on('end', () => { + onDone(req, res); + }); + result.pipe(res); } else { res.json(result); + onDone(req, res); } - - onDone(req, res); }) .catch(error => { - onDone(req, res); - next(error); });