Skip to content

Cherry pick #116998 to 26.3: Bound PostgreSQL protocol messages by their declared size - #120033

Merged
robot-ch-test-poll3 merged 13 commits into
backport/26.3/116998from
cherrypick/26.3/116998
Sep 18, 2026
Merged

robot-ch-test-poll3 merged 13 commits into
backport/26.3/116998from
cherrypick/26.3/116998

Conversation

@robot-ch-test-poll4

Copy link
Copy Markdown
Contributor

Original pull-request #116998

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

alexey-milovidov and others added 12 commits August 29, 2026 02:57
Only the startup message and the cancel request were parsed through a buffer
limited to the declared payload size. Every other message was parsed straight
from the socket, so a field could be sized from the wire and allocated before
any payload arrived, and a string without its terminator could grow past the end
of the message. Authentication messages are parsed before the client is
authenticated, so this was reachable without credentials.

`MessageTransport::receive` now reads the message length itself and parses the
message from a buffer limited to it, and the fields that carry an explicit
length grow as the bytes arrive instead of being resized to the declared size up
front. The two SASL messages of the SCRAM exchange no longer read their own type
byte: it is read and checked by the caller, like every other message type.
…ol-message-size-limit

# Conflicts:
#	src/Core/PostgreSQLProtocol.h
`MessageTransport::receive` limited parsing to the declared message length, but the
length was only an upper bound: whatever `deserialize` left unread stayed in the
socket and was then read as the next message. For a message whose parser reads
nothing, such as `Sync`, the whole payload was smuggled past the protocol state
machine, and the same held for a `Query` or `PasswordMessage` terminated early.

`receive` now skips the rest of the frame on both success and failure, and rejects a
message that carries more bytes than its parser consumed. Every `deserialize` of a
frontend message consumes its whole frame for a well-formed message, so the check
does not reject anything a client legitimately sends.

`gtest_postgresql_protocol` exercised the message length through `deserialize`, which
no longer reads it, so its cases are moved to `receive` and extended with the frame
boundary. The functional test gets the smuggled-tail case, and is renumbered to
`05054` because `05050` is taken on master.
The previous commit on this branch was supposed to carry this change, but only the test
rename ended up in it, so `MessageTransport::receive` still treated the declared length as
a mere upper bound: whatever `deserialize` left unread stayed in the socket and was then
read as the next message. For a message whose parser reads nothing, such as `Sync`, the
whole payload was smuggled past the protocol state machine, and the same held for a `Query`
or `PasswordMessage` terminated early.

`receive` now skips the rest of the frame on both success and failure, so a malformed
message realigns the stream instead of desynchronizing the connection, and rejects a
message that carries more bytes than its parser consumed. Every `deserialize` of a frontend
message consumes its whole frame for a well-formed message, so the check does not reject
anything a client legitimately sends.

`gtest_postgresql_protocol` exercised the message length through `deserialize`, which no
longer reads it, so its cases are moved to `receive` and extended with the frame boundary.
The functional test gets a `Query` smuggling a second `Query` in its tail and an oversized
`Sync`.
The server rejects the message but keeps the connection open when nothing has been sent for
the statement yet, so draining until the connection closes only hit the read timeout.

Verified locally against a private server with `postgresql_port` enabled: all five cases of
`05054_postgresql_protocol_message_size.sh` match the reference, and the nine
`PostgreSQLProtocol` unit tests pass.
… failures

`MessageTransport::receive` treated the declared message length as an upper
bound in one direction only. The `LimitReadBuffer` it parsed the message from
was configured with `read_no_more` alone, and `LimitReadBuffer::nextImpl`
returns `false` on EOF whenever `read_no_less` is zero, so a frame that ended
before its declared length was accepted as if it had ended exactly on the
boundary: a `Query` declaring 1000 bytes but sending only `SELECT 1` before
closing its write side was executed, and the post-parse check for unparsed
bytes never fired because `ignoreAll` returned `0`.

The limiter is now exact - `read_no_less` and `read_no_more` are both the
declared payload size - so a frame that ends early fails on the read instead
of being parsed from whatever arrived.

The drain of the rest of the frame is no longer wrapped in `SCOPE_EXIT_SAFE`,
which logged and suppressed a timeout or socket error and let the message
through as if the frame had been consumed. On the success path the drain is a
plain call, so its failure propagates. Realigning the stream after a failed
`deserialize` still has to be best-effort - it cannot report its own failure
without discarding the parsing error, which is the more informative one - so
only there is a failure logged and the original exception rethrown.

Tests: `ReceiveRejectsFrameShorterThanDeclared` covers a truncated frame for
`Query`, `PasswordMessage` and `SASLResponse` (the parser that reads to the
end of the frame), and `05054_postgresql_protocol_message_size.sh` gets a
`Query` that declares more bytes than it sends and then closes its write side,
which must be answered with an error instead of being executed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Master has since landed `FrontMessage::deserializePayload`, which parses each
extended-protocol message inside an exact-length `LimitReadBuffer`, realigns the
stream after a parse error and rejects trailing payload bytes. That is the same
frame-boundary contract this branch was enforcing centrally in
`MessageTransport::receive`, so the resolution keeps master's per-message
structure and re-applies only what is still missing from it:

- `readStringOfDeclaredSize` grows a field as its bytes arrive instead of
  resizing it to the size the client declared, so a tiny packet declaring a huge
  field no longer makes the server allocate that much up front. It is used for
  the `SASLInitialResponse` mechanism and for `Bind` parameters.
- `PasswordMessage`, `SASLInitialResponse`, `SASLResponse`, `Terminate`,
  `CopyInData` and `CopyDataQuery` now go through `deserializePayload` too, so
  the declared length is a frame boundary for the authentication messages as
  well, not only for the extended-protocol ones.
- `SASLInitialResponse` and `SASLResponse` no longer read the message type byte
  themselves; `ScrambleSHA256Auth::expectPasswordMessage` reads and checks it,
  as every other frontend message does through `receiveMessageType`.

`CopyInData` also stops reserving the declared payload size and reading it one
byte at a time.
When the client closes the connection before sending all bytes of the declared
frame, `LimitReadBuffer::nextImpl` throws `CANNOT_READ_ALL_DATA` and
`ReadBuffer::next` cancels the buffer. The `catch` block then called `ignore` on
that canceled buffer to keep the stream aligned, which is a logical error
(`ReadBuffer is canceled. Can't read from it.`) and aborted the debug and
sanitizer unit test jobs in `PostgreSQLProtocol.MessagesRejectFrameShorterThanDeclared`.
A canceled buffer has nothing left to align, so skip the drain and rethrow.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116998&sha=8620afedfa94e0e6b25084e76e8b2a6ff7baba1f&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%29
PR: #116998

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…age-size-limit

Bound PostgreSQL protocol messages by their declared size
@robot-ch-test-poll4 robot-ch-test-poll4 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Sep 14, 2026
@robot-ch-test-poll

Copy link
Copy Markdown
Contributor

Dear @thevar1able, @alexey-milovidov, this cherry-pick PR has not been updated for 3d0h1m45s. Please resolve the conflicts to backport #116998, or close this PR if the backport is no longer needed. This PR will be automatically closed after 7 days of inactivity.

…rrypick/26.3/116998

# Conflicts:
#	src/Core/PostgreSQLProtocol.h
#	src/Core/tests/gtest_postgresql_protocol.cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants