Repository navigation
fix(query): add pre-parse nesting-depth guard against transformer DoS - #3331
Conversation
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]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 57 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
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]>
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
exprrule (polylogue/archive/query/expression.py) is recursive ("(" expr ")"), and Lark's stockTransformer.transform()walk used by_BooleanQueryTransformerhas no depth guard of its own. A ~245-byte payload of n=250 nested parens drives that walk into a PythonRecursionError.This was already contained (a clean one-line CLI error via
machine_main.py's broadPolylogueErrorhandler — 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
_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._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-levelsessions where, pipeline stages via_session_source_predicate, and<unit> whereterminal sources via_parse_plain_unit_source_expression). Verified each of these three call sites subclasses through this one function, so no bypass exists today._MAX_QUERY_NESTING_DEPTH = 64ceiling: comfortably above any real hand- or tool-authored query, well below Python's default recursion limit (1000).QueryDepthExceededError(ExpressionCompileError)— a purpose-built typed error, not the generic unexpected-error fallback. Because it subclassesExpressionCompileError, the existing CLI (PolylogueErrorhandler inmachine_main.py), MCP (server_support.py), and HTTP (daemon/http.py) error paths already catch it correctly — no new plumbing needed._is_boolean_expressionroutes any expression starting with((or containingexists <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 inTestQueryNestingDepthGuard:RecursionError) with the typedQueryDepthExceededError, assertingtype(...) is QueryDepthExceededError(not the baseExpressionCompileError, not a bareRecursionError)sessions where ... | count) and unit-source (messages where ...) entry points too, not just the top-level pathdevtools verify --quick→ exit_code 0 (ruff format, ruff check, mypy --strict, render all --check) — also re-ran automatically via the pre-push hook.RecursionError; now rejected in ~0.00023s.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