Skip to content

Check every table name a statement gives, and route SELECT INTO to the primary - #35

Merged
artem-pplx merged 4 commits into
mainfrom
artem-pplx/table-access-unvisited-names
Nov 19, 2026
Merged

artem-pplx merged 4 commits into
mainfrom
artem-pplx/table-access-unvisited-names

Conversation

@artem-pplx

@artem-pplx artem-pplx commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Why

Table access refuses a statement that reaches a table listed in table access (the table_access plugin's tables), and finds the tables with visit_relations. That visitor reports the relations a statement reads or writes, not every table name it holds: DROP TABLE t, GRANT ... ON t, COMMENT ON TABLE t, CREATE TRIGGER ... ON t, CREATE TABLE c (LIKE t), REFERENCES t(a), the target of SELECT ... INTO t, a nested TABLE t, and both names in ALTER ... RENAME TO all passed. Postgres also renames a table with ALTER INDEX t RENAME TO n. The COPY t and VACUUM t checks looked only at top-level statements, so a COPY inside a BEGIN ATOMIC body or a rule's action passed too.

Separately, SELECT ... INTO t creates a table, but the router classified it as a read.

Change

  • unvisited_names lists the table names a statement gives that visit_relations skips: the tables of COPY and VACUUM, of DROP (table, foreign table, view, materialized view, index, sequence), of GRANT/REVOKE, of COMMENT ON (and a column's table), of CREATE/DROP TRIGGER (and a constraint trigger's FROM), LIKE (also after a column, and any LIKE in CREATE FOREIGN TABLE, which the parser reads as a column named like whose type is the table, a built-in type when the table is named as one, such as json), column and table REFERENCES, INHERITS, ALTER TABLE partitions, parents, added constraints and columns, and the old and new names of a rename, ALTER INDEX included. It runs on every statement through visit_statements, nested ones included.
  • A query visitor collects SELECT ... INTO targets and TABLE t reads in every query, so a CTE, an IN subquery, CREATE TABLE AS, a set operation or a subquery holding one is covered. A top-level TABLE t doesn't parse with sqlparser 0.64, so it's handled as an unparsed query.
  • GRANT/REVOKE ... ON ALL TABLES IN SCHEMA is refused, in any schema, while any table is listed in table access, following the existing rule for VACUUM of every table. The listed names carry no schema, so a name check can't tell which schema holds them. REVOKE is gated like GRANT: the rule is that a statement naming a listed table is refused, whatever its effect. Migrations or role setup that grant on all tables must connect to the server directly, not through the pooler. Tests pin both choices, and that neither statement is refused when no table is listed.
  • The module doc and docs/plugin-registration.md state that the check goes by name. Views, partition parents, functions, rules and triggers that already exist are allowed by their own names, and so are an index or sequence created with a listed table's name. Names inside strings (foreign table OPTIONS, dblink, table_to_xml/query_to_xml) aren't read. Those need server privileges. A string function body isn't read either: with plugins_require_parse or a process-wide plugin, table access refuses it, and without either it's forwarded.
  • is_mutation_set_expr returns true for a SELECT with INTO.

Impact

More statements naming a table listed in table access are refused with the existing 42501 message. Statements that don't name one are unaffected, except GRANT/REVOKE ... ON ALL TABLES IN SCHEMA, which, like VACUUM without a table, is refused while any table is listed in table access. A role, schema or column with the same name as a listed table is still allowed. SELECT ... INTO goes to the primary.

Tested locally: cargo test --lib (414 passed), with regression cases in test_names_visit_relations_misses_are_checked, test_table_command_is_checked, test_like_of_a_table_named_as_a_type_is_refused (which also checks every single-word type name the parser accepts after LIKE), test_every_table_grants_are_refused_only_with_a_forbidden_table and test_data_modifying_bodies_and_ctes_go_to_primary. With the new tests kept and the non-test code of table_access.rs reverted to 45a1d26, test_names_visit_relations_misses_are_checked and test_table_command_is_checked fail, and every new refused case (ALTER INDEX, a non-first LIKE, each nested TABLE t) is allowed. Reading only custom types after like, as before, lets LIKE json, LIKE string and LIKE timestamptz through, and checking only a foreign table's parents lets its LIKE through. cargo fmt --check passes and cargo clippy --lib --examples -- -Dwarnings reports nothing on the lines this PR changes. The tests workflow passes at this head (414 library tests, 4 others, and 315 Python tests passed with 14 xfailed).

Created with Perplexity

@artem-pplx artem-pplx left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict at 09346f4c: not clear. Two blockers.

Pass 1 of 2. This PR changes a security check, so a second reviewer on a different model will review the same head once the blockers are resolved.

  • Blockers. Two statements name a blocked table, read its rows on PostgreSQL 18, and are still allowed at this head. Both fixes are a few lines.

    • ALTER INDEX secrets RENAME TO x renames the table (inline at 224-227).
    • The TABLE secrets query form, nested in a CTE, an IN subquery or CREATE TABLE AS (inline at 274-290).

    main has both gaps, so nothing regresses. They block because the new docs and the description say these cases are refused. Narrowing the docs is an alternative, but the code fix is cheaper.

  • Correct.

    • The visit_statements recursion covers nested statements. With the Statement::Copy arm removed, the nested-COPY test fails.
    • SELECT ... INTO goes to the primary. Its test fails when is_mutation_set_expr is reverted.
    • I found no over-refusal of normal migration DDL beyond the ON ALL TABLES rule (a question, inline at 305-320).
  • Nonblocking (inline).

    • Non-first LIKE.
    • The doc examples should name table_to_xml/query_to_xml.
    • Four AST walks could be one visitor.

Description (nonblocking):

  1. Quoted: "Statements that don't name one are unaffected". GRANT/REVOKE ... ON ALL TABLES IN SCHEMA <any> is refused while any table is blocked. Suggested: "Statements that don't name one are unaffected, except GRANT/REVOKE ... ON ALL TABLES IN SCHEMA, which, like VACUUM without a table, is refused while any table is blocked."
  2. Quoted: "the old and new names of a rename". At this head ALTER INDEX's own name is skipped. Accurate once the first blocker is fixed.
  3. Quoted: "This repository's workflows don't run the test suite on pull requests." tests.yml is on main now (#34); this branch predates it, so only CodeQL runs. Suggested: "This branch predates the tests workflow; rebasing onto main runs it."
  4. Terms: the code and tests say "forbidden", this description says "blocked", and #37 says "gated". Pick one, or define "blocked" once (a table listed in the table_access plugin's tables).

Overlap with #37: both PRs edit the same region of TableAccess::run and the same use sqlparser::ast::Ellipsis list, so expect a textual conflict. The doc sentence about string function bodies conflicts too (see the inline comment at docs 119-122).

What ran:

  • cargo +stable test --lib at this head: 392 passed, matching the description.
  • TableAccess::run over about 100 statements.
  • A negative control: the COPY arm removed and the SELECT INTO routing reverted fails all three relevant tests.
  • A throwaway local PostgreSQL 18 to confirm the two leaks.

Reviewer: Claude Opus, High effort, pass 1 of 2. Comment-only.

Created with Perplexity

Comment thread src/plugins/table_access.rs Resolved
Comment thread src/plugins/table_access.rs Resolved
Comment thread src/plugins/table_access.rs Resolved
Comment thread src/plugins/table_access.rs Resolved
Comment thread docs/plugin-registration.md Resolved
Comment thread src/plugins/table_access.rs Resolved

artem-pplx commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

Follow-ups outside this PR's scope (from pass 1 at 09346f4c; main already has all of these):

  1. Unparsed DDL that names a table relies entirely on the unparsed-text rule. This covers CLUSTER, REINDEX, CREATE/ALTER PUBLICATION ... TABLE, CREATE STATISTICS, IMPORT FOREIGN SCHEMA ... LIMIT TO, COMMENT ON TRIGGER/POLICY/RULE/CONSTRAINT ... ON t, SECURITY LABEL, DROP INDEX CONCURRENTLY and ALTER SEQUENCE.
    • Without plugins_require_parse, all of these are forwarded. With it, they're refused only if the text names the table.
    • CREATE PUBLICATION p FOR ALL TABLES names no table, so it's forwarded either way.
    • might_touch_gated (src/query_router.rs) applies the every-table rule to VACUUM, but not to GRANT ... ALL TABLES or FOR ALL TABLES text. It could be extended to cover them.
  2. One shared name walker. src/relations.rs (the observer metric) and table_access.rs each walk table names their own way. relations.rs already handles TABLE t and SELECT INTO. A shared "names a statement gives" helper would stop them drifting apart. The TABLE t gap is an example of exactly that drift.
  3. EXPLAIN ANALYZE SELECT ... INTO t. Postgres creates the table here. Where the router sends this statement wasn't checked. Table access refuses it when the target is blocked.

Added at the final pass on 1fd18e7d (also already on main):

  1. Tableless ANALYZE. ANALYZE; processes every table, the same way a tableless VACUUM does, but every_table refuses only VACUUM and GRANT/REVOKE ... ON ALL TABLES.
  2. CREATE SEQUENCE s OWNED BY secrets.id. Neither visit_relations nor unvisited_names visits OwnedBy. Postgres requires ownership of the table.
  3. LIKE forms sqlparser 0.64 can't parse. These include LIKE enum, LIKE set, LIKE fixedstring, LIKE json.secrets (a schema named as a type), LIKE ... INCLUDING ALL, CREATE TABLE c OF secrets and SELECT 1 INTO LOCAL TEMP secrets. With plugins_require_parse they're refused because the text names the table. Without it they're forwarded, like other unparsed text.
  4. Optional style. unvisited_names could return Vec<Ident>, with .cloned(), instead of Cow<'_, Ident>. That drops the five .map(Cow::Borrowed) calls, at the cost of cloning names on the DDL paths only.

Added at the rebase check on 977783c4:

  1. Module doc wording. The new sentence at src/plugins/table_access.rs:12-14 says a string function body "is refused instead while pgcat requires parsing". The check also needs at least one table to be listed (!self.tables.is_empty()), which docs/plugin-registration.md states. Suggested wording: "...which is refused instead while a table is listed and pgcat requires parsing (plugins_require_parse, or a process-wide plugin)...".

Created with Perplexity

@artem-pplx artem-pplx left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final pass at 1862237: both earlier blockers are fixed. One narrow new blocker in the non-first LIKE check (inline).

Verified fixed, each with a negative control (reverting the fix makes its test fail):

  • ALTER INDEX <t> RENAME TO x now checks both names (test_names_visit_relations_misses_are_checked).
  • TABLE <t> nested in a CTE, CREATE TABLE AS, IN, UNION, FROM (...) and similar is collected and refused (test_table_command_is_checked).

New blocker:

  • LIKE after a column misses type-keyword table names. If a blocked table is named json, string, text, uuid, date or a similar type word, CREATE TABLE c (a int, LIKE json) parses and is allowed, even with plugins_require_parse. The fix and the test are in the inline comment. Docs and the description need no change once it's fixed.

Checked and fine:

  • Quoting and case folding, and 1-, 2- and 3-part names.
  • SELECT ... INTO targets, including keyword names, and their routing to the primary.
  • ALTER ... RENAME across the table, view, materialized view, foreign table and index kinds.
  • No over-refusal of normal DDL: a quoted "like" column, CHECK (b LIKE ...), CREATE INDEX secrets ON other.
  • GRANT/REVOKE ON ALL TABLES refused only when a table is blocked.

Additions to the earlier ledger. Both are optional and predate this PR:

  • GRANT SELECT, MAINTAIN ON ALL TABLES IN SCHEMA s TO r (MAINTAIN is new in PG 17) doesn't parse in sqlparser 0.64. The unparsed check doesn't treat it as every-table, so it's forwarded even with plugins_require_parse. The same goes for CREATE PUBLICATION ... FOR ALL TABLES. A follow-up could add both to the every-table words, next to vacuum.
  • CREATE PUBLICATION ... FOR TABLE t, SECURITY LABEL ON TABLE t, REINDEX, CLUSTER and ALTER SEQUENCE ... RENAME don't parse. They're refused with plugins_require_parse (the text names the table) and forwarded without it, as documented.

Ran on this head: cargo fmt --check, cargo test --lib (394 passed), the two negative controls, a 78-case router/plugin probe, and live PostgreSQL 18 runs confirming the scenario.

Reviewer: Gemini 4 Carbon, High effort, final independent pass (pass 2, after Claude Opus High). Comment-only.

Created with Perplexity

Comment thread src/plugins/table_access.rs Resolved

@artem-pplx artem-pplx left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final pass at 1fd18e7d: clear. No blockers.

Both fixes hold, and each one's test fails when the fix is removed:

  • A non-first LIKE <t> where <t> parses as a built-in type (json, string, timestamptz and others) is now refused.
  • CREATE FOREIGN TABLE c (LIKE secrets) SERVER s is now refused.

No remaining parsed-SQL bypass was found in the LIKE handling:

  • Type aliases (int4, float8, bool, timestamptz, double) print back as the word that was read.
  • Postgres rejects unquoted multi-word types, arrays and type modifiers after LIKE. A quoted name keeps its exact identifier.
  • Postgres 18.6 rejects LIKE inside CREATE TYPE ... AS, ALTER TABLE ... ADD, PARTITION OF column lists and CREATE TABLE ... AS.

No over-refusal was found: a quoted "like" column, ordinary column types, and LIKE of an unlisted table named as a type are all still allowed.

Description (nonblocking). In Impact:

  1. "the non-test code of table_access.rs reverted to the previous commit"

    The previous commit is now 18622378. Reverting to it doesn't fail test_table_command_is_checked. Suggested: "reverted to 09346f4".

  2. "(which also checks every type name the parser knows)"

    The loop skips keywords that don't parse after LIKE, and it tests single words only. Suggested: "(which also checks every single-word type name the parser accepts after LIKE)".

What ran on this head:

  • cargo +stable test --lib: 395 passed.
  • fmt --check and clippy --lib --tests: clean.
  • Two negative controls, each failing the expected tests.
  • Postgres 18.6 grammar checks.
  • All 10 CI checks green.

Reviewers: Claude Opus High ran pass 1 and the delta checks. A fresh Gemini 4 Carbon High agent ran this final, in place of the planned Astra model, which isn't available. Pass count: 1 full + 2 delta + 2 finals. The follow-up list in the earlier comment is updated. This is a comment-only review.

Created with Perplexity

@artem-pplx
artem-pplx marked this pull request as ready for review November 18, 2026 22:52
artem-pplx and others added 4 commits November 19, 2026 18:22
…e primary

visit_relations reports the relations a statement reads or writes, not every
table it names. Table access now also checks the names it skips, in nested
statements too: COPY, DROP, GRANT/REVOKE, COMMENT, CREATE/DROP TRIGGER,
LIKE, REFERENCES, SELECT INTO targets and RENAME TO. GRANT/REVOKE on all
tables in a schema is refused while any table is blocked, as VACUUM of every
table is. The module and plugin docs state that the check goes by name.

SELECT ... INTO creates a table, so it's a mutation for routing.

Co-authored-by: Perplexity <noreply@perplexity.ai>
Postgres renames a table with ALTER INDEX ... RENAME TO, so both names are
checked, not only the new one. TABLE t isn't an ObjectName, so
visit_relations skips it; the query visitor now collects it in every query,
nested ones too (CTEs, IN subqueries, CREATE TABLE AS, set operations). The
parser reads a LIKE that isn't a table's first element as a column named
like, whose type is the table; that column counts as a LIKE.

Tests pin that GRANT/REVOKE on all tables is refused in any schema while any
table is listed in table access, that a plain REVOKE is refused, and that
neither is refused with no table listed. The docs use "listed in table
access", name table_to_xml/query_to_xml, and say which same-named objects
are allowed.

Co-authored-by: Perplexity <noreply@perplexity.ai>
The parser reads a LIKE after a column as a column named like, and turns
a table named as a type it knows (json, text, timestamptz) into that
type, so only a custom type was checked. It reads every LIKE in CREATE
FOREIGN TABLE the same way, and that statement checked only its parents.

Co-authored-by: Perplexity <noreply@perplexity.ai>
…required

The "names inside strings" lists said a function body given as a string
isn't read. With plugins_require_parse or a process-wide plugin, table
access refuses it instead; without either, it's forwarded unread.

Co-authored-by: Perplexity <noreply@perplexity.ai>
@artem-pplx
artem-pplx force-pushed the artem-pplx/table-access-unvisited-names branch from 1fd18e7 to 977783c Compare November 19, 2026 18:25

@perplexedmontagna perplexedmontagna left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved at 977783c4. I found no merge blockers. I traced the name checks through simple queries, extended Parse, and the final rewrite. The regressions cover both names of a rename, nested TABLE reads, and LIKE targets that parse as type names. With read/write splitting on, parsed SELECT INTO selects the primary; ordinary reads remain eligible for replicas.

I ran all 414 Rust library tests and both formatting checks locally. Separate router checks confirmed that EXPLAIN ANALYZE SELECT INTO and a batch with a read after SELECT INTO also select the primary. CI passed.

Two non-blocking follow-ups:

  • In the plugin docs, qualify the schema-wide grant/revoke rule as applying to statements PgCat parses. Unsupported syntax follows the pool's existing parse-failure policy; keep PostgreSQL privileges authoritative.
  • On a warm pool with db_activity_based_routing enabled, my router check selected the primary for SELECT INTO but a replica for a separate, immediate read of the new table. The role-selection branch does not mark the target recently written. This is pre-existing; recording the target would extend read-after-write routing to this case.

Created with Perplexity

@artem-pplx artem-pplx left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clear at 977783c4: the rebase onto main (9c40703f, which includes #37) is resolved correctly, and the new docs commit is accurate. I checked only the rebase and 977783c, not the logic cleared earlier at 1fd18e7d.

Conflict resolution. git range-diff 388a33a8..1fd18e7d 9c40703f..977783c4 shows three resolutions, all in src/plugins/table_access.rs, and nothing else:

  • The sqlparser::ast import lists are merged, adding CreateFunction, CreateFunctionBody and CreateProcedureBody in the first commit and ColumnDef and DataType in the second.
  • #37's has_string_body now sits after this PR's helpers.
  • The test helpers refused_by(router, sql) and refused_with(tables, sql) both call the new refused_by_with.

Nothing from #37 was dropped. Outside table_access.rs and docs/, the changes from 1fd18e7d to 977783c4 match main's changes exactly. query_router.rs (plugins_require_parse, rejects_unparsed, the string-body routing) is unchanged from main. has_string_body, strict() and #37's tests (test_string_function_bodies_are_refused_with_plugins_require_parse, test_only_sql_function_bodies_are_read) are all present.

Merged run() denies exactly what either PR denies.

  • This PR's three name checks (visit_relations, unvisited_names, QueryNames) always run first and set found.
  • The every_table deny and #37's string-body deny run only when found is None. Otherwise found is denied at the end.
  • So a statement is refused if either PR alone would refuse it. A parsed RETURN or BEGIN ATOMIC body still has its tables checked.

Docs commit 977783c. The module doc and docs/plugin-registration.md now say a string function body is refused with plugins_require_parse or a process-wide plugin, and forwarded without either. That matches QueryRouter::plugins_require_parse() (src/query_router.rs:2073-2076): has_process_plugins() || (plugins_enabled() && pool_settings.plugins_require_parse). One optional wording nit is added to the ledger as item 8.

CI: run 44587736714 is green on this head (414 lib tests; 315 Python passed, 14 xfailed). Nothing was rerun locally, because both reviewers found that the source agrees with CI.

Reviewers: two different models, both clearing this exact head, because table access is security-sensitive. Claude Opus High did the first pass, and Gemini 4 Carbon High did a fresh, independent final. One pass each.

Created with Perplexity

@artem-pplx
artem-pplx merged commit ee262db into main Nov 19, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants