Skip to content

Commit a7dfa43

Browse files
BridgeARdanielleadams
authored andcommitted
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]> PR-URL: #41006 Reviewed-By: James M Snell <[email protected]>
1 parent a0326f0 commit a7dfa43

File tree

2 files changed

+31
-13
lines changed

2 files changed

+31
-13
lines changed

lib/assert.js

+19-13
Original file line numberDiff line numberDiff line change
@@ -966,21 +966,27 @@ 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(
972+
origStack.slice(origStackStart + 1),
973+
'\n'
974+
);
975+
// Filter all frames existing in err.stack.
976+
let newFrames = StringPrototypeSplit(newErr.stack, '\n');
977+
for (const errFrame of originalFrames) {
978+
// Find the first occurrence of the frame.
979+
const pos = ArrayPrototypeIndexOf(newFrames, errFrame);
980+
if (pos !== -1) {
981+
// Only keep new frames.
982+
newFrames = ArrayPrototypeSlice(newFrames, 0, pos);
983+
break;
984+
}
980985
}
986+
const stackStart = ArrayPrototypeJoin(newFrames, '\n');
987+
const stackEnd = ArrayPrototypeJoin(originalFrames, '\n');
988+
newErr.stack = `${stackStart}\n${stackEnd}`;
981989
}
982-
newErr.stack =
983-
`${ArrayPrototypeJoin(tmp1, '\n')}\n${ArrayPrototypeJoin(tmp2, '\n')}`;
984990
}
985991

986992
throw newErr;

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

+12
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)