From 469baa062ead2e44ab78405eb7b3bae75102caf7 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Sun, 20 May 2018 11:36:40 -0400 Subject: [PATCH] fs: add length validation to fs.truncate() This commit adds validation to the length parameter of fs.truncate(). Prior to this commit, passing a non-number would trigger a CHECK() in the binding layer. Backport-PR-URL: https://github.com/nodejs/node/pull/21171 PR-URL: https://github.com/nodejs/node/pull/20851 Fixes: https://github.com/nodejs/node/issues/20844 Reviewed-By: Ruben Bridgewater Reviewed-By: James M Snell Reviewed-By: Benjamin Gruenbaum Backport-PR-URL: https://github.com/nodejs/node/pull/21171 Co-authored-by: Shelley Vohr --- lib/fs.js | 2 ++ test/parallel/test-fs-truncate.js | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/lib/fs.js b/lib/fs.js index 7b05750307c118..cc559a898dc4ea 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -85,6 +85,7 @@ const { } = require('internal/constants'); const { isUint32, + validateInteger, validateInt32, validateUint32 } = require('internal/validators'); @@ -746,6 +747,7 @@ fs.truncate = function(path, len, callback) { len = 0; } + validateInteger(len, 'len'); callback = maybeCallback(callback); fs.open(path, 'r+', function(er, fd) { if (er) return callback(er); diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index 2f8839583202d0..347cc0e10492d6 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -179,6 +179,16 @@ function testFtruncate(cb) { process.on('exit', () => fs.closeSync(fd)); ['', false, null, {}, []].forEach((input) => { + assert.throws( + () => fs.truncate(file5, input, common.mustNotCall()), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError [ERR_INVALID_ARG_TYPE]', + message: 'The "len" argument must be of type number. ' + + `Received type ${typeof input}` + } + ); + assert.throws( () => fs.ftruncate(fd, input), { @@ -191,6 +201,16 @@ function testFtruncate(cb) { }); [-1.5, 1.5].forEach((input) => { + assert.throws( + () => fs.truncate(file5, input), + { + code: 'ERR_OUT_OF_RANGE', + name: 'RangeError [ERR_OUT_OF_RANGE]', + message: 'The value of "len" is out of range. It must be ' + + `an integer. Received ${input}` + } + ); + assert.throws( () => fs.ftruncate(fd, input), {