diff --git a/integration_test/postgres_test.go b/integration_test/postgres_test.go index 4ba9d6a..47292fa 100644 --- a/integration_test/postgres_test.go +++ b/integration_test/postgres_test.go @@ -373,6 +373,22 @@ func TestPostgresPolicy(t *testing.T) { require.Equal(t, pgRole, currentRole(t, conn)) }) + t.Run("pg_settings writes are rejected", func(t *testing.T) { + // pg_settings' update rule calls set_config, and an auto-updatable + // view over it forwards updates, so both would bypass pinned settings. + conn := dial(t, pgClientPassword) + for _, sql := range []string{ + "UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout'", + "CREATE TEMP VIEW settings_view AS SELECT * FROM pg_settings", + } { + err := exec(t, conn, sql) + require.Error(t, err) + var pgErr *pgconn.PgError + require.True(t, errors.As(err, &pgErr)) + require.Contains(t, pgErr.Message, "writing to pg_settings") + } + }) + t.Run("do block is rejected", func(t *testing.T) { conn := dial(t, pgClientPassword) err := exec(t, conn, "DO $$ BEGIN PERFORM 1; END $$") diff --git a/internal/postgres/config.go b/internal/postgres/config.go index 4dd1d8f..867961d 100644 --- a/internal/postgres/config.go +++ b/internal/postgres/config.go @@ -20,7 +20,8 @@ // 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); DO blocks; uninspectable function and procedure definitions; and +// settings); UPDATE or INSERT on pg_settings and view or rule definitions over +// it; DO blocks; uninspectable function and procedure definitions; and // the legacy wire-level FunctionCall protocol. SQL and PL/pgSQL routine bodies // are inspected recursively, while dynamic PL/pgSQL and other languages are // rejected. diff --git a/internal/postgres/policy.go b/internal/postgres/policy.go index 998df27..a037a13 100644 --- a/internal/postgres/policy.go +++ b/internal/postgres/policy.go @@ -33,6 +33,10 @@ const ( // RejectUninspectableRoutine — the client tried to define a function or // procedure whose body cannot be inspected safely. RejectUninspectableRoutine + // RejectSettingsCatalogWrite — the client tried to UPDATE or INSERT into + // pg_settings, or define a view or rule over it. Writes through pg_settings + // call set_config and would bypass pinned settings. + RejectSettingsCatalogWrite ) // ClassifyClientStatement inspects sql and returns whether the relay should @@ -40,9 +44,10 @@ 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 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). +// Beyond the role policy, the proxy rejects every set_config call, writes to +// pg_settings (directly or via a client-defined view or rule), 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 @@ -64,6 +69,8 @@ func ClassifyClientStatement(sql string, pinned map[string]struct{}) (allowed bo return false, RejectDoBlock case OpUninspectableRoutine: return false, RejectUninspectableRoutine + case OpSettingsCatalogWrite: + return false, RejectSettingsCatalogWrite } // RESET ALL / DISCARD ALL reset the proxy-managed role regardless of which // settings the upstream pins, so they are always rejected. diff --git a/internal/postgres/policy_test.go b/internal/postgres/policy_test.go index c273669..e76f68d 100644 --- a/internal/postgres/policy_test.go +++ b/internal/postgres/policy_test.go @@ -129,6 +129,9 @@ func TestClassifyClientStatement(t *testing.T) { {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: "update pg_settings rejected", sql: "UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout'", reason: RejectSettingsCatalogWrite}, + {name: "view over pg_settings rejected", sql: "CREATE TEMP VIEW v AS SELECT * FROM pg_settings", reason: RejectSettingsCatalogWrite}, + {name: "select pg_settings allowed", sql: "SELECT name, setting FROM pg_settings", allowed: true}, // DO blocks rejected outright. {name: "do block rejected", sql: "DO $$ BEGIN END $$", reason: RejectDoBlock}, diff --git a/internal/postgres/session.go b/internal/postgres/session.go index 7011504..7ea8e6c 100644 --- a/internal/postgres/session.go +++ b/internal/postgres/session.go @@ -492,6 +492,12 @@ func rejectError(reason RejectReason) *pgproto3.ErrorResponse { Code: "42501", Message: "blocked by iron-proxy policy: set_config is not supported because session settings are managed by the proxy", } + case RejectSettingsCatalogWrite: + return &pgproto3.ErrorResponse{ + Severity: "ERROR", + Code: "42501", + Message: "blocked by iron-proxy policy: writing to pg_settings, or defining a view or rule over it, is not supported because session settings are managed by the proxy", + } case RejectFunctionCall: return &pgproto3.ErrorResponse{ Severity: "ERROR", diff --git a/internal/postgres/sql.go b/internal/postgres/sql.go index fa9469f..6ce4b04 100644 --- a/internal/postgres/sql.go +++ b/internal/postgres/sql.go @@ -77,6 +77,12 @@ const ( // whose body cannot be inspected. Dynamic PL/pgSQL and unsupported languages // can hide role or GUC changes, so the policy rejects their definitions. OpUninspectableRoutine + // OpSettingsCatalogWrite is an UPDATE or INSERT targeting pg_settings, or a + // view or rule definition referencing it. pg_settings' update rule calls + // set_config with the row's name, and an auto-updatable view over it + // forwards updates the same way, so these reach any listed setting — + // including pinned built-in ones — without a set_config call in the SQL. + OpSettingsCatalogWrite ) // GUC names whose mutation we treat as a role change for policy purposes. @@ -403,6 +409,18 @@ func scanMutations(node *pg_query.Node) mutations { } case *pg_query.VariableShowStmt: // SHOW is read-only; ignore. + case *pg_query.UpdateStmt: + if isPgSettings(n.GetRelation()) && m.kind == 0 { + m.kind = OpSettingsCatalogWrite + } + case *pg_query.InsertStmt: + if isPgSettings(n.GetRelation()) && m.kind == 0 { + m.kind = OpSettingsCatalogWrite + } + case *pg_query.ViewStmt, *pg_query.RuleStmt: + if referencesPgSettings(msg) && m.kind == 0 { + m.kind = OpSettingsCatalogWrite + } case *pg_query.FuncCall: if name, ok := setConfigTarget(n); ok { if name != "" { @@ -418,6 +436,26 @@ func scanMutations(node *pg_query.Node) mutations { return m } +// isPgSettings reports whether rv names pg_settings. Any schema qualifier is +// matched: a user relation of that name is a harmless false positive, while +// schema-matching would have to track search_path. +func isPgSettings(rv *pg_query.RangeVar) bool { + return rv != nil && rv.GetRelname() == "pg_settings" +} + +// referencesPgSettings reports whether any relation reference in the tree +// rooted at m names pg_settings. +func referencesPgSettings(m protoreflect.Message) bool { + found := false + walkProto(m, func(msg protoreflect.Message) bool { + if rv, ok := msg.Interface().(*pg_query.RangeVar); ok && isPgSettings(rv) { + found = true + } + return !found + }) + return found +} + // roleKindFor returns the role-policy OpKind for a SET/RESET of the named GUC, // or 0 when the GUC is not role-affecting. kind distinguishes a write // (OpSetRole) from a reset (OpResetRole). diff --git a/internal/postgres/sql_test.go b/internal/postgres/sql_test.go index 6b23069..9ca1bf5 100644 --- a/internal/postgres/sql_test.go +++ b/internal/postgres/sql_test.go @@ -78,6 +78,21 @@ func TestClassify(t *testing.T) { // walker through the nested SelectStmt. {name: "prepare wrapping set_config caught", sql: "PREPARE p AS SELECT set_config('role', 'admin', false)", want: OpSetConfig}, + // pg_settings writes reach set_config through its update rule; an + // auto-updatable view or a rule over it forwards writes the same way. + {name: "update pg_settings", sql: "UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout'", want: OpSettingsCatalogWrite}, + {name: "update qualified pg_settings", sql: "UPDATE pg_catalog.pg_settings SET setting = '0' WHERE name = 'statement_timeout'", want: OpSettingsCatalogWrite}, + {name: "update pg_settings in cte", sql: "WITH x AS (UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout') SELECT 1", want: OpSettingsCatalogWrite}, + {name: "prepare update pg_settings", sql: "PREPARE p AS UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout'", want: OpSettingsCatalogWrite}, + {name: "insert pg_settings", sql: "INSERT INTO pg_settings (name, setting) VALUES ('statement_timeout', '0')", want: OpSettingsCatalogWrite}, + {name: "view over pg_settings", sql: "CREATE TEMP VIEW v AS SELECT * FROM pg_settings", want: OpSettingsCatalogWrite}, + {name: "view over pg_settings subquery", sql: "CREATE VIEW v AS SELECT * FROM (SELECT name, setting FROM pg_catalog.pg_settings) s", want: OpSettingsCatalogWrite}, + {name: "rule updating pg_settings", sql: "CREATE RULE r AS ON INSERT TO t DO ALSO UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout'", want: OpSettingsCatalogWrite}, + {name: "multi benign then update pg_settings", sql: "SELECT 1; UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout'", want: OpSettingsCatalogWrite}, + {name: "select pg_settings is other", sql: "SELECT setting FROM pg_settings WHERE name = 'statement_timeout'", want: OpOther}, + {name: "update reading pg_settings is other", sql: "UPDATE t SET x = (SELECT setting FROM pg_settings WHERE name = 'work_mem')", want: OpOther}, + {name: "view not over pg_settings is other", sql: "CREATE VIEW v AS SELECT * FROM t", want: OpOther}, + // DO blocks — rejected regardless of contents. {name: "do block empty", sql: "DO $$ BEGIN END $$", want: OpDoBlock}, {name: "do block with set role", sql: "DO $$ BEGIN EXECUTE 'SET ROLE admin'; END $$", want: OpDoBlock}, @@ -134,6 +149,16 @@ func TestClassify(t *testing.T) { sql: "CREATE FUNCTION f() RETURNS void LANGUAGE plpgsql AS $$ BEGIN PERFORM set_config('centaur.slack_user', 'U999', false); END $$", want: OpSetConfig, }, + { + name: "sql function updates pg_settings", + sql: "CREATE FUNCTION f() RETURNS void LANGUAGE sql AS $$ UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout' $$", + want: OpSettingsCatalogWrite, + }, + { + name: "plpgsql function updates pg_settings", + sql: "CREATE FUNCTION f() RETURNS void LANGUAGE plpgsql AS $$ BEGIN UPDATE pg_settings SET setting = '0' WHERE name = 'statement_timeout'; END $$", + want: OpSettingsCatalogWrite, + }, { name: "plpgsql procedure sets pinned guc", sql: "CREATE PROCEDURE p() LANGUAGE plpgsql AS $$ BEGIN SET centaur.slack_user = 'U999'; END $$",