Repository navigation
sql: reject a Postgres message length below 4 as a protocol error #32769
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
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
dffde01
sql: reject a Postgres message length below 4 as a protocol error
robobun 1fa2595
sql: use plain subtraction where length() guarantees a value of at le…
robobun 35bce47
sql: also reject a Postgres message length with the sign bit set
robobun c453621
ci: retrigger
robobun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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())); | ||
| } | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.