Skip to content

The agent that grows with you

fix(agent): anchor the Telegram token regex to a digit-run start (ReDoS)

Israel Lot70f79c8cde3c
diff --git a/agent/redact.py b/agent/redact.py
index 76f8da9ff5d..cab7396ea71 100644
--- a/agent/redact.py
+++ b/agent/redact.py
@@ -499,8 +499,12 @@ _AUTH_HEADER_RE = re.compile(r"((?:Proxy-)?Authorization:\s*)([A-Za-z][\w.+-]*\s
_SECRET_HEADER_NAMES = r"(?:x-api-key|x-goog-api-key|api-key|apikey|x-api-token|x-auth-token|x-access-token)"
_SECRET_HEADER_RE = re.compile(rf"({_SECRET_HEADER_NAMES}\s*:\s*)(\S+)", re.IGNORECASE)
-# Telegram bot tokens: [bot]<digits>:<token>, token >= 30 chars.
-_TELEGRAM_RE = re.compile(r"(bot)?(\d{8,}):([-A-Za-z0-9_]{30,})")
+# Telegram bot tokens: [bot]<digits>:<token>, token >= 30 chars. The lookbehind
+# anchors the id at the start of its digit run: without it, a long run of digits
+# with no ":<token>" after it (a Unity/YAML ``_typelessdata`` blob in a 2 MB PR
+# diff, hex/decimal dumps) retried the greedy ``\d{8,}`` from every digit —
+# quadratic, one core at 100% for hours while holding the GIL.
+_TELEGRAM_RE = re.compile(r"(?<!\d)(bot)?(\d{8,}):([-A-Za-z0-9_]{30,})")
_PRIVATE_KEY_RE = re.compile(r"-----BEGIN[A-Z ]*PRIVATE KEY-----[\s\S]*?-----END[A-Z ]*PRIVATE KEY-----")
diff --git a/tests/agent/test_redact.py b/tests/agent/test_redact.py
index 9427994d1b4..00b66429d33 100644
--- a/tests/agent/test_redact.py
+++ b/tests/agent/test_redact.py
@@ -529,6 +529,31 @@ class TestTelegramTokens:
result = redact_sensitive_text(text)
assert "ABCDEfghij" not in result
+ def test_long_digit_run_completes_fast(self):
+ """A long digit run with no ``:<token>`` after it must stay linear.
+
+ Without the run-start lookbehind, ``\\d{8,}`` retried from every digit
+ of the run (quadratic while holding the GIL): a 2 MB Unity asset diff
+ with a ``_typelessdata: 000...`` line pinned a core for hours inside
+ terminal-output redaction. The colon is what routes the text through
+ the Telegram pass.
+ """
+ import time
+
+ text = "_typelessdata: " + "0" * 300_000 + "\n"
+ t0 = time.perf_counter()
+ assert redact_sensitive_text(text, force=True) == text
+ assert time.perf_counter() - t0 < 2.0
+
+ def test_token_after_long_digit_run_still_redacted(self):
+ # The lookbehind must not change matching: a real token whose id
+ # starts its own digit run is still masked, digits embedded in a
+ # longer run are not an id.
+ text = "0" * 1000 + " bot123456789:ABCDEfghij-KLMNopqrst_UVWXyz12345"
+ result = redact_sensitive_text(text, force=True)
+ assert "ABCDEfghij" not in result
+ assert "123456789:***" in result
+
class TestPassthrough:
def test_empty_string(self):