Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
assert: use stricter stack frame detection in .ifError()
This makes sure arbitrary stack traces are not handled as stack
frames.

Signed-off-by: Ruben Bridgewater <ruben@bridgewater.de>
  • Loading branch information
BridgeAR committed Nov 28, 2021
commit 55445c1e0ef85023f31bc20f87d92b51fe17776c
32 changes: 19 additions & 13 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -966,21 +966,27 @@ assert.ifError = function ifError(err) {
// This will remove any duplicated frames from the error frames taken
// from within `ifError` and add the original error frames to the newly
// created ones.
const tmp2 = StringPrototypeSplit(origStack, '\n');
ArrayPrototypeShift(tmp2);
// Filter all frames existing in err.stack.
let tmp1 = StringPrototypeSplit(newErr.stack, '\n');
for (const errFrame of tmp2) {
// Find the first occurrence of the frame.
const pos = ArrayPrototypeIndexOf(tmp1, errFrame);
if (pos !== -1) {
// Only keep new frames.
tmp1 = ArrayPrototypeSlice(tmp1, 0, pos);
break;
const origStackStart = origStack.indexOf('\n at');
Comment thread
BridgeAR marked this conversation as resolved.
if (origStackStart !== -1) {
const originalFrames = StringPrototypeSplit(
origStack.slice(origStackStart + 1),
'\n'
);
// Filter all frames existing in err.stack.
let newFrames = StringPrototypeSplit(newErr.stack, '\n');
for (const errFrame of originalFrames) {
// Find the first occurrence of the frame.
const pos = ArrayPrototypeIndexOf(newFrames, errFrame);
if (pos !== -1) {
// Only keep new frames.
newFrames = ArrayPrototypeSlice(newFrames, 0, pos);
break;
}
}
const stackStart = ArrayPrototypeJoin(newFrames, '\n');
const stackEnd = ArrayPrototypeJoin(originalFrames, '\n');
newErr.stack = `${stackStart}\n${stackEnd}`;
}
newErr.stack =
`${ArrayPrototypeJoin(tmp1, '\n')}\n${ArrayPrototypeJoin(tmp2, '\n')}`;
}

throw newErr;
Expand Down
12 changes: 12 additions & 0 deletions test/parallel/test-assert-if-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,18 @@ const stack = err.stack;
})();
})();

assert.throws(
() => {
const error = new Error();
error.stack = 'Error: containing weird stack\nYes!\nI am part of a stack.';
assert.ifError(error);
},
(error) => {
assert(!error.stack.includes('Yes!'));
return true;
}
);

assert.throws(
() => assert.ifError(new TypeError()),
{
Expand Down