From 4f12d6c49f08c0dbfbbfbbe5074ba0cf7325b661 Mon Sep 17 00:00:00 2001 From: Matthew Slipper Date: Mon, 28 Sep 2026 22:07:03 -0600 Subject: [PATCH 1/2] fix: bound postgres frontend messages --- internal/postgres/relay_test.go | 160 +++++++++++++++++++++++++++++++- internal/postgres/session.go | 13 ++- 2 files changed, 171 insertions(+), 2 deletions(-) diff --git a/internal/postgres/relay_test.go b/internal/postgres/relay_test.go index 86ae1d3..617c70e 100644 --- a/internal/postgres/relay_test.go +++ b/internal/postgres/relay_test.go @@ -1,6 +1,7 @@ package postgres import ( + "encoding/binary" "io" "log/slog" "net" @@ -24,7 +25,7 @@ func TestRelayRejectsFunctionCall(t *testing.T) { require.NoError(t, upstream.Close()) }) - backend := pgproto3.NewBackend(relayClient, relayClient) + backend := newClientBackend(relayClient) frontend := pgproto3.NewFrontend(relayUpstream, relayUpstream) logger := slog.New(slog.NewTextHandler(io.Discard, nil)) r := newRelay(relayClient, relayUpstream, backend, frontend, &Upstream{}, logger) @@ -82,3 +83,160 @@ func TestRelayRejectsFunctionCall(t *testing.T) { require.FailNow(t, "client-to-server relay did not stop") } } + +func TestRelayClosesConnectionForOversizedFrontendMessage(t *testing.T) { + client, relayClient := net.Pipe() + relayUpstream, upstream := net.Pipe() + clientClosed := false + upstreamClosed := false + t.Cleanup(func() { + if !clientClosed { + require.NoError(t, client.Close()) + } + if !upstreamClosed { + require.NoError(t, upstream.Close()) + } + }) + + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + r := newRelay( + relayClient, + relayUpstream, + newClientBackend(relayClient), + pgproto3.NewFrontend(relayUpstream, relayUpstream), + &Upstream{}, + logger, + ) + + done := make(chan struct{}) + go func() { + defer close(done) + r.run() + }() + + header := make([]byte, 5) + header[0] = 'Q' + // The protocol length includes its own four bytes, but not the message type. + binary.BigEndian.PutUint32(header[1:], uint32(maxFrontendMessageBodyLen+5)) + _, err := client.Write(header) + require.NoError(t, err) + + require.NoError(t, client.SetReadDeadline(time.Now().Add(time.Second))) + _, err = client.Read(make([]byte, 1)) + require.ErrorIs(t, err, io.EOF) + + select { + case <-done: + case <-time.After(time.Second): + require.FailNow(t, "relay did not stop after oversized frontend message") + } + + require.NoError(t, client.Close()) + clientClosed = true + require.NoError(t, upstream.Close()) + upstreamClosed = true +} + +func TestRelayPreservesUpstreamTransactionStateOnReject(t *testing.T) { + statuses := []struct { + name string + value byte + }{ + {name: "transaction", value: 'T'}, + {name: "failed transaction", value: 'E'}, + } + protocols := []struct { + name string + send func(*pgproto3.Frontend) error + sync bool + }{ + { + name: "simple query", + send: func(client *pgproto3.Frontend) error { + client.Send(&pgproto3.Query{String: "SET ROLE other_role"}) + return client.Flush() + }, + }, + { + name: "extended query", + send: func(client *pgproto3.Frontend) error { + client.Send(&pgproto3.Parse{Query: "SET ROLE other_role"}) + return client.Flush() + }, + sync: true, + }, + } + + for _, status := range statuses { + for _, protocol := range protocols { + t.Run(status.name+"/"+protocol.name, func(t *testing.T) { + client, relayClient := net.Pipe() + relayUpstream, upstream := net.Pipe() + clientClosed := false + upstreamClosed := false + t.Cleanup(func() { + if !clientClosed { + require.NoError(t, client.Close()) + } + if !upstreamClosed { + require.NoError(t, upstream.Close()) + } + }) + + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + r := newRelay( + relayClient, + relayUpstream, + newClientBackend(relayClient), + pgproto3.NewFrontend(relayUpstream, relayUpstream), + &Upstream{}, + logger, + ) + + done := make(chan struct{}) + go func() { + defer close(done) + r.run() + }() + + upstreamProtocol := pgproto3.NewBackend(upstream, upstream) + upstreamProtocol.Send(&pgproto3.ReadyForQuery{TxStatus: status.value}) + require.NoError(t, upstreamProtocol.Flush()) + + clientProtocol := pgproto3.NewFrontend(client, client) + msg, err := clientProtocol.Receive() + require.NoError(t, err) + ready, ok := msg.(*pgproto3.ReadyForQuery) + require.True(t, ok) + require.Equal(t, status.value, ready.TxStatus) + + require.NoError(t, protocol.send(clientProtocol)) + + msg, err = clientProtocol.Receive() + require.NoError(t, err) + _, ok = msg.(*pgproto3.ErrorResponse) + require.True(t, ok) + if protocol.sync { + clientProtocol.Send(&pgproto3.Sync{}) + require.NoError(t, clientProtocol.Flush()) + } + + msg, err = clientProtocol.Receive() + require.NoError(t, err) + ready, ok = msg.(*pgproto3.ReadyForQuery) + require.True(t, ok) + require.Equal(t, status.value, ready.TxStatus) + + require.NoError(t, client.Close()) + clientClosed = true + select { + case <-done: + case <-time.After(time.Second): + require.FailNow(t, "relay did not stop") + } + require.NoError(t, upstream.Close()) + upstreamClosed = true + }) + } + } +} diff --git a/internal/postgres/session.go b/internal/postgres/session.go index 2486768..3941c21 100644 --- a/internal/postgres/session.go +++ b/internal/postgres/session.go @@ -14,6 +14,11 @@ import ( "github.com/jackc/pgx/v5/pgproto3" ) +// maxFrontendMessageBodyLen caps every client message after the startup packet. +// pgproto3 otherwise accepts bodies up to the protocol's multi-gigabyte length +// field and allocates the declared size before decoding the message. +const maxFrontendMessageBodyLen = 16 << 20 + // runSession owns a single client connection from accept through close. It // performs the proxy-side handshake under a deadline, selects a route from the // startup database name, opens an upstream connection through pgconn, issues @@ -24,7 +29,7 @@ func runSession(ctx context.Context, clientConn net.Conn, listener *Listener, lo _ = clientConn.SetDeadline(time.Now().Add(handshakeTimeout)) - backend := pgproto3.NewBackend(clientConn, clientConn) + backend := newClientBackend(clientConn) startup, err := receiveStartup(clientConn, backend) if err != nil { @@ -111,6 +116,12 @@ func runSession(ctx context.Context, clientConn net.Conn, listener *Listener, lo relay.run() } +func newClientBackend(conn net.Conn) *pgproto3.Backend { + backend := pgproto3.NewBackend(conn, conn) + backend.SetMaxBodyLen(maxFrontendMessageBodyLen) + return backend +} + // receiveStartup handles the optional SSLRequest / GSSEncRequest preludes and // returns the StartupMessage that follows. Returns (nil, nil) when the client // sent a CancelRequest (handled by closing the connection) since the proxy From 9b0e4db549a00fc10fb6b78f77e6d68ed627e6e2 Mon Sep 17 00:00:00 2001 From: Matthew Slipper Date: Mon, 28 Sep 2026 22:07:10 -0600 Subject: [PATCH 2/2] docs: document postgres message limit --- iron-proxy.example.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/iron-proxy.example.yaml b/iron-proxy.example.yaml index 2179d9c..9a9db37 100644 --- a/iron-proxy.example.yaml +++ b/iron-proxy.example.yaml @@ -713,8 +713,8 @@ transforms: # - Functions that wrap set_config under a different name. # # Limitations: client→proxy TLS is not supported (SSLRequest is refused); -# CancelRequest is not forwarded; one shared client credential per route -# (no per-user). +# CancelRequest is not forwarded; frontend messages are limited to 16 MiB; +# one shared client credential per route (no per-user). # # The proxy runs a single postgres listener: the postgres key is one object # with a bind address and a list of upstreams. A single listen address serves