Skip to content

fix(query): add pre-parse nesting-depth guard against transformer DoS - #3331

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/query-dsl-depth-guard
Jul 27, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/query-dsl-depth-guard

Conversation

@Sinity

@Sinity Sinity commented Jul 27, 2026

Copy link
Copy Markdown
Owner

Summary

Adds a cheap, quote-aware preflight scan that rejects adversarially deep parenthesis nesting in query-DSL Boolean expressions before the Lark parse/transform is attempted, closing a resource-amplification vector on the shared daemon/MCP/HTTP query surface.

Problem

The Boolean query grammar's expr rule (polylogue/archive/query/expression.py) is recursive ("(" expr ")"), and Lark's stock Transformer.transform() walk used by _BooleanQueryTransformer has no depth guard of its own. A ~245-byte payload of n=250 nested parens drives that walk into a Python RecursionError.

This was already contained (a clean one-line CLI error via machine_main.py's broad PolylogueError handler — no traceback, no process corruption across repeated bomb/good-query cycles), but it surfaced as the generic unexpected-error fallback rather than a purpose-built diagnostic, and cost a repeatable ~0.83s CPU per payload — a cheap, trivially-discoverable amplification vector for anyone hitting the shared query surface with adversarial nesting.

Solution

  • Added _expression_nesting_depth: a linear, single-pass scan over the raw expression text that tracks max parenthesis nesting depth, respecting quoted string literals and backslash escapes (mirrors the existing quote/escape handling already used by _split_pipeline_stages) so parens inside ~"note (see appendix)"-style quoted text are not counted as structural nesting.
  • Added _check_query_nesting_depth, called at the top of _transform_boolean_predicate — the single choke point through which every Boolean-grammar entry path reaches the Lark parser (top-level sessions where, pipeline stages via _session_source_predicate, and <unit> where terminal sources via _parse_plain_unit_source_expression). Verified each of these three call sites subclasses through this one function, so no bypass exists today.
  • New _MAX_QUERY_NESTING_DEPTH = 64 ceiling: comfortably above any real hand- or tool-authored query, well below Python's default recursion limit (1000).
  • New QueryDepthExceededError(ExpressionCompileError) — a purpose-built typed error, not the generic unexpected-error fallback. Because it subclasses ExpressionCompileError, the existing CLI (PolylogueError handler in machine_main.py), MCP (server_support.py), and HTTP (daemon/http.py) error paths already catch it correctly — no new plumbing needed.
  • The compact (non-Boolean) query grammar has no recursive paren rule today, so it isn't independently vulnerable, but _is_boolean_expression routes any expression starting with ( (or containing exists <unit>(, seq(, etc.) into the guarded Boolean path regardless.

Verification

  • devtools test tests/unit/cli/test_query_expression.py → 430 passed, 1 skipped. 6 new tests in TestQueryNestingDepthGuard:
    • reasonable nesting (ceiling − 1) and nesting exactly at the ceiling still parse (no false positive)
    • parentheses inside a quoted FTS phrase don't count toward depth
    • the n=250 bomb payload from the bug report is rejected in well under 0.1s (previously ~0.83s to RecursionError) with the typed QueryDepthExceededError, asserting type(...) is QueryDepthExceededError (not the base ExpressionCompileError, not a bare RecursionError)
    • the guard fires from the pipeline-stage (sessions where ... | count) and unit-source (messages where ...) entry points too, not just the top-level path
  • devtools verify --quick → exit_code 0 (ruff format, ruff check, mypy --strict, render all --check) — also re-ran automatically via the pre-push hook.
  • Manual timing: adversarial n=250 nested-paren payload previously ~0.83s CPU to RecursionError; now rejected in ~0.00023s.
  • Not run: devtools verify --seed-testmon (full-suite testmon seed) — this is optional first-time infra for the testmon inner loop, not a required gate; the focused file run + quick gate above are the project's required local verification for a change of this shape.

Ref polylogue-u0dm

Problem: the Boolean query grammar's `expr` rule
(polylogue/archive/query/expression.py) is recursive (`"(" expr ")"`), and
Lark's stock `Transformer.transform()` walk used by `_BooleanQueryTransformer`
has no depth guard of its own. A ~245-byte payload of n=250 nested parens
drives that walk into a Python RecursionError. This was contained today (a
clean one-line CLI error via machine_main.py's broad PolylogueError handler,
no traceback, no process corruption across repeated cycles) but surfaced as
the generic unexpected-error fallback rather than a purpose-built diagnostic,
and cost ~0.83s CPU per payload -- a cheap, repeatable resource-amplification
vector on the shared daemon/MCP/HTTP query surface.

What changed: added `_expression_nesting_depth` (linear, quote/escape-aware
scan mirroring `_split_pipeline_stages`'s existing depth tracking) and
`_check_query_nesting_depth`, called at the top of `_transform_boolean_predicate`
-- the single choke point through which every Boolean-grammar entry path
(top-level `sessions where`, pipeline stages, `<unit> where` terminal
sources) reaches the Lark parser. Expressions nesting parentheses past
`_MAX_QUERY_NESTING_DEPTH` (64, comfortably above any real query and well
below Python's default recursion limit) are rejected with a new
`QueryDepthExceededError(ExpressionCompileError)` before the parse/transform
is attempted, so a rejected expression costs a bounded scan instead of a
partial parse. Because it subclasses `ExpressionCompileError`, the existing
CLI (`PolylogueError` handler in machine_main.py), MCP
(`server_support.py`), and HTTP (`daemon/http.py`) error paths already catch
it correctly with no new plumbing.

Verification:
- devtools test tests/unit/cli/test_query_expression.py -> 430 passed, 1
  skipped (6 new tests: reasonable/at-ceiling nesting still parses, quoted
  parens don't count toward depth, the n=250 bomb payload is rejected in
  <0.1s with the typed QueryDepthExceededError and not the generic fallback,
  guard fires from pipeline-stage and unit-source entry points too).
- devtools verify --quick -> exit_code 0 (ruff format, ruff check,
  mypy --strict, render all --check).
- Manual timing: adversarial n=250 payload previously ~0.83s to
  RecursionError, now rejected in ~0.00023s.

Not run: devtools verify --seed-testmon (full-suite testmon seed) --
optional infra, not a required gate for this change; the two commands above
are the project's required local verification for a focused fix.

Ref polylogue-u0dm

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 57 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4e740aa9-f7cf-4a11-96fc-65e10daa90cd

📥 Commits

Reviewing files that changed from the base of the PR and between 7c45532 and 37fa964.

📒 Files selected for processing (2)
  • polylogue/archive/query/expression.py
  • tests/unit/cli/test_query_expression.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/query-dsl-depth-guard

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit bcdf938 into master Jul 27, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/query-dsl-depth-guard branch July 27, 2026 15:14
Sinity added a commit that referenced this pull request Jul 27, 2026
Fast-forwarding master after several parallel PRs merged (#3326-#3331)
triggered the documented post-merge reimport hazard: the beads-guard hook
correctly detected and restored 10 issues (yyvg.7, z9gh.7, z9gh.3, z9gh,
ihc8, t93b, n2f4, r7p6, u0dm, yyvg.6) whose live notes/status/priority were
newer than what the merged .beads/*.jsonl snapshot on disk reflected.

Co-Authored-By: Claude <[email protected]>
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