Repository navigation
🔒 Fix SQL Injection in PostgresStore - #24015
undivisible wants to merge 1 commit into
Conversation
This commit addresses potential SQL injection vulnerabilities in `backend/testing/pipeline_sim/postgres_store.py` and `backend/database/jobstore/postgres_store.py`. Specifically, direct string formatting (`f'DELETE FROM {table} ...'`) of the `table` variable directly into SQL queries has been replaced with the secure `psycopg.sql.SQL` string composition with `psycopg.sql.Identifier(table)` as arguments.
By escaping the table identifiers securely, this change effectively eliminates the risk of an attacker supplying a malformed string representing the target table and thereby manipulating the query.
Fixes include:
- `backend/testing/pipeline_sim/postgres_store.py`: `PgRows._all`, `PgSimStore.delete`
- `backend/database/jobstore/postgres_store.py`: `PostgresStore.read_doc`, `PostgresStore.write_doc`, `PostgresStore.delete_doc`
All related unit tests run locally (via `tests/unit/test_pipeline_sim*.py`, `tests/unit/test_jobstore_dual_store.py`) continue to pass.
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
Git-on-my-level
left a comment
There was a problem hiding this comment.
Verdict: the hardening direction is right and the SQL composition itself is correct — but this needs work before merge, because both red checks (Formatting, Backend unit suite) are caused by the diff itself.
What I verified on this head:
- backend/database/jobstore/postgres_store.py — read_doc/write_doc/delete_doc now build the typed-table queries with psycopg.sql.SQL(...).format(table=psycopg.sql.Identifier(table)) while namespace/key stay bound parameters. Correct psycopg 3 composition; result shapes and binding unchanged.
- backend/testing/pipeline_sim/postgres_store.py — _all() reproduces the original UNION ALL shape (Literal(t) for the name column, Identifier(t) for FROM) and the parameter count still matches (namespace * (len(_TYPED)+1)); delete() uses the same correct pattern. No f-string SQL remains in this file.
- To be precise about severity: this was not exploitable today — the formatted branch only ran when table was exactly one of _TYPED = {'jobs', 'results', 'control'}, and every other path already binds the table name as a parameter. This is defense-in-depth (your description says so; the title slightly oversells it). Still worth landing once green.
- Encouraging: Backend Hermetic Merge Gate, both stack gauntlets, and Hermetic Backend E2E pass on this head, so the composed queries do execute correctly against real Postgres.
Blocking issues (both introduced by this diff):
- Formatting fails: the formatter would reformat both changed files. Please run the repo formatter over backend/database/jobstore/postgres_store.py and backend/testing/pipeline_sim/postgres_store.py.
- Backend unit shard 1/6 fails with 9 pyright errors, all on the new lines of backend/database/jobstore/postgres_store.py:
- lines 292/307/326: "_psycopg" is private and used outside of the module in which it is declared (reportPrivateUsage)
- lines 294/295/309/312/328/329: "sql" is not a known attribute of module "psycopg" (reportAttributeAccessIssue) — psycopg's types sit outside the pyright lockfile, which is why this file's existing code uses the lazy-import-with-ignore convention (see jsonb() near the top).
A clean fix would be for database/jobstore/connection.py to expose a small public helper returning the module (or psycopg.sql) instead of importing the private _psycopg three times here, plus the appropriate pyright ignore comments for the sql attribute access.
Non-blocking: purge_namespace() at the bottom of backend/database/jobstore/postgres_store.py still formats f'DELETE FROM {table}'. The tuple it iterates is hardcoded ('jobs', 'results', 'control', 'docs', 'outbox'), so it is safe — but it is the same class of pattern; converting it (or leaving a one-line comment) would make the file consistent.
Security: strictly reduces injection risk; identifier quoting is client-side, so no new query plans or round-trips.
Blast radius: batch job-store CRUD (jobs/results/control) and the pipeline simulator; the passing hermetic gates cover exactly those paths.
USER IMPACT: none — this hardens how database queries are built internally; no user-visible behavior changes.
What I'd still want as a reviewer: green Formatting and Backend unit suite on a new head, your call on purge_namespace consistency, and optionally a small test asserting a table name outside the allowlist cannot alter the statement (Identifier quoting turns it into a missing-relation error).
This changes SQL construction in the production job store, so a maintainer should sign off on the final import/typing pattern before merge even once CI is green.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
## Summary Canonical re-cut of #24042 on current `main` (`72d5dfdc671a2ccb0ffbb983785e995d8bdaa507`). Head: `6a634c9706cd4f84d20cc492be8662f8ef5dc1b4`. This replaces f-string interpolation at all 13 assigned composition sites with `psycopg.sql` identifiers, literals, and typed literal SQL fragments. Runtime values remain query parameters. A single public `database.jobstore.connection.sql()` accessor preserves the lazy-postgres-driver invariant, and `_fenced_update` now types its SQL fragments as `LiteralString`. This is defense in depth, not a claim of a live exploit: the existing call paths already gate table/column choices through fixed allowlists, validated priorities/pools, or internal constants, as the reviewers of the overlapping PRs noted. Failure-Class: none ## Sites fixed - `backend/database/jobstore/postgres_store.py:261` — `due()`: quote the selected due column in both predicate and ordering. - `backend/database/jobstore/postgres_store.py:404` — `control_candidates()`: quote every priority/pool-derived column reference. - `backend/database/jobstore/postgres_store.py:508` — typed `read_doc()`: compose the table identifier and lock suffix. - `backend/database/jobstore/postgres_store.py:541` — `write_doc()`: quote the typed table identifier. - `backend/database/jobstore/postgres_store.py:556` — `delete_doc()`: quote the typed table identifier. - `backend/database/jobstore/postgres_store.py:569` — `service_frontier_in()`: quote the priority-derived column. - `backend/database/jobstore/postgres_store.py:593` — `purge_namespace()`: quote every cleanup table identifier. - `backend/database/jobstore/backfill.py:60` — `postgres_keys()`: quote the typed table identifier. - `backend/database/jobstore/outbox_pg.py:169` — `claim()`: compose the fixed `RETURNING` column list. - `backend/database/jobstore/outbox_pg.py:202` — `claim_key()`: compose the fixed `RETURNING` column list. - `backend/database/jobstore/outbox_pg.py:255` — `_fenced_update()`: compose only `LiteralString` set/guard fragments; keep claim data bound. - `backend/testing/pipeline_sim/postgres_store.py:35` — `PgRows._all()`: compose each typed table as `Identifier` and its projected name as `Literal` across the `UNION ALL`. - `backend/testing/pipeline_sim/postgres_store.py:210` — simulator `delete()`: quote the typed table identifier. `backend/database/jobstore/connection.py:28` adds the single lazy `psycopg.sql` accessor. The two simulator hunks are folded in from #24015. None of #24042's unrelated `commit_message.txt`, `test_sql.py`, or `.agent-brief/firestore-index-guard/tests.txt` files are carried over. ## Tests New hermetic behavioral coverage exercises every site above with hostile identifiers/values, verifies parameter tuples never enter rendered statement text, checks the outbox produces real `psycopg.sql.Composable` statements, and imports every changed module in clean subprocesses where `psycopg` is explicitly unavailable. Focused pytest runs (one process per file): | Test file | Result | | --- | ---: | | `test_jobstore_sql_composition.py` | 18 passed | | `test_jobstore_backfill.py` | 11 passed | | `test_jobstore_dual_store.py` | 68 passed | | `test_jobstore_migrations.py` | 7 passed | | `test_jobstore_postgres_locking.py` | 10 passed | | `test_jobstore_projection_mirror.py` | 8 passed | | `test_jobstore_protocol_parity.py` | 69 passed | | `test_jobstore_shadow_seams.py` | 23 passed | | `test_jobstore_codec.py` | 2 passed | | `test_batch_pipeline_lock_jobstore.py` | 2 passed | Total: **218 passed**. No full-suite or live-service run was used. - `bash backend/scripts/typecheck.sh`: **0 errors**. - `scripts/backend-python-format --check ...`: **7 files unchanged**. ## Supersedes and follow-up - Supersedes the original #24042 and overlapping #24015, #24023, and #24037; #24015's unique simulator coverage is retained here. - #24037's module-level psycopg import and #24015's private `_psycopg()` access are both avoided by the public lazy accessor. - #23806 must rebase after this merges and obtain fresh exact-head review; its recovery work is otherwise orthogonal. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/25116?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/25116?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25116&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
🎯 What: This PR fixes SQL injection vulnerabilities related to dynamic table names in the pipeline simulator's data store and the primary backend job store.
⚠️ Risk: Although the inputs are heavily gated/hardcoded internally in the current usages (
_TYPED = ('jobs', 'results', 'control')), directly formatting a Python string to serve as a table identifier in SQL opens the door for SQL Injection attacks if those input pathways are ever broadened or misconfigured in the future.🛡️ Solution: The queries in
backend/testing/pipeline_sim/postgres_store.pyandbackend/database/jobstore/postgres_store.pyhave been refactored to compose SQL via thepsycopg.sqlmodule (psycopg.sql.SQL+psycopg.sql.Identifier). This allowspsycopgto correctly and securely escape the dynamic identifiers.Because
psycopgis imported lazily in this codebase, the patch callsdatabase.jobstore.connection._psycopg()inside the respective methods to gain access topsycopg.sql.PR created automatically by Jules for task 14035200656394186844 started by @undivisible