Skip to content

Commit 134fd89

Browse files
committed
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 <[email protected]>
1 parent 265a47d commit 134fd89

File tree

2 files changed

+27
-13
lines changed

2 files changed

+27
-13
lines changed

lib/assert.js

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -966,21 +966,23 @@ assert.ifError = function ifError(err) {
966966
// This will remove any duplicated frames from the error frames taken
967967
// from within `ifError` and add the original error frames to the newly
968968
// created ones.
969-
const tmp2 = StringPrototypeSplit(origStack, '\n');
970-
ArrayPrototypeShift(tmp2);
971-
// Filter all frames existing in err.stack.
972-
let tmp1 = StringPrototypeSplit(newErr.stack, '\n');
973-
for (const errFrame of tmp2) {
974-
// Find the first occurrence of the frame.
975-
const pos = ArrayPrototypeIndexOf(tmp1, errFrame);
976-
if (pos !== -1) {
977-
// Only keep new frames.
978-
tmp1 = ArrayPrototypeSlice(tmp1, 0, pos);
979-
break;
969+
const origStackStart = origStack.indexOf('\n at');
970+
if (origStackStart !== -1) {
971+
const originalFrames = StringPrototypeSplit(origStack.slice(origStackStart + 1), '\n');
972+
// Filter all frames existing in err.stack.
973+
let newFrames = StringPrototypeSplit(newErr.stack, '\n');
974+
for (const errFrame of originalFrames) {
975+
// Find the first occurrence of the frame.
976+
const pos = ArrayPrototypeIndexOf(newFrames, errFrame);
977+
if (pos !== -1) {
978+
// Only keep new frames.
979+
newFrames = ArrayPrototypeSlice(newFrames, 0, pos);
980+
break;
981+
}
980982
}
983+
newErr.stack =
984+
`${ArrayPrototypeJoin(newFrames, '\n')}\n${ArrayPrototypeJoin(originalFrames, '\n')}`;
981985
}
982-
newErr.stack =
983-
`${ArrayPrototypeJoin(tmp1, '\n')}\n${ArrayPrototypeJoin(tmp2, '\n')}`;
984986
}
985987

986988
throw newErr;

test/parallel/test-assert-if-error.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,18 @@ const stack = err.stack;
3939
})();
4040
})();
4141

42+
assert.throws(
43+
() => {
44+
const error = new Error();
45+
error.stack = 'Error: containing weird stack\nYes!\nI am part of a stack.';
46+
assert.ifError(error);
47+
},
48+
(error) => {
49+
assert(!error.stack.includes('Yes!'));
50+
return true;
51+
}
52+
);
53+
4254
assert.throws(
4355
() => assert.ifError(new TypeError()),
4456
{

0 commit comments

Comments
 (0)