Skip to content

Refuse statements parsed as COPY FROM STDIN data - #30

Merged
artem-pplx merged 13 commits into
mainfrom
refuse-inline-copy-data
Nov 17, 2026
Merged

artem-pplx merged 13 commits into
mainfrom
refuse-inline-copy-data

Conversation

@artem-pplx

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

Copy link
Copy Markdown
Collaborator

This fixes existing behavior on every sqlparser version pgcat has used; it isn't a regression from the 0.64 upgrade.

What the server runs

In a simple Query, PostgreSQL parses the whole query string as SQL and runs the statements in order. COPY t FROM STDIN switches the connection to copy-in mode, and the data comes in CopyData messages until CopyDone or CopyFail. After that, the server runs the statements that followed the COPY in the query string. Data is never inline in a Query message. psql sends the COPY statement as its own Query and then streams the following lines of a script as CopyData. pgcat forwards CopyData, CopyDone and CopyFail separately from Query messages (the 'd' and 'c' | 'f' arms in client.rs), and none of them go through the query parser.

So with secrets gated, this Query makes the server copy into labels and then insert into secrets:

COPY labels FROM STDIN;
INSERT INTO secrets VALUES (1)

What the parser saw

Query sqlparser 0.52 (before #27) 0.62 (#27) 0.64 (main, #29)
COPY labels FROM STDIN; INSERT INTO secrets VALUES (1) one Copy: the INSERT is swallowed same Copy, then Insert: denied by table_access
COPY labels FROM STDIN; + newline + INSERT INTO secrets VALUES (1) one Copy same one Copy with payload: Some(..) holding the INSERT
COPY labels FROM STDIN; SELECT 1; + newline + INSERT INTO secrets VALUES (1) one Copy same Copy with the INSERT as payload, then Query

0.64 takes that text as the COPY's data (apache/datafusion-sqlparser-rs#2428), which is where the data sits in a psql script such as pg_dump's plain output, but not on the wire. On 0.52 and 0.62 plugins see neither form of the INSERT. On 0.64 they see the same-line form but not the next-line one, so the server runs an INSERT they never checked.

Change

parse_sql now refuses a statement tree that contains a Statement::Copy whose payload isn't blank, found with visit_statements so that a nested COPY counts too. The error is text after COPY FROM STDIN on a new line isn't supported. It sits next to the ONLY check and takes the same path: the client's existing unparsed handling refuses the query when rejects_unparsed says it might touch a gated table (as the INSERT above does), and otherwise forwards it as it forwards any query the parser can't read. With plugins_require_parse off and only table_access enabled, it's forwarded unchecked whatever it names, as any unparsed query is; plugins that refuse unparsed queries still reject it. Only the parse_sql path changes. CopyData handling doesn't change.

A payload of only spaces, tabs or line breaks can't be a statement, so it's still accepted. These are COPY t FROM STDIN; followed by a blank line, or by the indentation that closes a multi-line string in client code. A comment-only next line, such as -- c, is refused. A \. line makes the whole query a syntax error on the server, so it can't hide a statement either.

The check adds one walk of the parsed statements per query, like the ONLY check.

Testing

On rustc 1.99.1, with debug info off to save disk space (CARGO_PROFILE_DEV_DEBUG=0, CARGO_PROFILE_TEST_DEBUG=0):

  • test_statements_after_copy_from_stdin_are_checked uses a router that gates secrets. It takes four queries where the server runs an INSERT into secrets after a COPY: the same-line form, the next-line form, the next-line form after a same-line SELECT, and the next-line form after a blank line. Each must be read and denied, or refused unread. It also covers three forms a tokenizer change could break. After a CRLF, the INSERT must be refused unread. After a \. line, and after a comment that spans the line break (/* newline */), the parser reads SQL again, so the INSERT must be read and denied. It also needs text on a new line to be refused even when it names no gated table, and COPY ... FROM STDIN alone, or followed by blank text, to still parse.
  • With the new check disabled, the test fails on the next-line form, which is read and allowed. With 0.62 (and the check stubbed out, since 0.62 has no payload), it fails on the same-line form, which is also read and allowed.
  • cargo fmt --check: clean.
  • cargo test --locked --features test-plugins: 390 unit tests and 4 doc-tests pass.
  • cargo clippy --locked --lib --examples --tests --features test-plugins: no warnings on the changed lines, and the same warning set as main.

Created with Perplexity

artem-pplx and others added 7 commits November 16, 2026 22:45
Postgres drops empty statements, so `;VACUUM (FULL)` runs as a single
VACUUM of every table. first_word stopped at the `;` and returned "",
so rejects_unparsed forwarded it while a table was gated. Skip `;`
along with whitespace and comments.

Co-authored-by: Perplexity <noreply@perplexity.ai>
Add `/* a */;/* b */VACUUM (FULL)` and a form feed and vertical tab
prefix to the unparsed VACUUM test, so the order in which first_word
skips comments, `;` and whitespace stays covered.

Co-authored-by: Perplexity <noreply@perplexity.ai>
hickory-resolver 0.24 built each system nameserver with
trust_negative_responses off, so an NXDOMAIN from one server made it ask
the others. 0.26 turns it on, so one server that doesn't know the
database host makes the lookup fail. Read the system configuration and
turn it off for every nameserver before building the resolver.

Co-authored-by: Perplexity <noreply@perplexity.ai>
The test ordered the two answers with a 100 ms delay, so a scheduling
stall could let the A answer arrive first and the test pass without the
fix. Ask one nameserver at a time, in the given order, drop the delay,
and check that each nameserver got one query.

Co-authored-by: Perplexity <noreply@perplexity.ai>
c6e9a37 had hickory-resolver ask the other nameservers after an
NXDOMAIN, as 0.24 did. 0.26 limits a lookup to one timeout per server
and then returns a timeout instead of the error it already has, so an
NXDOMAIN followed by a nameserver that doesn't answer became a timeout,
retried for about 30 s with the default options. glibc, which resolves
the host when the connection is opened, takes the first NXDOMAIN as
final. Leave 0.26's default, so the cache gets the same answer at once.

Co-authored-by: Perplexity <noreply@perplexity.ai>
On 0.62 a query's parse time grows exponentially with nesting: f( and
ROW( double it with each level (6.5 s at depth 20 in a debug build),
POSITION( about triples it, and ARRAY[ hangs once it nests as deep as
the recursion limit. 0.63 and 0.64 parse all of them at depth 30 in
milliseconds and refuse ARRAY[ nested 48 deep at once.

0.64 reads ONLY before a table in FROM, UPDATE, DELETE and MERGE, and
`t *`, as markers on the real table, so plugins now check that table
instead of the query being refused. The parser still reads
`INSERT INTO ONLY t` as a table named ONLY, so that's still refused.

relations.rs follows the AST changes (a TABLE command's names are
Idents, SELECT INTO has a list of targets, index_hints is now
index_directives) without changing its labels.

Co-authored-by: Perplexity <noreply@perplexity.ai>
In a simple Query, the server reads the text after `COPY t FROM STDIN;`
as more statements and runs them after the COPY: COPY data comes only
in CopyData messages. sqlparser reads it differently. 0.52 and 0.62
take the rest of the query into the COPY. 0.64 parses the rest of the
COPY's line as statements, but takes the text from the next line on as
the COPY's data. So no plugin saw the INSERT in
`COPY labels FROM STDIN;\nINSERT INTO secrets VALUES (1)`, and the
server ran it.

parse_sql now refuses a COPY whose data isn't blank, as it does an
ONLY it can't read, so the query takes the unparsed path:
rejects_unparsed refuses it when it might touch a gated table.

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

@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 230abe75: not clear, because it inherits #29's blocker at 5d3ba0e1. That blocker is the unchecked ATTACH PARTITION <gated>, reproduced at this head. This PR's own change is clear; once rebased on the fixed #29, it only needs the second pass.

What holds:

  • No COPY payload variant gets a statement past the check: CR, LF or CRLF; WITH (FORMAT csv); column lists; a leading comment; a second COPY on the line; EXPLAIN COPY; or text after \., which is parsed and checked.
  • The whitespace exemption is sound. is_ascii_whitespace covers only characters PostgreSQL also treats as whitespace, so an exempt payload can't hold a statement.
  • The check covers Q, P and rewrites, because all three go through parse_sql.
  • With parse not required, the query is forwarded, which matches the contract from the previous PR.
  • cargo fmt --check is clean and the lib suite passes (389/389, --features test-plugins).

Nonblocking: extra test cases (inline) and one description item (separate comment).

Pass 1 of 2 (Opus, high effort). A second, independent pass with a different model follows.

Created with Perplexity

Comment thread src/query_router.rs Resolved

Copy link
Copy Markdown
Collaborator Author

Nonblocking: one description item at 230abe75.

and otherwise forwards it as it forwards any query the parser can't read.

With plugins_require_parse off, a payload that holds a statement is forwarded unchecked, whatever table it names. That's the same as main, but the sentence reads as if only harmless queries are forwarded. Suggested addition: "With plugins_require_parse off, it's forwarded unchecked whatever it names, as any unparsed query is."

The other claims match the head: the 389-test count, the 0.52/0.62/0.64 table, the \. claim and the comment-only line being refused.

Created with Perplexity

artem-pplx and others added 3 commits November 17, 2026 01:00
sqlparser 0.64 parses ATTACH PARTITION, DETACH PARTITION, INHERIT and
NO INHERIT in ALTER TABLE, and INHERITS in CREATE FOREIGN TABLE, which
0.62 didn't. It visits only the table altered or created, not the one
these name. So with a table gated and parse required,
`ALTER TABLE p ATTACH PARTITION secrets DEFAULT; SELECT * FROM p` went
from refused to allowed, and read secrets through p. table_access now
checks those names, in any statement.

nxdomain_is_not_held_for_a_silent_nameserver now waits at most 2 s for
the NXDOMAIN, so it fails if the answer is held, not only if it
changes.

Co-authored-by: Perplexity <noreply@perplexity.ai>
Co-authored-by: Perplexity <noreply@perplexity.ai>
A CRLF line break starts the COPY's data as LF does, so the INSERT after
it is refused. The parser reads SQL again after `\.`, and a comment that
spans the line break doesn't start the data, so the INSERT is read and
denied.

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

Copy link
Copy Markdown
Collaborator Author

Added that sentence to the description, at 4e7025b.

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 4e7025b4: clear, no blockers. This covers 230abe7, the merge of #29's 57cd0c17 (d82d7b0) and the new tests.

  • The new CRLF, \.-then-INSERT and /*\n*/ cases pass. The commit message correctly notes that the last two pass without the guard.
  • Mutation-tested: disabling only the COPY guard fails test_statements_after_copy_from_stdin_are_checked on the newline-plus-INSERT case.
  • A temporary test confirmed that the guard applies to Q, P and rewrites.
  • cargo +stable fmt --check is clean and the lib suite passes (390/390, --features test-plugins).
  • CI hasn't run, because the base isn't main.

Nonblocking: one description wording item (separate comment). The inherited nonblocking items are on #29.

Two passes: Opus (high effort) on 230abe7, then a fresh independent final with Astra (high effort) on this exact head.

Created with Perplexity

Copy link
Copy Markdown
Collaborator Author

Nonblocking: one description item at 4e7025b4.

With plugins_require_parse off, it's forwarded unchecked whatever it names, as any unparsed query is.

That holds when table_access is the only plugin. A plugin that refuses unparsed text on its own still rejects the query. Suggested: "With plugins_require_parse off and only table_access enabled, it's forwarded unchecked whatever it names, as any unparsed query is; plugins that refuse unparsed queries still reject it."

The rest matches the head: the title, the CRLF/\./comment cases and the 390-test count.

Created with Perplexity

artem-pplx and others added 2 commits November 17, 2026 01:26
The visitor doesn't report the parents in CREATE [UNLOGGED] TABLE ...
INHERITS or the tables in DROP FOREIGN TABLE. 0.64 newly parses CREATE
UNLOGGED TABLE and DROP FOREIGN TABLE, so with plugins_require_parse on,
these were refused as unparsed before and allowed after the upgrade.
Rows inserted into a child table are read from its parent, so inheriting
from a gated table adds rows that its readers see.

table_access now checks both, as it checks CREATE FOREIGN TABLE ...
INHERITS.

Co-authored-by: Perplexity <noreply@perplexity.ai>
Co-authored-by: Perplexity <noreply@perplexity.ai>
@artem-pplx
artem-pplx added this pull request to stack #31 November 17, 2026 01:37

@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 f58848b6: clear, no findings. The merge tree equals #29's 9af00e6 plus this PR's own query_router delta, which is byte-identical to the reviewed 57cd0c17..4e7025b4. The lib suite passes (390/390), and the description matches the head.

Security tier: an Opus (high effort) delta check, then a fresh independent final with Astra (high effort) on this exact head.

Created with Perplexity

@micahjz micahjz 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.

Verdict: APPROVE

PR/head: #30 at f58848b against #29/9af00e68d468b16c106a325999f53f286ca5f17d.

Change/flow: Reviewed the complete stacked tree and this PR’s delta. Query and Parse messages share parse_sql, as do validated rewrites. A nonblank Copy payload becomes a parser error before plugin execution; the existing rejects_unparsed policy decides whether it may be forwarded. CopyData/CopyDone/CopyFail handling is unchanged.

Findings: No new blocking findings. The visitor is recursive and the ASCII-whitespace exemption cannot contain executable SQL. Important configuration boundary: this is not unconditional rejection. Legacy table_access with plugins_require_parse=false still forwards parse failures, including a COPY naming a gated source that this guard changes from parsed to unparsed. Enforced legacy pools need plugins_require_parse=true; registered/configured plugins retain their existing fail-closed policy. That opt-out contract is explicitly documented, not validated as safe enforcement.

Validation: Independently ran cargo test --locked --features test-plugins at this head: 390 unit tests and 4 doc-tests pass. An additional 32-case matrix ran each SQL string through both Q and P and compared main, #29 and #30. Hidden INSERT tails after LF, CR, CRLF, CSV options and a same-line SELECT are allowed at #29 but refused here; terminator/comment-boundary forms are inspected and denied, and blank payloads remain accepted. Formatting and whitespace checks pass. Toolchain: rustc 1.100.0, debug info disabled.

Compatibility/rollout: Merge #29 first. No wire or data-format migration; protection requires the fixed binary on every serving pooler, and rollback reopens the old gap. Rust CodeQL was still in progress at the last check; other reported checks passed and an existing human approval is present. CI/merge gates remain separate from this source approval.

Exclusions: No code changes, merge, queue, deployment, live PostgreSQL/proxy integration test, private-plugin build, or production verification performed.

Created with Perplexity

Base automatically changed from fix-vacuum-check-after-semicolon to main November 17, 2026 01:44
main now has #29 squashed. This branch already had all of #29, so the
conflicts are resolved to this branch's side and the tree is unchanged.

Co-authored-by: Perplexity <noreply@perplexity.ai>
@artem-pplx
artem-pplx merged commit bab0350 into main Nov 17, 2026
6 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.

3 participants