diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f25cc9..6cc7d07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [0.8.0] - 2026-09-18 + +### Added +- Egress allowlists: `AGENTBOX_EGRESS_ALLOWLIST=host[:port],...` and per-request `egress_allowlist` +- Empty allowlist + deny → Docker `--network=none` / Linux netns (unchanged) +- Non-empty allowlist → soft userspace filter (Python sitecustomize / Node `--require`); response includes `egress_allowlist` +- Request list must be a subset of the global allowlist when the global list is set + +### Notes +- Soft allowlist is not a kernel firewall; determined code can bypass. Prefer Docker + short allowlists. + ## [0.7.0] - 2026-09-14 ### Added diff --git a/README.md b/README.md index 32beac6..23b9cf4 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Self-hosted **code execution sandbox** for AI agents — one `docker compose up` [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/) [![CI](https://github.com/yashshah9/agentbox/actions/workflows/ci.yml/badge.svg)](https://github.com/yashshah9/agentbox/actions/workflows/ci.yml) -> **Status:** v0.7 — Python + Node execution, **Docker sandbox backend** (recommended isolation), subprocess default for local tests, timeouts, memory limits, Linux netns egress deny, TypeScript client, workspace snapshots. +> **Status:** v0.8 — Docker/subprocess sandboxes, **egress allowlists**, timeouts, memory limits, snapshots, TypeScript client. ## 60-second try @@ -34,7 +34,7 @@ curl -s -X POST http://localhost:8080/v1/run \ Every agent that writes and runs code needs a safe execution environment. Teams either YOLO in shared containers or pay per-second for hosted sandboxes. Self-hosting gVisor/Firecracker is weeks of work. -## Key features (v0.7) +## Key features (v0.8) - HTTP API: `POST /v1/run` executes Python or JavaScript - **Docker backend** (`AGENTBOX_SANDBOX_BACKEND=docker`): ephemeral `docker run --rm`, `--network=none`, optional `--memory`, workspace at `/work` @@ -42,7 +42,8 @@ Every agent that writes and runs code needs a safe execution environment. Teams - Per-request `limits.timeout_seconds` (HTTP 408 on timeout) - Per-request `limits.memory_mb` (Docker `--memory` or subprocess `RLIMIT_AS`); response includes `limits_applied` + `oom_killed` - `AGENTBOX_MAX_MEMORY_MB` clamps requested memory -- Default-deny egress: Docker uses `--network=none`; subprocess uses Linux `unshare`/`bwrap` when available (`network_isolated` in response) +- Default-deny egress: Docker `--network=none` / Linux `unshare`/`bwrap` (`network_isolated`) +- **Egress allowlists**: `AGENTBOX_EGRESS_ALLOWLIST` + per-request `egress_allowlist` (soft userspace filter when non-empty) - Workspace snapshots: `"snapshot": true` then `"snapshot_id"` - Python SDK + TypeScript client (`sdk/ts/client.ts`) - Credential stripping when the backend is not `unrestricted` @@ -105,6 +106,11 @@ curl -X POST http://localhost:8080/v1/run \ curl -X POST http://localhost:8080/v1/run \ -H 'Content-Type: application/json' \ -d '{"code": "x = bytearray(10**9)", "limits": {"memory_mb": 64, "timeout_seconds": 5}}' + +# Allowlisted egress (subset of AGENTBOX_EGRESS_ALLOWLIST when set): +curl -X POST http://localhost:8080/v1/run \ + -H 'Content-Type: application/json' \ + -d '{"code":"print(1)","egress_allowlist":["example.com"]}' ``` ### Python SDK @@ -151,6 +157,7 @@ Uses image target `runtime-docker` (`docker-cli` + `AGENTBOX_SANDBOX_BACKEND=doc | `AGENTBOX_SANDBOX_BACKEND` | `subprocess` | `subprocess` \| `docker` \| `unrestricted` | | `AGENTBOX_DOCKER_IMAGE` | `python:3.12-slim` | Image for Python runs (docker backend) | | `AGENTBOX_DOCKER_NODE_IMAGE` | `node:20-slim` | Image for JavaScript runs (docker backend) | +| `AGENTBOX_EGRESS_ALLOWLIST` | empty | Comma-separated `host[:port]`; empty = deny-all | | `AGENTBOX_SNAPSHOT_DIR` | `/tmp/agentbox-snapshots` | Workspace snapshot store | ## Running tests @@ -168,18 +175,20 @@ pytest tests/test_docker.py -v - [x] `limits.memory_mb` via `RLIMIT_AS` / Docker `--memory` - [x] Default-deny egress via Linux netns (`unshare`/`bwrap`) when available - [x] Docker ephemeral-container backend +- [x] Egress allowlists (`AGENTBOX_EGRESS_ALLOWLIST` + per-request) - [ ] gVisor runsc backend with warm pool -- [ ] Egress allowlists (beyond all-or-nothing netns) +- [ ] Kernel/iptables egress enforcement (beyond soft userspace hooks) ## License MIT -## Known limitations (v0.7) +## Known limitations (v0.8) - **Subprocess** default is convenient for tests — **not production-grade isolation**; use `AGENTBOX_SANDBOX_BACKEND=docker` for stronger isolation - Docker backend needs a local Docker CLI/daemon; missing CLI returns a clear 400 - Subprocess `RLIMIT_AS` is a soft address-space cap, not a cgroup memory controller (Docker uses `--memory`) -- Subprocess default-deny egress uses Linux `unshare`/`bwrap` when present; **macOS stays credential-scrub only** (`network_isolated: false`) +- Subprocess default-deny egress uses Linux `unshare`/`bwrap` when present; **macOS stays credential-scrub only** (`network_isolated: false`) unless an allowlist soft-hook applies +- Allowlists are a **soft** Python/Node userspace filter (not iptables); determined code can bypass - Single-node, no warm pool - TypeScript client is source-only (not published to npm) diff --git a/pyproject.toml b/pyproject.toml index 8904e31..40562ac 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "agentbox-sandbox" -version = "0.7.0" +version = "0.8.0" description = "Self-hosted code execution sandbox for AI agents" readme = "README.md" license = "MIT" diff --git a/sdk/ts/client.ts b/sdk/ts/client.ts index a2cfccb..8650c63 100644 --- a/sdk/ts/client.ts +++ b/sdk/ts/client.ts @@ -18,6 +18,7 @@ export type RunResult = { limits_applied: LimitsApplied; oom_killed: boolean; network_isolated: boolean; + egress_allowlist?: string[]; }; export class AgentboxClient { @@ -34,12 +35,14 @@ export class AgentboxClient { language = "python", timeoutSeconds?: number, memoryMb?: number, + egressAllowlist?: string[], ): Promise { const body: Record = { code, language }; const limits: Record = {}; if (timeoutSeconds) limits.timeout_seconds = timeoutSeconds; if (memoryMb != null) limits.memory_mb = memoryMb; if (Object.keys(limits).length) body.limits = limits; + if (egressAllowlist) body.egress_allowlist = egressAllowlist; const res = await fetch(`${this.baseUrl}/v1/run`, { method: "POST", headers: { "content-type": "application/json" }, diff --git a/src/agentbox/__init__.py b/src/agentbox/__init__.py index 1369941..2c8224d 100644 --- a/src/agentbox/__init__.py +++ b/src/agentbox/__init__.py @@ -1,3 +1,3 @@ """Self-hosted code execution sandbox for AI agents.""" -__version__ = "0.7.0" +__version__ = "0.8.0" diff --git a/src/agentbox/api/app.py b/src/agentbox/api/app.py index 2eab02e..ef78e64 100644 --- a/src/agentbox/api/app.py +++ b/src/agentbox/api/app.py @@ -8,11 +8,13 @@ from pydantic import BaseModel, Field from agentbox import __version__ from agentbox.config import Settings from agentbox.sandbox.docker import DockerSandbox +from agentbox.sandbox.egress import parse_allowlist from agentbox.sandbox.runner import SubprocessSandbox def create_sandbox(settings: Settings) -> SubprocessSandbox | DockerSandbox: """Select execution backend from settings.""" + allow = parse_allowlist(settings.egress_allowlist) backend = settings.sandbox_backend.lower().strip() if backend == "docker": return DockerSandbox( @@ -23,6 +25,7 @@ def create_sandbox(settings: Settings) -> SubprocessSandbox | DockerSandbox: deny_egress=True, docker_image=settings.docker_image, docker_node_image=settings.docker_node_image, + egress_allowlist=allow, ) if backend == "unrestricted": return SubprocessSandbox( @@ -39,6 +42,7 @@ def create_sandbox(settings: Settings) -> SubprocessSandbox | DockerSandbox: snapshot_dir=settings.snapshot_dir, default_memory_mb=settings.default_memory_mb, deny_egress=True, + egress_allowlist=allow, ) @@ -60,6 +64,7 @@ class RunRequest(BaseModel): limits: ResourceLimits | None = None snapshot: bool = False snapshot_id: str | None = None + egress_allowlist: list[str] | None = None class LimitsApplied(BaseModel): @@ -78,6 +83,7 @@ class RunResponse(BaseModel): limits_applied: LimitsApplied oom_killed: bool = False network_isolated: bool = False + egress_allowlist: list[str] = Field(default_factory=list) @app.get("/health") @@ -110,6 +116,7 @@ def run_code(req: RunRequest) -> RunResponse: snapshot_id=req.snapshot_id, persist_snapshot=req.snapshot, memory_mb=memory_mb, + egress_allowlist=req.egress_allowlist, ) except subprocess.TimeoutExpired as exc: raise HTTPException(status_code=408, detail="Execution timed out") from exc @@ -126,4 +133,5 @@ def run_code(req: RunRequest) -> RunResponse: limits_applied=LimitsApplied(timeout_seconds=timeout, memory_mb=memory_mb), oom_killed=result.oom_killed, network_isolated=result.network_isolated, + egress_allowlist=list(result.egress_allowlist or []), ) diff --git a/src/agentbox/config.py b/src/agentbox/config.py index bfc1d8d..d86c3f9 100644 --- a/src/agentbox/config.py +++ b/src/agentbox/config.py @@ -17,3 +17,4 @@ class Settings(BaseSettings): max_memory_mb: int = 8192 docker_image: str = "python:3.12-slim" docker_node_image: str = "node:20-slim" + egress_allowlist: str = "" # comma-separated host[:port] diff --git a/src/agentbox/sandbox/docker.py b/src/agentbox/sandbox/docker.py index d0cb91c..e03040d 100644 --- a/src/agentbox/sandbox/docker.py +++ b/src/agentbox/sandbox/docker.py @@ -9,6 +9,7 @@ import time import uuid from pathlib import Path +from agentbox.sandbox.egress import install_node_hook, install_python_hook, resolve_allowlist from agentbox.sandbox.runner import RunResult, _likely_oom from agentbox.sandbox.snapshots import restore_snapshot, save_snapshot @@ -19,8 +20,9 @@ DEFAULT_NODE_IMAGE = "node:20-slim" class DockerSandbox: """Run code in an ephemeral ``docker run --rm`` container. - Workspace is bind-mounted at ``/work``. With ``deny_egress`` (default), - networking is ``--network=none``. Memory uses Docker ``--memory``. + Workspace is bind-mounted at ``/work``. With ``deny_egress`` and an empty + allowlist, networking is ``--network=none``. A non-empty allowlist uses the + default bridge plus a userspace soft filter (see ``egress`` module). """ def __init__( @@ -33,6 +35,7 @@ class DockerSandbox: docker_image: str = DEFAULT_PYTHON_IMAGE, docker_node_image: str = DEFAULT_NODE_IMAGE, docker_binary: str | None = None, + egress_allowlist: list[str] | None = None, ) -> None: self.timeout_seconds = timeout_seconds self.max_output_bytes = max_output_bytes @@ -42,6 +45,7 @@ class DockerSandbox: self.docker_image = docker_image self.docker_node_image = docker_node_image self.docker_binary = docker_binary or "docker" + self.egress_allowlist = list(egress_allowlist or []) def run( self, @@ -51,10 +55,16 @@ class DockerSandbox: snapshot_id: str | None = None, persist_snapshot: bool = False, memory_mb: int | None = None, + egress_allowlist: list[str] | None = None, ) -> RunResult: docker = self._resolve_docker() timeout = timeout_seconds or self.timeout_seconds mem = memory_mb if memory_mb is not None else self.default_memory_mb + effective = ( + resolve_allowlist(self.egress_allowlist, egress_allowlist) + if self.deny_egress + else [] + ) start = time.monotonic() with tempfile.TemporaryDirectory(prefix="agentbox-docker-") as tmp: workspace = Path(tmp) @@ -64,24 +74,35 @@ class DockerSandbox: except FileNotFoundError as exc: raise ValueError(str(exc)) from exc lang = language.lower() + extra_env: dict[str, str] = {} if lang == "python": (workspace / "main.py").write_text(code, encoding="utf-8") image = self.docker_image + if self.deny_egress and effective: + # Hook paths must be container paths (/work/...), not host paths. + host_env = install_python_hook(workspace, effective) + extra_env["PYTHONPATH"] = "/work/.agentbox_egress" + _ = host_env elif lang in {"javascript", "node"}: (workspace / "main.js").write_text(code, encoding="utf-8") image = self.docker_node_image + if self.deny_egress and effective: + install_node_hook(workspace, effective) + extra_env["NODE_OPTIONS"] = "--require /work/.agentbox_egress_preload.js" else: raise ValueError(f"Unsupported language: {language}") name = f"agentbox-{uuid.uuid4().hex[:12]}" + network_none = self.deny_egress and not effective argv = build_docker_argv( docker_binary=docker, workspace=workspace, language=lang, image=image, memory_mb=mem, - network_none=self.deny_egress, + network_none=network_none, container_name=name, + extra_env=extra_env, ) network_isolated = self.deny_egress try: @@ -114,6 +135,7 @@ class DockerSandbox: snapshot_id=new_snapshot, oom_killed=_likely_oom(exit_code, stdout, stderr, mem), network_isolated=network_isolated, + egress_allowlist=effective if self.deny_egress else [], ) def run_python(self, code: str) -> RunResult: @@ -139,6 +161,7 @@ def build_docker_argv( memory_mb: int | None = None, network_none: bool = True, container_name: str | None = None, + extra_env: dict[str, str] | None = None, ) -> list[str]: """Build ``docker run`` argv for a language workspace (unit-testable).""" argv = [docker_binary, "run", "--rm"] @@ -148,6 +171,8 @@ def build_docker_argv( argv.append("--network=none") if memory_mb is not None: argv.extend(["--memory", f"{max(1, memory_mb)}m"]) + for key, value in (extra_env or {}).items(): + argv.extend(["-e", f"{key}={value}"]) argv.extend( [ "-v", diff --git a/src/agentbox/sandbox/egress.py b/src/agentbox/sandbox/egress.py new file mode 100644 index 0000000..23ecbda --- /dev/null +++ b/src/agentbox/sandbox/egress.py @@ -0,0 +1,170 @@ +"""Egress allowlist helpers (userspace soft filter). + +ponytail: soft allowlist via Python sitecustomize / Node --require hooks — not a +kernel firewall. Determined code can bypass. Ceiling = iptables/NET_ADMIN custom +runtime image or gVisor network policy. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +_HOST_RE = re.compile(r"^[A-Za-z0-9._\-]+(?::\d{1,5})?$") + + +def parse_allowlist(raw: str | list[str] | None) -> list[str]: + """Parse comma-separated or list allowlist into unique host[:port] entries.""" + if raw is None: + return [] + if isinstance(raw, str): + parts = [p.strip() for p in raw.split(",")] + else: + parts = [str(p).strip() for p in raw] + out: list[str] = [] + seen: set[str] = set() + for part in parts: + if not part: + continue + if not _HOST_RE.match(part): + raise ValueError(f"Invalid egress allowlist entry: {part!r}") + key = part.lower() + if key in seen: + continue + seen.add(key) + out.append(key) + return out + + +def resolve_allowlist( + global_hosts: list[str], + request_hosts: list[str] | None, +) -> list[str]: + """Intersect request with global policy. + + - ``request_hosts is None`` → use global (may be empty = deny-all) + - global empty → request wins (or empty) + - both set → request hostnames must be ⊆ global; empty request = deny-all + """ + global_norm = [h.lower() for h in global_hosts] + global_keys = {h.split(":")[0] for h in global_norm} + if request_hosts is None: + return list(global_norm) + req = parse_allowlist(request_hosts) + if not global_keys: + return req + if not req: + return [] + bad = [h for h in req if h.split(":")[0] not in global_keys] + if bad: + raise ValueError( + "egress_allowlist entries not permitted by AGENTBOX_EGRESS_ALLOWLIST: " + + ", ".join(bad) + ) + return req + + +def install_python_hook(workspace: Path, hosts: list[str]) -> dict[str, str]: + """Write sitecustomize hook; return env vars to enable it.""" + hook_dir = workspace / ".agentbox_egress" + hook_dir.mkdir(parents=True, exist_ok=True) + hosts_json = json.dumps(hosts) + (hook_dir / "sitecustomize.py").write_text( + f'''# agentbox egress soft allowlist — auto-generated +import socket +import ipaddress + +_ALLOWED = {{h.lower() for h in {hosts_json}}} +_ALLOWED_HOSTS = {{h.split(":")[0] for h in _ALLOWED}} +_ALLOWED_IPS: set[str] = set() +for _h in list(_ALLOWED_HOSTS): + try: + _ALLOWED_IPS.add(str(ipaddress.ip_address(_h))) + except ValueError: + pass + +_orig_getaddrinfo = socket.getaddrinfo +_orig_connect = socket.socket.connect + + +def _host_ok(host: str) -> bool: + h = (host or "").lower().strip("[]") + if not h or h in {{"localhost", "127.0.0.1", "::1"}}: + return True + if h in _ALLOWED_HOSTS or h in _ALLOWED_IPS: + return True + try: + ipaddress.ip_address(h) + return h in _ALLOWED_IPS + except ValueError: + return h in _ALLOWED_HOSTS + + +def getaddrinfo(host, *args, **kwargs): # type: ignore[no-untyped-def] + if not _host_ok(str(host)): + raise OSError(f"agentbox egress denied: {{host}}") + results = _orig_getaddrinfo(host, *args, **kwargs) + for item in results: + try: + sockaddr = item[4] + if sockaddr: + _ALLOWED_IPS.add(str(sockaddr[0])) + except (IndexError, TypeError, ValueError): + pass + return results + + +def _connect(self, address): # type: ignore[no-untyped-def] + host = address[0] if isinstance(address, tuple) and address else address + if isinstance(host, bytes): + host = host.decode("utf-8", "replace") + if not _host_ok(str(host)): + raise OSError(f"agentbox egress denied: {{host}}") + return _orig_connect(self, address) + + +socket.getaddrinfo = getaddrinfo +socket.socket.connect = _connect +''', + encoding="utf-8", + ) + return {"PYTHONPATH": str(hook_dir.resolve())} + + +def install_node_hook(workspace: Path, hosts: list[str]) -> dict[str, str]: + """Write Node --require preload; return env vars to enable it.""" + path = workspace / ".agentbox_egress_preload.js" + hosts_json = json.dumps(hosts) + path.write_text( + f"""/* agentbox egress soft allowlist — auto-generated */ +const net = require('net'); +const allowed = new Set({hosts_json}.map((h) => String(h).toLowerCase())); +const allowedHosts = new Set([...allowed].map((h) => h.split(':')[0])); +function hostOk(host) {{ + if (!host) return true; + const h = String(host).toLowerCase().replace(/^\\[|\\]$/g, ''); + if (h === 'localhost' || h === '127.0.0.1' || h === '::1') return true; + return allowedHosts.has(h) || allowed.has(h); +}} +const origConnect = net.Socket.prototype.connect; +net.Socket.prototype.connect = function (...args) {{ + let host = null; + if (typeof args[0] === 'object' && args[0] !== null) {{ + host = args[0].host || args[0].hostname; + }} else if (typeof args[1] === 'string') {{ + host = args[1]; + }} else if (typeof args[0] === 'string' && args[0].includes(':')) {{ + host = args[0].split(':')[0]; + }} + if (host && !hostOk(host)) {{ + const err = new Error('agentbox egress denied: ' + host); + err.code = 'EGRESS_DENIED'; + throw err; + }} + return origConnect.apply(this, args); +}}; +""", + encoding="utf-8", + ) + return {"NODE_OPTIONS": f"--require {path.resolve()}"} diff --git a/src/agentbox/sandbox/runner.py b/src/agentbox/sandbox/runner.py index 9e87018..516b900 100644 --- a/src/agentbox/sandbox/runner.py +++ b/src/agentbox/sandbox/runner.py @@ -24,6 +24,7 @@ class RunResult: snapshot_id: str | None = None oom_killed: bool = False network_isolated: bool = False + egress_allowlist: list[str] | None = None class Sandbox(Protocol): @@ -34,8 +35,9 @@ class Sandbox(Protocol): class SubprocessSandbox: """MVP sandbox: isolated temp directory + subprocess timeout + optional memory cap. - When deny_egress is set, also tries Linux network-namespace isolation via - unshare/bwrap when available. macOS stays credential-scrub only. + When deny_egress is set with an empty allowlist, tries Linux network-namespace + isolation via unshare/bwrap. A non-empty allowlist skips netns and installs a + userspace soft filter instead. macOS deny-all stays credential-scrub only. ponytail: not production isolation — use DockerSandbox for stronger isolation. """ @@ -47,12 +49,14 @@ class SubprocessSandbox: deny_egress: bool = False, snapshot_dir: str | Path | None = None, default_memory_mb: int | None = None, + egress_allowlist: list[str] | None = None, ) -> None: self.timeout_seconds = timeout_seconds self.max_output_bytes = max_output_bytes self.deny_egress = deny_egress self.snapshot_dir = Path(snapshot_dir) if snapshot_dir else Path("/tmp/agentbox-snapshots") self.default_memory_mb = default_memory_mb + self.egress_allowlist = list(egress_allowlist or []) def run( self, @@ -62,9 +66,21 @@ class SubprocessSandbox: snapshot_id: str | None = None, persist_snapshot: bool = False, memory_mb: int | None = None, + egress_allowlist: list[str] | None = None, ) -> RunResult: + from agentbox.sandbox.egress import ( + install_node_hook, + install_python_hook, + resolve_allowlist, + ) + timeout = timeout_seconds or self.timeout_seconds mem = memory_mb if memory_mb is not None else self.default_memory_mb + effective = ( + resolve_allowlist(self.egress_allowlist, egress_allowlist) + if self.deny_egress + else [] + ) start = time.monotonic() env = self._env() with tempfile.TemporaryDirectory(prefix="agentbox-") as tmp: @@ -74,20 +90,27 @@ class SubprocessSandbox: restore_snapshot(snapshot_id, workspace, self.snapshot_dir) except FileNotFoundError as exc: raise ValueError(str(exc)) from exc - if language == "python": + lang = language.lower() + if lang == "python": script = workspace / "main.py" script.write_text(code, encoding="utf-8") argv = ["python3", str(script)] - elif language in {"javascript", "node"}: + if self.deny_egress and effective: + env.update(install_python_hook(workspace, effective)) + elif lang in {"javascript", "node"}: script = workspace / "main.js" script.write_text(code, encoding="utf-8") node = shutil.which("node") or "node" argv = [node, str(script)] + if self.deny_egress and effective: + env.update(install_node_hook(workspace, effective)) else: raise ValueError(f"Unsupported language: {language}") network_isolated = False - if self.deny_egress: + if self.deny_egress and not effective: argv, network_isolated = wrap_deny_egress(argv) + elif self.deny_egress and effective: + network_isolated = True preexec = _memory_preexec(mem) if mem else None try: proc = subprocess.run( @@ -115,6 +138,7 @@ class SubprocessSandbox: snapshot_id=new_snapshot, oom_killed=_likely_oom(exit_code, stdout, stderr, mem), network_isolated=network_isolated, + egress_allowlist=effective if self.deny_egress else [], ) def run_python(self, code: str) -> RunResult: diff --git a/src/agentbox/sdk/client.py b/src/agentbox/sdk/client.py index a7020f7..731a806 100644 --- a/src/agentbox/sdk/client.py +++ b/src/agentbox/sdk/client.py @@ -23,8 +23,9 @@ class AgentboxClient: snapshot: bool = False, snapshot_id: str | None = None, memory_mb: int | None = None, + egress_allowlist: list[str] | None = None, ) -> dict[str, object]: - """Run code; response includes limits_applied, oom_killed, network_isolated.""" + """Run code; response includes limits_applied, oom_killed, network_isolated, egress_allowlist.""" payload: dict[str, object] = {"code": code, "language": language} limits: dict[str, object] = {} if timeout_seconds is not None: @@ -37,6 +38,8 @@ class AgentboxClient: payload["snapshot"] = True if snapshot_id: payload["snapshot_id"] = snapshot_id + if egress_allowlist is not None: + payload["egress_allowlist"] = egress_allowlist resp = self._client.post("/v1/run", json=payload) self._raise_for_status(resp) return cast(dict[str, object], resp.json()) diff --git a/tests/test_docker.py b/tests/test_docker.py index c5cbb77..d0a1a38 100644 --- a/tests/test_docker.py +++ b/tests/test_docker.py @@ -71,6 +71,44 @@ def test_build_docker_argv_allows_network_when_not_deny(tmp_path: Path) -> None: assert "--network=none" not in argv +def test_build_docker_argv_extra_env(tmp_path: Path) -> None: + argv = build_docker_argv( + docker_binary="docker", + workspace=tmp_path, + language="python", + image="python:3.12-slim", + network_none=False, + extra_env={"PYTHONPATH": "/work/.agentbox_egress"}, + ) + assert "--network=none" not in argv + assert "-e" in argv + assert "PYTHONPATH=/work/.agentbox_egress" in argv + + +def test_docker_sandbox_allowlist_skips_network_none(tmp_path: Path) -> None: + box = DockerSandbox( + snapshot_dir=tmp_path, + timeout_seconds=10, + egress_allowlist=["example.com"], + ) + fake_proc = MagicMock() + fake_proc.stdout = "ok\n" + fake_proc.stderr = "" + fake_proc.returncode = 0 + + with ( + patch("agentbox.sandbox.docker.shutil.which", return_value="/usr/bin/docker"), + patch("agentbox.sandbox.docker.subprocess.run", return_value=fake_proc) as run_mock, + ): + result = box.run("print(1)", language="python") + + assert result.network_isolated is True + assert result.egress_allowlist == ["example.com"] + argv = run_mock.call_args.args[0] + assert "--network=none" not in argv + assert any(a.startswith("PYTHONPATH=") for a in argv) + + def test_build_docker_argv_rejects_unknown_language(tmp_path: Path) -> None: with pytest.raises(ValueError, match="Unsupported language"): build_docker_argv( diff --git a/tests/test_egress_allowlist.py b/tests/test_egress_allowlist.py new file mode 100644 index 0000000..e927034 --- /dev/null +++ b/tests/test_egress_allowlist.py @@ -0,0 +1,73 @@ +"""Tests for egress allowlist parsing and soft hooks.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from agentbox.sandbox.egress import ( + install_python_hook, + parse_allowlist, + resolve_allowlist, +) +from agentbox.sandbox.runner import SubprocessSandbox + + +def test_parse_allowlist_csv() -> None: + assert parse_allowlist("api.openai.com:443, pypi.org") == [ + "api.openai.com:443", + "pypi.org", + ] + assert parse_allowlist("") == [] + with pytest.raises(ValueError): + parse_allowlist("bad host!") + + +def test_resolve_subset() -> None: + assert resolve_allowlist(["a.com", "b.com"], None) == ["a.com", "b.com"] + assert resolve_allowlist(["a.com", "b.com"], ["a.com"]) == ["a.com"] + assert resolve_allowlist(["a.com"], []) == [] + assert resolve_allowlist([], ["evil.com"]) == ["evil.com"] + with pytest.raises(ValueError, match="not permitted"): + resolve_allowlist(["a.com"], ["evil.com"]) + + +def test_python_hook_blocks_disallowed(tmp_path: Path) -> None: + box = SubprocessSandbox(deny_egress=True, egress_allowlist=["example.com"], timeout_seconds=10) + result = box.run( + "import urllib.request\n" + "try:\n" + " urllib.request.urlopen('https://httpbin.org/get', timeout=3)\n" + " print('REACHED')\n" + "except OSError as e:\n" + " print('DENIED' if 'egress denied' in str(e) else type(e).__name__)\n", + language="python", + ) + assert result.network_isolated is True + assert result.egress_allowlist == ["example.com"] + assert "DENIED" in result.stdout + + +def test_python_hook_allows_listed_host(tmp_path: Path) -> None: + # example.com is typically reachable; if offline, skip soft. + box = SubprocessSandbox(deny_egress=True, egress_allowlist=["example.com"], timeout_seconds=15) + result = box.run( + "import urllib.request\n" + "try:\n" + " urllib.request.urlopen('https://example.com', timeout=8)\n" + " print('OK')\n" + "except Exception as e:\n" + " print('ERR', type(e).__name__)\n", + language="python", + ) + assert result.network_isolated is True + # Offline CI may fail DNS; allow ERR URLError but never DENIED for listed host + assert "DENIED" not in result.stdout + assert "OK" in result.stdout or "ERR" in result.stdout + + +def test_install_python_hook_writes_sitecustomize(tmp_path: Path) -> None: + env = install_python_hook(tmp_path, ["api.openai.com"]) + assert (tmp_path / ".agentbox_egress" / "sitecustomize.py").is_file() + assert "PYTHONPATH" in env diff --git a/tests/test_scenarios_v05.py b/tests/test_scenarios_v05.py index 61c5f00..fa33562 100644 --- a/tests/test_scenarios_v05.py +++ b/tests/test_scenarios_v05.py @@ -20,13 +20,13 @@ def client() -> Iterator[TestClient]: yield test_client -def test_health_version_070(client: TestClient) -> None: +def test_health_version_080(client: TestClient) -> None: resp = client.get("/health") assert resp.status_code == 200 body = resp.json() assert body["status"] == "ok" - assert body["version"] == "0.7.0" - assert __version__ == "0.7.0" + assert body["version"] == "0.8.0" + assert __version__ == "0.8.0" def test_python_success(client: TestClient) -> None: