prompty icon indicating copy to clipboard operation
prompty copied to clipboard

ReDoS in tool-call argument parsing (Python agent loop)

Open cr-sbarbouche opened this issue 1 month ago • 0 comments

Bug description

_resilient_json_parse in runtime/python/prompty/prompty/core/tool_dispatch.py strips markdown fences from tool-call arguments with this regex (copied from spec §9.8):

^\s*```(?:json)?\s*\n?(.*?)\n?\s*```\s*$

\s*, \n? and the lazy .*? can all match the same whitespace, so when the string starts with a fence but never closes it, the engine tries every way of splitting the whitespace between them. Runtime grows cubically with the length of the input.

The arguments string is whatever the model emitted, so anything that can steer the model (a prompt injection in a retrieved document or a tool result) can make the agent loop hang inside dispatch_tool / dispatch_tool_async.

Steps to reproduce

import time
from prompty.core.tool_dispatch import _resilient_json_parse

for n in (200, 400, 800, 1600):
    s = "```json" + " " * n + "x"
    t = time.perf_counter()
    _resilient_json_parse(s)
    print(n, round((time.perf_counter() - t) * 1000, 1), "ms")
n spaces after the fence newlines after the fence
200 5 ms 19 ms
400 35 ms 136 ms
800 260 ms 1,024 ms
1600 1,994 ms 7,963 ms

Doubling the input is roughly 8x the time, so a 10k character argument string takes minutes at that rate.

Expected behavior

An argument string that is not valid JSON comes back as None (and the dispatcher returns its usual "all parse strategies failed" error) in time proportional to its length.

Actual behavior

The call blocks a CPU core for as long as the regex takes, and the agent loop is stuck with it. Sync and async dispatch are both affected since they share the parser.

Your environment

  • prompty Python runtime 2.0.3 (main at 007abf34), CPython 3.12.9, macOS

Other runtimes

The same pattern is copied into the other runtimes, since it comes from the spec:

Runtime Location Status
Python core/tool_dispatch.py:282 Vulnerable, fix coming in a PR for this issue
TypeScript core/tool-dispatch.ts:259 Vulnerable, same growth in Node (1.5 s at n=1600)
Java ToolDispatch.java:37 Same pattern, not measured
C# ToolDispatch.cs:263 Same pattern, not measured
Rust tool_dispatch.rs:209 Not affected, the regex crate has no backtracking

I'm only fixing Python here. The spec regex in §9.8 probably needs a note as well, since anyone implementing it literally will end up with the same bug.

Proposed fix

Drop the regex for this step. Strip the string, check that it starts and ends with a fence, drop an optional json tag, and hand the middle to json.loads, which already ignores surrounding whitespace. Same results as the regex, linear time.

cr-sbarbouche avatar Oct 17 '26 14:10 cr-sbarbouche