Implementing Multi-Factor Authentication in a PostgreSQL Binary Protocol Proxy

Multi-Factor Authentication (MFA) is not just for web apps. PostgreSQL can enforce it. But using MFA with the Postgres binary protocol requires precision. The protocol is strict. Every byte counts. When proxying it, the server and client must stay in sync through authentication flows, query parsing, and data streaming.

A Postgres binary protocol proxy sits between the client and the database. It reads and writes the exact wire messages defined in the PostgreSQL protocol spec—StartupMessage, AuthenticationMD5Password, AuthenticationSASL, AuthenticationOk, Query, DataRow, and more. To integrate MFA, the proxy must intercept authentication, pause it, and trigger a second factor challenge without breaking protocol sequence.

The standard workflow is:

  1. Client sends StartupMessage with username and database.
  2. Proxy passes or modifies this to the server.
  3. Server responds with Authentication request.
  4. Proxy halts normal flow after primary authentication and issues MFA challenge out-of-band (TOTP, WebAuthn, push notification).
  5. On success, proxy sends AuthenticationOk to client and resumes protocol.

Key constraints when implementing MFA in a Postgres binary protocol proxy:

  • Maintain exact packet framing and message ordering defined by PostgreSQL.
  • Avoid sending partial or malformed messages; clients will close the connection instantly.
  • Handle SSL negotiation correctly if using TLS, since MFA prompts often require secure transport.
  • Keep latency low; extra round trips for MFA should not block query execution longer than necessary.
  • Ensure MFA verification happens before sending AuthenticationOk to prevent bypass.

Binary protocol proxying adds complexity because Postgres clients expect opaque backend behavior. Extending authentication means building a complete state machine inside the proxy, tracking handshake phase, MFA phase, and post-auth query streaming. Log everything. Any mismatch between client expectations and proxy behavior will cause immediate errors.

Engineers building MFA for Postgres over the binary protocol should use robust libraries for parsing and composing protocol messages. Avoid hacks that rely on plaintext session control. Test with multiple PostgreSQL versions, since protocol changes can break compatibility.

Strong authentication is a simple idea, but real-world MFA over a binary protocol is unforgiving. Done right, it provides the extra layer that credentials alone cannot.

See it live in minutes with hoop.dev and integrate MFA into your Postgres proxy without breaking a single packet.