Skip to content

Commit

Permalink
fs: add length validation to fs.truncate()
Browse files Browse the repository at this point in the history
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: #21171
PR-URL: #20851
Fixes: #20844
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>

Backport-PR-URL: #21171
Co-authored-by: Shelley Vohr <shelley.vohr@gmail.com>
  • Loading branch information
2 people authored and targos committed Jun 6, 2018
1 parent e94231e commit 56e5336
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ const {
} = require('internal/constants');
const {
isUint32,
validateInteger,
validateInt32,
validateUint32
} = require('internal/validators');
Expand Down Expand Up @@ -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);
Expand Down
20 changes: 20 additions & 0 deletions test/parallel/test-fs-truncate.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
{
Expand All @@ -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),
{
Expand Down

0 comments on commit 56e5336

Please sign in to comment.