From 29882c75050c37a809b12cbcb1c538a4e3b3e1e0 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 | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/vfs.js b/src/vfs.js index a0c4b5b..75c09ba 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,17 +79,23 @@ 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); + onDone(req, res); }); /**