Skip to content

fix(pg): destroy socket on connection error during connect - #3875

Open
priyanshub18 wants to merge 1 commit into
brianc:masterfrom
priyanshub18:fix/destroy-socket-on-connect-error
Open

priyanshub18 wants to merge 1 commit into
brianc:masterfrom
priyanshub18:fix/destroy-socket-on-connect-error

Conversation

@priyanshub18

Copy link
Copy Markdown

Fixes #3869
Fixes #3870

Problem

When an error occurs during Client#connect() (for example, an async password callback rejecting or returning a non-string, or a TLS 1.3 server rejecting the client certificate with an alert followed by FIN), _handleErrorWhileConnecting() sets this._connectionError = true, clears connectionTimeoutHandle, and rejects connect() — without destroying this.connection.stream.

Because the underlying stream is left open and the connect timeout has been cleared:

  1. Socket / connection leak (Socket left open when a password function rejects during connect #3869): Servers and proxies (such as RDS Proxy) hold the half-authenticated connection open indefinitely; pg-pool drops the failed client without calling end(), leaking one connection per retry.
  2. Hanging client.end() (client.end() never resolves when the server rejects the client certificate during connect() #3870): Calling client.end() after a TLS 1.3 client-cert alert + FIN tries to send a Terminate message and waits forever for connection.once('end'), which never fires.

Solution

  • Destroy this.connection.stream in Client#_handleErrorWhileConnecting() (guarded with typeof this.connection.stream.destroy === 'function' so unit-test/custom mock streams without .destroy() remain safe).
  • The con.once('end', ...) handler already checks this._connectionError, so destroying the stream does not invoke _connectionCallback or emit 'error' a second time; it marks this._ended = true and emits 'end', allowing client.end() to resolve immediately and closing the server-side socket.

Testing

  • Added packages/pg/test/unit/client/connect-error-closes-socket-tests.js (no Postgres server required) covering:
    • Async password function rejecting during connect (verifies server socket closes and client.end() resolves)
    • Async password function resolving to a non-string (42) during connect (verifies server socket closes)
    • TLS 1.3 client-certificate rejection from a fake SSLRequest/TLS server (verifies client.end() resolves promptly)
  • Verified with:
    • make test-unit in packages/pg (all unit tests passing)
    • yarn build
    • yarn lint

Credits to @ambasta, @hamarshehmhmd, and @joshuavivo for the issue reports, root-cause analysis, and TLS reproduction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant