fs: harden filehandle.read(params) typecheck

Make sure that first argument is a nullable object

Co-authored-by: Antoine du Hamel <duhamelantoine1995@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/42772
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
LiviaMedeiros 2022-04-18 19:05:51 +08:00 committed by Node.js GitHub Bot
parent 53633c033d
commit 29953a0b88
2 changed files with 16 additions and 2 deletions

View file

@ -77,6 +77,7 @@ const {
validateBuffer, validateBuffer,
validateEncoding, validateEncoding,
validateInteger, validateInteger,
validateObject,
validateString, validateString,
} = require('internal/validators'); } = require('internal/validators');
const pathModule = require('path'); const pathModule = require('path');
@ -517,6 +518,9 @@ async function read(handle, bufferOrParams, offset, length, position) {
let buffer = bufferOrParams; let buffer = bufferOrParams;
if (!isArrayBufferView(buffer)) { if (!isArrayBufferView(buffer)) {
// This is fh.read(params) // This is fh.read(params)
if (bufferOrParams !== undefined) {
validateObject(bufferOrParams, 'options', { nullable: true });
}
({ ({
buffer = Buffer.alloc(16384), buffer = Buffer.alloc(16384),
offset = 0, offset = 0,

View file

@ -153,14 +153,24 @@ async function executeOnHandle(dest, func) {
}); });
} }
// Use fallback buffer allocation when input not buffer // Use fallback buffer allocation when first argument is null
{ {
await executeOnHandle(dest, async (handle) => { await executeOnHandle(dest, async (handle) => {
const ret = await handle.read(0, 0, 0, 0); const ret = await handle.read(null, 0, 0, 0);
assert.strictEqual(ret.buffer.length, 16384); assert.strictEqual(ret.buffer.length, 16384);
}); });
} }
// TypeError if buffer is not ArrayBufferView or nullable object
{
await executeOnHandle(dest, async (handle) => {
await assert.rejects(
async () => handle.read(0, 0, 0, 0),
{ code: 'ERR_INVALID_ARG_TYPE' }
);
});
}
// Bytes written to file match buffer // Bytes written to file match buffer
{ {
await executeOnHandle(dest, async (handle) => { await executeOnHandle(dest, async (handle) => {