diff --git a/packages/pg-protocol/src/inbound-parser.test.ts b/packages/pg-protocol/src/inbound-parser.test.ts index 8687194c3..24d439604 100644 --- a/packages/pg-protocol/src/inbound-parser.test.ts +++ b/packages/pg-protocol/src/inbound-parser.test.ts @@ -582,4 +582,24 @@ describe('PgPacketStream', function () { parser.parse(oneFieldBuf, () => {}) assert.strictEqual((parser as any).reader.buffer.byteLength, 0) }) + + describe('error and notice messages with an empty body', function () { + for (const code of [0x45, 0x4e]) { + it('returns for code ' + String.fromCharCode(code) + ' at the end of the buffer', function () { + const messages: BackendMessage[] = [] + new Parser().parse(Buffer.from([code, 0, 0, 0, 4]), (msg) => messages.push(msg)) + assert.strictEqual(messages.length, 1) + assert.strictEqual(messages[0].name, 'error') + }) + + it('returns an error for code ' + String.fromCharCode(code) + ' and keeps parsing', function () { + const empty = Buffer.from([code, 0, 0, 0, 4]) + const messages: BackendMessage[] = [] + new Parser().parse(Buffer.concat([empty, readyForQueryBuffer]), (msg) => messages.push(msg)) + assert.strictEqual(messages.length, 2) + assert.strictEqual(messages[0].name, 'error') + assert.strictEqual(messages[1].name, 'readyForQuery') + }) + } + }) }) diff --git a/packages/pg-protocol/src/parser.ts b/packages/pg-protocol/src/parser.ts index df48ca4a1..7f3a3b132 100644 --- a/packages/pg-protocol/src/parser.ts +++ b/packages/pg-protocol/src/parser.ts @@ -209,9 +209,11 @@ export class Parser { message = parseBackendKeyData(reader) break case MessageCodes.ErrorMessage: + reader.setBuffer(0, packetBody(bytes, offset, length)) message = parseErrorMessage(reader, 'error') break case MessageCodes.NoticeMessage: + reader.setBuffer(0, packetBody(bytes, offset, length)) message = parseErrorMessage(reader, 'notice') break case MessageCodes.RowDescriptionMessage: @@ -379,10 +381,26 @@ const parseAuthenticationResponse = (reader: BufferReader, length: number) => { return message } +// `length` includes the int32 length field and excludes the message code. +// Clamp ErrorResponse/NoticeResponse reads to that body so a short frame +// cannot consume the next message or run off the end of the buffer. +const packetBody = (bytes: Buffer, offset: number, length: number): Buffer => { + const bodyLength = length - 4 + if (bodyLength <= 0) { + return emptyBuffer + } + return bytes.slice(offset, offset + bodyLength) +} + const parseErrorMessage = (reader: BufferReader, name: MessageName) => { const fields: Record = {} let fieldType = reader.string(1) while (fieldType !== '\0') { + // Past the declared body, BufferReader.string returns '' rather than NUL. + // Continuing would spin forever. + if (fieldType === '') { + return new DatabaseError('unterminated error or notice message', LATEINIT_LENGTH, 'error') + } fields[fieldType] = reader.cstring() fieldType = reader.string(1) }