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>
  • Loading branch information
BridgeAR committed Nov 28, 2021
1 parent 265a47d commit 134fd89
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
28 changes: 15 additions & 13 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -966,21 +966,23 @@ 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;
}
}
newErr.stack =
`${ArrayPrototypeJoin(newFrames, '\n')}\n${ArrayPrototypeJoin(originalFrames, '\n')}`;
}
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 134fd89

Please sign in to comment.