Skip to content

Commit

Permalink
util: fix inspection of errors with tampered name or stack property
Browse files Browse the repository at this point in the history
This makes sure that `util.inspect()` does not throw while inspecting
errors that have the name or stack property set to a different type
than string.

Fixes: #30572

PR-URL: #30576
Reviewed-By: David Carlier <devnexen@gmail.com>
Reviewed-By: Anto Aravinth <anto.aravinth.cse@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
  • Loading branch information
BridgeAR authored and targos committed Dec 1, 2019
1 parent 5ef4dce commit 1040e72
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -932,12 +932,12 @@ function getFunctionBase(value, constructor, tag) {
}

function formatError(err, constructor, tag, ctx) {
let stack = err.stack || ErrorPrototypeToString(err);
const name = err.name != null ? String(err.name) : 'Error';
let len = name.length;
let stack = err.stack ? String(err.stack) : ErrorPrototypeToString(err);

// A stack trace may contain arbitrary data. Only manipulate the output
// for "regular errors" (errors that "look normal") for now.
const name = err.name || 'Error';
let len = name.length;
if (constructor === null ||
(name.endsWith('Error') &&
stack.startsWith(name) &&
Expand Down
29 changes: 29 additions & 0 deletions test/parallel/test-util-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,35 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
);
}

// Tampered error stack or name property (different type than string).
// Note: Symbols are not supported by `Error#toString()` which is called by
// accessing the `stack` property.
[
[404, '404: foo', '[404]'],
[0, '0: foo', '[RangeError: foo]'],
[0n, '0: foo', '[RangeError: foo]'],
[null, 'null: foo', '[RangeError: foo]'],
[undefined, 'RangeError: foo', '[RangeError: foo]'],
[false, 'false: foo', '[RangeError: foo]'],
['', 'foo', '[RangeError: foo]'],
[[1, 2, 3], '1,2,3: foo', '[1,2,3]'],
].forEach(([value, outputStart, stack]) => {
let err = new RangeError('foo');
err.name = value;
assert(
util.inspect(err).startsWith(outputStart),
util.format(
'The name set to %o did not result in the expected output "%s"',
value,
outputStart
)
);

err = new RangeError('foo');
err.stack = value;
assert.strictEqual(util.inspect(err), stack);
});

// https://github.com/nodejs/node-v0.x-archive/issues/1941
assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}');

Expand Down

0 comments on commit 1040e72

Please sign in to comment.