Skip to content

Commit

Permalink
assert: use stricter stack frame detection in .ifError()
Browse files Browse the repository at this point in the history
This makes sure arbitrary stack traces are not handled as stack
frames.

Signed-off-by: Ruben Bridgewater <ruben@bridgewater.de>

PR-URL: #41006
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
BridgeAR authored and danielleadams committed Jan 31, 2022
1 parent 1364f05 commit 45cd06b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 13 deletions.
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');
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

0 comments on commit 45cd06b

Please sign in to comment.