Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 1 addition & 2 deletions src/sql/postgres/protocol/CommandComplete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ impl CommandComplete {
&mut self,
mut reader: NewReader<Container>,
) -> Result<(), bun_core::Error> {
let length = reader.length()?;
debug_assert!(length >= 4);
reader.length()?;

let tag = reader.read_z()?;
*self = Self { command_tag: tag };
Expand Down
23 changes: 3 additions & 20 deletions src/sql/postgres/protocol/ErrorResponse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,9 @@ impl ErrorResponse {
pub fn decode_internal<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
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::<Container>(reader)?,
Expand All @@ -41,20 +38,6 @@ impl ErrorResponse {
) -> Result<Self, AnyPostgresError> {
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<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
let remaining_bytes = reader.length()?.saturating_sub(4);
if remaining_bytes > 0 {
return Ok(Self {
messages: FieldMessage::decode_list::<Container>(reader)?,
});
}
Ok(Self::default())
}
}

// `to_js` lives on an extension trait in the `bun_sql_jsc` crate.
3 changes: 1 addition & 2 deletions src/sql/postgres/protocol/NegotiateProtocolVersion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ impl NegotiateProtocolVersion {
pub fn decode_internal<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
let length = reader.length()?;
debug_assert!(length >= 4);
reader.length()?;

let version = reader.int4()?;
let mut this = Self {
Expand Down
10 changes: 7 additions & 3 deletions src/sql/postgres/protocol/NewReader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,13 @@ impl<Context: ReaderContext> NewReaderWrap<Context> {

pub fn length(&mut self) -> Result<PostgresInt32, AnyPostgresError> {
let expected = self.int::<PostgresInt32>()?;
// `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)?;
Comment thread
robobun marked this conversation as resolved.
Resolved

Ok(expected)
}
Expand Down
4 changes: 1 addition & 3 deletions src/sql/postgres/protocol/NoticeResponse.rs
Original file line number Diff line number Diff line change
@@ -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;
3 changes: 1 addition & 2 deletions src/sql/postgres/protocol/NotificationResponse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ impl NotificationResponse {
pub fn decode_internal<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
let length = reader.length()?;
debug_assert!(length >= 4);
reader.length()?;

Ok(Self {
pid: reader.int4()?,
Expand Down
3 changes: 1 addition & 2 deletions src/sql/postgres/protocol/ParameterStatus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ impl ParameterStatus {
pub fn decode_internal<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
let length = reader.length()?;
debug_assert!(length >= 4);
reader.length()?;

Ok(Self {
name: reader.read_z()?,
Expand Down
3 changes: 1 addition & 2 deletions src/sql/postgres/protocol/ReadyForQuery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ impl ReadyForQuery {
pub fn decode_internal<Container: super::new_reader::ReaderContext>(
mut reader: NewReader<Container>,
) -> Result<Self, AnyPostgresError> {
let length = reader.length()?;
debug_assert!(length >= 4);
reader.length()?;

let status = reader.int::<u8>()?;
// TransactionStatusIndicator is a `#[repr(transparent)] struct(u8)` newtype —
Expand Down
5 changes: 1 addition & 4 deletions src/sql_jsc/postgres/PostgresRequest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,10 +498,7 @@ pub(crate) fn on_data<Context: ReaderContext>(
_ => {
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"))?;
}
Expand Down
2 changes: 1 addition & 1 deletion src/sql_jsc/postgres/PostgresSQLConnection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
127 changes: 127 additions & 0 deletions test/js/sql/postgres-invalid-message-length.test.ts
Original file line number Diff line number Diff line change
@@ -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<any> {
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<void>(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<any> {
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<void>(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<void>(r => server.close(() => r()));
}
});
7 changes: 4 additions & 3 deletions test/js/sql/wire-frames.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading