Skip to content

Commit 751a42a

Browse files
committed
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 <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Benjamin Gruenbaum <[email protected]>
1 parent f8464c8 commit 751a42a

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
@@ -78,6 +78,7 @@ const {
7878
const {
7979
isUint32,
8080
validateAndMaskMode,
81+
validateInteger,
8182
validateInt32,
8283
validateUint32
8384
} = require('internal/validators');
@@ -609,6 +610,7 @@ function truncate(path, len, callback) {
609610
len = 0;
610611
}
611612

613+
validateInteger(len, 'len');
612614
callback = maybeCallback(callback);
613615
fs.open(path, 'r+', function(er, fd) {
614616
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)