File size: 8,407 Bytes
4732653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474686b
4732653
474686b
 
4732653
474686b
 
 
 
 
 
 
 
4732653
474686b
4732653
 
 
 
474686b
 
4732653
474686b
4732653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import asyncio
import shutil
import subprocess
import time
from dataclasses import dataclass
from pathlib import Path

from sysadmin_env.overlayfs import OverlayFSManager


@dataclass
class CommandResult:
    stdout: str = ""
    stderr: str = ""
    exit_code: int = -1
    execution_time: float = 0.0
    timed_out: bool = False


class Sandbox:
    _HOST_RO_BINDS = [
        "/usr/bin",
        "/usr/sbin",
        "/usr/lib",
        "/usr/lib64",
        "/usr/share",
        "/bin",
        "/sbin",
        "/lib",
        "/lib64",
        "/etc/alternatives",
        "/etc/ld.so.cache",
    ]

    def __init__(
        self,
        lowerdir: str | Path,
        *,
        timeout: float = 30.0,
        isolate_network: bool = True,
        overlay_base_dir: str | None = None,
    ):
        self._lowerdir = Path(lowerdir).resolve()
        self._timeout = timeout
        self._isolate_network = isolate_network
        self._overlay = OverlayFSManager(base_dir=overlay_base_dir)
        self._created = False
        self._destroyed = False

    @property
    def is_created(self) -> bool:
        return self._created

    @property
    def is_destroyed(self) -> bool:
        return self._destroyed

    @property
    def overlay(self) -> OverlayFSManager:
        return self._overlay

    @property
    def merged_root(self) -> Path:
        return Path("/")

    @property
    def state_root(self) -> Path | None:
        return self._overlay.merged

    def create(self) -> None:
        if self._created:
            raise RuntimeError("sandbox already created")
        if self._destroyed:
            raise RuntimeError("sandbox has been destroyed and cannot be recreated")

        print("sandbox verify bwrap start")
        self._verify_bwrap_available()
        print("sandbox verify bwrap complete")
        print(f"sandbox create stack {self._lowerdir}")
        self._overlay.create_stack(self._lowerdir)
        print("sandbox overlay mount start")
        try:
            self._overlay.mount()
        except Exception as exc:
            print(f"sandbox overlay mount failed {type(exc).__name__.lower()}")
            raise
        print("sandbox overlay mount complete")
        print("sandbox runtime layout start")
        self._ensure_runtime_layout()
        print("sandbox runtime layout complete")
        self._created = True
        print("sandbox created")

    def _verify_bwrap_available(self) -> None:
        bwrap_bin = shutil.which("bwrap")
        if bwrap_bin is None:
            raise FileNotFoundError("bwrap binary not found in path")
        print(f"sandbox bwrap found {bwrap_bin}")

    def _ensure_runtime_layout(self) -> None:
        if self._overlay.merged is None:
            raise RuntimeError("overlay stack not ready")

        for relative in [
            Path("bin"),
            Path("sbin"),
            Path("lib"),
            Path("lib64"),
            Path("usr"),
            Path("usr/bin"),
            Path("usr/sbin"),
            Path("usr/lib"),
            Path("usr/lib64"),
            Path("usr/share"),
            Path("usr/local"),
            Path("usr/local/bin"),
            Path("etc"),
            Path("etc/alternatives"),
            Path("var"),
            Path("var/tmp"),
            Path("tmp"),
            Path("dev"),
            Path("proc"),
            Path("run"),
            Path("root"),
            Path("home"),
        ]:
            (self._overlay.merged / relative).mkdir(parents=True, exist_ok=True)

    def _build_bwrap_command(self, command: str) -> list[str]:
        if self._overlay.merged is None:
            raise RuntimeError("sandbox storage not ready")

        merged = str(self._overlay.merged)

        cmd = [
            "bwrap",
            "--bind",
            merged,
            "/",
            "--proc",
            "/proc",
            "--dev",
            "/dev",
            "--tmpfs",
            "/tmp",
            "--unshare-pid",
            "--unshare-uts",
            "--unshare-cgroup-try",
            "--die-with-parent",
            "--hostname",
            "sandbox",
            "--clearenv",
            "--setenv",
            "PATH",
            "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
            "--setenv",
            "HOME",
            "/root",
            "--setenv",
            "TERM",
            "xterm",
            "--uid",
            "0",
            "--gid",
            "0",
            "--cap-drop",
            "ALL",
        ]

        if self._isolate_network:
            cmd.append("--unshare-net")

        for host_path in self._HOST_RO_BINDS:
            if Path(host_path).exists():
                cmd.extend(["--ro-bind", host_path, host_path])

        cmd.extend([
            "--chdir",
            "/",
            "--",
            "/bin/sh",
            "-c",
            command,
        ])

        return cmd

    def execute(self, command: str, *, timeout: float | None = None) -> CommandResult:
        if not self._created:
            raise RuntimeError("sandbox not created call create first")
        if self._destroyed:
            raise RuntimeError("sandbox has been destroyed")

        effective_timeout = timeout if timeout is not None else self._timeout
        bwrap_cmd = self._build_bwrap_command(command)

        result = CommandResult()
        start = time.perf_counter()

        try:
            proc = subprocess.run(
                bwrap_cmd,
                capture_output=True,
                text=True,
                timeout=effective_timeout,
            )
            result.stdout = proc.stdout
            result.stderr = proc.stderr
            result.exit_code = proc.returncode
        except subprocess.TimeoutExpired as exc:
            result.stdout = exc.stdout if isinstance(exc.stdout, str) else (exc.stdout or b"").decode("utf-8", errors="replace")
            result.stderr = exc.stderr if isinstance(exc.stderr, str) else (exc.stderr or b"").decode("utf-8", errors="replace")
            result.exit_code = -1
            result.timed_out = True

        result.execution_time = time.perf_counter() - start
        return result

    async def execute_async(self, command: str, *, timeout: float | None = None) -> CommandResult:
        if not self._created:
            raise RuntimeError("sandbox not created call create first")
        if self._destroyed:
            raise RuntimeError("sandbox has been destroyed")

        effective_timeout = timeout if timeout is not None else self._timeout
        bwrap_cmd = self._build_bwrap_command(command)

        result = CommandResult()
        start = time.perf_counter()

        try:
            proc = await asyncio.create_subprocess_exec(
                *bwrap_cmd,
                stdout=asyncio.subprocess.PIPE,
                stderr=asyncio.subprocess.PIPE,
            )
            try:
                stdout_bytes, stderr_bytes = await asyncio.wait_for(
                    proc.communicate(),
                    timeout=effective_timeout,
                )
                result.stdout = stdout_bytes.decode("utf-8", errors="replace")
                result.stderr = stderr_bytes.decode("utf-8", errors="replace")
                result.exit_code = proc.returncode
            except asyncio.TimeoutError:
                proc.kill()
                await proc.wait()
                result.exit_code = -1
                result.timed_out = True
        except OSError as exc:
            result.stderr = str(exc)
            result.exit_code = -1

        result.execution_time = time.perf_counter() - start
        return result

    def reset(self) -> float:
        if not self._created:
            raise RuntimeError("sandbox not created call create first")
        if self._destroyed:
            raise RuntimeError("sandbox has been destroyed")

        latency = self._overlay.reset()
        self._ensure_runtime_layout()
        print(f"sandbox reset {latency:.1f}ms")
        return latency

    def destroy(self) -> None:
        if self._destroyed:
            return

        self._overlay.cleanup()
        self._created = False
        self._destroyed = True
        print("sandbox destroyed")

    def __enter__(self):
        self.create()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.destroy()
        return False