File size: 3,138 Bytes
6b693de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from __future__ import annotations

import re
import resource
import shlex
import shutil
import subprocess
from pathlib import Path

MAX_INPUT_BYTES = 1_000_000
MAX_COMMAND_CHARS = 4_000
ENV_PATTERN = re.compile(r"\$ENV\b|(?<![A-Za-z0-9_.])env(?![A-Za-z0-9_])")
MODULE_PATTERN = re.compile(r"(?<![A-Za-z0-9_.])(?:import|include|load|modulemeta)(?![A-Za-z0-9_])")
INPUT_PATTERN = re.compile(r"(?<![A-Za-z0-9_.])inputs?(?![A-Za-z0-9_])")


class UnsafeCommandError(ValueError):
    pass


def check_command(command: str) -> list[str]:
    if not command.strip():
        raise UnsafeCommandError("The jq command is empty.")
    if len(command) > MAX_COMMAND_CHARS:
        raise UnsafeCommandError("The jq command is too long.")
    try:
        arguments = shlex.split(command)
    except ValueError as error:
        raise UnsafeCommandError(f"Cannot parse jq command: {error}") from error
    if not arguments or arguments[0] != "jq":
        raise UnsafeCommandError("Only jq commands are allowed.")
    if ENV_PATTERN.search(command) or MODULE_PATTERN.search(command) or INPUT_PATTERN.search(command):
        raise UnsafeCommandError("Environment, module, and additional-input access are not allowed.")
    index = 1
    options = []
    while index < len(arguments) and arguments[index] in {"-c", "-r", "-s"}:
        options.append(arguments[index])
        index += 1
    if len(options) > 1:
        raise UnsafeCommandError("Use at most one jq option.")
    if index != len(arguments) - 1:
        raise UnsafeCommandError("Expected exactly one jq filter and no filenames or other options.")
    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_jq(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("jq")
    if executable is None:
        bundled = Path(__file__).parent / "bin" / "jq"
        if bundled.is_file():
            runnable = Path("/tmp/jqweave-jq")
            if not runnable.exists():
                shutil.copyfile(bundled, runnable)
            runnable.chmod(0o755)
            executable = str(runnable)
    if executable is None:
        raise RuntimeError("No jq executable is available on PATH or in the bundled runtime.")
    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"jq exited with status {result.returncode}")
    return result.stdout