diff --git a/README.md b/README.md index 9a5e1e2..9546814 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Single binary. Single YAML config. - **PostgreSQL MITM proxy.** Optional listener that authenticates clients against proxy-managed credentials, injects `SET ROLE` on the upstream session, and rejects client attempts to mutate the role (`SET ROLE`, - `set_config('role', ...)`, DO blocks, etc.) via a SQL AST walk. Pairs with + any `set_config` call, DO blocks, etc.) via a SQL AST walk. Pairs with PostgreSQL row-level security to give per-tenant data isolation when the application connects as a shared service-account user. **Requires PgBouncer (if used) to run in `pool_mode = session`** — transaction or diff --git a/integration_test/postgres_test.go b/integration_test/postgres_test.go index 21cca18..4ba9d6a 100644 --- a/integration_test/postgres_test.go +++ b/integration_test/postgres_test.go @@ -307,13 +307,31 @@ func TestPostgresPolicy(t *testing.T) { require.Equal(t, pgRole, role) }) - t.Run("set_config for other gucs passes through", func(t *testing.T) { - // Only role-mutating GUCs trigger the rejection; set_config for benign - // parameters should pass through. - conn := dial(t, pgClientPassword) - results, err := conn.Exec(context.Background(), "SELECT set_config('application_name', 'iron-test', false)").ReadAll() + t.Run("parameterized set_config target is rejected", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + conn, err := pgx.Connect(ctx, connStr(pgClientPassword)) require.NoError(t, err) - require.Len(t, results, 1) + t.Cleanup(func() { require.NoError(t, conn.Close(context.Background())) }) + + _, err = conn.Exec(ctx, "SELECT set_config($1, $2, false)", "role", "other_role") + require.Error(t, err) + var pgErr *pgconn.PgError + require.True(t, errors.As(err, &pgErr)) + require.Contains(t, pgErr.Message, "set_config is not supported") + + var role string + require.NoError(t, conn.QueryRow(ctx, "SELECT current_role").Scan(&role)) + require.Equal(t, pgRole, role) + }) + + t.Run("set_config for other gucs is rejected", func(t *testing.T) { + conn := dial(t, pgClientPassword) + _, err := conn.Exec(context.Background(), "SELECT set_config('application_name', 'iron-test', false)").ReadAll() + require.Error(t, err) + var pgErr *pgconn.PgError + require.True(t, errors.As(err, &pgErr)) + require.Contains(t, pgErr.Message, "set_config is not supported") }) t.Run("session setting is injected at session start", func(t *testing.T) { diff --git a/internal/postgres/config.go b/internal/postgres/config.go index 3323f71..409d6d2 100644 --- a/internal/postgres/config.go +++ b/internal/postgres/config.go @@ -17,12 +17,13 @@ // While the relay is running the proxy is mostly transparent. It rejects // client-issued role-changing statements (`SET ROLE`, `RESET ROLE`, // `SET SESSION AUTHORIZATION`, `RESET SESSION AUTHORIZATION`) and their -// function-call equivalents (`set_config('role', ...)`); any `SET`, `RESET`, or -// `set_config` of a setting the upstream pins; the reset-everything statements +// function-call equivalents; all calls to `set_config`; any `SET` or `RESET` +// of a setting the upstream pins; the reset-everything statements // `RESET ALL` and `DISCARD ALL` (which would clear the managed role and pinned -// settings); and DO blocks. Multi-statement Simple Queries are allowed as long -// as every statement passes; a batch is rejected if any statement is rejected. -// Extended Query, COPY, and prepared statements pass through unchanged. +// settings); DO blocks; and the legacy wire-level FunctionCall protocol. +// Multi-statement Simple Queries are allowed as long as every statement passes; +// a batch is rejected if any statement is rejected. Extended Query, COPY, and +// prepared statements pass through unchanged. // // The proxy runs a single postgres listener fronting multiple upstream // databases: the top-level postgres: block is one object with a listen address diff --git a/internal/postgres/policy.go b/internal/postgres/policy.go index 414a5b0..80c9c8f 100644 --- a/internal/postgres/policy.go +++ b/internal/postgres/policy.go @@ -14,10 +14,9 @@ const ( // The plpgsql body is opaque to our SQL-level AST walker; rejecting // avoids the risk of an embedded role change. RejectDoBlock - // RejectPinnedSetting — the client tried to SET / RESET / set_config a - // session variable the upstream pins. The proxy sets these at session start - // and forbids overrides so a setting used as a security boundary can't be - // changed. + // RejectPinnedSetting — the client tried to SET or RESET a session variable + // the upstream pins. The proxy sets these at session start and forbids + // overrides so a setting used as a security boundary can't be changed. RejectPinnedSetting // RejectResetAll — the client tried RESET ALL, which would reset the // proxy-managed role and every pinned setting. @@ -25,6 +24,12 @@ const ( // RejectDiscardAll — the client tried DISCARD ALL, which (like RESET ALL) // resets the proxy-managed role and every pinned setting. RejectDiscardAll + // RejectSetConfig — the client called set_config. Dynamic targets cannot be + // inspected safely, so all calls are rejected regardless of the GUC name. + RejectSetConfig + // RejectFunctionCall — the client used the legacy wire-level FunctionCall + // protocol, which invokes a function by OID without inspectable SQL text. + RejectFunctionCall ) // ClassifyClientStatement inspects sql and returns whether the relay should @@ -32,9 +37,9 @@ const ( // the lowercased set of setting names this upstream forbids the client from // mutating; pass nil when the upstream pins nothing. // -// Beyond the role policy, the proxy rejects any SET / RESET / set_config of a -// pinned setting, and any RESET ALL / DISCARD ALL (which would reset the -// managed role and every pinned setting at once). +// Beyond the role policy, the proxy rejects every set_config call, any SET or +// RESET of a pinned setting, and any RESET ALL / DISCARD ALL (which would reset +// the managed role and every pinned setting at once). // // Multi-statement Simple Queries are allowed when every statement passes; // Classify aggregates the batch, so a single offending statement anywhere @@ -47,6 +52,8 @@ func ClassifyClientStatement(sql string, pinned map[string]struct{}) (allowed bo switch op.Kind { case OpSetRole, OpSetSessionAuthorization, OpResetRole, OpResetSessionAuthorization: return false, RejectClientRoleChange + case OpSetConfig: + return false, RejectSetConfig case OpDoBlock: // DO blocks contain opaque plpgsql we can't introspect from the SQL // AST. Rather than risk an embedded role change slipping through, diff --git a/internal/postgres/policy_test.go b/internal/postgres/policy_test.go index 555e966..763de34 100644 --- a/internal/postgres/policy_test.go +++ b/internal/postgres/policy_test.go @@ -54,7 +54,7 @@ func TestClassifyClientStatement(t *testing.T) { {name: "set pinned rejected", sql: "SET centaur.slack_channel_id = 'C999'", pinned: pinned, reason: RejectPinnedSetting}, {name: "set local pinned rejected", sql: "SET LOCAL centaur.slack_channel_id = 'C999'", pinned: pinned, reason: RejectPinnedSetting}, {name: "reset pinned rejected", sql: "RESET centaur.slack_channel_id", pinned: pinned, reason: RejectPinnedSetting}, - {name: "set_config pinned rejected", sql: "SELECT set_config('centaur.slack_channel_id', 'C999', false)", pinned: pinned, reason: RejectPinnedSetting}, + {name: "set_config pinned rejected", sql: "SELECT set_config('centaur.slack_channel_id', 'C999', false)", pinned: pinned, reason: RejectSetConfig}, {name: "set pinned buried in batch rejected", sql: "SELECT 1; SET centaur.slack_channel_id = 'C999'", pinned: pinned, reason: RejectPinnedSetting}, {name: "reset all rejected even with pin", sql: "RESET ALL", pinned: pinned, reason: RejectResetAll}, // Reading a pinned setting is fine; only writes are blocked. @@ -65,12 +65,14 @@ func TestClassifyClientStatement(t *testing.T) { {name: "set formerly-pinned allowed without pin", sql: "SET centaur.slack_channel_id = 'C999'", allowed: true}, // Function-call bypass attempts — caught by AST walker. - {name: "set_config role rejected", sql: "SELECT set_config('role', 'admin', false)", reason: RejectClientRoleChange}, - {name: "pg_catalog set_config role rejected", sql: "SELECT pg_catalog.set_config('role', 'admin', false)", reason: RejectClientRoleChange}, - {name: "set_config session_authorization rejected", sql: "SELECT set_config('session_authorization', 'admin', false)", reason: RejectClientRoleChange}, - {name: "set_config role in cte rejected", sql: "WITH x AS (SELECT set_config('role', 'admin', false)) SELECT * FROM x", reason: RejectClientRoleChange}, + {name: "set_config role rejected", sql: "SELECT set_config('role', 'admin', false)", reason: RejectSetConfig}, + {name: "pg_catalog set_config role rejected", sql: "SELECT pg_catalog.set_config('role', 'admin', false)", reason: RejectSetConfig}, + {name: "set_config session_authorization rejected", sql: "SELECT set_config('session_authorization', 'admin', false)", reason: RejectSetConfig}, + {name: "set_config role in cte rejected", sql: "WITH x AS (SELECT set_config('role', 'admin', false)) SELECT * FROM x", reason: RejectSetConfig}, + {name: "set_config non-role setting rejected", sql: "SELECT set_config('search_path', 'public', false)", reason: RejectSetConfig}, + {name: "set_config parameter target rejected", sql: "SELECT set_config($1, $2, false)", reason: RejectSetConfig}, + {name: "set_config cast target rejected", sql: "SELECT set_config('role'::text, 'admin', false)", reason: RejectSetConfig}, {name: "current_setting role allowed", sql: "SELECT current_setting('role')", allowed: true}, - {name: "set_config search_path allowed", sql: "SELECT set_config('search_path', 'public', false)", allowed: true}, // DO blocks rejected outright. {name: "do block rejected", sql: "DO $$ BEGIN END $$", reason: RejectDoBlock}, diff --git a/internal/postgres/relay_test.go b/internal/postgres/relay_test.go new file mode 100644 index 0000000..86ae1d3 --- /dev/null +++ b/internal/postgres/relay_test.go @@ -0,0 +1,84 @@ +package postgres + +import ( + "io" + "log/slog" + "net" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgproto3" + "github.com/stretchr/testify/require" +) + +func TestRelayRejectsFunctionCall(t *testing.T) { + client, relayClient := net.Pipe() + relayUpstream, upstream := net.Pipe() + clientClosed := false + t.Cleanup(func() { + if !clientClosed { + require.NoError(t, client.Close()) + } + require.NoError(t, relayClient.Close()) + require.NoError(t, relayUpstream.Close()) + require.NoError(t, upstream.Close()) + }) + + backend := pgproto3.NewBackend(relayClient, relayClient) + frontend := pgproto3.NewFrontend(relayUpstream, relayUpstream) + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + r := newRelay(relayClient, relayUpstream, backend, frontend, &Upstream{}, logger) + r.txStatus = 'T' + + done := make(chan struct{}) + go func() { + defer close(done) + r.clientToServer() + }() + + clientProtocol := pgproto3.NewFrontend(client, client) + clientProtocol.Send(&pgproto3.FunctionCall{ + Function: 1, + ArgFormatCodes: []uint16{0}, + Arguments: [][]byte{[]byte("role"), []byte("other_role"), []byte("false")}, + ResultFormatCode: 0, + }) + require.NoError(t, clientProtocol.Flush()) + + msg, err := clientProtocol.Receive() + require.NoError(t, err) + pgErr, ok := msg.(*pgproto3.ErrorResponse) + require.True(t, ok) + require.Equal(t, "0A000", pgErr.Code) + require.Contains(t, pgErr.Message, "FunctionCall") + + msg, err = clientProtocol.Receive() + require.NoError(t, err) + ready, ok := msg.(*pgproto3.ReadyForQuery) + require.True(t, ok) + require.Equal(t, byte('T'), ready.TxStatus) + + require.NoError(t, upstream.SetReadDeadline(time.Now().Add(50*time.Millisecond))) + _, err = upstream.Read(make([]byte, 1)) + var netErr net.Error + require.ErrorAs(t, err, &netErr) + require.True(t, netErr.Timeout()) + require.NoError(t, upstream.SetReadDeadline(time.Time{})) + + clientProtocol.Send(&pgproto3.Query{String: "SELECT 1"}) + require.NoError(t, clientProtocol.Flush()) + upstreamProtocol := pgproto3.NewBackend(upstream, upstream) + upstreamMsg, err := upstreamProtocol.Receive() + require.NoError(t, err) + query, ok := upstreamMsg.(*pgproto3.Query) + require.True(t, ok) + require.Equal(t, "SELECT 1", query.String) + + require.NoError(t, client.Close()) + clientClosed = true + select { + case <-done: + case <-time.After(time.Second): + require.FailNow(t, "client-to-server relay did not stop") + } +} diff --git a/internal/postgres/session.go b/internal/postgres/session.go index 0f87a88..2486768 100644 --- a/internal/postgres/session.go +++ b/internal/postgres/session.go @@ -267,9 +267,8 @@ func completeClientHandshake(backend *pgproto3.Backend, hj *pgconn.HijackedConn) // relay drives the bidirectional message pump between client and upstream // after the role has been set on the upstream session. // -// Two goroutines do socket I/O: c2s reads client messages and rejects -// role-changing statements (and DO blocks) before forwarding everything else; -// s2c is a pure passthrough. +// Two goroutines do socket I/O: c2s reads client messages and applies the +// statement and protocol policy before forwarding; s2c is a pure passthrough. // // Writes to the client serialize through clientWriteMu since both goroutines // may write — c2s when synthesizing a reject, s2c when forwarding the normal @@ -285,6 +284,10 @@ type relay struct { logger *slog.Logger clientWriteMu sync.Mutex + // txStatus is the last ReadyForQuery status received from upstream. It is + // protected by clientWriteMu so synthetic ReadyForQuery messages preserve + // the upstream transaction state. + txStatus byte // skipExtended, when true, drops client Bind/Describe/Execute/Close // messages until a Sync is observed. Set when a Parse is rejected: per the @@ -304,6 +307,7 @@ func newRelay(clientConn, upstreamConn net.Conn, backend *pgproto3.Backend, fron frontend: frontend, upstream: upstream, logger: logger, + txStatus: 'I', } } @@ -327,8 +331,8 @@ func (r *relay) run() { <-done } -// clientToServer reads frontend messages from the client and forwards them -// upstream, rejecting only role-changing statements and DO blocks. +// clientToServer reads frontend messages from the client and forwards those +// permitted by the statement and protocol policy upstream. func (r *relay) clientToServer() { for { msg, err := r.backend.Receive() @@ -370,13 +374,23 @@ func (r *relay) clientToServer() { return } + case *pgproto3.FunctionCall: + if r.skipExtended { + continue + } + // FunctionCall invokes a function by OID without carrying SQL text, + // so the proxy cannot apply its statement policy. The protocol is a + // legacy fast path; reject it rather than forwarding an opaque call. + r.writeReject(RejectFunctionCall, true) + continue + case *pgproto3.Sync: if r.skipExtended { // We rejected an earlier Parse in this extended-query batch. // Synthesize a ReadyForQuery for the client and consume the // Sync without forwarding upstream. r.skipExtended = false - r.writeClient(&pgproto3.ReadyForQuery{TxStatus: 'I'}) + r.writeReadyForQuery() continue } r.frontend.Send(m) @@ -406,17 +420,29 @@ func (r *relay) writeReject(reason RejectReason, withReadyForQuery bool) { r.backend.Send(rejectError(reason)) if withReadyForQuery { - r.backend.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'}) + r.backend.Send(&pgproto3.ReadyForQuery{TxStatus: r.txStatus}) } _ = r.backend.Flush() } +// writeReadyForQuery writes a synthetic ReadyForQuery carrying the most recent +// transaction status observed from upstream. +func (r *relay) writeReadyForQuery() { + r.clientWriteMu.Lock() + defer r.clientWriteMu.Unlock() + r.backend.Send(&pgproto3.ReadyForQuery{TxStatus: r.txStatus}) + _ = r.backend.Flush() +} + // writeClient writes one or more BackendMessages to the client under the // shared write mutex. func (r *relay) writeClient(msgs ...pgproto3.BackendMessage) { r.clientWriteMu.Lock() defer r.clientWriteMu.Unlock() for _, m := range msgs { + if ready, ok := m.(*pgproto3.ReadyForQuery); ok { + r.txStatus = ready.TxStatus + } r.backend.Send(m) } _ = r.backend.Flush() @@ -435,7 +461,7 @@ func rejectError(reason RejectReason) *pgproto3.ErrorResponse { return &pgproto3.ErrorResponse{ Severity: "ERROR", Code: "42501", - Message: "blocked by iron-proxy policy: this session setting is managed by the proxy; clients may not SET / RESET / set_config it", + Message: "blocked by iron-proxy policy: this session setting is managed by the proxy; clients may not SET or RESET it", } case RejectResetAll: return &pgproto3.ErrorResponse{ @@ -449,13 +475,25 @@ func rejectError(reason RejectReason) *pgproto3.ErrorResponse { Code: "42501", Message: "blocked by iron-proxy policy: DISCARD ALL would reset the proxy-managed role and session settings", } + case RejectSetConfig: + return &pgproto3.ErrorResponse{ + Severity: "ERROR", + Code: "42501", + Message: "blocked by iron-proxy policy: set_config is not supported because session settings are managed by the proxy", + } + case RejectFunctionCall: + return &pgproto3.ErrorResponse{ + Severity: "ERROR", + Code: "0A000", + Message: "blocked by iron-proxy policy: the legacy FunctionCall protocol is not supported", + } case RejectClientRoleChange: fallthrough default: return &pgproto3.ErrorResponse{ Severity: "ERROR", Code: "42501", - Message: "blocked by iron-proxy policy: role is managed by the proxy; clients may not issue SET ROLE / SET SESSION AUTHORIZATION / RESET ROLE / set_config('role',...) / set_config('session_authorization',...)", + Message: "blocked by iron-proxy policy: role is managed by the proxy; clients may not issue SET ROLE / SET SESSION AUTHORIZATION / RESET ROLE", } } } diff --git a/internal/postgres/sql.go b/internal/postgres/sql.go index c6ebbd2..1b2b3b0 100644 --- a/internal/postgres/sql.go +++ b/internal/postgres/sql.go @@ -6,8 +6,8 @@ import ( // The wasilibs package is a pure-Go (wazero-based) drop-in for pg_query_go's // Parse function, sparing us from a CGO build dependency. AST node types // still come from the pganalyze package; wasilibs re-uses them. - pgparse "github.com/wasilibs/go-pgquery" pg_query "github.com/pganalyze/pg_query_go/v6" + pgparse "github.com/wasilibs/go-pgquery" "google.golang.org/protobuf/reflect/protoreflect" lru "github.com/hashicorp/golang-lru/v2" @@ -49,8 +49,7 @@ const ( // OpOther is any statement not matched by a more specific case. OpOther OpKind = iota // OpSetRole is `SET ROLE ` or anything anywhere in the AST that - // changes the `role` GUC — including SET LOCAL, SET SESSION, - // and function-call bypasses like `set_config('role', ...)`. + // changes the `role` GUC through SET, including SET LOCAL and SET SESSION. OpSetRole // OpSetSessionAuthorization is the equivalent for `session_authorization`. OpSetSessionAuthorization @@ -69,6 +68,10 @@ const ( // upstream so Postgres produces the canonical syntax error; the proxy // doesn't try to second-guess. OpParseError + // OpSetConfig is any call to set_config, regardless of schema qualification + // or whether its target setting is a string literal. Dynamic targets cannot + // be proven safe at Parse time, so the policy rejects the function wholesale. + OpSetConfig ) // GUC names whose mutation we treat as a role change for policy purposes. @@ -78,13 +81,6 @@ var roleGUCs = map[string]OpKind{ "session_authorization": OpSetSessionAuthorization, } -// dangerous set_config / current_setting target GUCs. We don't reject reads -// (current_setting), only writes (set_config). -var roleGUCsForSetConfig = map[string]OpKind{ - "role": OpSetRole, - "session_authorization": OpSetSessionAuthorization, -} - // classifyCache memoizes Classify results so repeated queries (the common // case in ORM workloads where the same parameterized SQL fires hundreds of // times per connection) don't re-parse on the hot path. Bounded so a @@ -204,10 +200,12 @@ func scanMutations(node *pg_query.Node) mutations { case *pg_query.VariableShowStmt: // SHOW is read-only; ignore. case *pg_query.FuncCall: - if name, kind := setConfigTarget(n); name != "" { - m.setGUCs = append(m.setGUCs, name) - if kind != 0 && m.kind == 0 { - m.kind = kind + if name, ok := setConfigTarget(n); ok { + if name != "" { + m.setGUCs = append(m.setGUCs, name) + } + if m.kind == 0 { + m.kind = OpSetConfig } } } @@ -233,46 +231,42 @@ func roleKindFor(name string, kind pg_query.VariableSetKind) OpKind { return base } -// setConfigTarget inspects fc and, when it is a call to set_config (or -// pg_catalog.set_config) whose first argument is a string-literal GUC name, -// returns that lowercased name and the role-policy OpKind for it (0 when the -// target is not role-affecting). Returns ("", 0) when fc is not such a call. -func setConfigTarget(fc *pg_query.FuncCall) (name string, kind OpKind) { +// setConfigTarget inspects fc and reports whether it is a call to set_config, +// including schema-qualified forms. When the first argument is a string +// literal, name is its lowercased value; dynamic targets return an empty name +// with ok=true so the policy can still reject the call. +func setConfigTarget(fc *pg_query.FuncCall) (name string, ok bool) { names := fc.GetFuncname() if len(names) == 0 { - return "", 0 + return "", false } // Funcname is a list of String nodes: ["set_config"] for unqualified // or ["pg_catalog", "set_config"] for schema-qualified. We accept any // schema qualifier and trust that user-defined set_config functions // are also suspicious — better a rare false positive than a bypass. last := names[len(names)-1] - lastStr, ok := last.Node.(*pg_query.Node_String_) - if !ok { - return "", 0 + lastStr, isString := last.Node.(*pg_query.Node_String_) + if !isString { + return "", false } if !strings.EqualFold(lastStr.String_.GetSval(), "set_config") { - return "", 0 + return "", false } args := fc.GetArgs() if len(args) < 1 { - return "", 0 + return "", true } - param, ok := stringConst(args[0]) - if !ok { - return "", 0 + param, isConst := stringConst(args[0]) + if !isConst { + return "", true } - lower := strings.ToLower(param) - // roleGUCsForSetConfig returns the zero OpKind (0) for non-role names, which - // is exactly the "not role-affecting" signal callers expect. - return lower, roleGUCsForSetConfig[lower] + return strings.ToLower(param), true } // stringConst returns the string value of node if it's an A_Const with a // string value, else ("", false). set_config's first argument is the GUC -// name; we only flag calls where it's a literal we can read at parse time. -// `set_config(my_var, ...)` where my_var is a variable evaluates at run -// time and is invisible to us — accepted limitation. +// name. Literal targets are retained for mutation metadata; non-literal +// targets are still classified as OpSetConfig and rejected by policy. func stringConst(node *pg_query.Node) (string, bool) { if node == nil { return "", false diff --git a/internal/postgres/sql_test.go b/internal/postgres/sql_test.go index 4d28265..81a4689 100644 --- a/internal/postgres/sql_test.go +++ b/internal/postgres/sql_test.go @@ -52,30 +52,31 @@ func TestClassify(t *testing.T) { {name: "multi select then select allowed", sql: "SELECT 1; SELECT 2", want: OpOther}, {name: "multi benign then set role", sql: "SELECT 1; SET ROLE tenant", want: OpSetRole}, {name: "multi benign then do block", sql: "SELECT 1; DO $$ BEGIN END $$", want: OpDoBlock}, - {name: "multi benign then set_config role", sql: "SELECT 1; SELECT set_config('role', 'admin', false)", want: OpSetRole}, + {name: "multi benign then set_config role", sql: "SELECT 1; SELECT set_config('role', 'admin', false)", want: OpSetConfig}, {name: "multi non-role sets allowed", sql: "SET search_path = public; SELECT 1", want: OpOther}, // Trailing semicolon alone is *not* multi (pg_query collapses it). {name: "trailing semicolon not multi", sql: "SET ROLE tenant;", want: OpSetRole}, // set_config function-call bypass attempts - {name: "set_config role top level", sql: "SELECT set_config('role', 'admin', false)", want: OpSetRole}, - {name: "set_config role local flag", sql: "SELECT set_config('role', 'admin', true)", want: OpSetRole}, - {name: "pg_catalog set_config role", sql: "SELECT pg_catalog.set_config('role', 'admin', false)", want: OpSetRole}, - {name: "set_config session_authorization", sql: "SELECT set_config('session_authorization', 'admin', false)", want: OpSetSessionAuthorization}, - {name: "set_config case insensitive name", sql: "SELECT set_config('ROLE', 'admin', false)", want: OpSetRole}, - {name: "set_config nested in select", sql: "SELECT 1, set_config('role', 'admin', false), 2", want: OpSetRole}, - {name: "set_config in subquery", sql: "SELECT * FROM (SELECT set_config('role', 'admin', false)) s", want: OpSetRole}, - {name: "set_config in cte", sql: "WITH x AS (SELECT set_config('role', 'admin', false)) SELECT * FROM x", want: OpSetRole}, - {name: "set_config in where clause", sql: "SELECT 1 WHERE set_config('role', 'admin', false) = 'admin'", want: OpSetRole}, - {name: "set_config inside insert", sql: "INSERT INTO t SELECT set_config('role', 'admin', false)", want: OpSetRole}, - - // set_config for safe parameters — allowed. - {name: "set_config search_path allowed", sql: "SELECT set_config('search_path', 'public', false)", want: OpOther}, + {name: "set_config role top level", sql: "SELECT set_config('role', 'admin', false)", want: OpSetConfig}, + {name: "set_config role local flag", sql: "SELECT set_config('role', 'admin', true)", want: OpSetConfig}, + {name: "pg_catalog set_config role", sql: "SELECT pg_catalog.set_config('role', 'admin', false)", want: OpSetConfig}, + {name: "set_config session_authorization", sql: "SELECT set_config('session_authorization', 'admin', false)", want: OpSetConfig}, + {name: "set_config case insensitive name", sql: "SELECT set_config('ROLE', 'admin', false)", want: OpSetConfig}, + {name: "set_config nested in select", sql: "SELECT 1, set_config('role', 'admin', false), 2", want: OpSetConfig}, + {name: "set_config in subquery", sql: "SELECT * FROM (SELECT set_config('role', 'admin', false)) s", want: OpSetConfig}, + {name: "set_config in cte", sql: "WITH x AS (SELECT set_config('role', 'admin', false)) SELECT * FROM x", want: OpSetConfig}, + {name: "set_config in where clause", sql: "SELECT 1 WHERE set_config('role', 'admin', false) = 'admin'", want: OpSetConfig}, + {name: "set_config inside insert", sql: "INSERT INTO t SELECT set_config('role', 'admin', false)", want: OpSetConfig}, + {name: "set_config non-role setting", sql: "SELECT set_config('search_path', 'public', false)", want: OpSetConfig}, + {name: "set_config parameter target", sql: "SELECT set_config($1, $2, false)", want: OpSetConfig}, + {name: "set_config cast target", sql: "SELECT set_config('role'::text, 'admin', false)", want: OpSetConfig}, + {name: "set_config computed target", sql: "SELECT set_config(concat('ro', 'le'), 'admin', false)", want: OpSetConfig}, {name: "current_setting role is read only", sql: "SELECT current_setting('role')", want: OpOther}, // PREPARE wrapping a SELECT that calls set_config — caught by the // walker through the nested SelectStmt. - {name: "prepare wrapping set_config caught", sql: "PREPARE p AS SELECT set_config('role', 'admin', false)", want: OpSetRole}, + {name: "prepare wrapping set_config caught", sql: "PREPARE p AS SELECT set_config('role', 'admin', false)", want: OpSetConfig}, // DO blocks — rejected regardless of contents. {name: "do block empty", sql: "DO $$ BEGIN END $$", want: OpDoBlock}, diff --git a/iron-proxy.example.yaml b/iron-proxy.example.yaml index ae9786f..2179d9c 100644 --- a/iron-proxy.example.yaml +++ b/iron-proxy.example.yaml @@ -699,8 +699,10 @@ transforms: # inside CTEs, subqueries, function arguments, etc.: # - SET ROLE / RESET ROLE / SET SESSION AUTHORIZATION / RESET SESSION # AUTHORIZATION — direct GUC mutation. -# - SELECT set_config('role', ...), SELECT pg_catalog.set_config(...) and -# the same for 'session_authorization' — function-call bypasses. +# - All calls to set_config, including schema-qualified and parameterized +# forms. Dynamic targets cannot be proven safe when the query is parsed. +# - The legacy wire-level FunctionCall protocol, which invokes functions by +# OID without carrying SQL text the proxy can inspect. # - DO $$ ... $$ blocks — the plpgsql body is opaque to the SQL parser, so # we reject rather than risk an embedded role change. # - Multi-statement Simple Queries — kept as a single-statement guard. @@ -744,11 +746,12 @@ transforms: # # client issues runs as this role on the upstream database. # role: tenant_role # # Optional session variables (GUCs) the proxy SETs at session start, -# # before the SET ROLE. The proxy also pins these: a client may not SET, -# # RESET, or set_config them afterwards (nor RESET ALL / DISCARD ALL), so -# # a setting used as a security boundary (e.g. an RLS key) can't be -# # overridden. Names must be bare or dotted GUC identifiers; role and -# # session_authorization are reserved (use role above). +# # before the SET ROLE. The proxy also pins these: a client may not SET +# # or RESET them afterwards (nor RESET ALL / DISCARD ALL), so a setting +# # used as a security boundary (e.g. an RLS key) can't be overridden. +# # All set_config calls are blocked. Names must be bare or dotted GUC +# # identifiers; role and session_authorization are reserved (use role +# # above). # settings: # - name: app.tenant_id # value: centaur