Skip to content

sql(mysql,postgres): reject duplicate auth requests; make connectionTimeout an absolute handshake deadline - #36308

Merged
Jarred-Sumner merged 8 commits into
mainfrom
farm/ddc10b2a/sql-auth-loop-and-connect-deadline
Jul 29, 2026
Merged

Jarred-Sumner merged 8 commits into
mainfrom
farm/ddc10b2a/sql-auth-loop-and-connect-deadline

Conversation

@robobun

@robobun robobun commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

A hostile or MITM'd server that answers every client auth packet with another AuthSwitchRequest (MySQL 0xFE) or AuthenticationSASL / MD5Password / CleartextPassword (Postgres R) drives Bun into an unbounded authentication loop at 100% CPU, pre-auth, with no application-visible signal. connectionTimeout never fires because on_data re-arms the connect-phase timer on every inbound packet, so any server that dribbles bytes (e.g. one greeting byte per 1.5s) holds the client indefinitely.

client answered 40 AuthSwitchRequests on ONE connection in 7863ms (connectionTimeout: 2 never fired) -> BUG

mysql2 / libmysqlclient refuse a second auth-switch; libpq rejects a second AuthenticationSASL with duplicate SASL authentication request.

Cause

Two independent defects, shared between the adapters:

  1. MySQLConnection::handle_auth honoured every PacketType::AUTH_SWITCH with no per-handshake state. The Postgres Authentication::SASL / ClearTextPassword / MD5Password arms likewise accepted a fresh request in every authentication state.
  2. JSMySQLConnection::on_data and PostgresSQLConnection::on_data bracketed processing with a reset_connection_timeout() (mysql) / disable_connection_timeout() + reset_connection_timeout() (postgres), turning the connect deadline into a per-packet inactivity timer.

Fix

MySQL: record that an AuthSwitchRequest has been honoured and reject a second one with ERR_MYSQL_UNEXPECTED_PACKET. on_data now leaves the connect-phase timer running until the auth OK transitions the connection to Connected, at which point it is re-armed as the idle timer.

Postgres: AuthenticationSASL, AuthenticationCleartextPassword and AuthenticationMD5Password are only accepted while authentication_state is Pending; any later arrival is rejected with ERR_POSTGRES_UNEXPECTED_MESSAGE. A new AuthenticationState::ClearText records that a cleartext password was sent. on_data now leaves the connect-phase timer running until ReadyForQuery transitions the connection to Connected.

Verification

New scripted wire-server tests:

  • test/js/sql/sql-mysql-duplicate-auth-switch.test.ts: a second AuthSwitchRequest is rejected after exactly one response; the one-switch happy path still connects; a server that trickles the greeting one byte per 200ms fails at the 1s connectionTimeout.
  • test/js/sql/postgres-duplicate-auth-request.test.ts: duplicate and mixed-method auth requests are rejected after exactly one response; the single-request cleartext and MD5 happy paths still connect; a server that trickles bytes during auth fails at the 1s connectionTimeout.

Existing wire-frames.test.ts, sql-mysql-auth-short-nonce.test.ts, sql-connect-error-reporting.test.ts, postgres-frame-boundary.test.ts, postgres-invalid-message-length.test.ts, and the scripted cases in sql-mysql.auth.test.ts pass unchanged.

Closes #33671 (postgres half, now folded in and rebased).


[review] gate passed · iteration 4 · 7 files touched

fails on main (without fix)
ASAN without fix: 11 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/sql/postgres-duplicate-auth-request.test.ts test/js/sql/sql-mysql-duplicate-auth-switch.test.ts
bun test v1.4.0 (2d1c00e96)

test/js/sql/sql-mysql-duplicate-auth-switch.test.ts:
(fail) MySQL: a second AuthSwitchRequest to the same plugin is rejected [5000.63ms]
  ^ this test timed out after 5000ms.
(fail) MySQL: at most two AuthSwitchRequests are honoured per handshake [5000.22ms]
  ^ this test timed out after 5000ms.
(fail) MySQL: caching_sha2 perform_full_authentication is honoured at most once [5000.20ms]
  ^ this test timed out after 5000ms.
(pass) MySQL: a single AuthSwitchRequest to a different plugin then OK still connects [145.61ms]
(pass) MySQL: a single AuthSwitchRequest to the greeting's plugin then OK still connects [82.40ms]
(fail) MySQL: connectionTimeout bounds the whole handshake, not per packet [5000.14ms]
  ^ this test timed out after 5000ms.

test/js/sql/postgres-duplicate-auth-request.test.ts:
(fail) postgres: duplicate AuthenticationSASL is rejected, not answered again [5000.18ms]
  ^ this test timed out af
... (truncated)

release without fix: 11 FAILED
bun test v1.4.0-canary.1 (1498d7b77)

test/js/sql/sql-mysql-duplicate-auth-switch.test.ts:
(fail) MySQL: a second AuthSwitchRequest to the same plugin is rejected [5000.60ms]
  ^ this test timed out after 5000ms.
(fail) MySQL: at most two AuthSwitchRequests are honoured per handshake [5000.54ms]
  ^ this test timed out after 5000ms.
(fail) MySQL: caching_sha2 perform_full_authentication is honoured at most once [5000.53ms]
  ^ this test timed out after 5000ms.
(pass) MySQL: a single AuthSwitchRequest to a different plugin then OK still connects [4.80ms]
(pass) MySQL: a single AuthSwitchRequest to the greeting's plugin then OK still connects [1.94ms]
(fail) MySQL: connectionTimeout bounds the whole handshake, not per packet [5000.08ms]
  ^ this test timed out after 5000ms.

test/js/sql/postgres-duplicate-auth-request.test.ts:
(fail) postgres: duplicate AuthenticationSASL is rejected, not answered again [5000.11ms]
  ^ this test timed out after 5000ms.
(fail) postgres: duplicate AuthenticationCleartextPassword is rejected, not answered again [5000.13ms]
  ^ this test timed out after 5000ms.
(fail) postgres: duplicate AuthenticationMD5Password is rejected, not answered
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/sql/postgres-duplicate-auth-request.test.ts test/js/sql/sql-mysql-duplicate-auth-switch.test.ts
bun test v1.4.0 (2d1c00e96)

test/js/sql/sql-mysql-duplicate-auth-switch.test.ts:
(pass) MySQL: a second AuthSwitchRequest to the same plugin is rejected [842.62ms]
(pass) MySQL: at most two AuthSwitchRequests are honoured per handshake [129.45ms]
(pass) MySQL: caching_sha2 perform_full_authentication is honoured at most once [230.70ms]
(pass) MySQL: a single AuthSwitchRequest to a different plugin then OK still connects [143.35ms]
(pass) MySQL: a single AuthSwitchRequest to the greeting's plugin then OK still connects [79.30ms]
(pass) MySQL: connectionTimeout bounds the whole handshake, not per packet [1057.49ms]

test/js/sql/postgres-duplicate-auth-request.test.ts:
(pass) postgres: duplicate AuthenticationSASL is rejected, not answered again [120.42ms]
(pass) postgres: duplicate AuthenticationCleartextPassword is rejected, not answered again [62.32ms]
(pass) postgres: duplicate AuthenticationMD5Password is rejected, not answered ag
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     2d1c00e96f
  features     baseline

22 deps, 108 codegen, 1171 objects in 998ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1234] install /workspace/bun
bun install v1.4.0-canary.1 (1498d7b77)

Checked 124 installs across 170 packages (no changes) [21.00ms]
[2/1234] install /workspace/bun/packages/bun-error
bun install v1.4.0-canary.1 (1498d7b77)

Checked 1 install across 2 packages (no changes) [1.00ms]
[3/1234] install /workspace/bun/src/node-fallbacks
bun install v1.4.0-canary.1 (1498d7b77)

Checked 129 installs across 147 packages (no changes) [10.00ms]
[4/1234] gen bindgenv2
[5/1234] gen ErrorCode+*.h
[6/1234] fetch tinycc
[tinycc] up to date
[7/1234] fetch libjpeg-turbo
[libjpeg-turbo] up to date
[8/1234] fetch zlib
[zlib] up to date
[9/1234] fetch picohttpparser
[picohttpparser] up to date
[10/1234] gen .bind.ts → GeneratedBindings.cpp
[11/1234] gen ProcessBindingConstants.lut.h
Generating /workspace/bun/build/release/codegen/ProcessBindingConstants.lut.h from 
... (truncated)
diff hotspot
src/sql_jsc/mysql/JSMySQLConnection.rs             |   5 +-
 src/sql_jsc/mysql/MySQLConnection.rs               |  26 +-
 src/sql_jsc/postgres/AuthenticationState.rs        |   1 +
 src/sql_jsc/postgres/PostgresSQLConnection.rs      |  34 ++-
 .../js/sql/postgres-duplicate-auth-request.test.ts | 207 +++++++++++++++
 .../js/sql/sql-mysql-duplicate-auth-switch.test.ts | 284 +++++++++++++++++++++
 test/js/sql/wire-frames.ts                         |  16 ++
 7 files changed, 563 insertions(+), 10 deletions(-)

gate history · 5 passed · 1 rejected · iteration 4

evidence per changed file
file                                                 reads  edits  tests
src/sql_jsc/mysql/JSMySQLConnection.rs                   4      3      0
src/sql_jsc/mysql/MySQLConnection.rs                    12     14      0
src/sql_jsc/postgres/AuthenticationState.rs              1      1      0
src/sql_jsc/postgres/PostgresSQLConnection.rs            5      7      0
test/js/sql/postgres-duplicate-auth-request.test.ts      1      5      0
test/js/sql/sql-mysql-duplicate-auth-switch.test.ts      3      8      0
test/js/sql/wire-frames.ts                               2      1      0

…onTimeout an absolute handshake deadline

A malicious or MITM'd server that answers every client auth packet with
another AuthSwitchRequest (mysql) or AuthenticationSASL/MD5/Cleartext
(postgres) drove the client into an unbounded auth loop at 100% CPU,
pre-auth, with no application-visible signal. connectionTimeout never
fired because on_data re-armed the connect-phase timer on every inbound
packet, so any server that trickles bytes held the client indefinitely.

MySQL: track whether an AuthSwitchRequest has already been honoured and
reject a second one with ERR_MYSQL_UNEXPECTED_PACKET (mysql2 and
libmysqlclient refuse a second switch). on_data now leaves the
connect-phase timer running until the auth OK transitions the connection
to Connected.

Postgres: AuthenticationSASL / AuthenticationCleartextPassword /
AuthenticationMD5Password each start an authentication exchange and are
now only accepted while authentication_state is Pending; any later
arrival is rejected with ERR_POSTGRES_UNEXPECTED_MESSAGE (libpq:
"duplicate SASL authentication request"). on_data now leaves the
connect-phase timer running until ReadyForQuery transitions the
connection to Connected.
@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

The MySQL and PostgreSQL SQL clients now bound authentication protocol exchanges, reject duplicate authentication requests, and preserve connection deadlines across partial handshakes. New fault-injection tests cover invalid loops, valid authentication, and trickled handshake timeouts.

SQL protocol authentication hardening

Layer / File(s) Summary
MySQL authentication switch bounds
src/sql_jsc/mysql/MySQLConnection.rs, src/sql_jsc/mysql/JSMySQLConnection.rs, test/js/sql/sql-mysql-duplicate-auth-switch.test.ts
MySQL tracks authentication plugin switches, rejects repeated or excessive switches, conditions timeout resets on Connected, and tests valid and invalid switch sequences.
PostgreSQL authentication state validation
src/sql_jsc/postgres/AuthenticationState.rs, src/sql_jsc/postgres/PostgresSQLConnection.rs, test/js/sql/postgres-duplicate-auth-request.test.ts, test/js/sql/wire-frames.ts
PostgreSQL adds cleartext authentication state, rejects duplicate or mixed authentication requests, and tests valid authentication flows with generated MD5 and SASL frames.
Handshake-wide connection deadlines
src/sql_jsc/postgres/PostgresSQLConnection.rs, test/js/sql/postgres-duplicate-auth-request.test.ts
PostgreSQL changes timeout disable/reset behavior to require Connected and tests timeout enforcement during trickled handshake data.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: blocking duplicate auth requests and making connectionTimeout a handshake deadline.
Description check ✅ Passed The description is detailed and includes verification, but it uses custom headings instead of the template's exact sections.

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready for review; diff is green, CI flaky on unrelated lanes.

Reproduced with the script in the report: stock bun answers 40 AuthSwitchRequests over ~8s with connectionTimeout: 2 never firing; with this change the client errors with ERR_MYSQL_UNEXPECTED_PACKET on the second request and exits 0.

MySQL: auth_switch_count caps at 2 and a second switch back to a plugin already tried is refused (a first switch to the greeting's plugin, which Azure/ProxySQL send to deliver a fresh nonce, is still honoured); full_auth_requested bounds caching_sha2 perform_full_authentication to one round. on_data leaves the connect-phase timer running until Connected.

Postgres half folds in #33671 which was conflicting with main.

Fail-before / pass-after on both new test files (11 bug cases fail on stock bun, 4 happy-path boundaries pass on both). Verification cells: endless-AuthSwitch rejects in ~200ms, 500ms/byte trickle times out at ~2.1s with connectionTimeout: 2.

CI: both new test/js/sql/ files pass on every lane across builds 84774, 84829 and 84992. Every remaining failure in 84992 is tagged [flaky] and none touch sql. Needs a maintainer to merge.

@github-actions

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. 100% cpu if use sslmode on mysql #24845 - Reports 100% CPU when using sslmode on MySQL, which matches the unbounded auth-loop spin this PR fixes by rejecting duplicate AUTH_SWITCH requests

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #24845

🤖 Generated with Claude Code

@robobun

robobun commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Re #24845: that report describes 100% CPU in the idle state after a successful TLS query against a real MySQL server, not an authentication loop. This PR bounds the pre-auth handshake; leaving #24845 open since it's a different symptom.

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. sql(postgres): reject duplicate authentication requests #33671 - Both reject duplicate authentication requests in Postgres SQL connections; sql(mysql,postgres): reject duplicate auth requests; make connectionTimeout an absolute handshake deadline #36308 supersedes sql(postgres): reject duplicate authentication requests #33671 by folding in the postgres half and extending the fix to MySQL

🤖 Generated with Claude Code

…urrent plugin

Replaces the boolean one-switch cap with an auth_switch_count and an explicit
same-plugin check: reject when count >= 2 or when the requested plugin equals
the plugin already in use (the signature of the ping-pong attack; mysql2 errors
on a repeated auth switch).
Comment thread src/sql_jsc/mysql/JSMySQLConnection.rs Resolved
Comment thread src/sql_jsc/mysql/MySQLConnection.rs Resolved
Comment thread src/sql_jsc/mysql/JSMySQLConnection.rs Resolved
Comment thread src/sql_jsc/mysql/MySQLConnection.rs Resolved
@robobun

robobun commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:05 AM PT - Jul 29th, 2026

@robobun, your commit 2d1c00e is building: #84992

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional findings (outside current diff — PR may have been updated during review):

  • 🔴 src/sql_jsc/mysql/MySQLConnection.rs:899-908 — The auth_switched guard bounds PacketType::AUTH_SWITCH, but the sibling PacketType::MORE_DATA arm in the same handle_auth match still lets a hostile server drive an unbounded caching_sha2 ping-pong: over TLS each CONTINUE_AUTH (0x04) elicits another plaintext-password write with no state change, and over plain TCP with allowPublicKeyRetrieval: true it oscillates AuthenticationAwaitingPk ↔ Authenticating. The absolute-deadline timer only bounds this when connectionTimeout > 0; connectionTimeout: 0 is an explicitly supported value that disables the timer (src/js/internal/sql/shared.ts:730), leaving the loop structurally unbounded — the same class this PR targets. A per-handshake flag on the CONTINUE_AUTH / public-key branches mirroring auth_switched would close it (REVIEW.md: "fix the whole class — parallel switch arms").

    Extended reasoning...

    What the bug is

    This PR adds auth_switched: bool to structurally bound PacketType::AUTH_SWITCH — a second AuthSwitchRequest is now rejected with UnexpectedPacket. However, the immediately adjacent PacketType::MORE_DATA arm in the same handle_auth match (MySQLConnection.rs:807–880, specifically the FastAuthStatus::CONTINUE_AUTH branch at :828) has no equivalent per-handshake state, so a hostile/MITM server can still drive an unbounded auth ping-pong through the caching_sha2_password continuation path — the exact loop shape this PR fixes for AUTH_SWITCH.

    Step-by-step proof (TLS path — the common production configuration)

    1. Server greets with caching_sha2_password; client sends HandshakeResponse41. status = Authenticating, auth_plugin = Some(CachingSha2Password), tls_status = SslOk.
    2. Server sends MORE_DATA (0x01) with body [0x04] → FastAuthStatus::CONTINUE_AUTH.
    3. handle_auth MORE_DATA arm, CONTINUE_AUTH branch: since tls_status == SslOk, the client writes the plaintext password packet (writer().write_z(&self.password)) and calls flush_data(). No field on self changes — status stays Authenticating, auth_plugin stays CachingSha2Password, no counter advances.
    4. Server replies with another MORE_DATA [0x04]. Step 3 repeats. Forever.

    The plain-TCP variant (with allowPublicKeyRetrieval: true) alternates: CONTINUE_AUTH → set_status(AuthenticationAwaitingPk) + send PublicKeyRequest → next MORE_DATA hits handle_handshake_decode_public_key which explicitly does set_status(Authenticating) + sends encrypted password → server sends CONTINUE_AUTH again → back to step 1. Also unbounded.

    Why the PR's other fix does not fully cover this

    The on_data change makes connectionTimeout an absolute deadline, which bounds the loop to ~30 s at the default. But connectionTimeout: 0 is an explicitly supported value:

    • src/js/internal/sql/shared.ts:1997 only rejects < 0; 0 is accepted.
    • src/js/internal/sql/shared.ts:730 documents "an explicit connectionTimeout of 0 disables the connect timer".
    • In JSMySQLConnection.rs, get_timeout_interval() returns connection_timeout_ms during handshake, and reset_connection_timeout() returns early when interval == 0, so no timer is ever armed.

    With connectionTimeout: 0 the MORE_DATA loop is structurally unbounded — the identical failure mode ("unbounded authentication loop at 100% CPU, pre-auth") that this PR's description names as the defect. Even at the 30 s default, that is 30 s of tight-loop CPU + repeated password transmission on every connection attempt, pre-auth — the AUTH_SWITCH arm was not left in that state, it got a structural bound.

    Why this belongs in this PR

    REVIEW.md, Correctness: the bug class, not the bug: "Fix the whole class in the same PR … grep for every sibling site sharing the pattern: parallel switch arms". MORE_DATA is a literal sibling match arm of AUTH_SWITCH in the same function, with the same threat model (hostile/MITM server driving auth ping-pong) and the same fix shape. The PR description frames the defect generically as "unbounded authentication loop" and cites mysql2/libmysqlclient as the reference; leaving one of the two server-driven auth-request arms unguarded means the class is only half-fixed.

    How to fix

    Mirror auth_switched with a per-handshake flag on the CONTINUE_AUTH path — e.g. a full_auth_sent: bool (or a small round counter) set when the client writes the plaintext-password / encrypted-password / public-key-request response, and checked at the top of the CONTINUE_AUTH branch to return AnyMySQLError::UnexpectedPacket on repeat. One flag covers both the TLS and AuthenticationAwaitingPk variants.

…nd per handshake

The MORE_DATA/CONTINUE_AUTH arm (the sibling of AUTH_SWITCH in handle_auth)
had the same unbounded loop: over TLS each 0x04 elicited another plaintext
password write with no state change, and over plain TCP with
allowPublicKeyRetrieval it oscillated AwaitingPk <-> Authenticating.
@robobun

robobun commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch on the MORE_DATA/CONTINUE_AUTH sibling arm. Addressed in c68f8ae: full_auth_requested: bool guards the caching_sha2 perform_full_authentication path so a second 0x04 is rejected with ERR_MYSQL_UNEXPECTED_PACKET. New test covers the plain-TCP + allowPublicKeyRetrieval loop (stock bun sends 20 encrypted passwords; fixed build rejects after the first).

Comment thread src/sql_jsc/mysql/MySQLConnection.rs Resolved
Comment thread src/sql_jsc/mysql/MySQLConnection.rs Resolved
Azure Database for MySQL, ProxySQL and similar front-ends answer the
HandshakeResponse with an AuthSwitchRequest naming the plugin the greeting
already advertised, carrying a fresh nonce; libmysqlclient, mysql2 and
go-sql-driver/mysql all honour it. Gate the same-plugin rejection on
auth_switch_count > 0 so only a second switch back to a plugin already tried
is refused.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both earlier blocking findings are addressed: the first-AuthSwitch-to-greeting-plugin regression is now gated on auth_switch_count > 0 (cd5b298), and the caching_sha2 CONTINUE_AUTH sibling arm is bounded by full_auth_requested (c68f8ae). I also traced the connect→idle timer handoff under the new Connected-gated reset in on_data for both adapters — the transition still re-arms the idle timer once the OK/ReadyForQuery packet lands. Deferring to a human given this is pre-auth protocol handling and changes connection-timeout semantics.

Extended reasoning...

My two prior inline findings on this PR are resolved and the remaining inline comment is a test-style nit. Beyond that I verified the timer semantics change does not strand the connection without a timer: on the packet that transitions status to Connected, MySQL's deferred block runs after read_and_process_data clears IS_PROCESSING_DATA with status already Connected, and Postgres clears the flag at on_data:1063 before the gated reset_connection_timeout() at 1065-1067 — so the idle timer is armed on both paths. Not auto-approving because this is security-sensitive pre-auth handling across two adapters plus a behavioural change to what connectionTimeout measures.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The three earlier findings (Azure/ProxySQL same-plugin first switch, the unguarded CONTINUE_AUTH sibling arm, and the inlined pgRaw frame) are all addressed in the current diff, and I found nothing new. Deferring to a human because this is auth-protocol state-machine code across both adapters and it changes what connectionTimeout means (per-packet → absolute handshake deadline).

What was reviewed

  • Traced the Postgres Pending-only guard against SASLContinue/SASLFinal/Ok — those arms use sasl_state_mut()/separate variants, so the SCRAM continuation flow is unaffected.
  • Checked the timer gating on both sides: reset_connection_timeout() removes-then-reinserts, so the handshake→Connected transition inside on_data correctly re-arms as the idle timer; on_connection_timeout already early-returns on IS_PROCESSING_DATA.
  • Walked the auth_switch_count / auth_plugin guard through the greeting→switch→switch sequences; the same-plugin clause now only trips on the second switch, and full_auth_requested bounds the PK-retrieval loop.
Extended reasoning...

Overview

Bounds the pre-auth handshake against hostile/MITM servers in both SQL adapters: MySQL gains auth_switch_count (cap 2, plus a same-plugin check gated on count > 0) and full_auth_requested for the caching_sha2 CONTINUE_AUTH arm; Postgres now only accepts AuthenticationSASL/ClearTextPassword/MD5Password while authentication_state == Pending (new ClearText variant records that a password was sent). Both adapters' on_data stop resetting the connect-phase timer per packet, making connectionTimeout an absolute connect→ready deadline. Two new fault-injection test files cover the loop cases, the happy-path boundaries, and the trickle-timeout, plus two new frame builders in wire-frames.ts.

Security risks

This is the security fix — it closes a pre-auth CPU-spin / stall DoS. The residual risk is over-tightening: rejecting a sequence a real server legitimately sends. My earlier round caught exactly that (the same-plugin first-switch rejection would have broken Azure MySQL / ProxySQL); the fix in cd5b298 gates it on count > 0 and adds a happy-path test for the fresh-nonce pattern. I re-walked the remaining rejection paths and each corresponds to a sequence libmysqlclient/mysql2/libpq also refuse. full_auth_requested is not reset on an intervening AUTH_SWITCH, so a caching_sha2 → CONTINUE_AUTH → switch-away → switch-back-to-caching_sha2 → CONTINUE_AUTH sequence would be rejected, but I could not find any real server that does this and the count cap would terminate it one packet later anyway.

Level of scrutiny

High — this is authentication protocol state-machine logic, and the connectionTimeout change is a user-visible semantic shift (previously any handshake activity kept the connection alive; now it's a hard deadline). A maintainer should confirm they want the timeout semantics change and glance at the two rejection guards.

Other factors

This has already been through two rounds of my review with fixes landed for each finding; the bug-hunt system found nothing on the current head. Tests are thorough (fail-before/pass-after evidence in the PR body covers 11 bug cases + 4 boundary cases across debug-ASAN and release). CI is green on the touched files; the one red lane is an unrelated worker_threads SIGABRT also failing on main. #33671 is superseded by this PR.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found this round — the earlier findings (Azure/ProxySQL first-switch compat, the CONTINUE_AUTH sibling arm, and the pgRaw helper) are all addressed. Deferring to a maintainer because this changes the user-visible connectionTimeout semantics on both adapters (per-packet inactivity → absolute connect→ready deadline) alongside the auth-state-machine guards, and that behaviour shift is worth a human sign-off.

What was reviewed:

  • Traced the Postgres on_data timer bracket: connect-phase timer now stays armed through auth; on the ReadyForQuery → Connected transition the exit-side reset_connection_timeout() still runs and swaps to the idle timer; the Connected → Failed mid-on_data path leaves the timer cancelled, same net effect as before.
  • Verified the MD5 arm's pre-existing authentication_state.set(Md5) makes the new Pending-only guard effective there; SASLContinue/SASLFinal are separate arms and unaffected.
  • Checked full_auth_requested is set before both the plain-TCP public-key-request branch and the TLS cleartext-password branch, so both loop shapes are bounded.
  • Confirmed the auth_switch_count > 0 && same-plugin clause admits the first same-plugin switch (Azure fresh-nonce) and only rejects a repeat.
Extended reasoning...

Overview

The PR hardens the MySQL and Postgres SQL clients against a hostile-server pre-auth DoS: (1) a per-handshake counter/flag rejects repeated AuthSwitchRequest / CONTINUE_AUTH (MySQL) and repeated Authentication{SASL,CleartextPassword,MD5Password} (Postgres) with ERR_*_UNEXPECTED_*; (2) on_data on both adapters now leaves the connect-phase timer running until the connection reaches Connected, so connectionTimeout is an absolute connect→ready deadline instead of a per-packet inactivity window. Two new fault-injection test files exercise the duplicate-request rejections, the happy-path boundaries, and the trickle-timeout, plus two new frame builders in wire-frames.ts.

Security risks

The change is itself a security hardening (bounds a pre-auth CPU spin and an indefinite hang). The risk surface is regression: over-tight guards could reject legitimate server sequences. That already happened once in review (the same-plugin first-switch clause broke Azure MySQL / ProxySQL) and was fixed by gating on auth_switch_count > 0. I re-checked the Postgres SASL flow — SASLContinue/SASLFinal are separate match arms so the multi-roundtrip SCRAM exchange is unaffected by the new Pending-only gate on AuthenticationSASL.

Level of scrutiny

High. This is auth-path protocol state on two adapters, and it changes the user-observable contract of connectionTimeout. A legitimately slow server (cold-start container, congested link) that previously survived because each packet reset the timer will now hit ERR_*_CONNECTION_TIMEOUT at the absolute deadline. That is almost certainly the right behaviour (matches libpq / mysql2), but it is a behaviour change a maintainer should confirm — in particular whether any docs / release notes need to mention it.

Other factors

  • All three of my prior inline findings are resolved and the fixes look right on re-read.
  • Test coverage is good: fail-before/pass-after on 11 bug cases, 4 boundary happy paths, both adapters, the mixed-method Postgres matrix, and the caching_sha2 public-key loop.
  • The Postgres SASL arm's guard was flipped from "lazy-init if not already Sasl" to "reject if not Pending" — I confirmed nothing else sets authentication_state back to Pending after the first request, so this can't false-positive on the legitimate single-request path.
  • The MySQL timer gate is in the scopeguard::defer!, so it runs after read_and_process_data has cleared IS_PROCESSING_DATA; reset_connection_timeout()'s own is_processing_data() early-return therefore doesn't interfere.

@Jarred-Sumner
Jarred-Sumner merged commit b4ee407 into main Jul 29, 2026
52 of 55 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/ddc10b2a/sql-auth-loop-and-connect-deadline branch July 29, 2026 11:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants