Skip to content

The platform for continuously improving AI agents.

16.5 KB
Raw Blame
"""A persistent Python namespace, one cell at a time, and the limits untrusted code runs
under. Both workspace providers run cells through ``run``, so this file imports the
standard library only: the native sandbox serves it behind a Unix socket, and a Modal
sandbox, which has no server, reaches it with one ``cell`` process for each cell.

    kernel.py serve <socket> [limits-json]     hold the namespace and answer requests
    kernel.py cell <work> <data> <limits-json> run the request on stdin in the conversation's
                                               kernel, starting one when it has none
    kernel.py stop <work>                      end the conversation's kernel
    kernel.py copy <path> <copy> <max-bytes>   copy a regular file the kernel wrote, never
                                               a link's target, refusing more than max-bytes
"""

import ast
import contextlib
import ctypes
import fcntl
import io
import json
import linecache
import os
import resource
import signal
import socket
import stat
import struct
import subprocess
import sys
import time
import traceback

OUTPUT_CHARS = 60_000
# What a kernel may answer: its bounded output and error, as JSON. The kernel runs the
# tenant's code, so its caller holds it to this size itself.
MAX_REPLY_BYTES = 1024**2
REPLY_GRACE_SECONDS = 15
START_SECONDS = 20
SOCKET = ".kernel.sock"
# Uids of conversation kernels in a sandbox that has no server to hand them out.
FIRST_UID = 20000

# Landlock file rights by ABI version: each version adds rights after the 13 of the first.
_FS_RIGHTS = {1: 13, 2: 14, 3: 15, 4: 15, 5: 16}
_EXECUTE, _WRITE_FILE, _READ_FILE, _READ_DIR = 1, 2, 4, 8
_ON_FILES = _EXECUTE | _WRITE_FILE | _READ_FILE | (1 << 14) | (1 << 15)
_READ = _EXECUTE | _READ_FILE | _READ_DIR
_SYSTEM = ("/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc", "/opt")
_SOCKET_CALL = {"x86_64": (0xC000003E, 41), "aarch64": (0xC00000B7, 198)}


def _libc():
    libc = ctypes.CDLL(None, use_errno=True)
    libc.syscall.restype = ctypes.c_long
    return libc


def landlock_abi() -> int:
    """The Landlock version this host enforces; 0 when it has none. Without it the uid of a
    run is all that keeps it from the files and process list of the others."""
    if sys.platform != "linux":
        return 0
    return max(0, _libc().syscall(444, None, ctypes.c_size_t(0), 1))


def _landlock(libc, work: str, readable: tuple[str, ...]) -> None:
    """Limit this process and its children to the files named here, deny TCP and keep its
    signals and abstract sockets to itself, as far as this Linux supports."""
    abi = landlock_abi()
    if not abi:
        return
    files = (1 << _FS_RIGHTS[min(abi, 5)]) - 1
    attributes = struct.pack("QQQ", files, 3 if abi >= 4 else 0, 3 if abi >= 6 else 0)
    size = 24 if abi >= 6 else 16 if abi >= 4 else 8
    ruleset = libc.syscall(444, attributes, ctypes.c_size_t(size), 0)
    if ruleset < 0:
        raise OSError(ctypes.get_errno(), "landlock_create_ruleset")
    rights = dict.fromkeys((*_SYSTEM, sys.prefix, sys.base_prefix, *readable), _READ)
    # Its own entry only: the rest of /proc names every other run's processes.
    rights |= dict.fromkeys(("/proc/self", "/proc/cpuinfo", "/proc/meminfo"), _READ)
    # duckdb aborts when it cannot read its memory limit under the cgroup tree.
    rights |= dict.fromkeys(("/sys/devices/system/cpu", "/sys/fs/cgroup"), _READ)
    rights |= dict.fromkeys(("/dev/null", "/dev/zero", "/dev/random", "/dev/urandom"), 6)
    # multiprocessing keeps its semaphores in /dev/shm; a run's own uid guards its files.
    rights |= dict.fromkeys((work, "/dev/shm"), files)
    for path, allowed in rights.items():
        try:
            target = os.open(path, os.O_PATH | os.O_CLOEXEC)
        except OSError:
            continue
        if not os.path.isdir(path):
            allowed &= _ON_FILES
        rule = struct.pack("=Qi", allowed & files, target)
        if libc.syscall(445, ruleset, 1, rule, 0):
            raise OSError(ctypes.get_errno(), f"landlock_add_rule {path}")
        os.close(target)
    if libc.syscall(446, ruleset, 0):
        raise OSError(ctypes.get_errno(), "landlock_restrict_self")
    os.close(ruleset)


def _unix_sockets_only(libc) -> None:
    """A seccomp filter: ``socket()`` answers EACCES for every family but AF_UNIX, so a run
    reaches no other run, whatever network its container has."""
    architecture, socket_call = _SOCKET_CALL[os.uname().machine]
    kill, allow, refuse = 0x80000000, 0x7FFF0000, 0x00050000 | 13
    program = [
        (0x20, 0, 0, 4),  # load the architecture
        (0x15, 1, 0, architecture),
        (0x06, 0, 0, kill),  # another ABI numbers its calls differently
        (0x20, 0, 0, 0),  # load the call number
        (0x35, 0, 1, 0x40000000),  # the x32 numbering of the same architecture
        (0x06, 0, 0, kill),
        (0x15, 0, 3, socket_call),
        (0x20, 0, 0, 16),  # load the socket family
        (0x15, 1, 0, socket.AF_UNIX),
        (0x06, 0, 0, refuse),
        (0x06, 0, 0, allow),
    ]
    filters = b"".join(struct.pack("HBBI", *instruction) for instruction in program)
    held = ctypes.create_string_buffer(filters)
    filter_program = struct.pack("HP", len(program), ctypes.addressof(held))
    if libc.prctl(22, 2, filter_program, 0, 0):
        raise OSError(ctypes.get_errno(), "seccomp")


def confine(work: str, readable: tuple[str, ...] = ()) -> None:
    """Keep this process and every child to ``work``, the libraries and ``readable``, and
    to Unix sockets. Runs of different projects share one container; these limits need no
    privilege and cannot be taken off again. A sandbox on another system than Linux is a
    development sandbox with no isolation at all."""
    if sys.platform != "linux":
        return
    libc = _libc()
    if libc.prctl(38, 1, 0, 0, 0):  # no_new_privs: an unprivileged filter requires it
        raise OSError(ctypes.get_errno(), "no_new_privs")
    _landlock(libc, work, readable)
    _unix_sockets_only(libc)


class Interrupted(BaseException):
    """Not an Exception: a cell's own ``except Exception`` must not swallow its deadline."""


def _interrupt(_signal, _frame):
    raise Interrupted


class _Output(io.TextIOBase):
    """What a cell printed, kept to its first and last halves: a loop that prints without
    end cannot fill the kernel's memory."""

    half = OUTPUT_CHARS // 2

    def __init__(self):
        self.head, self.tail, self.omitted = "", "", 0

    def writable(self):
        return True

    def write(self, text):
        room = self.half - len(self.head)
        self.head += text[:room]
        if rest := text[room:]:
            kept = self.tail + rest
            self.omitted += max(0, len(kept) - self.half)
            self.tail = kept[-self.half :]
        return len(text)

    def result(self) -> tuple[str, bool]:
        gap = f"\n… {self.omitted:,} characters omitted …\n" if self.omitted else ""
        # A lone surrogate is valid in a Python string and in no JSON a server will send on.
        text = (self.head + gap + self.tail).encode("utf-8", "replace").decode()
        return text, bool(self.omitted)


def run(code, namespace, timeout, cell):
    printed, failure = _Output(), _Output()
    started = time.monotonic()
    # One name per cell: a traceback through an earlier cell's function shows that cell.
    linecache.cache[cell] = (len(code), None, code.splitlines(keepends=True), cell)
    signal.alarm(timeout)
    try:
        with contextlib.redirect_stdout(printed), contextlib.redirect_stderr(printed):
            tree = ast.parse(code, cell)
            shown = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None
            exec(compile(tree, cell, "exec"), namespace)
            if shown is not None:
                value = eval(compile(ast.Expression(shown.value), cell, "eval"), namespace)
                if value is not None:
                    print(repr(value))
    except Interrupted:
        failure.write(f"The execution ran longer than {timeout}s and was interrupted.")
    except BaseException as exc:
        failure.write(
            "".join(traceback.format_exception(type(exc), exc, exc.__traceback__.tb_next))
        )
    finally:
        signal.alarm(0)
    output, truncated = printed.result()
    error = failure.result()[0]
    return {
        "ok": not error,
        "output": output,
        "error": error,
        "truncated": truncated,
        "seconds": round(time.monotonic() - started, 3),
    }


def serve(path, limits):
    for name, value in limits.get("rlimits", {}).items():
        resource.setrlimit(getattr(resource, name), (value, value))
    if "cpus" in limits:
        os.sched_setaffinity(0, sorted(os.sched_getaffinity(0))[: limits["cpus"]])
    signal.signal(signal.SIGALRM, _interrupt)
    # A kernel has no display: plots are files.
    os.environ.setdefault("MPLBACKEND", "Agg")
    work = os.getcwd()
    sys.path.insert(0, work)
    # Before the socket exists: a kernel that answers is a confined kernel.
    confine(work, readable=tuple(limits.get("readable", ())))
    namespace = {"__name__": "__main__"}
    cells = 0
    listener = socket.socket(socket.AF_UNIX)
    listener.bind(path)
    listener.listen()
    while True:
        connection, _ = listener.accept()
        # A caller that left, or sent no request, takes nothing down with it.
        with (
            contextlib.suppress(OSError, ValueError, KeyError),
            connection,
            connection.makefile("rwb") as stream,
        ):
            request = json.loads(stream.readline())
            cells += 1
            reply = run(request["code"], namespace, request["timeout"], f"<cell {cells}>")
            stream.write(json.dumps(reply).encode())


def _text(value) -> str:
    # A lone surrogate is valid in a Python string and in no JSON a caller will send on.
    return str(value).encode("utf-8", "replace").decode()


def exchange(path: str, request: dict) -> dict:
    """One cell and its reply, within one deadline and one size. The kernel runs the
    tenant's code: nothing it sends is taken on trust."""
    deadline = time.monotonic() + request["timeout"] + REPLY_GRACE_SECONDS
    received = bytearray()
    with socket.socket(socket.AF_UNIX) as connection:
        connection.settimeout(REPLY_GRACE_SECONDS)
        connection.connect(path)
        connection.sendall(json.dumps(request).encode() + b"\n")
        while True:
            connection.settimeout(max(0.01, deadline - time.monotonic()))
            chunk = connection.recv(65536)
            if not chunk:
                break
            received += chunk
            if len(received) > MAX_REPLY_BYTES or time.monotonic() > deadline:
                raise ValueError("The kernel's reply passed its limits.")
    reply = json.loads(received)
    return {
        "ok": reply["ok"] is True,
        "output": _text(reply["output"]),
        "error": _text(reply["error"]),
        "truncated": reply["truncated"] is True,
        "seconds": float(reply["seconds"]),
    }


def answers(path: str) -> bool:
    with socket.socket(socket.AF_UNIX) as probe:
        try:
            probe.connect(path)
        except OSError:
            return False
    return True


@contextlib.contextmanager
def _locked(path: str):
    with open(path, "a+") as handle:
        fcntl.flock(handle, fcntl.LOCK_EX)
        yield handle


def _uid(work: str) -> int:
    """The conversation's own uid, kept beside the conversations: a kernel of another
    sandbox that mounts the same folders runs under the same uid."""
    with _locked(os.path.join(os.path.dirname(work), ".uids")) as registry:
        os.chmod(registry.name, 0o600)
        registry.seek(0)
        uids = json.loads(registry.read() or "{}")
        name = os.path.basename(work)
        if name not in uids:
            uids[name] = FIRST_UID + len(uids)
            registry.seek(0)
            registry.truncate()
            registry.write(json.dumps(uids))
            registry.flush()
            os.fsync(registry.fileno())
        return uids[name]


def _launch(work: str, data: str, limits: dict) -> bool:
    """Start the conversation's kernel under its own uid; whether an earlier kernel of the
    conversation existed."""
    uid = _uid(work)
    existed = os.path.isdir(work)
    os.makedirs(work, exist_ok=True)
    os.chown(work, uid, uid)
    os.chmod(work, 0o700)
    # A mount is a link to the provider's own path, so a relative link would leave it.
    link = os.path.join(work, "data")
    if not os.path.islink(link) or os.readlink(link) != data:
        with contextlib.suppress(FileNotFoundError, IsADirectoryError):
            os.unlink(link)
        with contextlib.suppress(FileExistsError):
            os.symlink(data, link)
    path = os.path.join(work, SOCKET)
    with contextlib.suppress(FileNotFoundError):
        os.unlink(path)
    name = os.path.basename(work)
    with open(f"/tmp/kernel-{name}.err", "ab") as errors:
        process = subprocess.Popen(
            [sys.executable, "-I", os.path.abspath(__file__), "serve", SOCKET, json.dumps(limits)],
            cwd=work,
            stdin=subprocess.DEVNULL,
            stdout=subprocess.DEVNULL,
            stderr=errors,
            start_new_session=True,
            user=uid,
            group=uid,
            extra_groups=[],
            env={
                "PATH": os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin"),
                "HOME": work,
                "TMPDIR": work,
                "MPLCONFIGDIR": work,
                **{k: v for k, v in os.environ.items() if k == "TIKTOKEN_CACHE_DIR"},
            },
        )
    with open(f"/tmp/kernel-{name}.pid", "w") as pid:
        pid.write(str(process.pid))
    deadline = time.monotonic() + START_SECONDS
    while not answers(path):
        if process.poll() is not None or time.monotonic() > deadline:
            process.kill()
            raise SystemExit("The kernel did not start.")
        time.sleep(0.05)
    return existed


def cell(work: str, data: str, limits: dict) -> None:
    """Run the request on stdin and print ``{"reply", "restarted"}``: a reply of null is a
    kernel that ended during the cell."""
    request = json.loads(sys.stdin.read())
    path = os.path.join(work, SOCKET)
    restarted = False
    with _locked(f"/tmp/kernel-{os.path.basename(work)}.lock"):
        if not answers(path):
            restarted = _launch(work, data, limits)
        used = _pid(work)
    try:
        reply = exchange(path, request)
    except (OSError, ValueError, KeyError, TypeError):
        # The kernel's own deadline did not fire: it is stuck outside Python, or dead.
        stop(work, only=used)
        reply = None
    print(json.dumps({"reply": reply, "restarted": restarted}))


def _pid(work: str) -> int | None:
    with (
        contextlib.suppress(OSError, ValueError),
        open(f"/tmp/kernel-{os.path.basename(work)}.pid") as pid,
    ):
        return int(pid.read())
    return None


def stop(work: str, *, only: int | None = None) -> None:
    """End the conversation's kernel; with ``only``, that kernel alone, leaving one that
    started since and its names."""
    name = os.path.basename(work)
    # The lock a start holds: a kernel started meanwhile keeps its names.
    with _locked(f"/tmp/kernel-{name}.lock"):
        current = _pid(work)
        target = current if only is None else only
        if target is not None:
            with contextlib.suppress(OSError):
                os.killpg(target, signal.SIGKILL)
        if only is None or current == only:
            for path in (f"/tmp/kernel-{name}.pid", os.path.join(work, SOCKET)):
                with contextlib.suppress(FileNotFoundError):
                    os.unlink(path)


def copy(path: str, target: str, limit: int) -> None:
    """The kernel controls the name, and the file while it is read: open it without
    following a link, as one regular file with one name, and read no more than ``limit``."""
    source = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    with os.fdopen(source, "rb") as opened:
        status = os.fstat(opened.fileno())
        if not stat.S_ISREG(status.st_mode) or status.st_nlink != 1:
            raise SystemExit("Not one regular file.")
        content = opened.read(limit + 1)
    if len(content) > limit:
        raise SystemExit("The file is too large.")
    with open(target, "xb") as out:
        out.write(content)


if __name__ == "__main__":
    mode = sys.argv[1]
    if mode == "serve":
        serve(sys.argv[2], json.loads(sys.argv[3]) if len(sys.argv) > 3 else {})
    elif mode == "cell":
        cell(sys.argv[2], sys.argv[3], json.loads(sys.argv[4]))
    elif mode == "stop":
        stop(sys.argv[2])
    elif mode == "copy":
        copy(sys.argv[2], sys.argv[3], int(sys.argv[4]))