From f763ac7dd09c33b071fcfb2c5a1e5438028ef0a1 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 13 Aug 2018 20:13:30 +0200 Subject: [PATCH] util: escape symbol and non-enumerable keys These keys require escaping as they might also contain line breaks and other special characters. PR-URL: https://github.com/nodejs/node/pull/22300 Reviewed-By: James M Snell Reviewed-By: Benjamin Gruenbaum Reviewed-By: Matteo Collina --- lib/util.js | 5 +++-- test/parallel/test-util-inspect.js | 20 +++++++++++++++----- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/lib/util.js b/lib/util.js index 501bc953ed3554..d9306643a9c216 100644 --- a/lib/util.js +++ b/lib/util.js @@ -1208,9 +1208,10 @@ function formatProperty(ctx, value, recurseTimes, key, array) { return str; } if (typeof key === 'symbol') { - name = `[${ctx.stylize(key.toString(), 'symbol')}]`; + const tmp = key.toString().replace(strEscapeSequencesReplacer, escapeFn); + name = `[${ctx.stylize(tmp, 'symbol')}]`; } else if (desc.enumerable === false) { - name = `[${key}]`; + name = `[${key.replace(strEscapeSequencesReplacer, escapeFn)}]`; } else if (keyStrRegExp.test(key)) { name = ctx.stylize(key, 'name'); } else { diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 4e7f9ff055398a..e948b9861ba908 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -890,22 +890,22 @@ if (typeof Symbol !== 'undefined') { const options = { showHidden: true }; let subject = {}; - subject[Symbol('symbol')] = 42; + subject[Symbol('sym\nbol')] = 42; - assert.strictEqual(util.inspect(subject), '{ [Symbol(symbol)]: 42 }'); + assert.strictEqual(util.inspect(subject), '{ [Symbol(sym\\nbol)]: 42 }'); assert.strictEqual( util.inspect(subject, options), - '{ [Symbol(symbol)]: 42 }' + '{ [Symbol(sym\\nbol)]: 42 }' ); Object.defineProperty( subject, Symbol(), { enumerable: false, value: 'non-enum' }); - assert.strictEqual(util.inspect(subject), '{ [Symbol(symbol)]: 42 }'); + assert.strictEqual(util.inspect(subject), '{ [Symbol(sym\\nbol)]: 42 }'); assert.strictEqual( util.inspect(subject, options), - "{ [Symbol(symbol)]: 42, [Symbol()]: 'non-enum' }" + "{ [Symbol(sym\\nbol)]: 42, [Symbol()]: 'non-enum' }" ); subject = [1, 2, 3]; @@ -1678,3 +1678,13 @@ util.inspect(process); assert.strictEqual(inspect(1n), '1n'); assert.strictEqual(inspect(Object(-1n)), '[BigInt: -1n]'); assert.strictEqual(inspect(Object(13n)), '[BigInt: 13n]'); + +// Verify non-enumerable keys get escaped. +{ + const obj = {}; + Object.defineProperty(obj, 'Non\nenumerable\tkey', { value: true }); + assert.strictEqual( + util.inspect(obj, { showHidden: true }), + '{ [Non\\nenumerable\\tkey]: true }' + ); +}