diff --git a/src/sql/postgres/protocol/CommandComplete.rs b/src/sql/postgres/protocol/CommandComplete.rs index 52834908fd04..ac9ba078c54e 100644 --- a/src/sql/postgres/protocol/CommandComplete.rs +++ b/src/sql/postgres/protocol/CommandComplete.rs @@ -18,8 +18,7 @@ impl CommandComplete { &mut self, mut reader: NewReader, ) -> Result<(), bun_core::Error> { - let length = reader.length()?; - debug_assert!(length >= 4); + reader.length()?; let tag = reader.read_z()?; *self = Self { command_tag: tag }; diff --git a/src/sql/postgres/protocol/ErrorResponse.rs b/src/sql/postgres/protocol/ErrorResponse.rs index 3f7ac272cf23..fd2302a578cf 100644 --- a/src/sql/postgres/protocol/ErrorResponse.rs +++ b/src/sql/postgres/protocol/ErrorResponse.rs @@ -22,12 +22,9 @@ impl ErrorResponse { pub fn decode_internal( mut reader: NewReader, ) -> Result { - let mut remaining_bytes = reader.length()?; - if remaining_bytes < 4 { - return Err(AnyPostgresError::InvalidMessageLength); - } - remaining_bytes = remaining_bytes.saturating_sub(4); - + // A length of exactly 4 is an empty message (no fields); `length()` + // already rejected anything smaller. + let remaining_bytes = reader.length()? - 4; if remaining_bytes > 0 { return Ok(Self { messages: FieldMessage::decode_list::(reader)?, @@ -41,20 +38,6 @@ impl ErrorResponse { ) -> Result { Self::decode_internal(NewReader { wrapped: context }) } - - /// `NoticeResponse` decode: a declared length below 4 decodes as an empty - /// notice instead of failing, unlike `ErrorResponse`. - pub fn decode_notice_internal( - mut reader: NewReader, - ) -> Result { - let remaining_bytes = reader.length()?.saturating_sub(4); - if remaining_bytes > 0 { - return Ok(Self { - messages: FieldMessage::decode_list::(reader)?, - }); - } - Ok(Self::default()) - } } // `to_js` lives on an extension trait in the `bun_sql_jsc` crate. diff --git a/src/sql/postgres/protocol/NegotiateProtocolVersion.rs b/src/sql/postgres/protocol/NegotiateProtocolVersion.rs index 7d7ffc50f005..7fae35725d52 100644 --- a/src/sql/postgres/protocol/NegotiateProtocolVersion.rs +++ b/src/sql/postgres/protocol/NegotiateProtocolVersion.rs @@ -14,8 +14,7 @@ impl NegotiateProtocolVersion { pub fn decode_internal( mut reader: NewReader, ) -> Result { - let length = reader.length()?; - debug_assert!(length >= 4); + reader.length()?; let version = reader.int4()?; let mut this = Self { diff --git a/src/sql/postgres/protocol/NewReader.rs b/src/sql/postgres/protocol/NewReader.rs index f58855aab3a2..3f9d496a458a 100644 --- a/src/sql/postgres/protocol/NewReader.rs +++ b/src/sql/postgres/protocol/NewReader.rs @@ -156,9 +156,13 @@ impl NewReaderWrap { pub fn length(&mut self) -> Result { let expected = self.int::()?; - // `int4` is u32 so always nonnegative; the saturating sub guards - // underflow when len < 4. - self.ensure_capacity(expected.saturating_sub(4) as usize)?; + // The length of every Postgres v3 message is a signed Int32 that + // includes its own 4 bytes, so a value below 4 (or negative, i.e. the + // sign bit set on the wire) is malformed. `expected` is server-controlled. + if expected < 4 || expected > i32::MAX as u32 { + return Err(AnyPostgresError::InvalidMessageLength); + } + self.ensure_capacity((expected - 4) as usize)?; Ok(expected) } diff --git a/src/sql/postgres/protocol/NoticeResponse.rs b/src/sql/postgres/protocol/NoticeResponse.rs index 6ba4dfb3bb3a..483688ef2964 100644 --- a/src/sql/postgres/protocol/NoticeResponse.rs +++ b/src/sql/postgres/protocol/NoticeResponse.rs @@ -1,5 +1,3 @@ /// NoticeResponse has the same wire format as ErrorResponse — a length-prefixed -/// list of field messages — so it reuses the same type. Notices decode via -/// `decode_notice_internal`, which tolerates a declared length below 4 -/// (decoding as empty) where `ErrorResponse` fails. +/// list of field messages — so it reuses the same type and decoder. pub type NoticeResponse = crate::postgres::protocol::error_response::ErrorResponse; diff --git a/src/sql/postgres/protocol/NotificationResponse.rs b/src/sql/postgres/protocol/NotificationResponse.rs index 8be370f79d13..de26afb09c79 100644 --- a/src/sql/postgres/protocol/NotificationResponse.rs +++ b/src/sql/postgres/protocol/NotificationResponse.rs @@ -16,8 +16,7 @@ impl NotificationResponse { pub fn decode_internal( mut reader: NewReader, ) -> Result { - let length = reader.length()?; - debug_assert!(length >= 4); + reader.length()?; Ok(Self { pid: reader.int4()?, diff --git a/src/sql/postgres/protocol/ParameterStatus.rs b/src/sql/postgres/protocol/ParameterStatus.rs index 286562774705..c35de18361b7 100644 --- a/src/sql/postgres/protocol/ParameterStatus.rs +++ b/src/sql/postgres/protocol/ParameterStatus.rs @@ -14,8 +14,7 @@ impl ParameterStatus { pub fn decode_internal( mut reader: NewReader, ) -> Result { - let length = reader.length()?; - debug_assert!(length >= 4); + reader.length()?; Ok(Self { name: reader.read_z()?, diff --git a/src/sql/postgres/protocol/ReadyForQuery.rs b/src/sql/postgres/protocol/ReadyForQuery.rs index b2ad7bb20fb6..11ce84b3b7f3 100644 --- a/src/sql/postgres/protocol/ReadyForQuery.rs +++ b/src/sql/postgres/protocol/ReadyForQuery.rs @@ -18,8 +18,7 @@ impl ReadyForQuery { pub fn decode_internal( mut reader: NewReader, ) -> Result { - let length = reader.length()?; - debug_assert!(length >= 4); + reader.length()?; let status = reader.int::()?; // TransactionStatusIndicator is a `#[repr(transparent)] struct(u8)` newtype — diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index a6960d01d30b..ea3f319e6937 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -498,10 +498,7 @@ pub(crate) fn on_data( _ => { bun_core::scoped_log!(Postgres, "Unknown message: {}", c as char); let length = reader.length()?; - if length < 4 { - return Err(AnyPostgresError::InvalidMessageLength); - } - let to_skip = length.saturating_sub(4); + let to_skip = length - 4; bun_core::scoped_log!(Postgres, "to_skip: {}", to_skip); reader.skip(usize::try_from(to_skip).expect("int cast"))?; } diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 1d5b7d6344a6..a99b5da8861e 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -2973,7 +2973,7 @@ impl PostgresSQLConnection { } MessageType::NoticeResponse => { debug!("UNSUPPORTED NoticeResponse"); - let _resp = protocol::NoticeResponse::decode_notice_internal(reader.reborrow())?; + let _resp = protocol::NoticeResponse::decode_internal(reader.reborrow())?; // _resp dropped at scope end } MessageType::NotificationResponse => { diff --git a/test/js/sql/postgres-invalid-message-length.test.ts b/test/js/sql/postgres-invalid-message-length.test.ts new file mode 100644 index 000000000000..f6ef55a89278 --- /dev/null +++ b/test/js/sql/postgres-invalid-message-length.test.ts @@ -0,0 +1,127 @@ +// Fault-injection test: requires a server that refuses / drops / sends malformed +// frames, which a healthy container will not do on demand. DO NOT COPY THIS +// PATTERN — anything a real server can produce belongs in describeWithContainer. +// All wire-protocol bytes come from test/js/sql/wire-frames.ts; do not inline +// Buffer.alloc frame construction here. +// +// Every PostgreSQL v3 backend message carries an Int32 length that includes its +// own 4 bytes (https://www.postgresql.org/docs/current/protocol-message-formats.html), +// so a declared length below 4 is malformed and makes the stream unframeable +// (libpq treats it as a sync loss). The length is server-controlled input: +// shared servers, poolers (pgbouncer/pgcat), tunnels and sidecars all sit on +// the connection path. It must surface as ERR_POSTGRES_INVALID_MESSAGE_LENGTH +// on that connection rather than being trusted. +import { SQL } from "bun"; +import { expect, test } from "bun:test"; +import { listeningServer, pgAuthenticationOk, pgCString, pgRaw, pgReadyForQuery } from "./wire-frames"; + +// connectionTimeout (seconds) bounds the connect-retry budget; keep it short +// in tests that expect the failure to surface. + +/** + * Reply to the startup packet with AuthenticationOk followed by `frames`, so + * `frames` arrive before ReadyForQuery and connect() observes them. Returns + * connect()'s rejection. + */ +async function connectError(frames: Buffer[]): Promise { + const { port, server } = await listeningServer(socket => { + socket.once("data", () => socket.write(Buffer.concat([pgAuthenticationOk(), ...frames]))); + socket.on("error", () => {}); + }); + const db = new SQL({ url: `postgres://postgres@127.0.0.1:${port}/postgres`, max: 1, connectionTimeout: 1 }); + try { + await db.connect(); + throw new Error("expected connect() to reject"); + } catch (err) { + return err; + } finally { + await db.close({ timeout: 0 }); + await new Promise(r => server.close(() => r())); + } +} + +/** + * Complete the handshake normally, then answer the first simple query with + * `frames`, so they arrive while a request is in flight. Returns the query's + * rejection. + */ +async function queryError(frames: Buffer[]): Promise { + const { port, server } = await listeningServer(socket => { + let startup = true; + socket.on("data", data => { + if (startup) { + startup = false; + socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); + return; + } + if (data[0] !== 0x51 /* 'Q' */) return; + socket.write(Buffer.concat(frames)); + }); + socket.on("error", () => {}); + }); + const db = new SQL({ url: `postgres://postgres@127.0.0.1:${port}/postgres`, max: 1, connectionTimeout: 1 }); + try { + await db`select x`.simple(); + throw new Error("expected the query to reject"); + } catch (err) { + return err; + } finally { + await db.close({ timeout: 0 }); + await new Promise(r => server.close(() => r())); + } +} + +// Each entry drives a backend-message decoder with a length field that cannot +// be valid: below the 4 bytes the field itself occupies, or negative (the +// field is a signed Int32). All of them must fail the connection with the +// same protocol error. +const malformed: { name: string; frame: Buffer }[] = [ + // ReadyForQuery is Byte1('Z') Int32(5) Byte1(status); only the length lies. + { name: "ReadyForQuery declaring length 3", frame: pgRaw("Z", Buffer.from("I"), 3) }, + { name: "ReadyForQuery declaring length 0", frame: pgRaw("Z", Buffer.from("I"), 0) }, + // writeInt32BE(-1) puts 0xFFFFFFFF on the wire, the signed high half. + { name: "ReadyForQuery declaring length -1", frame: pgRaw("Z", Buffer.from("I"), -1) }, + { name: "ParameterStatus declaring length 3", frame: pgRaw("S", Buffer.alloc(0), 3) }, + { name: "NotificationResponse declaring length 3", frame: pgRaw("A", Buffer.alloc(0), 3) }, + // NoticeResponse is not exempt: an unframeable length is fatal even for a notice. + { name: "NoticeResponse declaring length 3", frame: pgRaw("N", Buffer.alloc(0), 3) }, + { name: "ErrorResponse declaring length 3", frame: pgRaw("E", Buffer.alloc(0), 3) }, + // An unrecognized message type takes the skip-by-declared-length path. + { name: "unknown message type declaring length 3", frame: pgRaw("X", Buffer.alloc(0), 3) }, +]; + +test.each(malformed)("postgres: $name is a protocol error", async ({ frame }) => { + const err = await connectError([frame]); + expect({ code: err.code, name: err.name }).toEqual({ + code: "ERR_POSTGRES_INVALID_MESSAGE_LENGTH", + name: "PostgresError", + }); +}); + +// CommandComplete is only decoded while a request is in flight, so it has to be +// injected as the answer to a query rather than during the startup phase. +test("postgres: CommandComplete declaring length 3 fails the in-flight query", async () => { + const err = await queryError([pgRaw("C", pgCString("SELECT 1"), 3)]); + expect({ code: err.code, name: err.name }).toEqual({ + code: "ERR_POSTGRES_INVALID_MESSAGE_LENGTH", + name: "PostgresError", + }); +}); + +// Boundary: a length of exactly 4 (an empty NoticeResponse) is the smallest +// valid value and must still be accepted. +test("postgres: an empty NoticeResponse (length exactly 4) is accepted", async () => { + const { port, server } = await listeningServer(socket => { + socket.once("data", () => + socket.write(Buffer.concat([pgAuthenticationOk(), pgRaw("N", Buffer.alloc(0)), pgReadyForQuery()])), + ); + socket.on("error", () => {}); + }); + const db = new SQL({ url: `postgres://postgres@127.0.0.1:${port}/postgres`, max: 1 }); + try { + await expect(db.connect()).resolves.toBeDefined(); + } finally { + await db.close({ timeout: 0 }); + await new Promise(r => server.close(() => r())); + } +}); diff --git a/test/js/sql/wire-frames.ts b/test/js/sql/wire-frames.ts index 3b1100f06aba..221241102030 100644 --- a/test/js/sql/wire-frames.ts +++ b/test/js/sql/wire-frames.ts @@ -118,11 +118,12 @@ export function pgErrorResponse(fields: { S: string; C: string; M: string; [k: s } // PostgreSQL FE/BE protocol §55.7 generic backend message: Byte1(type) Int32(len = 4 + body.length) body -// Low-level escape hatch for fault-injection tests that need a deliberately malformed body. -export function pgRaw(type: string, body: Buffer): Buffer { +// Low-level escape hatch for fault-injection tests that need a deliberately malformed body, +// or (via `declaredLength`) a length field that lies about the body it precedes. +export function pgRaw(type: string, body: Buffer, declaredLength: number = body.length + 4): Buffer { const buf = Buffer.alloc(5 + body.length); buf.write(type, 0); - buf.writeInt32BE(body.length + 4, 1); + buf.writeInt32BE(declaredLength, 1); body.copy(buf, 5); return buf; }