Skip to content

SQL guard reads statements with PostgreSQL's parser - #2133

Merged
MikeyPetrillo merged 8 commits into
mainfrom
claude/sweet-brown-i99jl3
Dec 4, 2026
Merged

MikeyPetrillo merged 8 commits into
mainfrom
claude/sweet-brown-i99jl3

Conversation

@MikeyPetrillo

Copy link
Copy Markdown
Owner

The SQL guard reads a statement with PostgreSQL's own parser, judges what would run, and signs a write only when it changes one table by fixed values in its WHERE. Text that does not parse is blocked.

@MikeyPetrillo

Copy link
Copy Markdown
Owner Author

@strix-security review

@strix-security

strix-security Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Strix Security Review

To fix before merging (7)

PR summary: The SQL guard now reads a submission with PostgreSQL's own parser (libpg-query, run off-process in a small pool) instead of a lexical pass, and signs a write only when it is an INSERT of plain VALUES or an UPDATE/DELETE of one table whose WHERE ties a column to a value.

Review summary

Reviewed the rewrite that moves the SQL guard's judgment onto PostgreSQL's parse tree (libpg-query, run in a forked process pool) and restricts signed writes to ones sql-bound.js proves. The parse-tree traversal, the bounds proof, the process pool and admission caps, and the certificate path were traced end to end, including the EXPLAIN/ANALYZE gating, the removed lexical analyzer's consumers, and every spelling of the ANALYZE option. The pool's deadline, large-text serialisation, operator-run refusal and fair admission hold up, and no dangling consumer was left behind.

The confirmed problems sit in the verdict-to-certificate boundary of the new judge. A statement whose kind is taken from the text's first word rather than the parsed node collects no risk id, so SELECT … INTO, EXPLAIN ANALYZE CREATE TABLE … AS and a plain REFRESH MATERIALIZED VIEW come back as a pass and the Ed25519 token is accepted for them; COPY … FROM STDIN likewise passes with no risk id at all, so a bulk load is certified under a contract that says only plain-VALUES inserts and bounded UPDATE/DELETE pass. On the reading side, the new named function and setting lists miss the set-returning form of pg_settings and every setting name except primary_conninfo, so the configuration the server-access rule exists to keep out is available by another spelling, and a search_path change is not treated as altering what a later statement resolves to. Separately, the cross-dialect marker scan still never looks inside a dollar-quoted body, so text a MySQL/MariaDB executor runs as code can still be signed.

Ruled out (7)
  • Can a caller obtain a valid certificate for arbitrary SQL by attaching its own public key to sql-cert-verify?
    Choosing a verification key is a pre-existing, documented multi-deployment feature of a stateless signature check that authorizes nothing, and no consumer in the repo treats a certificate's presence as authority.
  • Does the guard sign usable certificates for warn verdicts, including block risks a caller downgrades with allow?
    The signed payload carries the real verdict and verification rejects anything that is not a pass, so such a token cannot pass the only verify path wired up.
  • Can other sessions' live SQL be read through a certified pass on pg_stat_activity or pg_stat_statements?
    PostgreSQL masks other roles' query text unless the executing role already holds pg_read_all_stats or is superuser, and the guard certifies any plain SELECT, so it is not a read-confidentiality control.
  • Do the replication-slot peek functions slip past the server-access list and read the WAL?
    pg_replication_slot_peek_changes and its binary form are not callable functions in PostgreSQL, so such a statement errors instead of reading anything.
  • Can pg_signal_backend terminate another session through a certified pass?
    pg_signal_backend is a predefined role, not a callable function, and every real signal and log function is blocked as server-access.
  • Can a large multi-statement submission make the server parse an oversized reply and stall the shared event loop?
    Measured reply amplification, with one large text at a time and two slots, keeps the parent's parse in the low milliseconds and event-loop gaps to tens of milliseconds.
  • Can one wallet fill the admission queue with large texts and keep other callers out of the guard?
    Admission hands a free slot to the caller holding the fewest places, so another caller waits about one job rather than the queue depth, and the queued text is the same string the in-flight request already holds.
Review history (3)
  • Review 3 · 4e1070b · Dec 4 20:35 UTC · Found 2 new Medium Vulnerabilities and 2 new Low Vulnerabilities
  • Review 2 · 57049ef · Dec 4 20:18 UTC · Nothing new
  • Review 1 · 0f51f62 · Dec 4 20:07 UTC · Found 2 Medium Vulnerabilities and 1 Low Vulnerability

Fixed the findings? re-run the review, or tag @strix-security in a PR comment to run a fresh review.

Review 3 on this PR · 4e1070b · requested Dec 4 20:26 UTC by @MikeyPetrillo


Reviewed by Strix
Re-run review · Configure security review settings · Try a deeper review with @strix-security /deep

@socket-security

socket-security Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addednpm/​libpg-query@​18.3.010010010096100

View full report

@MikeyPetrillo

Copy link
Copy Markdown
Owner Author

@strix-security review

@MikeyPetrillo

Copy link
Copy Markdown
Owner Author

@strix-security review

@MikeyPetrillo

Copy link
Copy Markdown
Owner Author

@strix-security review

@strix-security strix-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Strix flagged 3 new security findings below. See the pinned summary comment for the full PR status.

Comment thread src/tools/sql-judge.js
Comment on lines +196 to +198
case "CreateTableAsStmt": case "RefreshMatViewStmt": case "intoClause":
creates = true;
break;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 MEDIUM: Schema changes are classified by the statement's first word, not its parse tree

TL;DR: Any caller of the guard can get a signed certificate for a statement that creates or replaces a table. The statement kind is read from the first word of the text, so EXPLAIN ANALYZE CREATE TABLE ... AS SELECT looks like a query and REFRESH MATERIALIZED VIEW matches no keyword it classifies. Deciding the kind from the parsed statement, and giving that branch a risk id, closes both.

Cause, impact and fix

Cause: The branch that recognises a table being created or a materialized view being refreshed only sets the mutating flag and attaches no risk id, while the statement kind that decides the schema-change warning is taken from the first word of the raw text rather than from the statement the parser returns under an EXPLAIN or PREPARE.

Impact: Schema changes reach a pass verdict and are signed: an agent's executor accepts the certificate, so a REFRESH MATERIALIZED VIEW ... WITH NO DATA empties a live view, and an EXPLAIN ANALYZE CREATE TABLE ... AS SELECT both alters the schema and copies a whole table under a certificate its operator trusts.

Fix: Give the creating and replacing nodes their own risk ids — ddl for a table created as a select, bound-not-proven for a refreshed materialized view and truncate for WITH NO DATA — and take the statement kind from the unwrapped parse node instead of the first word. Add cases for the EXPLAIN ANALYZE forms, SELECT ... INTO and REFRESH MATERIALIZED VIEW.

🟡 EXPLAIN ANALYZE prefix hides a schema-changing CTAS from the ddl risk, yielding a pass verdict and a valid certificate

Severity: MEDIUM

TL;DR: sql-judge.js keys the ddl risk on the statement's first word, so EXPLAIN ANALYZE CREATE TABLE ... AS SELECT is read as a plain read, gains no risk id, and returns verdict pass with a signed certificate.

Impact: A caller submitting SQL to the paid guard obtains a certificate its own executor accepts for a schema change plus an unbounded full-table copy — the same statement without the prefix is refused, so the certified/unsigned boundary is bypassed by one keyword.

Root cause:

  • Whether a schema change is flagged is decided from the first word of the raw text rather than from the statement node the judge already unwrapped, so any non-DDL prefix hides a DDL statement from the ddl risk.
  • The CreateTableAsStmt / RefreshMatViewStmt / intoClause branch only sets creates, and creates feeds nothing but the round-trip mutating flag — no risk id is ever attached, so the verdict is whatever the first word says.
  • EXPLAIN ANALYZE executes the statement it explains, so the CTAS stays on the executed path, yet named still resolves to read and the ddl risk is skipped while mutating is reported true.
  • SELECT ... INTO and REFRESH MATERIALIZED VIEW already passed before this PR; for the EXPLAIN ANALYZE ... AS SELECT forms the replaced analyzer returned warn, so that part is a regression introduced here.
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: EXPLAIN ANALYZE prefix hides a schema-changing CTAS from the ddl risk, yielding a pass verdict and a valid certificate
Severity: MEDIUM

**TL;DR:** sql-judge.js keys the `ddl` risk on the statement's first word, so `EXPLAIN ANALYZE CREATE TABLE ... AS SELECT` is read as a plain read, gains no risk id, and returns verdict `pass` with a signed certificate.

**Impact:** A caller submitting SQL to the paid guard obtains a certificate its own executor accepts for a schema change plus an unbounded full-table copy — the same statement without the prefix is refused, so the certified/unsigned boundary is bypassed by one keyword.

**Root cause:**
- Whether a schema change is flagged is decided from the first word of the raw text rather than from the statement node the judge already unwrapped, so any non-DDL prefix hides a DDL statement from the `ddl` risk.
- The `CreateTableAsStmt` / `RefreshMatViewStmt` / `intoClause` branch only sets `creates`, and `creates` feeds nothing but the round-trip `mutating` flag — no risk id is ever attached, so the verdict is whatever the first word says.
- `EXPLAIN ANALYZE` executes the statement it explains, so the CTAS stays on the executed path, yet `named` still resolves to `read` and the `ddl` risk is skipped while `mutating` is reported true.
- `SELECT ... INTO` and `REFRESH MATERIALIZED VIEW` already passed before this PR; for the `EXPLAIN ANALYZE ... AS SELECT` forms the replaced analyzer returned `warn`, so that part is a regression introduced here.

Location: src/tools/sql-judge.js:196-198
Context: primary fix: a table-creating node must carry a risk id, not just flip `mutating`
```
// Before:
      case "CreateTableAsStmt": case "RefreshMatViewStmt": case "intoClause":
        creates = true;
        break;
// After:
      case "CreateTableAsStmt": case "RefreshMatViewStmt": case "intoClause":
        creates = true;
        ids.add("ddl");
        break;
```

Location: src/tools/sql-judge.js:264-266
Context: the kind that gates the ddl risk comes from the first word, after the tree has already been unwrapped
```
  const verb = /[A-Z]+/.exec(scrubSql(text).scrubbed.toUpperCase())?.[0] ?? null;
  const named = KIND_OF.get(verb) ?? "other";
  if (named === "ddl" && !["drop-object", "truncate", "drop-column"].some((id) => ids.has(id))) ids.add("ddl");
```

Location: src/tools/sql-judge.js:156-159
Context: statement text under EXPLAIN is unwrapped here, but only for the bound check, not for the statement kind
```
  // The statement that runs, under an EXPLAIN, PREPARE or COPY: the one write that can be certified.
  let top = root;
  for (let inner; (inner = (top.ExplainStmt ?? top.PrepareStmt ?? top.CopyStmt)?.query);) top = inner;
  top = Object.values(top)[0];
```

How to fix:
Attach the `ddl` risk id wherever a table-creating or matview-refreshing node is visited (`CreateTableAsStmt`, `RefreshMatViewStmt`, `intoClause`), so those statements warn regardless of any EXPLAIN/PREPARE prefix or of how the text happens to start. Derive the statement kind used for the `ddl` risk from the unwrapped top-level statement node rather than from the first word of the raw text, and add regression tests asserting a non-pass verdict for `EXPLAIN ANALYZE CREATE TABLE ... AS SELECT`, `EXPLAIN ANALYZE CREATE MATERIALIZED VIEW ... AS SELECT`, `SELECT ... INTO`, and `REFRESH MATERIALIZED VIEW`.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.
🟡 SQL guard signs a pass certificate for `REFRESH MATERIALIZED VIEW` (including `WITH NO DATA`), which discards an existing object's contents

Severity: MEDIUM

TL;DR: sql-judge.js treats RefreshMatViewStmt as an object-creating node, so REFRESH MATERIALIZED VIEW mv WITH NO DATA returns verdict pass with no named risk and receives a signed execution certificate.

Impact: Anyone submitting SQL to the guard gets a certificate the operator's database layer accepts, so a compromised or confused agent can empty or lock out an existing materialized view and break every query that reads it — defeating the single check placed between the agent and the production schema.

Root cause:

  • The judge decides safety by adding risk ids while walking the parse tree, and a statement that adds none is reported as pass; nodes outside the switch's short list are judged safe by silence rather than by a rule.
  • RefreshMatViewStmt is grouped in the same creates = true branch as CreateTableAsStmt and intoClause, although a refresh replaces the entire contents of an existing object instead of creating a new one, and its skipData flag is never read by the walk (booleans are not object-valued children).
  • Nothing downstream corrects it: the verb REFRESH is not in KIND_OF, the ddl shim requires named === "ddl", and src/tools/sql-guard-kit.js signs every verdict that is not block, so the executor is handed a pass certificate with no way to see that the write was unbounded.
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: SQL guard signs a pass certificate for `REFRESH MATERIALIZED VIEW` (including `WITH NO DATA`), which discards an existing object's contents
Severity: MEDIUM
CWE: CWE-863

**TL;DR:** `sql-judge.js` treats `RefreshMatViewStmt` as an object-creating node, so `REFRESH MATERIALIZED VIEW mv WITH NO DATA` returns verdict `pass` with no named risk and receives a signed execution certificate.

**Impact:** Anyone submitting SQL to the guard gets a certificate the operator's database layer accepts, so a compromised or confused agent can empty or lock out an existing materialized view and break every query that reads it — defeating the single check placed between the agent and the production schema.

**Root cause:**
- The judge decides safety by adding risk ids while walking the parse tree, and a statement that adds none is reported as `pass`; nodes outside the switch's short list are judged safe by silence rather than by a rule.
- `RefreshMatViewStmt` is grouped in the same `creates = true` branch as `CreateTableAsStmt` and `intoClause`, although a refresh replaces the entire contents of an existing object instead of creating a new one, and its `skipData` flag is never read by the walk (booleans are not object-valued children).
- Nothing downstream corrects it: the verb `REFRESH` is not in `KIND_OF`, the `ddl` shim requires `named === "ddl"`, and `src/tools/sql-guard-kit.js` signs every verdict that is not `block`, so the executor is handed a `pass` certificate with no way to see that the write was unbounded.

Location: src/tools/sql-judge.js:196-198
Context: RefreshMatViewStmt shares the object-creating branch, so it produces no risk id
```
// Before:
      case "CreateTableAsStmt": case "RefreshMatViewStmt": case "intoClause":
        creates = true;
        break;
// After:
      case "RefreshMatViewStmt": // replaces an existing object's contents; WITH NO DATA empties it
        ids.add(n.skipData ? "truncate" : "bound-not-proven");
        creates = true;
        break;
      case "CreateTableAsStmt": case "intoClause":
        creates = true;
        break;
```

Location: src/tools/sql-judge.js:332-332
Context: An empty risk set becomes `pass`, which the handler then signs
```
    verdict: blocked.length ? "block" : collected.length ? "warn" : "pass",
```

Location: src/tools/sql-judge.js:17-24
Context: `REFRESH` is absent from KIND_OF, so the statement is named "other" and the ddl shim never applies

How to fix:
Give `RefreshMatViewStmt` its own branch instead of sharing the object-creating nodes: add the existing `truncate` risk (block) when `skipData` is set, since that form empties the materialized view and leaves it unscannable, and `bound-not-proven` (warn) otherwise, so no verifiable certificate is issued for it. Add pass/warn/block cases for `REFRESH MATERIALIZED VIEW`, `... WITH NO DATA` and `... CONCURRENTLY` to `scripts/test-sql-guard.js`, alongside the `CREATE TABLE AS` and `SELECT ... INTO` controls. Review the remaining maintenance statements that currently reach `pass` with no risk (for example `VACUUM FULL`, `REINDEX`, `LOCK TABLE ... IN ACCESS EXCLUSIVE MODE`) against the documented claim that only plain-value inserts and column-bounded updates/deletes pass.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.

React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss these findings.

Comment thread src/tools/sql-guard.js
i++;
}
return { scrubbed: out, hadComment, unterminated };
return { scrubbed: out, hadComment, unterminated, dialect: dialect || /`|#(?![>#=-])/.test(out) };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 LOW: Dollar-quoted bodies are blanked before the other-dialect check

TL;DR: Any caller submitting SQL can have text certified as a harmless query while a MySQL or MariaDB executor runs a DROP TABLE inside it. A $tag$...$tag$ body is blanked as a literal before the executable-comment check, and the dialect flag is then read from that blanked text, although only PostgreSQL reads the body as a string. Testing the dollar-quoted body for /*! restores the warning.

Cause, impact and fix

Cause: Cross-dialect detection was moved onto the scrubbed text, and the dollar-quote branch replaces the whole body with filler before the /*! / /*M! test can see it, so anything the body contains is invisible to both that test and the dialect scan.

Impact: A statement whose executed content is a destructive one is signed as a pass, so a table and its data can be dropped under a certificate the executor accepts — the one check standing between a confused agent and the production schema is spent on text it did not really read.

Fix: Decide the dialect flag from the raw submission, or inspect the dollar-quote body for /*!, /*M!, backticks and # before blanking it, and restore the regression test for SELECT $a$ /*! DROP TABLE t */ $a$.

🔵 PostgreSQL dollar quotes hide MySQL executable comments from the SQL guard's other-dialect check, so it signs a clean pass for a destructive statement

Severity: LOW

TL;DR: scrubSql blanks a $tag$…$tag$ body before the /*! check, so analyzeSql never flags other-dialect and signs a clean pass (and certificate) for text MySQL/MariaDB executes as a destructive statement.

Impact: An agent that must obtain a signed pass before its SQL runs can submit text the guard certifies as a harmless SELECT, while a MySQL/MariaDB executor runs the embedded DROP TABLE; the table and its data are lost.

Root cause:

  • Cross-dialect detection was moved from the raw submission onto the scrubbed text, on the assumption that anything inside a literal is inert on every engine - but $tag$...$tag$ quotes only in PostgreSQL, so its body is still code on MySQL/MariaDB.
  • The dollar-quote branch at src/tools/sql-guard.js:73-84 blanks the whole body before the /*! / /*M! test at line 60 can see it, and dialect is then read from that same blanked text at line 112.
  • The PR also dropped the old raw-text /\/\*M?!/ check and the control test asserting SELECT $a$ /*! DROP TABLE t */ $a$ blocks, so src/tools/sql-judge.js:321 sees dialect === false and returns pass with risks: [], which issueCertificate signs.
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: PostgreSQL dollar quotes hide MySQL executable comments from the SQL guard's other-dialect check, so it signs a clean pass for a destructive statement
Severity: LOW
CWE: CWE-185

**TL;DR:** `scrubSql` blanks a `$tag$…$tag$` body before the `/*!` check, so `analyzeSql` never flags `other-dialect` and signs a clean `pass` (and certificate) for text MySQL/MariaDB executes as a destructive statement.

**Impact:** An agent that must obtain a signed `pass` before its SQL runs can submit text the guard certifies as a harmless `SELECT`, while a MySQL/MariaDB executor runs the embedded `DROP TABLE`; the table and its data are lost.

**Root cause:**
- Cross-dialect detection was moved from the raw submission onto the scrubbed text, on the assumption that anything inside a literal is inert on every engine - but `$tag$...$tag$` quotes only in PostgreSQL, so its body is still code on MySQL/MariaDB.
- The dollar-quote branch at `src/tools/sql-guard.js:73-84` blanks the whole body before the `/*!` / `/*M!` test at line 60 can see it, and `dialect` is then read from that same blanked text at line 112.
- The PR also dropped the old raw-text `/\/\*M?!/` check and the control test asserting `SELECT $a$ /*! DROP TABLE t */ $a$` blocks, so `src/tools/sql-judge.js:321` sees `dialect === false` and returns `pass` with `risks: []`, which `issueCertificate` signs.

Location: src/tools/sql-guard.js:73-84
Context: dollar-quote branch blanks the body before the dialect checks run
```
// Before:
    if (c === "$" && !/[A-Za-z0-9_$\u0080-\uffff]/.test(src[i - 1] || "")) {
      const m = /^\$(?:[A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/.exec(src.slice(i, i + 256));
      if (m) {
        const tag = m[0];
        const close = src.indexOf(tag, i + tag.length);
        const end = close === -1 ? src.length : close + tag.length;
        if (close === -1) unterminated = unterminated || "dollar-quoted string";
        out += FILL.repeat(end - i);
        i = end;
        continue;
      }
    }
// After:
    if (c === "$" && !/[A-Za-z0-9_$\u0080-\uffff]/.test(src[i - 1] || "")) {
      const m = /^\$(?:[A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/.exec(src.slice(i, i + 256));
      if (m) {
        const tag = m[0];
        const close = src.indexOf(tag, i + tag.length);
        const end = close === -1 ? src.length : close + tag.length;
        if (close === -1) unterminated = unterminated || "dollar-quoted string";
        // A dollar quote is a literal only in postgres: another database reads
        // the body as code, so what it would run there is still a risk.
        const body = src.slice(i + tag.length, close === -1 ? src.length : close);
        if (/\/\*M?!/.test(body) || /`|#(?![>#=-])/.test(body)) dialect = true;
        out += FILL.repeat(end - i);
        i = end;
        continue;
      }
    }
```

Location: src/tools/sql-guard.js:112-112
Context: dialect is decided from the scrubbed text, from which the whole dollar-quoted body has already been removed
```
  return { scrubbed: out, hadComment, unterminated, dialect: dialect || /`|#(?![>#=-])/.test(out) };
```

Location: src/tools/sql-judge.js:321-321
Context: the only place other-dialect is raised; it never fires when the comment sits inside a dollar quote
```
  if (dialect) push("other-dialect");
```

How to fix:
Decide the `dialect` flag from the raw submission, or check the dollar-quote body itself before blanking it: a `$tag$` body is not a string on a database that has no dollar quoting, so a `/*!` or `/*M!` executable comment there must still raise `other-dialect`. Single- and double-quoted content can stay exempt, since those are literals on the other engines too. Restore the removed control test for `SELECT $a$ /*! DROP TABLE t */ $a$`, and make the `other-dialect` catalogue text say plainly which quoting forms are exempt.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.

React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss these findings.

@MikeyPetrillo

Copy link
Copy Markdown
Owner Author

@strix-security review

@strix-security strix-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Strix flagged 4 new security findings below. See the pinned summary comment for the full PR status.

Comment thread src/tools/sql-judge.js
Comment on lines +196 to +200
case "CopyStmt":
if (n.is_program) ids.add("copy-from-program");
else if (n.filename) ids.add("server-access");
if (n.is_from && inCatalog(n.relation)) ids.add("system-catalog-write");
break;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 MEDIUM: COPY … FROM STDIN is certified as a plain read

TL;DR: A caller can get a signed pass, accepted by sql-cert-verify, for COPY t FROM STDIN, whose rows arrive over the connection after the check. The CopyStmt branch judges only the file and program channels, so a copy that reads its rows from the client collects no risk. Recording bound-not-proven there keeps it out of pass.

Cause, impact and fix

Cause: The verdict comes only from the collected risk ids, and a COPY … FROM with neither filename nor is_program collects none, although judgeStatement counts the copy kind as mutating.

Impact: The certificate covers the statement text alone, so the executor runs an unbounded bulk insert of values the check never saw.

Fix: Add bound-not-proven, or a block-level id, in the CopyStmt branch when is_from is set without filename or is_program, and add regression cases for COPY t FROM STDIN and COPY t (a,b) FROM STDIN.

🟡 COPY ... FROM STDIN gets a pass verdict and a verify-valid execution certificate for an uninspected bulk insert

Severity: MEDIUM

TL;DR: The CopyStmt branch of judgeTree records no risk id for COPY <table> FROM STDIN, so the verdict is pass and sql-guard signs a certificate that sql-cert-verify accepts for an unbounded bulk insert.

Impact: A compromised or confused agent gets a signed pass for a table bulk load whose rows it streams afterwards, so the database layer obeys an unbounded insert of values the certified statement hash never covered.

Root cause:

  • The verdict is computed from the collected risk ids alone, so any statement the traversal records nothing for is signed as a pass whether or not it changes data.
  • The CopyStmt branch judges only the data channel - is_program, filename, catalog target - and never applies bound-not-proven to a COPY whose rows arrive from the connection, though that id exists for exactly this shape.
  • judgeStatement marks the copy kind (and n.is_from) as mutating, so the code knows the statement writes while riskIds stays empty and analyzeSql returns pass.
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: COPY ... FROM STDIN gets a pass verdict and a verify-valid execution certificate for an uninspected bulk insert
Severity: MEDIUM
CWE: CWE-863

**TL;DR:** The `CopyStmt` branch of `judgeTree` records no risk id for `COPY <table> FROM STDIN`, so the verdict is pass and `sql-guard` signs a certificate that `sql-cert-verify` accepts for an unbounded bulk insert.

**Impact:** A compromised or confused agent gets a signed pass for a table bulk load whose rows it streams afterwards, so the database layer obeys an unbounded insert of values the certified statement hash never covered.

**Root cause:**
- The verdict is computed from the collected risk ids alone, so any statement the traversal records nothing for is signed as a pass whether or not it changes data.
- The `CopyStmt` branch judges only the data channel - `is_program`, `filename`, catalog target - and never applies `bound-not-proven` to a COPY whose rows arrive from the connection, though that id exists for exactly this shape.
- `judgeStatement` marks the `copy` kind (and `n.is_from`) as mutating, so the code knows the statement writes while `riskIds` stays empty and `analyzeSql` returns pass.

Location: src/tools/sql-judge.js:196-200
Context: CopyStmt branch: no risk id for a COPY FROM the connection
```
// Before:
      case "CopyStmt":
        if (n.is_program) ids.add("copy-from-program");
        else if (n.filename) ids.add("server-access");
        if (n.is_from && inCatalog(n.relation)) ids.add("system-catalog-write");
        break;
// After:
      case "CopyStmt":
        if (n.is_program) ids.add("copy-from-program");
        else if (n.filename) ids.add("server-access");
        if (n.is_from && !n.is_program && !n.filename) ids.add("bound-not-proven"); // its rows arrive on the connection, after this text
        if (n.is_from && inCatalog(n.relation)) ids.add("system-catalog-write");
        break;
```

How to fix:
Treat a COPY that reads its rows from the connection as unproven rather than as a plain-values insert: in the `CopyStmt` branch, record `bound-not-proven` (or a dedicated block-severity id) when `is_from` is set with neither `is_program` nor `filename`, so such a statement can never reach a `pass` verdict and no certificate is issued for it. Add a regression case asserting that `COPY t FROM STDIN` and `COPY t (a,b) FROM STDIN` do not verify, alongside the existing COPY controls, and reflect the rule in the tool description (a COPY of fixed rows can be inline in an INSERT; one whose rows arrive on the connection is not certifiable).

Please fix this vulnerability. If you propose a fix, make it concise and minimal.

React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss these findings.

Comment thread src/tools/sql-judge.js
Comment on lines +218 to +221
if (name === "current_setting") {
const setting = plain(n.args?.[0]);
if (typeof setting !== "string" || setting.toLowerCase() === "primary_conninfo") ids.add("server-access");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 MEDIUM: Server configuration is read under a certificate when the name is unlisted

TL;DR: A caller can get a signed pass, accepted by sql-cert-verify, for SELECT * FROM pg_show_all_settings(), SHOW archive_command or current_setting('restore_command'). Server configuration is guarded by hand-written lists of function and setting names, so any spelling outside them is certified. Matching that data by category keeps the whole configuration behind the block.

Cause, impact and fix

Cause: SYSTEM_FUNCTION enumerates function names, and the current_setting and VariableShowStmt arms test one literal, primary_conninfo; both decide by exact string rather than by what the value is, so an unlisted settings function or setting name adds no risk id.

Impact: The server's own configuration, including archive_command, restore_command, install paths and primary_conninfo, is readable under a certificate, although pg_settings, pg_file_settings, SHOW ALL and pg_show_all_file_settings() all block.

Fix: Match the settings-returning catalog functions, pg_show_all_settings and pg_settings_get_flags among them, in SYSTEM_FUNCTION, and replace the primary_conninfo literal with one shared set of server-configuration setting names used by both the current_setting and SHOW arms.

🟡 `pg_show_all_settings()` bypasses the new server-access block and receives an executor-valid pass certificate

Severity: MEDIUM

TL;DR: The new server-access function list in src/tools/sql-judge.js omits pg_show_all_settings(), the set-returning function behind the blocked pg_settings view, so the same server-configuration dump is judged pass and signed.

Impact: An agent whose SQL only runs when it carries a certificate from this guard can read the entire server configuration (file paths, connection strings, and primary_conninfo when the executing role is privileged), although pg_settings, SHOW ALL, current_setting('primary_conninfo') and pg_show_all_file_settings() are all blocked.

Root cause:

  • This PR adds the server-access risk and detects it by matching call names against a hand-written regex instead of resolving the function against pg_proc, so every settings-returning function that is not in that string passes, with no second check behind it.
  • pg_show_all_settings reaches only the FuncCall arm of judgeTree, adds no id, contributes no RangeVar for SERVER_RELATION to test, and leaves mutating: false, so the verdict is pass; sql-guard-kit.js withholds a certificate only on block, so a valid Ed25519 token is signed and accepted by verifyCertificate.
  • The omission is not a deliberate scope choice: the same data is blocked through the view, through SHOW ALL, through current_setting('primary_conninfo'), and through the sibling pg_show_all_file_settings(), which is itself in the list.
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: `pg_show_all_settings()` bypasses the new server-access block and receives an executor-valid pass certificate
Severity: MEDIUM
CWE: CWE-184

**TL;DR:** The new server-access function list in `src/tools/sql-judge.js` omits `pg_show_all_settings()`, the set-returning function behind the blocked `pg_settings` view, so the same server-configuration dump is judged `pass` and signed.

**Impact:** An agent whose SQL only runs when it carries a certificate from this guard can read the entire server configuration (file paths, connection strings, and `primary_conninfo` when the executing role is privileged), although `pg_settings`, `SHOW ALL`, `current_setting('primary_conninfo')` and `pg_show_all_file_settings()` are all blocked.

**Root cause:**
- This PR adds the `server-access` risk and detects it by matching call names against a hand-written regex instead of resolving the function against `pg_proc`, so every settings-returning function that is not in that string passes, with no second check behind it.
- `pg_show_all_settings` reaches only the `FuncCall` arm of `judgeTree`, adds no id, contributes no `RangeVar` for `SERVER_RELATION` to test, and leaves `mutating: false`, so the verdict is `pass`; `sql-guard-kit.js` withholds a certificate only on `block`, so a valid Ed25519 token is signed and accepted by `verifyCertificate`.
- The omission is not a deliberate scope choice: the same data is blocked through the view, through `SHOW ALL`, through `current_setting('primary_conninfo')`, and through the sibling `pg_show_all_file_settings()`, which is itself in the list.

Location: src/tools/sql-judge.js:33-33
Context: server-access function list: add the SRF behind pg_settings
```
// Before:
  "pg_read_(?:binary_)?file(?:_old)?|pg_ls_.*|pg_stat_file|pg_file_.*|pg_logdir_ls|pg_hba_file_rules|pg_ident_file_mappings|pg_show_all_file_settings|pg_extension_config_dump|pg_export_snapshot",
// After:
  "pg_read_(?:binary_)?file(?:_old)?|pg_ls_.*|pg_stat_file|pg_file_.*|pg_logdir_ls|pg_hba_file_rules|pg_ident_file_mappings|pg_show_all_(?:file_)?settings|pg_settings_get_flags|pg_extension_config_dump|pg_export_snapshot",
```

Location: src/tools/sql-judge.js:215-227
Context: FuncCall dispatch that the uncatalogued name falls through

How to fix:
Add `pg_show_all_settings` (and other settings-returning catalog helpers such as `pg_settings_get_flags`) to the server-access function list, ideally resolving the called function name against `pg_proc` so catalog functions are matched by identity rather than by an enumerated string. Add regression cases for `SELECT * FROM pg_show_all_settings()` and its `pg_catalog.`-qualified form to `scripts/test-sql-guard.js` next to the existing `pg_settings` / `SHOW ALL` cases.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.
🔵 `server-access` blocks only `primary_conninfo`, so `SHOW archive_command` / `current_setting('restore_command')` return `pass` with a signed certificate

Severity: LOW

TL;DR: The current_setting arm in judgeTree adds server-access only for the literal name primary_conninfo, so reading any other server setting by name (SHOW archive_command, SELECT current_setting('restore_command')) gets verdict pass and a signed certificate.

Impact: A confused or compromised agent submitting SQL gets a valid pass certificate for reading the database host's own configuration — archive/restore/ssl-passphrase commands and install paths — which this same file blocks through pg_file_settings, pg_show_all_file_settings() and SHOW ALL, exposing any credentials embedded in those commands.

Root cause:

  • Server settings are judged by a one-name denylist keyed on the literal in the arm, so every setting name outside that list is certified by default instead of being judged against an explicit safe set.
  • The arm at src/tools/sql-judge.js:218-221 adds a risk only when the name is not a plain literal or is exactly primary_conninfo; the twin VariableShowStmt arm at 235-236 repeats the same all|primary_conninfo list, so SHOW archive_command passes too.
  • The file already treats those same values as server-access under other spellings — pg_settings, pg_file_settings, pg_show_all_file_settings() and SHOW ALL all block — so the sensitivity is acknowledged while the by-name path is left open.
  • This is new code: the pre-PR guard was lexical and had no server-access id or setting awareness at all, so the classification decision is introduced here.
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: `server-access` blocks only `primary_conninfo`, so `SHOW archive_command` / `current_setting('restore_command')` return `pass` with a signed certificate
Severity: LOW
CWE: CWE-184

**TL;DR:** The `current_setting` arm in `judgeTree` adds `server-access` only for the literal name `primary_conninfo`, so reading any other server setting by name (`SHOW archive_command`, `SELECT current_setting('restore_command')`) gets verdict `pass` and a signed certificate.

**Impact:** A confused or compromised agent submitting SQL gets a valid pass certificate for reading the database host's own configuration — archive/restore/ssl-passphrase commands and install paths — which this same file blocks through `pg_file_settings`, `pg_show_all_file_settings()` and `SHOW ALL`, exposing any credentials embedded in those commands.

**Root cause:**
- Server settings are judged by a one-name denylist keyed on the literal in the arm, so every setting name outside that list is certified by default instead of being judged against an explicit safe set.
- The arm at `src/tools/sql-judge.js:218-221` adds a risk only when the name is not a plain literal or is exactly `primary_conninfo`; the twin `VariableShowStmt` arm at `235-236` repeats the same `all|primary_conninfo` list, so `SHOW archive_command` passes too.
- The file already treats those same values as `server-access` under other spellings — `pg_settings`, `pg_file_settings`, `pg_show_all_file_settings()` and `SHOW ALL` all block — so the sensitivity is acknowledged while the by-name path is left open.
- This is new code: the pre-PR guard was lexical and had no `server-access` id or setting awareness at all, so the classification decision is introduced here.

Location: src/tools/sql-judge.js:218-221
Context: the current_setting arm keyed on one literal name
```
// Before:
        if (name === "current_setting") {
          const setting = plain(n.args?.[0]);
          if (typeof setting !== "string" || setting.toLowerCase() === "primary_conninfo") ids.add("server-access");
        }
// After:
        if (name === "current_setting") {
          const setting = plain(n.args?.[0]);
          // A setting's value is the server's own configuration: a connection string,
          // a shell command, or a host path. pg_settings, pg_file_settings,
          // pg_show_all_file_settings and SHOW ALL are blocked for that reason; one
          // name each is the same value by another spelling.
          if (typeof setting !== "string" || SERVER_SETTING.test(setting)) ids.add("server-access");
        }
```

Location: src/tools/sql-judge.js:235-236
Context: twin arm: SHOW of one setting by name passes the same way
```
      case "VariableShowStmt": // ALL shows every setting
        if (/^(?:all|primary_conninfo)$/i.test(n.name)) ids.add("server-access");
```

How to fix:
Judge a setting name against a shared server-configuration set instead of one literal, and use that same set in both the `current_setting` and `SHOW` arms: the connection-string, command and host-path settings (`primary_conninfo`, `archive_command`, `archive_cleanup_command`, `restore_command`, `recovery_end_command`, `ssl_passphrase_command`, `data_directory`, `config_file`, `hba_file`, `ident_file`, `ssl_key_file`, `krb_server_keyfile`, socket/log directories). Keep the existing blocks for a non-literal name and for a cast, and consider failing closed on an unrecognised name, since a caller reading an application GUC can still use a known-safe allow-list. Add a test asserting `SHOW archive_command`, `SELECT current_setting('archive_command')` and `SELECT current_setting('restore_command')` block, alongside the existing `primary_conninfo` cases.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.

React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss these findings.

Comment thread src/tools/sql-judge.js
Comment on lines +143 to +149
function settingRisk(name, value) {
if (name === undefined || name === "session_replication_role") return "replication-role-bypass";
if (name === "role" || name === "session_authorization") return "privilege-change";
// Off, a backslash in an ordinary string is an escape, and later statements read otherwise than they were judged.
if (name === "standard_conforming_strings" && !/^(?:on|true|yes|1)$/.test(value ?? "")) return "unread-statement";
return null;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 LOW: SET search_path is not a risk, so a later write resolves elsewhere

TL;DR: A caller can get a signed pass, accepted by sql-cert-verify, for a two-statement submission that sets search_path to cron and writes job, which the qualified INSERT INTO cron.job blocks. settingRisk names each risky setting by hand and has no search_path entry, so nothing marks the changed name resolution. Returning a risk for it keeps that submission out of pass.

Cause, impact and fix

Cause: settingRisk is an explicit list of session settings, so a setting that relocates where a later bare table name resolves is not a risk at all. The following write is then judged on the name as written, and inCatalog sees job, not cron.job.

Impact: A write to an extension control schema's table, and the SQL it schedules there, is certified when reached through search_path and refused when spelled cron.job.

Fix: Return a risk id for search_path in settingRisk, so any changed name resolution keeps the submission away from pass, and add a test for the set_config('search_path', …) form; the suite pins SET search_path = app as a pass today.

🔵 `search_path` is not a risk in `settingRisk`, so a later unqualified write to a `cron`-schema table gets a pass certificate the qualified form is blocked from

Severity: LOW

TL;DR: settingRisk (sql-judge.js:143-149) returns no risk for search_path, so SET search_path = cron; INSERT INTO job … earns verdict pass and a verifying Ed25519 certificate, while the schema-qualified INSERT INTO cron.job … is blocked.

Impact: A caller of the guard can obtain a signed pass for a write to pg_cron's job table by setting search_path first, and for the SQL stashed there, which runs later entirely outside the guard that refuses DROP and unbounded writes.

Root cause:

  • settingRisk is a hand-written list of session settings, so one that relocates where a later statement's bare table name resolves is not a risk at all, and no id is added to the submission.
  • SET search_path = cron therefore adds no risk id and leaves its own statement non-mutating (sql-judge.js:208-214), so the write that follows is judged only on the name as written, which inCatalog reads as job rather than cron.job (sql-judge.js:183 and 201-202).
  • The catalogue does intend to stop that write: INSERT INTO cron.job … and SELECT cron.schedule(…) are both block, so the same effect is certified or refused depending only on how the table is named.
Prompt to fix with AI
This is a security vulnerability found during a code review.

Vulnerability: `search_path` is not a risk in `settingRisk`, so a later unqualified write to a `cron`-schema table gets a pass certificate the qualified form is blocked from
Severity: LOW
CWE: CWE-1287

**TL;DR:** `settingRisk` (sql-judge.js:143-149) returns no risk for `search_path`, so `SET search_path = cron; INSERT INTO job …` earns verdict `pass` and a verifying Ed25519 certificate, while the schema-qualified `INSERT INTO cron.job …` is blocked.

**Impact:** A caller of the guard can obtain a signed pass for a write to pg_cron's job table by setting `search_path` first, and for the SQL stashed there, which runs later entirely outside the guard that refuses `DROP` and unbounded writes.

**Root cause:**
- `settingRisk` is a hand-written list of session settings, so one that relocates where a later statement's bare table name resolves is not a risk at all, and no id is added to the submission.
- `SET search_path = cron` therefore adds no risk id and leaves its own statement non-mutating (sql-judge.js:208-214), so the write that follows is judged only on the name as written, which `inCatalog` reads as `job` rather than `cron.job` (sql-judge.js:183 and 201-202).
- The catalogue does intend to stop that write: `INSERT INTO cron.job …` and `SELECT cron.schedule(…)` are both `block`, so the same effect is certified or refused depending only on how the table is named.

Location: src/tools/sql-judge.js:143-149
Context: The setting that changes name resolution is not in the risk list
```
// Before:
function settingRisk(name, value) {
  if (name === undefined || name === "session_replication_role") return "replication-role-bypass";
  if (name === "role" || name === "session_authorization") return "privilege-change";
  // Off, a backslash in an ordinary string is an escape, and later statements read otherwise than they were judged.
  if (name === "standard_conforming_strings" && !/^(?:on|true|yes|1)$/.test(value ?? "")) return "unread-statement";
  return null;
}
// After:
function settingRisk(name, value) {
  if (name === undefined || name === "session_replication_role") return "replication-role-bypass";
  if (name === "role" || name === "session_authorization") return "privilege-change";
  // Off, a backslash in an ordinary string is an escape, and later statements read otherwise than they were judged.
  if (name === "standard_conforming_strings" && !/^(?:on|true|yes|1)$/.test(value ?? "")) return "unread-statement";
  // Which schema a later statement's bare table name resolves in. Judged on the
  // name as written, that write is another schema's table altogether.
  if (name === "search_path") return "unread-statement";
  return null;
}
```

Location: src/tools/sql-judge.js:201-203
Context: Where the write's table name is checked, and where the redirect slips past
```
      case "RangeVar": case "relation":
        if ((!n.schemaname || /^(?:pg_catalog|information_schema)$/.test(n.schemaname)) && SERVER_RELATION.test(n.relname)) ids.add("server-access");
        break;
```

How to fix:
Treat any change of `search_path` as a risk in `settingRisk`, the way `standard_conforming_strings` and `role` already are, and preferably under a dedicated warn-level id (`name-resolution-change`) added to `RISK_CATALOGUE` alongside a comment saying statements after it no longer mean what they read as. Any risk id is enough: `verifyCertificate` only accepts `verdict === "pass"`, so a warning alone stops the certificate from being usable. Update the `SET search_path = app` pass expectation pinned in `scripts/test-sql-guard.js` to match, and cover `SET search_path = cron; INSERT INTO job …` / the `set_config('search_path', …)` equivalent with a test that requires no certificate.

Please fix this vulnerability. If you propose a fix, make it concise and minimal.

React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss these findings.

@MikeyPetrillo
MikeyPetrillo merged commit fb1c7e0 into main Dec 4, 2026
86 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.

1 participant