Repository navigation
Description
Describe the problem
- What are you trying to solve?
Several useful "guard rail" extensions inspect every statement after it is parsed and reject the ones that break a policy. All of them are written in C and register post_parse_analyze_hook (or ExecutorStart_hook). Because of that, they cannot run on managed PostgreSQL services such as Amazon RDS and Aurora, where pg_tle is the supported way to add extension logic. Two examples:
- pg-safeupdate rejects
UPDATE/DELETEstatements that have noWHEREclause. This prevents the classic "I updated every row in production" accident. - sql_firewall has a learning mode that records the normalized query IDs an application issues. Its enforcing mode then rejects (or warns about) any statement whose query ID is not on that allowlist. This is a well-known defense against SQL injection.
Neither policy can be built with the tools RDS and Aurora offer today:
- Event triggers only fire for DDL. Non-C
ddl_command_starttriggers cannot see the parse tree (see Use event triggers as a more general mechanism for hooksΒ #150; in that discussion, maintainers noted that event triggers only overlap with the DDL-related hooks). - Statement-level DML triggers can count the rows a statement touched (through transition tables), but they cannot see whether a
WHEREclause was present. They also have to be created on every table. - pgaudit and Database Activity Streams can detect unexpected statements after they run, but they cannot block them.
- Users cannot port these extensions to
pg_tlebecause they depend on C hooks (compare Add feature to install q3c extension in RDS PostgreSQL via pg_tleΒ #182, which ran into the same wall for C functions).
pg_tle already has the right model for this: the passcheck and clientauth hooks let pgtle_admin register a trusted-language function that C code calls at a well-defined point. This issue proposes extending that model to statement checking.
Describe the proposal
- What is the feature you are proposing?
New feature type: querycheck
SELECT pgtle.register_feature('my_query_policy', 'querycheck');Functions registered this way are called from a post_parse_analyze_hook installed by pg_tle. As with passcheck and clientauth, a function rejects the statement by raising an error, and returning normally lets it through. Registered functions run in alphabetical order, matching the existing behavior from #60.
Hook function signature
querycheck_hook(query jsonb) RETURNS voidWhy a single jsonb argument instead of positional arguments
passcheck passes positional arguments. For querycheck we propose one jsonb document instead, for the following reasons:
- Stable signature across pg_tle and PostgreSQL versions. The information worth exposing about a statement will grow over time: new command types such as
MERGE ... RETURNING, new clauses, new fields requested by users. If the signature is positional, every addition changes it and breaks every function that is already registered. Withjsonb, new keys can be added without touching existing policies, and a"version"key lets functions detect format changes. - The data is naturally nested. A single statement can contain several data-modifying statements, for example data-modifying CTEs (
WITH d AS (DELETE ...) SELECT ...). Each one has its own command type, target table, andWHEREstatus. Positional scalar arguments cannot represent this without parallel arrays that are hard to use. - Hides PostgreSQL internals. User code never sees the
Querynode, whose layout changes between major versions. pg_tle owns the translation fromQueryto the documented JSON schema and can absorb upstream changes in one place. - Works the same in every trusted language. PL/pgSQL has jsonb operators, PL/v8 receives a native JavaScript object, and PL/Perl and PL/Rust can decode it easily. The one fixed signature
(jsonb) RETURNS voidis also easy forregister_featureto validate. - Fields that don't apply can be missing or
null. For example,has_where_clausehas no meaning forINSERT. With positional arguments, every argument has to have some value for every command type.
The trade-off is that pg_tle builds a small jsonb value for each checked statement. This cost happens only when the feature is enabled and at least one function is registered (see "Fast path" below), and it is small compared with the SPI call that runs the user's function anyway.
JSON document (draft schema, "version": 1)
{
"version": 1,
"command_type": "SELECT", // top-level: SELECT | INSERT | UPDATE | DELETE | MERGE | UTILITY
"utility_tag": null, // for UTILITY: command tag, e.g. "CREATE TABLE"
"query_id": 1234567890123, // Query->queryId; null if query IDs are not computed (see below)
"query_text": "WITH d AS (DELETE FROM t RETURNING *) SELECT * FROM d",
// this statement only, sliced by stmt_location / stmt_len
"top_level": true, // false when issued from inside a function (e.g. PL/pgSQL)
"session_user": "app_user",
"current_user": "app_user", // differs from session_user inside SECURITY DEFINER functions
"relations": [ // every RTE_RELATION in the whole query, including CTEs and subqueries
{"oid": 16384, "name": "public.t"}
],
"statements": [ // the top-level statement plus every data-modifying CTE, flattened
{
"command_type": "SELECT",
"source": "top_level",
"cte_name": null,
"target_relation": null,
"has_where_clause": null
},
{
"command_type": "DELETE",
"source": "cte",
"cte_name": "d",
"target_relation": {"oid": 16384, "name": "public.t"},
"has_where_clause": false
}
]
}Field semantics
statementslists the top-level statement and every data-modifying CTE. (PostgreSQL only allows data-modifying CTEs in the top-levelWITH, so a flat list is enough.) Checks that look only at the top-levelcommand_typecan be bypassed by wrapping the DML in a CTE, so policies such as safeupdate should iterate overstatements. The document describes the statement as written, before the rule system rewrites it. For example, aDELETEon a view with aDO INSTEADrule is reported as aDELETEon the view.has_where_clauseis purely syntactic. It reports whether the statement has aWHEREclause, not whether that clause limits any rows. In particular,WHERE trueandWHERE 1 = 1reporttrue, which is the same behavior as pg-safeupdate. By command type:UPDATE/DELETE:trueif aWHEREclause is present (Query->jointree->qualsis not NULL). This includesUPDATE ... FROM ... WHERE, where the join condition sits inWHERE, andWHERE CURRENT OF.UPDATE ... FROMwithout aWHEREclause reportsfalse.SELECT:trueif aWHEREclause is present.JOIN ... ONconditions do not count.INSERT:null. The entry also gets"on_conflict": "nothing" | "update" | null.ON CONFLICT DO UPDATEonly touches rows that conflict on the arbiter index, so it is not treated as an unrestricted update.MERGE:null, becauseMERGEalways has anONjoin condition. The entry also gets"merge_actions": ["UPDATE", "DELETE", "INSERT", ...]so that policies can decide how to treat it.UTILITY:null.
relationsgives both the OID and the schema-qualified name. In PL/pgSQL,(r->>'oid')::oid::regclassgives aregclass, and thenameis there for logging and plain comparisons.session_user/current_user: both values are provided because they differ insideSECURITY DEFINERfunctions. Identity-based policies such as a firewall should normally usesession_user.query_idisnullwhen PostgreSQL did not compute a query ID. This happens whencompute_query_id = off, or when it isautoand no loaded module requested query IDs. On RDS and Aurora,pg_stat_statementsis usually loaded, so query IDs are normally available. To guarantee them, we propose a postmaster-context GUC,pgtle.querycheck_compute_query_id(defaultoff). When it is on, pg_tle callsEnableQueryId()in_PG_init. Policies that rely onquery_idshould fail closed when it isnull.top_levelis tracked with a nesting counter maintained in executor and utility hooks, the same waypg_stat_statementstracks it.
Examples
safeupdate equivalent
CREATE FUNCTION safeupdate_check(q jsonb)
RETURNS void LANGUAGE plpgsql AS $$
DECLARE
s jsonb;
BEGIN
FOR s IN SELECT jsonb_array_elements(q -> 'statements') LOOP
IF s ->> 'command_type' IN ('UPDATE', 'DELETE')
AND NOT (s ->> 'has_where_clause')::boolean THEN
RAISE EXCEPTION '% on % requires a WHERE clause',
s ->> 'command_type', s -> 'target_relation' ->> 'name'
USING ERRCODE = 'cardinality_violation';
END IF;
END LOOP;
END $$;
SELECT pgtle.register_feature('safeupdate_check', 'querycheck');This also rejects WITH d AS (DELETE FROM t RETURNING *) SELECT * FROM d.
sql_firewall equivalent (allowlist by query ID)
CREATE TABLE firewall.allowed (query_id bigint PRIMARY KEY, query_text text);
CREATE FUNCTION firewall_check(q jsonb)
RETURNS void LANGUAGE plpgsql AS $$
BEGIN
IF q ->> 'session_user' = 'app_user'
AND q ->> 'command_type' <> 'UTILITY'
AND (q ->> 'query_id' IS NULL -- fail closed when no query ID is available
OR NOT EXISTS (SELECT 1 FROM firewall.allowed a
WHERE a.query_id = (q ->> 'query_id')::bigint)) THEN
RAISE EXCEPTION 'statement rejected by firewall (query_id=%)', q ->> 'query_id';
END IF;
END $$;
SELECT pgtle.register_feature('firewall_check', 'querycheck');A "learning" mode is just a variant of the function that inserts query_id and query_text into firewall.allowed instead of raising.
Configuration (following the passcheck and clientauth pattern)
| GUC | Values | Context | Purpose |
|---|---|---|---|
pgtle.enable_querycheck |
off (default) / on / require |
SIGHUP | require rejects every statement when no function is registered, mirroring enable_password_check |
pgtle.querycheck_skip_roles (name TBD) |
role list | SIGHUP | Roles exempt from the hook so that an admin can always fix a broken policy (see "Safety" below) |
pgtle.querycheck_compute_query_id |
on / off (default) |
postmaster | Makes pg_tle request query IDs so that query_id is always filled |
Implementation sketch
-
Install
post_parse_analyze_hookin_PG_init, chaining to the previous hook (for example, pg_stat_statements). As withpasscheck, the hook is always installed so that enabling it does not require a restart. -
Walk the
Querytree, includingcteListand subqueries, to build the JSON document. Then call the registered functions through SPI. This is the same approachpasscheck_run_user_functionsuses, but it runs in the current backend and database. No background worker is needed. -
Recursion guard: a backend-local flag skips the hook while a
querycheckfunction is running, so that SQL inside the policy function is not checked again. -
Per-backend cache of registered functions:
passcheckreadspgtle.feature_infoon each call. Doing that on every statement would be too expensive. The list should be cached and invalidated with a relcache/syscache callback (or a shared-memory counter thatregister_feature/unregister_featurebumps). -
Fast path: when the GUC is
off, the current role is exempt, or noquerycheckfunction is registered, the hook returns before building any JSON and without SPI. -
How would it solve the problem?
Statement-level policies such as safeupdate and SQL firewalls become possible on RDS and Aurora without loading arbitrary C code. The trust model stays the same as today: only pgtle_admin can register functions, and those functions are written in trusted languages.
Open questions for the maintainers
post_parse_analyze_hookorExecutorStart_hook? Parse analysis does not run again on every execution of a prepared or cached plan. For allowlist and safeupdate policies that is usually fine: the statement was checked when it was prepared, and it is re-checked when the plan is invalidated.ExecutorStart_hookwould check every execution, but it adds per-execution overhead. One option is to offer only parse analysis at first.- Nested statements: the
top_levelfield lets policies decide whether to check them. Should the hook be called for nested statements at all, or should a GUC turn that off for performance? - Is SPI safe here? Running SPI from
post_parse_analyze_hookhas precedent: extensions already run catalog and table lookups from parser and planner hooks. Maintainers may still want a stricter mechanism. - JSON schema versioning: is a
"version"key enough, or should a function declare the schema version it expects when it is registered?
Safety considerations
A buggy querycheck function with require could make a database unusable, much like the clientauth hang issues (#252, #316). Possible mitigations:
offby default.pgtle_adminand the roles listed in the skip-roles GUC are never checked.- Statements issued by the hook itself are never checked (the recursion guard).
- Document how to recover, for example with
ALTER SYSTEMor a parameter-group change followed by a reload.
Describe alternatives
-
How would you solve the problem today if the feature is not built?
- Put a SQL-aware proxy (built on libpg_query) in front of the database. This works, but it adds a hop. It also has to handle the extended protocol and prepared statements, and network rules must stop clients from connecting to the database directly.
- Check SQL statically in the application or in CI. This does not cover ad-hoc
psqlsessions, which are exactly where accidental full-tableUPDATEs happen. - Use statement-level triggers with transition tables to reject statements that touch "too many" rows. This is only a heuristic, and it has to be installed on every table.
- Run self-managed PostgreSQL on EC2 so the C extensions can be used. This gives up the benefits of a managed service.
-
What other alternatives are there?
- Upstream PostgreSQL changes that expose the parse tree to non-C code (the direction discussed in Use event triggers as a more general mechanism for hooksΒ #150). This would be more general, but it would take years to reach managed services, and it currently targets DDL only.
- Expose the internal
ProcessUtilityhook to users (related to Allow list commands to process in ProcessUtility hookΒ #212). This covers DDL only, not DML.
If the maintainers think this direction is worth exploring, I will build a proof-of-concept PR (with regression tests and safeupdate- and firewall-style examples), as was done in #174 before #227.
Activity