Skip to content

🔒 Fix potential SQL injection in jobstore backfill postgres_keys - #24023

Open
undivisible wants to merge 2 commits into
mainfrom
fix-backfill-sql-injection-7165385646914771110
Open

undivisible wants to merge 2 commits into
mainfrom
fix-backfill-sql-injection-7165385646914771110

Conversation

@undivisible

@undivisible undivisible commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

🎯 What: Fixed a potential SQL injection vulnerability in backend/database/jobstore/backfill.py where a table name was dynamically inserted into a raw SQL query string using f-strings (f'SELECT key FROM {table} ...').

⚠️ Risk: If a malicious or unexpected value were somehow passed to the table argument in postgres_keys, it could allow arbitrary SQL execution. While table might currently be constrained by the _TYPED allowlist earlier in the code block, using unescaped f-strings for SQL construction is an insecure pattern susceptible to injection if logic changes or constraints fail.

🛡️ Solution: Updated the unparameterized query inside postgres_keys to safely escape the table name by utilizing the psycopg.sql module (sql.SQL and sql.Identifier). This acts as robust defense-in-depth and eliminates the insecure pattern.

Failure-Class: none


PR created automatically by Jules for task 7165385646914771110 started by @undivisible

View guided diff Turn on auto-fix

Replaced the dynamic string construction of the SQL table name parameter in
`postgres_keys` within `backend/database/jobstore/backfill.py`. The f-string
logic has been updated to use `psycopg.sql.SQL` and `sql.Identifier` to safely
and correctly format the table identifier into the query.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 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 @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

Replaced the dynamic string construction of the SQL table name parameter in
`postgres_keys` within `backend/database/jobstore/backfill.py`. The f-string
logic has been updated to use `psycopg.sql.SQL` and `sql.Identifier` to safely
and correctly format the table identifier into the query.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production change here is correct and nicely scoped; two non-blocking items before merge (a green CI run and one unrelated file).

backend/database/jobstore/backfill.py — postgres_keys(): the _TYPED branch now composes the table name via psycopg sql.SQL(...).format(sql.Identifier(table)). I verified the rendered statement is SELECT key FROM "jobs" WHERE namespace = %s — identifier safely quoted, namespace still a bound parameter, and the docs branch remains fully parameterized. psycopg (v3) is already the driver used across database/jobstore/ (connection.py, postgres_store.py, dual_store.py), so the new local import is consistent. Since table must be a literal member of _TYPED = {"jobs", "results", "control"}, this is defense-in-depth rather than an exploitable fix — the PR description frames that honestly. Nit: consider hoisting from psycopg import sql to module scope; the quote-style/reformat churn slightly inflates the diff but is harmless.

Related follow-up (not blocking): the same pattern still exists in backend/database/jobstore/postgres_store.py — read_doc/write_doc/delete_doc interpolate {table} behind the same _TYPED gate (e.g. SELECT doc FROM {table} around line 292). A consistency pass there would close the whole family.

.agent-brief/firestore-index-guard/tests.txt — this new file lists seven backend/tests/unit/test_firestore_*.py files (all exist) but is unrelated to this fix and the directory does not exist on main. It reads like a stray agent-session artifact; please drop it from this PR or note what it's for.

CI: Backend unit suite (shard 3/6) failed on test_episode_boundary_evidence.py::test_evidence_is_idempotent_and_late_retry_cannot_reopen, ::test_no_split_inside_a_signal_but_end_and_quiet_are_hard, and test_daily_summary_job_resilience.py — none reachable from this diff. I reproduced those tests locally on this head and again with the change reverted: identical failure set both ways, and main's unit runs are green today, so the red run is not caused by this change. Please re-run the failed jobs (or rebase) so this head carries a green unit run before merge.

Security: net hardening, no new surface. Performance: none — same single query per call.
USER IMPACT: none — internal hardening of a backfill/migration utility; no observable behavior change for users.

Still wanted before merge: (1) a green Backend unit suite run on this head, (2) drop or justify .agent-brief/firestore-index-guard/tests.txt, (3) optional follow-up applying the same sql.Identifier treatment in postgres_store.py. Because this touches the Postgres jobstore data-migration layer, maintainer sign-off is needed before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution security-review Touches auth, provider routing, secrets, or security-sensitive surfaces needs-maintainer-review Needs a human maintainer to sign off before merge labels Oct 29, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

The core fix is correct and verified; one unrelated file should be dropped, and the red Backend unit suite is pre-existing main flakiness, not from this change.

  • backend/database/jobstore/backfill.py — postgres_keys(): the table in _TYPED branch now composes the query with psycopg's sql.SQL("SELECT key FROM {} WHERE namespace = %s").format(sql.Identifier(table)) and keeps namespace as a bound parameter — the correct way to interpolate an identifier, behavior-preserving for the three allowlisted tables (jobs/results/control). Fair severity note: this is defense-in-depth rather than an exploitable fix today, since the only caller (backfill_table) validates table in MIRRORED_TABLES before the call — exactly as the PR description frames it. Good change.
  • The rest of the backfill.py diff (single→double quote churn on the ValueError / _pages / log-warning lines, the import re-wrap, and the backfill() signature reformat) is formatter output; harmless, just inflates the diff slightly.
  • .agent-brief/firestore-index-guard/tests.txt — unrelated to this fix. .agent-brief/ on main contains only report notes and has no firestore-index-guard/ directory; this looks like a stray agent-workspace artifact. Please drop it from the PR.
  • CI: the Backend unit suite failures (test_daily_summary_job_resilience.py::test_generated_log_line_feeds_the_recap_log_metric, and the two test_episode_boundary_evidence.py failures) do not exercise this module — the two episode-boundary failures reproduce identically on main (run 40915185789), so this is pre-existing main flakiness, not a regression. backend/tests/unit/test_jobstore_backfill.py (which covers postgres_keys) is green in this run.

Security: strictly strengthens SQL construction; blast radius is the offline A6 backfill census path only. Performance/cost: unchanged — same single query per census. Related follow-up (not blocking): the same f-string {table} pattern this PR fixes still exists in backend/database/jobstore/postgres_store.py behind the same _TYPED gate (SELECT/INSERT/DELETE around lines 292, 303, 316, 347); a consistency pass there would close the whole family.

USER IMPACT: none — internal hardening of an offline backfill tool; users will notice no difference.

What I'd still want as a reviewer:

  1. Drop the unrelated .agent-brief/firestore-index-guard/tests.txt file.
  2. A small assertion in backend/tests/unit/test_jobstore_backfill.py that postgres_keys routes the table name through sql.Identifier (e.g., a fake conn capturing the composed query) so the safe pattern can't silently regress.
  3. Merge only after maintainer sign-off (this is a security-labeled change to SQL construction) and a green unit-suite run once main's flakiness is triaged.

by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
## 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. -->

This branch has not been deployed

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

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants