Skip to content

Feature request: querycheck hook β€” let trusted-language functions inspect and reject statements after parse analysisΒ #327

Backlog

Description

@soudai

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 / DELETE statements that have no WHERE clause. 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_start triggers 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 WHERE clause 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_tle because 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 void

Why a single jsonb argument instead of positional arguments

passcheck passes positional arguments. For querycheck we propose one jsonb document instead, for the following reasons:

  1. 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. With jsonb, new keys can be added without touching existing policies, and a "version" key lets functions detect format changes.
  2. 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, and WHERE status. Positional scalar arguments cannot represent this without parallel arrays that are hard to use.
  3. Hides PostgreSQL internals. User code never sees the Query node, whose layout changes between major versions. pg_tle owns the translation from Query to the documented JSON schema and can absorb upstream changes in one place.
  4. 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 void is also easy for register_feature to validate.
  5. Fields that don't apply can be missing or null. For example, has_where_clause has no meaning for INSERT. 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

  • statements lists the top-level statement and every data-modifying CTE. (PostgreSQL only allows data-modifying CTEs in the top-level WITH, so a flat list is enough.) Checks that look only at the top-level command_type can be bypassed by wrapping the DML in a CTE, so policies such as safeupdate should iterate over statements. The document describes the statement as written, before the rule system rewrites it. For example, a DELETE on a view with a DO INSTEAD rule is reported as a DELETE on the view.
  • has_where_clause is purely syntactic. It reports whether the statement has a WHERE clause, not whether that clause limits any rows. In particular, WHERE true and WHERE 1 = 1 report true, which is the same behavior as pg-safeupdate. By command type:
    • UPDATE / DELETE: true if a WHERE clause is present (Query->jointree->quals is not NULL). This includes UPDATE ... FROM ... WHERE, where the join condition sits in WHERE, and WHERE CURRENT OF. UPDATE ... FROM without a WHERE clause reports false.
    • SELECT: true if a WHERE clause is present. JOIN ... ON conditions do not count.
    • INSERT: null. The entry also gets "on_conflict": "nothing" | "update" | null. ON CONFLICT DO UPDATE only touches rows that conflict on the arbiter index, so it is not treated as an unrestricted update.
    • MERGE: null, because MERGE always has an ON join condition. The entry also gets "merge_actions": ["UPDATE", "DELETE", "INSERT", ...] so that policies can decide how to treat it.
    • UTILITY: null.
  • relations gives both the OID and the schema-qualified name. In PL/pgSQL, (r->>'oid')::oid::regclass gives a regclass, and the name is there for logging and plain comparisons.
  • session_user / current_user: both values are provided because they differ inside SECURITY DEFINER functions. Identity-based policies such as a firewall should normally use session_user.
  • query_id is null when PostgreSQL did not compute a query ID. This happens when compute_query_id = off, or when it is auto and no loaded module requested query IDs. On RDS and Aurora, pg_stat_statements is usually loaded, so query IDs are normally available. To guarantee them, we propose a postmaster-context GUC, pgtle.querycheck_compute_query_id (default off). When it is on, pg_tle calls EnableQueryId() in _PG_init. Policies that rely on query_id should fail closed when it is null.
  • top_level is tracked with a nesting counter maintained in executor and utility hooks, the same way pg_stat_statements tracks 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_hook in _PG_init, chaining to the previous hook (for example, pg_stat_statements). As with passcheck, the hook is always installed so that enabling it does not require a restart.

  • Walk the Query tree, including cteList and subqueries, to build the JSON document. Then call the registered functions through SPI. This is the same approach passcheck_run_user_functions uses, 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 querycheck function is running, so that SQL inside the policy function is not checked again.

  • Per-backend cache of registered functions: passcheck reads pgtle.feature_info on 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 that register_feature / unregister_feature bumps).

  • Fast path: when the GUC is off, the current role is exempt, or no querycheck function 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

  1. post_parse_analyze_hook or ExecutorStart_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_hook would check every execution, but it adds per-execution overhead. One option is to offer only parse analysis at first.
  2. Nested statements: the top_level field 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?
  3. Is SPI safe here? Running SPI from post_parse_analyze_hook has precedent: extensions already run catalog and table lookups from parser and planner hooks. Maintainers may still want a stricter mechanism.
  4. 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:

  • off by default.
  • pgtle_admin and 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 SYSTEM or 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 psql sessions, which are exactly where accidental full-table UPDATEs 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?

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions