mirror of
https://github.com/yashshah9/agentbox.git
synced 2026-11-18 18:03:44 +00:00
feat(v0.6): Linux network namespace deny-egress
Context: - When deny_egress is on, probe unshare/bwrap and wrap runs in a netns; report network_isolated. - Falls back to credential scrub when privileges are missing. Test Plan: - docker compose run --rm test pytest tests/ -q Additional Notes: - Version 0.6.0.
This commit is contained in:
@@ -1,5 +1,14 @@
|
||||
# Changelog
|
||||
|
||||
## [0.6.0] - 2026-09-14
|
||||
|
||||
### Added
|
||||
- Real default-deny egress on Linux when possible: wrap runs with `unshare --net` (preferred) or `bwrap --unshare-net`
|
||||
- Run response includes `network_isolated` so callers know whether netns wrapping applied
|
||||
|
||||
### Notes
|
||||
- macOS and hosts without `unshare`/`bwrap` still scrub credentials only (`network_isolated: false`)
|
||||
|
||||
## [0.5.0] - 2026-09-14
|
||||
|
||||
### Added
|
||||
|
||||
@@ -7,7 +7,7 @@ Self-hosted **code execution sandbox** for AI agents — one `docker compose up`
|
||||
[](https://www.python.org/downloads/)
|
||||
[](https://github.com/yashshah9/agentbox/actions/workflows/ci.yml)
|
||||
|
||||
> **Status:** v0.5 — Python + Node subprocess sandbox, timeouts, `limits.memory_mb` / `oom_killed` / `limits_applied`, TypeScript client, workspace snapshots.
|
||||
> **Status:** v0.6 — Python + Node subprocess sandbox, timeouts, memory limits, Linux default-deny egress (`unshare`/`bwrap`) with `network_isolated`, TypeScript client, workspace snapshots.
|
||||
|
||||
## 60-second try
|
||||
|
||||
@@ -34,16 +34,17 @@ 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.5)
|
||||
## Key features (v0.6)
|
||||
|
||||
- HTTP API: `POST /v1/run` executes Python or JavaScript
|
||||
- Per-request `limits.timeout_seconds` (HTTP 408 on timeout)
|
||||
- Per-request `limits.memory_mb` (sets `RLIMIT_AS`; 16–8192); response includes `limits_applied` + `oom_killed`
|
||||
- `AGENTBOX_MAX_MEMORY_MB` clamps requested memory
|
||||
- Default-deny egress when possible: Linux wraps with `unshare --net` or `bwrap --unshare-net`; response includes `network_isolated`
|
||||
- Workspace snapshots: `"snapshot": true` then `"snapshot_id"`
|
||||
- Python SDK + TypeScript client (`sdk/ts/client.ts`)
|
||||
- Docker image includes Node.js for the JS runtime
|
||||
- Credential stripping when the backend is not `unrestricted`
|
||||
- Credential stripping when the backend is not `unrestricted` (macOS stays scrub-only)
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -135,17 +136,18 @@ pytest tests/ -v
|
||||
- [x] Node.js runtime + TypeScript client + per-run timeout
|
||||
- [x] Filesystem snapshot/restore (tar workspaces)
|
||||
- [x] `limits.memory_mb` via `RLIMIT_AS`
|
||||
- [x] Default-deny egress via Linux netns (`unshare`/`bwrap`) when available
|
||||
- [ ] gVisor runsc backend with warm pool
|
||||
- [ ] Default-deny egress with allowlists (kernel netns)
|
||||
- [ ] Egress allowlists (beyond all-or-nothing netns)
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
## Known limitations (v0.4)
|
||||
## Known limitations (v0.6)
|
||||
|
||||
- Subprocess sandbox only — **not production-grade isolation**
|
||||
- `RLIMIT_AS` is a soft address-space cap, not a cgroup memory controller
|
||||
- Credential stripping is not a network namespace
|
||||
- Default-deny egress uses Linux `unshare`/`bwrap` when present; **macOS stays credential-scrub only** (`network_isolated: false`)
|
||||
- Single-node, no warm pool
|
||||
- TypeScript client is source-only (not published to npm)
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "agentbox-sandbox"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
description = "Self-hosted code execution sandbox for AI agents"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
|
||||
@@ -17,6 +17,7 @@ export type RunResult = {
|
||||
snapshot_id?: string | null;
|
||||
limits_applied: LimitsApplied;
|
||||
oom_killed: boolean;
|
||||
network_isolated: boolean;
|
||||
};
|
||||
|
||||
export class AgentboxClient {
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""Self-hosted code execution sandbox for AI agents."""
|
||||
|
||||
__version__ = "0.5.0"
|
||||
__version__ = "0.6.0"
|
||||
|
||||
@@ -50,6 +50,7 @@ class RunResponse(BaseModel):
|
||||
snapshot_id: str | None = None
|
||||
limits_applied: LimitsApplied
|
||||
oom_killed: bool = False
|
||||
network_isolated: bool = False
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
@@ -97,4 +98,5 @@ def run_code(req: RunRequest) -> RunResponse:
|
||||
snapshot_id=result.snapshot_id,
|
||||
limits_applied=LimitsApplied(timeout_seconds=timeout, memory_mb=memory_mb),
|
||||
oom_killed=result.oom_killed,
|
||||
network_isolated=result.network_isolated,
|
||||
)
|
||||
|
||||
@@ -23,6 +23,7 @@ class RunResult:
|
||||
duration_ms: int
|
||||
snapshot_id: str | None = None
|
||||
oom_killed: bool = False
|
||||
network_isolated: bool = False
|
||||
|
||||
|
||||
class Sandbox(Protocol):
|
||||
@@ -33,6 +34,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.
|
||||
|
||||
ponytail: not production isolation — upgrade path is gVisor/docker backend.
|
||||
"""
|
||||
|
||||
@@ -81,6 +85,9 @@ class SubprocessSandbox:
|
||||
argv = [node, str(script)]
|
||||
else:
|
||||
raise ValueError(f"Unsupported language: {language}")
|
||||
network_isolated = False
|
||||
if self.deny_egress:
|
||||
argv, network_isolated = wrap_deny_egress(argv)
|
||||
preexec = _memory_preexec(mem) if mem else None
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
@@ -107,6 +114,7 @@ class SubprocessSandbox:
|
||||
duration_ms=duration,
|
||||
snapshot_id=new_snapshot,
|
||||
oom_killed=_likely_oom(exit_code, stdout, stderr, mem),
|
||||
network_isolated=network_isolated,
|
||||
)
|
||||
|
||||
def run_python(self, code: str) -> RunResult:
|
||||
@@ -125,6 +133,55 @@ class SubprocessSandbox:
|
||||
return env
|
||||
|
||||
|
||||
def wrap_deny_egress(argv: list[str]) -> tuple[list[str], bool]:
|
||||
"""Wrap argv with a network namespace when unshare or bwrap can isolate.
|
||||
|
||||
Prefer ``unshare --net``; fall back to ``bwrap --unshare-net``. Probes first so
|
||||
we do not wrap when the binary exists but lacks privileges (common in
|
||||
unprivileged containers). Returns ``(argv, network_isolated)``.
|
||||
"""
|
||||
unshare = shutil.which("unshare")
|
||||
if unshare and _can_isolate([unshare, "--net", "true"]):
|
||||
return [unshare, "--net", "--", *argv], True
|
||||
bwrap = shutil.which("bwrap")
|
||||
if bwrap:
|
||||
probe = [
|
||||
bwrap,
|
||||
"--unshare-net",
|
||||
"--bind",
|
||||
"/",
|
||||
"/",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--",
|
||||
"true",
|
||||
]
|
||||
if _can_isolate(probe):
|
||||
return [
|
||||
bwrap,
|
||||
"--unshare-net",
|
||||
"--bind",
|
||||
"/",
|
||||
"/",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--",
|
||||
*argv,
|
||||
], True
|
||||
return argv, False
|
||||
|
||||
|
||||
def _can_isolate(cmd: list[str]) -> bool:
|
||||
try:
|
||||
return subprocess.run(cmd, capture_output=True, timeout=2, check=False).returncode == 0
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
|
||||
|
||||
def _likely_oom(exit_code: int, stdout: str, stderr: str, memory_mb: int | None) -> bool:
|
||||
"""Heuristic: true when the process likely hit a memory cap.
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ class AgentboxClient:
|
||||
snapshot_id: str | None = None,
|
||||
memory_mb: int | None = None,
|
||||
) -> dict[str, object]:
|
||||
"""Run code; response includes limits_applied and oom_killed."""
|
||||
"""Run code; response includes limits_applied, oom_killed, network_isolated."""
|
||||
payload: dict[str, object] = {"code": code, "language": language}
|
||||
limits: dict[str, object] = {}
|
||||
if timeout_seconds is not None:
|
||||
|
||||
@@ -31,6 +31,8 @@ def test_run_python(client: TestClient) -> None:
|
||||
assert body["limits_applied"]["timeout_seconds"] >= 1
|
||||
assert "memory_mb" in body["limits_applied"]
|
||||
assert body["oom_killed"] is False
|
||||
assert "network_isolated" in body
|
||||
assert isinstance(body["network_isolated"], bool)
|
||||
|
||||
|
||||
def test_run_rejects_unknown_language(client: TestClient) -> None:
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Tests for deny_egress network-namespace wrapping."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import sys
|
||||
from collections.abc import Iterator
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from agentbox.api.app import app
|
||||
from agentbox.sandbox.runner import SubprocessSandbox, wrap_deny_egress
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client() -> Iterator[TestClient]:
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_wrap_prefers_unshare(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def fake_which(name: str) -> str | None:
|
||||
return {"unshare": "/usr/bin/unshare", "bwrap": "/usr/bin/bwrap"}.get(name)
|
||||
|
||||
monkeypatch.setattr(shutil, "which", fake_which)
|
||||
monkeypatch.setattr(
|
||||
"agentbox.sandbox.runner._can_isolate", lambda cmd: cmd[0].endswith("unshare")
|
||||
)
|
||||
argv, isolated = wrap_deny_egress(["python3", "main.py"])
|
||||
assert isolated is True
|
||||
assert argv == ["/usr/bin/unshare", "--net", "--", "python3", "main.py"]
|
||||
|
||||
|
||||
def test_wrap_falls_back_to_bwrap(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def fake_which(name: str) -> str | None:
|
||||
return {"bwrap": "/usr/bin/bwrap"}.get(name)
|
||||
|
||||
monkeypatch.setattr(shutil, "which", fake_which)
|
||||
monkeypatch.setattr("agentbox.sandbox.runner._can_isolate", lambda cmd: True)
|
||||
argv, isolated = wrap_deny_egress(["python3", "main.py"])
|
||||
assert isolated is True
|
||||
assert argv[:3] == ["/usr/bin/bwrap", "--unshare-net", "--bind"]
|
||||
assert argv[-3:] == ["--", "python3", "main.py"]
|
||||
|
||||
|
||||
def test_wrap_skips_when_probe_fails(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(shutil, "which", lambda name: "/usr/bin/unshare")
|
||||
monkeypatch.setattr("agentbox.sandbox.runner._can_isolate", lambda cmd: False)
|
||||
argv, isolated = wrap_deny_egress(["python3", "main.py"])
|
||||
assert isolated is False
|
||||
assert argv == ["python3", "main.py"]
|
||||
|
||||
|
||||
def test_wrap_noop_without_tools(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(shutil, "which", lambda _name: None)
|
||||
cmd = ["python3", "main.py"]
|
||||
argv, isolated = wrap_deny_egress(cmd)
|
||||
assert isolated is False
|
||||
assert argv == cmd
|
||||
|
||||
|
||||
def test_run_reports_network_isolated_false_without_tools(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(shutil, "which", lambda name: "python3" if name == "python3" else None)
|
||||
box = SubprocessSandbox(deny_egress=True, timeout_seconds=5)
|
||||
result = box.run("print('ok')")
|
||||
assert result.exit_code == 0
|
||||
assert result.network_isolated is False
|
||||
assert "ok" in result.stdout
|
||||
|
||||
|
||||
def test_api_includes_network_isolated(client: TestClient) -> None:
|
||||
resp = client.post("/v1/run", json={"code": "print(1)"})
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert "network_isolated" in body
|
||||
assert isinstance(body["network_isolated"], bool)
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="netns isolation is Linux-only")
|
||||
@pytest.mark.skipif(
|
||||
shutil.which("unshare") is None and shutil.which("bwrap") is None,
|
||||
reason="unshare/bwrap not installed",
|
||||
)
|
||||
def test_live_network_isolation_blocks_egress() -> None:
|
||||
"""Optional: real isolation when running on Linux with unshare/bwrap privileges."""
|
||||
from agentbox.sandbox.runner import wrap_deny_egress
|
||||
|
||||
_, can = wrap_deny_egress(["true"])
|
||||
if not can:
|
||||
pytest.skip("unshare/bwrap present but cannot create netns (need privileges)")
|
||||
box = SubprocessSandbox(deny_egress=True, timeout_seconds=10)
|
||||
code = (
|
||||
"import socket\n"
|
||||
"s = socket.socket()\n"
|
||||
"try:\n"
|
||||
" s.settimeout(2)\n"
|
||||
" s.connect(('1.1.1.1', 80))\n"
|
||||
" print('CONNECTED')\n"
|
||||
"except OSError as e:\n"
|
||||
" print('BLOCKED')\n"
|
||||
" print(type(e).__name__)\n"
|
||||
"finally:\n"
|
||||
" s.close()\n"
|
||||
)
|
||||
result = box.run(code)
|
||||
assert result.network_isolated is True
|
||||
assert "CONNECTED" not in result.stdout
|
||||
assert "BLOCKED" in result.stdout or result.exit_code != 0
|
||||
@@ -20,13 +20,13 @@ def client() -> Iterator[TestClient]:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_health_version_050(client: TestClient) -> None:
|
||||
def test_health_version_060(client: TestClient) -> None:
|
||||
resp = client.get("/health")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["status"] == "ok"
|
||||
assert body["version"] == "0.5.0"
|
||||
assert __version__ == "0.5.0"
|
||||
assert body["version"] == "0.6.0"
|
||||
assert __version__ == "0.6.0"
|
||||
|
||||
|
||||
def test_python_success(client: TestClient) -> None:
|
||||
@@ -202,6 +202,7 @@ def test_sdk_client_run_response_fields(client: TestClient) -> None:
|
||||
assert body["limits_applied"]["memory_mb"] == 64
|
||||
assert body["limits_applied"]["timeout_seconds"] == 10
|
||||
assert "oom_killed" in body
|
||||
assert "network_isolated" in body
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
@@ -229,6 +230,7 @@ def test_sdk_client_run_response_fields(client: TestClient) -> None:
|
||||
}
|
||||
assert result["limits_applied"]["memory_mb"] == 64
|
||||
assert "oom_killed" in result
|
||||
assert "network_isolated" in result
|
||||
finally:
|
||||
sdk.close()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user