Skip to content

Commit b08601b

Browse files
BridgeARBethGriggs
authored andcommitted
util: fix inspection of errors with tampered name or stack property
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>
1 parent 49c6c37 commit b08601b

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

lib/internal/util/inspect.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -904,12 +904,12 @@ function getFunctionBase(value, constructor, tag) {
904904
}
905905

906906
function formatError(err, constructor, tag, ctx) {
907-
let stack = err.stack || ErrorPrototype.toString(err);
907+
const name = err.name != null ? String(err.name) : 'Error';
908+
let len = name.length;
909+
let stack = err.stack ? String(err.stack) : ErrorPrototype.toString(err);
908910

909911
// A stack trace may contain arbitrary data. Only manipulate the output
910912
// for "regular errors" (errors that "look normal") for now.
911-
const name = err.name || 'Error';
912-
let len = name.length;
913913
if (constructor === null ||
914914
(name.endsWith('Error') &&
915915
stack.startsWith(name) &&

test/parallel/test-util-inspect.js

+29
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,35 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324');
690690
);
691691
}
692692

693+
// Tampered error stack or name property (different type than string).
694+
// Note: Symbols are not supported by `Error#toString()` which is called by
695+
// accessing the `stack` property.
696+
[
697+
[404, '404: foo', '[404]'],
698+
[0, '0: foo', '[RangeError: foo]'],
699+
[0n, '0: foo', '[RangeError: foo]'],
700+
[null, 'null: foo', '[RangeError: foo]'],
701+
[undefined, 'RangeError: foo', '[RangeError: foo]'],
702+
[false, 'false: foo', '[RangeError: foo]'],
703+
['', 'foo', '[RangeError: foo]'],
704+
[[1, 2, 3], '1,2,3: foo', '[1,2,3]'],
705+
].forEach(([value, outputStart, stack]) => {
706+
let err = new RangeError('foo');
707+
err.name = value;
708+
assert(
709+
util.inspect(err).startsWith(outputStart),
710+
util.format(
711+
'The name set to %o did not result in the expected output "%s"',
712+
value,
713+
outputStart
714+
)
715+
);
716+
717+
err = new RangeError('foo');
718+
err.stack = value;
719+
assert.strictEqual(util.inspect(err), stack);
720+
});
721+
693722
// https://github.com/nodejs/node-v0.x-archive/issues/1941
694723
assert.strictEqual(util.inspect(Object.create(Date.prototype)), 'Date {}');
695724

0 commit comments

Comments
 (0)