Skip to content

Commit

Permalink
buffer: stricter Buffer.isBuffer
Browse files Browse the repository at this point in the history
Make "fake" Buffer subclasses whose instances are not valid Uint8Arrays
fail the test.

Fixes: nodejs#11954
  • Loading branch information
TimothyGu committed Sep 21, 2017
1 parent 2eab4f8 commit ee2d44a
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,14 @@ function fromObject(obj) {
// Static methods

Buffer.isBuffer = function isBuffer(b) {
return b instanceof Buffer;
if (!isUint8Array(b))
return false;
// Subclassing Buffer is not officially supported currently, and actually
// subclassing it requires some awkward code that users are unlikely to do.
// Therefore prioritize the fast case over the full `instanceof`.
// Refs: https://github.com/nodejs/node/issues/9531#issuecomment-265611061
const proto = Object.getPrototypeOf(b);
return proto === Buffer.prototype || proto instanceof Buffer.prototype;
};


Expand Down
31 changes: 31 additions & 0 deletions test/parallel/test-buffer-isbuffer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use strict';
require('../common');
const assert = require('assert');
const { Buffer } = require('buffer');

const t = (val, exp) => assert.strictEqual(Buffer.isBuffer(val), exp);

function FakeBuffer() {}
FakeBuffer.prototype = Object.create(Buffer.prototype);

class ExtensibleBuffer extends Buffer {
constructor() {
super(new ArrayBuffer(0), 0, 0);
Object.setPrototypeOf(this, new.target.prototype);
}
}

t(0, false);
t(true, false);
t('foo', false);
t(Symbol(), false);
t(null, false);
t(undefined, false);
t(() => {}, false);

t({}, false);
t(new Uint8Array(2), false);
t(new FakeBuffer(), false);
t(new ExtensibleBuffer(), true);
t(Buffer.from('foo'), true);
t(Buffer.allocUnsafeSlow(2), true);
1 change: 1 addition & 0 deletions test/parallel/test-util.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ assert.strictEqual(true, util.isPrimitive(NaN));
assert.strictEqual(true, util.isPrimitive(Symbol('symbol')));

// isBuffer
assert.strictEqual(util.isBuffer, Buffer.isBuffer);
assert.strictEqual(false, util.isBuffer('foo'));
assert.strictEqual(true, util.isBuffer(Buffer.from('foo')));

Expand Down

0 comments on commit ee2d44a

Please sign in to comment.