From 1847696f4b6284bad45f452bc8595927074118dc Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 5 Feb 2019 15:41:18 -0800 Subject: [PATCH] util: protect against monkeypatched Object prototype for inspect() Prevent affects of monkeypatching (for example) Object.keys() when calling util.inspect(). PR-URL: https://github.com/nodejs/node/pull/25953 Reviewed-By: Anna Henningsen Reviewed-By: Joyee Cheung Reviewed-By: Colin Ihrig --- lib/internal/util/inspect.js | 15 ++++++++------- .../test-util-primordial-monkeypatching.js | 11 +++++++++++ 2 files changed, 19 insertions(+), 7 deletions(-) create mode 100644 test/parallel/test-util-primordial-monkeypatching.js diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 0f81ab5d0296e9..94d6ef8706f7f3 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -63,6 +63,11 @@ const { isBigUint64Array } = require('internal/util/types'); +const assert = require('internal/assert'); + +// Avoid monkey-patched built-ins. +const { Object } = primordials; + const ReflectApply = Reflect.apply; // This function is borrowed from the function with the same name on V8 Extras' @@ -383,13 +388,9 @@ function getKeys(value, showHidden) { try { keys = Object.keys(value); } catch (err) { - if (isNativeError(err) && - err.name === 'ReferenceError' && - isModuleNamespaceObject(value)) { - keys = Object.getOwnPropertyNames(value); - } else { - throw err; - } + assert(isNativeError(err) && err.name === 'ReferenceError' && + isModuleNamespaceObject(value)); + keys = Object.getOwnPropertyNames(value); } if (symbols.length !== 0) { keys.push(...symbols.filter((key) => propertyIsEnumerable(value, key))); diff --git a/test/parallel/test-util-primordial-monkeypatching.js b/test/parallel/test-util-primordial-monkeypatching.js new file mode 100644 index 00000000000000..bf282a12122872 --- /dev/null +++ b/test/parallel/test-util-primordial-monkeypatching.js @@ -0,0 +1,11 @@ +'use strict'; + +// Monkeypatch Object.keys() so that it throws an unexpected error. This tests +// that `util.inspect()` is unaffected by monkey-patching `Object`. + +require('../common'); +const assert = require('assert'); +const util = require('util'); + +Object.keys = () => { throw new Error('fhqwhgads'); }; +assert.strictEqual(util.inspect({}), '{}');