from __future__ import annotations import re import resource import shlex import shutil import subprocess MAX_INPUT_BYTES = 1_000_000 MAX_COMMAND_CHARS = 4_000 FILE_COMMAND_PATTERN = re.compile(r"(?:^|[;{\s'\"])[rRwWe!|](?:\s|$)") SHELL_PATTERN = re.compile(r"[`|]") class UnsafeCommandError(ValueError): pass def check_command(command: str) -> list[str]: if not command.strip(): raise UnsafeCommandError("The sed command is empty.") if len(command) > MAX_COMMAND_CHARS: raise UnsafeCommandError("The sed command is too long.") try: arguments = shlex.split(command) except ValueError as error: raise UnsafeCommandError(f"Cannot parse sed command: {error}") from error if not arguments or arguments[0] != "sed": raise UnsafeCommandError("Only sed commands are allowed.") if SHELL_PATTERN.search(command): raise UnsafeCommandError("Pipes and shell control operators are not allowed.") if FILE_COMMAND_PATTERN.search(command): raise UnsafeCommandError("File and process commands are not allowed.") index = 1 scripts = 0 while index < len(arguments): argument = arguments[index] if argument in {"-n", "--quiet", "--silent"}: index += 1 elif argument in {"-e", "--expression"}: if index + 1 >= len(arguments): raise UnsafeCommandError("Missing sed expression.") scripts += 1 index += 2 elif argument.startswith("-"): raise UnsafeCommandError(f"Unsupported sed option: {argument}") else: scripts += 1 index += 1 if scripts != 1: raise UnsafeCommandError("Expected exactly one sed expression and no filenames.") return arguments def limit_resources() -> None: resource.setrlimit(resource.RLIMIT_CPU, (2, 2)) resource.setrlimit(resource.RLIMIT_AS, (256_000_000, 256_000_000)) resource.setrlimit(resource.RLIMIT_FSIZE, (1_000_000, 1_000_000)) resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) resource.setrlimit(resource.RLIMIT_NOFILE, (16, 16)) def run_sed(command: str, input_text: str, timeout: float = 3.0) -> str: arguments = check_command(command) if len(input_text.encode("utf-8")) > MAX_INPUT_BYTES: raise ValueError("Input text exceeds the 1 MB limit.") executable = shutil.which("sed") if executable is None: raise RuntimeError("No sed executable is available on PATH.") result = subprocess.run( [executable, *arguments[1:]], input=input_text, text=True, capture_output=True, timeout=timeout, env={"LC_ALL": "C", "PATH": "/usr/bin:/bin"}, preexec_fn=limit_resources, start_new_session=True, check=False, ) if result.returncode != 0: raise ValueError(result.stderr.strip() or f"sed exited with status {result.returncode}") return result.stdout