Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
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.

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>
  • Loading branch information
cjihrig authored and codebytere committed Jun 6, 2018
commit 4bc889d3f4b898687be7f76d140c9194e9f6ad56
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