Skip to content

Commit 469baa0

Browse files
cjihrigcodebytere
authored andcommitted
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: #21171 PR-URL: #20851 Fixes: #20844 Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]> Backport-PR-URL: #21171 Co-authored-by: Shelley Vohr <[email protected]>
1 parent a0cfb0c commit 469baa0

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

lib/fs.js

+2
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ const {
8585
} = require('internal/constants');
8686
const {
8787
isUint32,
88+
validateInteger,
8889
validateInt32,
8990
validateUint32
9091
} = require('internal/validators');
@@ -746,6 +747,7 @@ fs.truncate = function(path, len, callback) {
746747
len = 0;
747748
}
748749

750+
validateInteger(len, 'len');
749751
callback = maybeCallback(callback);
750752
fs.open(path, 'r+', function(er, fd) {
751753
if (er) return callback(er);

test/parallel/test-fs-truncate.js

+20
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,16 @@ function testFtruncate(cb) {
179179
process.on('exit', () => fs.closeSync(fd));
180180

181181
['', false, null, {}, []].forEach((input) => {
182+
assert.throws(
183+
() => fs.truncate(file5, input, common.mustNotCall()),
184+
{
185+
code: 'ERR_INVALID_ARG_TYPE',
186+
name: 'TypeError [ERR_INVALID_ARG_TYPE]',
187+
message: 'The "len" argument must be of type number. ' +
188+
`Received type ${typeof input}`
189+
}
190+
);
191+
182192
assert.throws(
183193
() => fs.ftruncate(fd, input),
184194
{
@@ -191,6 +201,16 @@ function testFtruncate(cb) {
191201
});
192202

193203
[-1.5, 1.5].forEach((input) => {
204+
assert.throws(
205+
() => fs.truncate(file5, input),
206+
{
207+
code: 'ERR_OUT_OF_RANGE',
208+
name: 'RangeError [ERR_OUT_OF_RANGE]',
209+
message: 'The value of "len" is out of range. It must be ' +
210+
`an integer. Received ${input}`
211+
}
212+
);
213+
194214
assert.throws(
195215
() => fs.ftruncate(fd, input),
196216
{

0 commit comments

Comments
 (0)