Skip to content

Fix zlib reset misuse on maxPayload error to prevent callback race and incorrect error code #2285

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 2, 2025
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
14 changes: 14 additions & 0 deletions lib/permessage-deflate.js
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,14 @@ function inflateOnData(chunk) {
this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';
this[kError][kStatusCode] = 1009;
this.removeListener('data', inflateOnData);

//
// The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the
// fact that in Node.js versions prior to 13.10.0, the callback for
// `zlib.flush()` is not called if `zlib.close()` is used. Utilizing
// `zlib.reset()` ensures that either the callback is invoked or an error is
// emitted.
//
this.reset();
}

Expand All @@ -509,6 +517,12 @@ function inflateOnError(err) {
// closed when an error is emitted.
//
this[kPerMessageDeflate]._inflate = null;

if (this[kError]) {
this[kCallback](this[kError]);
return;
}

err[kStatusCode] = 1007;
this[kCallback](err);
}
22 changes: 20 additions & 2 deletions test/permessage-deflate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -590,9 +590,27 @@ describe('PerMessageDeflate', () => {
});
});

it("doesn't call the callback twice when `maxPayload` is exceeded", (done) => {
it('calls the callback when `maxPayload` is exceeded (1/2)', (done) => {
const perMessageDeflate = new PerMessageDeflate({}, false, 25);
const buf = Buffer.from('A'.repeat(50));
const buf = Buffer.alloc(50, 'A');

perMessageDeflate.accept([{}]);
perMessageDeflate.compress(buf, true, (err, data) => {
if (err) return done(err);

perMessageDeflate.decompress(data, true, (err) => {
assert.ok(err instanceof RangeError);
assert.strictEqual(err.message, 'Max payload size exceeded');
done();
});
});
});

it('calls the callback when `maxPayload` is exceeded (2/2)', (done) => {
// A copy of the previous test but with a larger input. See
// https://github.com/websockets/ws/pull/2285.
const perMessageDeflate = new PerMessageDeflate({}, false, 25);
const buf = Buffer.alloc(1024 * 1024, 'A');

perMessageDeflate.accept([{}]);
perMessageDeflate.compress(buf, true, (err, data) => {
Expand Down