Regex Timeout Guard for Untrusted Input

Run operator-supplied regular expressions with the regex module timeout, an input length cap, and explicit failure handling.

PythonSecurity Boundaries

Code

pythonsnippet
38 lines
import regex

USER_PATTERN = regex.compile(
    r"^(?P<user>[a-z0-9_]{3,32})@(?P<domain>[a-z0-9.-]{1,120})$"
)


def safe_fullmatch(
    pattern: regex.Pattern,
    text: str,
    *,
    timeout: float = 0.05,
    max_length: int = 4096,
) -> regex.Match | None:
    if len(text) > max_length:
        raise ValueError(f"input length {len(text)} exceeds {max_length}")
    try:
        return pattern.fullmatch(text, timeout=timeout)
    except TimeoutError as error:
        raise TimeoutError("pattern evaluation exceeded the time budget") from error


if __name__ == "__main__":
    match = safe_fullmatch(USER_PATTERN, "ada_lovelace@example.com")
    assert match is not None
    print(match.group("user"), match.group("domain"))

    try:
        safe_fullmatch(USER_PATTERN, "x" * 5000)
    except ValueError as error:
        print("rejected:", error)

    evil = regex.compile(r"^(a+)+$")
    try:
        safe_fullmatch(evil, "a" * 4000 + "b", timeout=0.001)
    except TimeoutError as error:
        print("timeout:", error)

How the snippet works

Count the function safe_fullmatch as the entire surface area of Regex Timeout Guard for Untrusted Input.

A ValueError and TimeoutError is raised inside an except block, so it is conditional on that failure being handled in the first place.

What to watch for

  • Dependency check: regex — not built-in, must be present in the project.
  • The guard len(text) > max_length short-circuits the flow with an early raise when its condition holds.

Applying it

Entry signature: def safe_fullmatch( pattern: regex.Pattern, text: str, *, timeout: float = 0.05, max_length: int = 4096, ) …

The demo output is labeled (rejected:, timeout:), so every printed line maps back to its originating operation.

Statements that matter

except TimeoutError as error:
    raise TimeoutError("pattern evaluation exceeded the time budget") from error
except TimeoutError as error:
    print("timeout:", error)
except ValueError as error:
    print("rejected:", error)

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `ValueError` and `TimeoutError` fires only while that failure type is already being handled, not on its own trigger.
Does this require external packages?
Yes — `regex`. Add it to your project before running the snippet.