fix(onebot): validate payload limits and correct frame diagnostics
Reject invalid payload limits consistently in configuration files, restores, and API writes. Preserve pending frame bytes when reporting oversized messages. Refs #627
This commit is contained in:
4 files changed
+213
-72
No files matched your search
@@ -119,8 +119,8 @@ const DIAG_BUFFER_LIMIT = 64 * 1024;
|
||||
* payload exceeds `maxPayload`.
|
||||
*
|
||||
* The native parser rejects an oversized frame without saying where it is or how
|
||||
* large it is, so the reporting path re-reads the bytes buffered since the last
|
||||
* delivered message. Walking from a frame boundary removes the "the first bytes of
|
||||
* large it is, so the reporting path re-reads the retained bytes from the first
|
||||
* unparsed frame. Walking from a frame boundary removes the "the first bytes of
|
||||
* this chunk are the offending header" assumption: earlier data frames, interleaved
|
||||
* control frames and a header split across chunks are all stepped over correctly.
|
||||
* Returns `null` when the walk cannot reach a verdict, in which case the caller
|
||||
@@ -298,9 +298,9 @@ export class WebSocket extends EventEmitter {
|
||||
protected _msgCompressed = false;
|
||||
|
||||
// Diagnostic re-read of inbound bytes, kept only so an oversized-frame error
|
||||
// can name the offending frame. It never feeds parsing, is cleared whenever a
|
||||
// message is delivered, and downgrades the error text (instead of growing)
|
||||
// once the small budget would be exceeded.
|
||||
// can name the offending frame. It follows the parser's frame boundaries,
|
||||
// retaining any partial next frame, and downgrades the error text once the
|
||||
// small budget would be exceeded. It never feeds parsing.
|
||||
private _diagChunks: Buffer[] = [];
|
||||
private _diagBytes = 0;
|
||||
private _diagOverflow = false;
|
||||
@@ -368,6 +368,7 @@ export class WebSocket extends EventEmitter {
|
||||
}
|
||||
|
||||
for (const f of res.frames) {
|
||||
this._consumeDiagnosticFrame(f);
|
||||
this._handleFrame(f);
|
||||
|
||||
if (this._readyState === CLOSED) {
|
||||
@@ -401,21 +402,57 @@ export class WebSocket extends EventEmitter {
|
||||
return `${message}: ${info.payloadBytes} B ${opcodeLabel(info.opcode)} frame exceeds the ${limit}`;
|
||||
}
|
||||
|
||||
/** Keep a bounded copy of the bytes received since the last delivered message. */
|
||||
/** Keep bounded diagnostic bytes starting at the first unparsed frame. */
|
||||
private _recordDiagnosticBytes(chunk: Buffer): void {
|
||||
this._diagBytes += chunk.length;
|
||||
|
||||
if (this._diagOverflow) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._diagBytes + chunk.length > DIAG_BUFFER_LIMIT) {
|
||||
if (this._diagBytes > DIAG_BUFFER_LIMIT) {
|
||||
this._diagOverflow = true;
|
||||
this._diagChunks = [];
|
||||
this._diagBytes = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
this._diagChunks.push(chunk);
|
||||
this._diagBytes += chunk.length;
|
||||
}
|
||||
|
||||
private _consumeDiagnosticFrame(frame: ParsedFrame): void {
|
||||
const payloadBytes = frame.payload.length;
|
||||
// The parser enforces minimal length encoding and the masking direction,
|
||||
// so every accepted frame has this exact wire length, including controls.
|
||||
const lengthBytes = payloadBytes <= 125 ? 0 : payloadBytes <= 65535 ? 2 : 8;
|
||||
let remaining = 2 + lengthBytes + (this._isServer ? 4 : 0) + payloadBytes;
|
||||
this._diagBytes -= remaining;
|
||||
|
||||
if (this._diagBytes === 0) {
|
||||
this._resetDiagnosticBytes();
|
||||
return;
|
||||
}
|
||||
|
||||
// Once bytes are discarded, wait until the parser drains all pending
|
||||
// bytes before recording again; a new read may start inside a frame.
|
||||
if (this._diagOverflow) {
|
||||
return;
|
||||
}
|
||||
|
||||
let consumedChunks = 0;
|
||||
|
||||
while (remaining > 0) {
|
||||
const chunk = this._diagChunks[consumedChunks]!;
|
||||
|
||||
if (remaining < chunk.length) {
|
||||
this._diagChunks[consumedChunks] = chunk.subarray(remaining);
|
||||
break;
|
||||
}
|
||||
|
||||
remaining -= chunk.length;
|
||||
consumedChunks += 1;
|
||||
}
|
||||
|
||||
this._diagChunks.splice(0, consumedChunks);
|
||||
}
|
||||
|
||||
private _resetDiagnosticBytes(): void {
|
||||
@@ -572,7 +609,6 @@ export class WebSocket extends EventEmitter {
|
||||
this._msgSize = 0;
|
||||
this._msgValidator = null;
|
||||
this._msgCompressed = false;
|
||||
this._resetDiagnosticBytes();
|
||||
this.emit('message', data, isBinary);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -946,6 +946,43 @@ describe.skipIf(!nativeIo)('WebSocket incoming frames', () => {
|
||||
expect(errors[0]!.code).toBe(1009);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ isServer: false, previousPayloadBytes: 1 },
|
||||
{ isServer: false, previousPayloadBytes: 126 },
|
||||
{ isServer: true, previousPayloadBytes: 1 },
|
||||
{ isServer: true, previousPayloadBytes: 126 },
|
||||
])('preserves a split header after delivering the preceding message: %j', (options) => {
|
||||
const { isServer, previousPayloadBytes } = options;
|
||||
const { ws, socket } = createWs({ isServer, maxPayload: 1024 });
|
||||
const errors: Array<Error & { code?: number }> = [];
|
||||
const messages: Buffer[] = [];
|
||||
ws.on('error', (err) => errors.push(err));
|
||||
ws.on('message', (data) => messages.push(data));
|
||||
const payload = Buffer.alloc(previousPayloadBytes, 0x61);
|
||||
const precedingFrame = isServer
|
||||
? clientFrame(OP_TEXT, payload)
|
||||
: serverFrame(OP_TEXT, payload);
|
||||
const header = Buffer.from([0x82, isServer ? 0xfe : 0x7e, 0x82, 0x7e]);
|
||||
socket.emit('data', Buffer.concat([precedingFrame, header.subarray(0, 2)]));
|
||||
expect(messages).toEqual([payload]);
|
||||
expect(errors).toHaveLength(0);
|
||||
|
||||
// The length bytes resemble a new frame header. Losing the buffered
|
||||
// prefix would invent a size from the mask or payload bytes that follow.
|
||||
socket.emit(
|
||||
'data',
|
||||
Buffer.concat([
|
||||
header.subarray(2),
|
||||
isServer ? MASK : Buffer.alloc(0),
|
||||
Buffer.from([0x20, 0x00]),
|
||||
]),
|
||||
);
|
||||
expect(errors[0]!.message).toBe(
|
||||
'WebSocket protocol error: Payload exceeds configured max: 33406 B binary frame exceeds the 1024 byte limit (maxPayloadBytes)',
|
||||
);
|
||||
expect(errors[0]!.code).toBe(1009);
|
||||
});
|
||||
|
||||
it('skips interleaved control frames while locating the oversized frame', () => {
|
||||
const { ws, socket } = createWs({ isServer: true });
|
||||
const errors: Array<Error & { code?: number }> = [];
|
||||
@@ -972,13 +1009,15 @@ describe.skipIf(!nativeIo)('WebSocket incoming frames', () => {
|
||||
ws.on('error', (err) => {
|
||||
errors.push(err);
|
||||
});
|
||||
// Build up more than the 64 KiB diagnostic budget with a fragmented
|
||||
// message, so the offending header never gets buffered.
|
||||
const fragment = Buffer.alloc(8 * 1024, 0x61);
|
||||
for (let i = 0; i < 12; i += 1) {
|
||||
socket.emit('data', clientFrame(i === 0 ? OP_TEXT : OP_CONT, fragment, false));
|
||||
}
|
||||
socket.emit('data', maskedOversizedHeader(OP_TEXT, 2 * 1024 * 1024));
|
||||
// This single read exceeds the diagnostic budget before the parser
|
||||
// reports the error, so no reliable header is retained.
|
||||
socket.emit(
|
||||
'data',
|
||||
Buffer.concat([
|
||||
clientFrame(OP_TEXT, Buffer.alloc(96 * 1024, 0x61)),
|
||||
maskedOversizedHeader(OP_TEXT, 2 * 1024 * 1024),
|
||||
]),
|
||||
);
|
||||
expect(errors[0]!.message).toBe(
|
||||
'WebSocket protocol error: Payload exceeds configured max: an inbound frame exceeds the 1048576 byte limit (maxPayloadBytes)',
|
||||
);
|
||||
@@ -986,6 +1025,56 @@ describe.skipIf(!nativeIo)('WebSocket incoming frames', () => {
|
||||
expect(errors[0]!.code).toBe(1009);
|
||||
});
|
||||
|
||||
it('releases parsed fragments and control frames from the diagnostic budget', () => {
|
||||
const maxPayload = 1024 * 1024;
|
||||
const { ws, socket } = createWs({ isServer: true, maxPayload });
|
||||
const errors: Error[] = [];
|
||||
ws.on('error', (err) => errors.push(err));
|
||||
const fragment = Buffer.alloc(8 * 1024, 0x61);
|
||||
|
||||
for (let i = 0; i < 12; i += 1) {
|
||||
socket.emit('data', clientFrame(i === 0 ? OP_TEXT : OP_CONT, fragment, i === 11));
|
||||
socket.emit('data', clientFrame(OP_PING, Buffer.from('hb')));
|
||||
}
|
||||
|
||||
expect(errors).toHaveLength(0);
|
||||
socket.emit('data', maskedOversizedHeader(OP_BIN, 2 * 1024 * 1024));
|
||||
expect(errors[0]!.message).toContain('2097152 B binary frame');
|
||||
});
|
||||
|
||||
it('recovers diagnostics after a complete frame exceeds the diagnostic budget', () => {
|
||||
const { ws, socket } = createWs({ isServer: true, maxPayload: 1024 * 1024 });
|
||||
const errors: Error[] = [];
|
||||
const messages: Buffer[] = [];
|
||||
ws.on('error', (err) => errors.push(err));
|
||||
ws.on('message', (data) => messages.push(data));
|
||||
const payload = Buffer.alloc(96 * 1024, 0x61);
|
||||
socket.emit('data', clientFrame(OP_TEXT, payload));
|
||||
expect(messages).toEqual([payload]);
|
||||
expect(errors).toHaveLength(0);
|
||||
socket.emit('data', maskedOversizedHeader(OP_BIN, 2 * 1024 * 1024));
|
||||
expect(errors[0]!.message).toContain('2097152 B binary frame');
|
||||
});
|
||||
|
||||
it('keeps size unknown when a partial next header was discarded by the budget', () => {
|
||||
const { ws, socket } = createWs({ isServer: true, maxPayload: 1024 * 1024 });
|
||||
const errors: Error[] = [];
|
||||
ws.on('error', (err) => errors.push(err));
|
||||
const header = maskedOversizedHeader(OP_BIN, 2 * 1024 * 1024);
|
||||
socket.emit(
|
||||
'data',
|
||||
Buffer.concat([
|
||||
clientFrame(OP_TEXT, Buffer.alloc(96 * 1024, 0x61)),
|
||||
header.subarray(0, 2),
|
||||
]),
|
||||
);
|
||||
expect(errors).toHaveLength(0);
|
||||
socket.emit('data', header.subarray(2));
|
||||
expect(errors[0]!.message).toBe(
|
||||
'WebSocket protocol error: Payload exceeds configured max: an inbound frame exceeds the 1048576 byte limit (maxPayloadBytes)',
|
||||
);
|
||||
});
|
||||
|
||||
it('names the message type when a binary frame exceeds the limit', () => {
|
||||
const { ws, socket } = createWs({ isServer: true, maxPayload: 4 });
|
||||
const errors: Array<Error & { code?: number }> = [];
|
||||
|
||||
Reference in new issue
Block a user