pybubble 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pybubble/__cli__.py +229 -0
- pybubble/__init__.py +14 -0
- pybubble/data.py +0 -0
- pybubble/rootfs.py +79 -0
- pybubble/sandbox.py +135 -0
- pybubble-0.1.1.dist-info/METADATA +76 -0
- pybubble-0.1.1.dist-info/RECORD +10 -0
- pybubble-0.1.1.dist-info/WHEEL +4 -0
- pybubble-0.1.1.dist-info/entry_points.txt +2 -0
- pybubble-0.1.1.dist-info/licenses/LICENSE +202 -0
pybubble/__cli__.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""CLI interface for pybubble - run code in sandboxes or generate rootfs files from dockerfiles."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from pybubble.rootfs import generate_rootfs
|
|
12
|
+
from pybubble.sandbox import Sandbox
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def cmd_run(args):
|
|
16
|
+
"""Run a command in a sandbox."""
|
|
17
|
+
async def _run():
|
|
18
|
+
sandbox = Sandbox(
|
|
19
|
+
work_dir=args.work_dir,
|
|
20
|
+
rootfs=args.rootfs,
|
|
21
|
+
rootfs_path=args.rootfs_path
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Join the command parts back together
|
|
25
|
+
if not args.cmd:
|
|
26
|
+
print("Error: No command provided", file=sys.stderr)
|
|
27
|
+
return 1
|
|
28
|
+
cmd_str = " ".join(args.cmd)
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
stdout, stderr = await sandbox.run(
|
|
32
|
+
cmd_str,
|
|
33
|
+
allow_network=args.network,
|
|
34
|
+
timeout=args.timeout
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
if stdout:
|
|
38
|
+
sys.stdout.buffer.write(stdout)
|
|
39
|
+
if stderr:
|
|
40
|
+
sys.stderr.buffer.write(stderr)
|
|
41
|
+
|
|
42
|
+
return 0
|
|
43
|
+
except Exception as e:
|
|
44
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
45
|
+
return 1
|
|
46
|
+
|
|
47
|
+
return asyncio.run(_run())
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cmd_run_python(args):
|
|
51
|
+
"""Run Python code in a sandbox."""
|
|
52
|
+
async def _run():
|
|
53
|
+
sandbox = Sandbox(
|
|
54
|
+
work_dir=args.work_dir,
|
|
55
|
+
rootfs=args.rootfs,
|
|
56
|
+
rootfs_path=args.rootfs_path
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
# Read code from file or use provided code string
|
|
61
|
+
if args.file:
|
|
62
|
+
code = Path(args.file).read_text()
|
|
63
|
+
elif args.code:
|
|
64
|
+
code = args.code
|
|
65
|
+
else:
|
|
66
|
+
# Read from stdin
|
|
67
|
+
code = sys.stdin.read()
|
|
68
|
+
|
|
69
|
+
stdout, stderr = await sandbox.run_python(
|
|
70
|
+
code,
|
|
71
|
+
allow_network=args.network,
|
|
72
|
+
timeout=args.timeout
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
if stdout:
|
|
76
|
+
sys.stdout.buffer.write(stdout)
|
|
77
|
+
if stderr:
|
|
78
|
+
sys.stderr.buffer.write(stderr)
|
|
79
|
+
|
|
80
|
+
return 0
|
|
81
|
+
except Exception as e:
|
|
82
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
83
|
+
return 1
|
|
84
|
+
|
|
85
|
+
return asyncio.run(_run())
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def cmd_generate_rootfs(args):
|
|
89
|
+
"""Generate a rootfs file from a Dockerfile."""
|
|
90
|
+
dockerfile = Path(args.dockerfile)
|
|
91
|
+
output_file = Path(args.output)
|
|
92
|
+
|
|
93
|
+
if not dockerfile.exists():
|
|
94
|
+
print(f"Error: Dockerfile not found: {dockerfile}", file=sys.stderr)
|
|
95
|
+
return 1
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
generate_rootfs(dockerfile, output_file, compress_level=args.compress_level)
|
|
99
|
+
print(f"Successfully generated rootfs: {output_file}")
|
|
100
|
+
return 0
|
|
101
|
+
except Exception as e:
|
|
102
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
103
|
+
return 1
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def clear_cache(args):
|
|
107
|
+
"""Clear the cache."""
|
|
108
|
+
cache_dir = Path(os.getenv("HOME")) / ".cache" / "pybubble"
|
|
109
|
+
shutil.rmtree(cache_dir)
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main():
|
|
114
|
+
"""Main CLI entry point."""
|
|
115
|
+
parser = argparse.ArgumentParser(
|
|
116
|
+
description="Run code in sandboxes or generate rootfs files from dockerfiles",
|
|
117
|
+
prog="pybubble"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
|
121
|
+
|
|
122
|
+
# Run command subparser
|
|
123
|
+
run_parser = subparsers.add_parser("run", help="Run a shell command in a sandbox")
|
|
124
|
+
run_parser.add_argument(
|
|
125
|
+
"rootfs",
|
|
126
|
+
help="Path to rootfs tarball or URL"
|
|
127
|
+
)
|
|
128
|
+
run_parser.add_argument(
|
|
129
|
+
"cmd",
|
|
130
|
+
nargs=argparse.REMAINDER,
|
|
131
|
+
help="Shell command to run (use -- before command if it starts with -)"
|
|
132
|
+
)
|
|
133
|
+
run_parser.add_argument(
|
|
134
|
+
"--work-dir",
|
|
135
|
+
default="work",
|
|
136
|
+
help="Working directory for sandbox sessions (default: work)"
|
|
137
|
+
)
|
|
138
|
+
run_parser.add_argument(
|
|
139
|
+
"--rootfs-path",
|
|
140
|
+
help="Path to extract/cache rootfs (default: auto-generated cache path)"
|
|
141
|
+
)
|
|
142
|
+
run_parser.add_argument(
|
|
143
|
+
"--network",
|
|
144
|
+
action="store_true",
|
|
145
|
+
help="Allow network access"
|
|
146
|
+
)
|
|
147
|
+
run_parser.add_argument(
|
|
148
|
+
"--timeout",
|
|
149
|
+
type=float,
|
|
150
|
+
default=10.0,
|
|
151
|
+
help="Command timeout in seconds (default: 10.0)"
|
|
152
|
+
)
|
|
153
|
+
run_parser.set_defaults(func=cmd_run)
|
|
154
|
+
|
|
155
|
+
# Run Python subparser
|
|
156
|
+
python_parser = subparsers.add_parser("python", help="Run Python code in a sandbox")
|
|
157
|
+
python_parser.add_argument(
|
|
158
|
+
"rootfs",
|
|
159
|
+
help="Path to rootfs tarball or URL"
|
|
160
|
+
)
|
|
161
|
+
python_parser.add_argument(
|
|
162
|
+
"--code",
|
|
163
|
+
help="Python code to run (or use --file or stdin)"
|
|
164
|
+
)
|
|
165
|
+
python_parser.add_argument(
|
|
166
|
+
"--file",
|
|
167
|
+
help="Path to Python file to run"
|
|
168
|
+
)
|
|
169
|
+
python_parser.add_argument(
|
|
170
|
+
"--work-dir",
|
|
171
|
+
default="work",
|
|
172
|
+
help="Working directory for sandbox sessions (default: work)"
|
|
173
|
+
)
|
|
174
|
+
python_parser.add_argument(
|
|
175
|
+
"--rootfs-path",
|
|
176
|
+
help="Path to extract/cache rootfs (default: auto-generated cache path)"
|
|
177
|
+
)
|
|
178
|
+
python_parser.add_argument(
|
|
179
|
+
"--network",
|
|
180
|
+
action="store_true",
|
|
181
|
+
help="Allow network access"
|
|
182
|
+
)
|
|
183
|
+
python_parser.add_argument(
|
|
184
|
+
"--timeout",
|
|
185
|
+
type=float,
|
|
186
|
+
default=10.0,
|
|
187
|
+
help="Command timeout in seconds (default: 10.0)"
|
|
188
|
+
)
|
|
189
|
+
python_parser.set_defaults(func=cmd_run_python)
|
|
190
|
+
|
|
191
|
+
# Generate rootfs subparser
|
|
192
|
+
rootfs_parser = subparsers.add_parser(
|
|
193
|
+
"rootfs",
|
|
194
|
+
help="Generate a rootfs file from a Dockerfile"
|
|
195
|
+
)
|
|
196
|
+
rootfs_parser.add_argument(
|
|
197
|
+
"dockerfile",
|
|
198
|
+
help="Path to Dockerfile"
|
|
199
|
+
)
|
|
200
|
+
rootfs_parser.add_argument(
|
|
201
|
+
"output",
|
|
202
|
+
help="Output path for the generated rootfs tarball"
|
|
203
|
+
)
|
|
204
|
+
rootfs_parser.add_argument(
|
|
205
|
+
"--compress-level",
|
|
206
|
+
type=int,
|
|
207
|
+
default=6,
|
|
208
|
+
help="Compression level for the generated rootfs tarball (default: 6)"
|
|
209
|
+
)
|
|
210
|
+
rootfs_parser.set_defaults(func=cmd_generate_rootfs)
|
|
211
|
+
|
|
212
|
+
cache_clear_parser = subparsers.add_parser(
|
|
213
|
+
"clear-cache",
|
|
214
|
+
help="Clear the cache"
|
|
215
|
+
)
|
|
216
|
+
cache_clear_parser.set_defaults(func=clear_cache)
|
|
217
|
+
|
|
218
|
+
args = parser.parse_args()
|
|
219
|
+
|
|
220
|
+
if not args.command:
|
|
221
|
+
parser.print_help()
|
|
222
|
+
return 1
|
|
223
|
+
|
|
224
|
+
return args.func(args)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
if __name__ == "__main__":
|
|
228
|
+
sys.exit(main())
|
|
229
|
+
|
pybubble/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Core functionality for the pybubble package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib import metadata
|
|
6
|
+
|
|
7
|
+
from .sandbox import Sandbox
|
|
8
|
+
|
|
9
|
+
__all__ = ["__version__", "Sandbox"]
|
|
10
|
+
|
|
11
|
+
try: # pragma: no cover - exercised when installed
|
|
12
|
+
__version__ = metadata.version("pybubble")
|
|
13
|
+
except metadata.PackageNotFoundError: # pragma: no cover - local fallback
|
|
14
|
+
__version__ = "0.0.0"
|
pybubble/data.py
ADDED
|
File without changes
|
pybubble/rootfs.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
import subprocess
|
|
5
|
+
import tarfile
|
|
6
|
+
|
|
7
|
+
tarball_hash_cache: dict[Path, str] = {}
|
|
8
|
+
|
|
9
|
+
def _compute_tarball_hash(tarball_path: Path) -> str:
|
|
10
|
+
"""Compute SHA256 hash of tarball content."""
|
|
11
|
+
if tarball_path in tarball_hash_cache:
|
|
12
|
+
return tarball_hash_cache[tarball_path]
|
|
13
|
+
|
|
14
|
+
sha256 = hashlib.sha256()
|
|
15
|
+
with open(tarball_path, "rb") as f:
|
|
16
|
+
while chunk := f.read(8192):
|
|
17
|
+
sha256.update(chunk)
|
|
18
|
+
|
|
19
|
+
tarball_hash_cache[tarball_path] = sha256.hexdigest()
|
|
20
|
+
return tarball_hash_cache[tarball_path]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _get_cache_dir() -> Path:
|
|
24
|
+
"""Get the cache directory for rootfs files."""
|
|
25
|
+
home = os.getenv("HOME")
|
|
26
|
+
if home is None:
|
|
27
|
+
home = str(Path.home())
|
|
28
|
+
cache_base = Path(home) / ".cache" / "pybubble" / "rootfs"
|
|
29
|
+
return cache_base
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def setup_rootfs(rootfs: str, rootfs_path: Path | None = None) -> Path:
|
|
33
|
+
"""Sets up a reusable rootfs from a specified image tarball (local file only).
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
rootfs: Path to rootfs tarball (local file)
|
|
37
|
+
rootfs_path: Optional specific path to extract rootfs. If None, uses cache based on tarball hash.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
Path to the extracted rootfs directory.
|
|
41
|
+
"""
|
|
42
|
+
# Local file path
|
|
43
|
+
tarball_path = Path(rootfs)
|
|
44
|
+
if not tarball_path.exists():
|
|
45
|
+
raise FileNotFoundError(f"Rootfs tarball not found: {rootfs}")
|
|
46
|
+
|
|
47
|
+
# Determine if we should use cache or specific path
|
|
48
|
+
if rootfs_path is None:
|
|
49
|
+
# Use cache based on tarball hash
|
|
50
|
+
tarball_hash = _compute_tarball_hash(tarball_path)
|
|
51
|
+
# Use hash-based cache directory
|
|
52
|
+
rootfs_dir = _get_cache_dir() / tarball_hash
|
|
53
|
+
else:
|
|
54
|
+
# Use specific path provided by user
|
|
55
|
+
rootfs_dir = Path(rootfs_path)
|
|
56
|
+
|
|
57
|
+
# Check if rootfs directory already exists (cached)
|
|
58
|
+
if rootfs_dir.exists():
|
|
59
|
+
return rootfs_dir
|
|
60
|
+
|
|
61
|
+
# Extract the tarball to the rootfs directory
|
|
62
|
+
try:
|
|
63
|
+
# Create rootfs directory if it doesn't exist
|
|
64
|
+
rootfs_dir.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
|
|
66
|
+
# Extract the tarball
|
|
67
|
+
with tarfile.open(tarball_path, "r:*") as tar:
|
|
68
|
+
tar.extractall(rootfs_dir)
|
|
69
|
+
except Exception as e:
|
|
70
|
+
raise RuntimeError(f"Failed to extract rootfs tarball: {e}") from e
|
|
71
|
+
|
|
72
|
+
return rootfs_dir
|
|
73
|
+
|
|
74
|
+
def generate_rootfs(dockerfile: Path, output_file: Path, compress_level: int = 6) -> None:
|
|
75
|
+
"""Generates a rootfs from a Dockerfile. Docker must be installed for this to work."""
|
|
76
|
+
subprocess.run(["docker", "rm", "-f", "pybubble_rootfs"], check=True)
|
|
77
|
+
subprocess.run(["docker", "build", "-t", "pybubble_rootfs", "-f", dockerfile, "."], check=True)
|
|
78
|
+
subprocess.run(["docker", "create", "--name", "pybubble_rootfs", "pybubble_rootfs"], check=True)
|
|
79
|
+
subprocess.run(["bash", "-c", f"docker export pybubble_rootfs | gzip -{compress_level} > {output_file}"], check=True)
|
pybubble/sandbox.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import subprocess
|
|
4
|
+
import tempfile
|
|
5
|
+
import shlex
|
|
6
|
+
|
|
7
|
+
from pybubble.rootfs import setup_rootfs
|
|
8
|
+
|
|
9
|
+
def is_system_compatible() -> bool:
|
|
10
|
+
"""Checks if the system is Linux-based and has bubblewrap installed."""
|
|
11
|
+
try:
|
|
12
|
+
result = subprocess.run(
|
|
13
|
+
["bwrap", "--help"],
|
|
14
|
+
stdout=subprocess.PIPE,
|
|
15
|
+
stderr=subprocess.PIPE,
|
|
16
|
+
timeout=5.0
|
|
17
|
+
)
|
|
18
|
+
# If there's an error message in stderr (like "command not found"), bwrap is not installed
|
|
19
|
+
if result.stderr and b"command not found" in result.stderr.lower():
|
|
20
|
+
return False
|
|
21
|
+
# If the command succeeded or stderr is empty/minimal, bwrap is installed
|
|
22
|
+
return True
|
|
23
|
+
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Sandbox:
|
|
28
|
+
def __init__(self, rootfs: str | Path, work_dir: str | Path | None = None, rootfs_path: str | Path | None = None):
|
|
29
|
+
"""Creates a sandbox from the specified rootfs tarball, expected to be in the form of a tarball or compressed tarball.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
rootfs: Path to rootfs tarball
|
|
33
|
+
work_dir: Path to writable working directory for sandbox sessions. If None, uses a unique directory in `/tmp` (default: None)
|
|
34
|
+
rootfs_path: Path to extract/cache rootfs. If None, uses cache dir based on tarball hash (default: None)
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
# Create temporary directory if work_dir is not provided
|
|
38
|
+
if not is_system_compatible():
|
|
39
|
+
raise RuntimeError("System is not compatible with pybubble. Please ensure bubblewrap is installed and in your PATH.")
|
|
40
|
+
|
|
41
|
+
if work_dir is None:
|
|
42
|
+
self._temp_dir = tempfile.TemporaryDirectory(dir="/tmp")
|
|
43
|
+
self.work_dir = Path(self._temp_dir.name)
|
|
44
|
+
self.persist_session = False
|
|
45
|
+
else:
|
|
46
|
+
self._temp_dir = None
|
|
47
|
+
self.work_dir = Path(work_dir)
|
|
48
|
+
self.persist_session = True
|
|
49
|
+
|
|
50
|
+
# Ensure work_dir exists
|
|
51
|
+
Path.mkdir(self.work_dir, parents=True, exist_ok=True)
|
|
52
|
+
|
|
53
|
+
# Temp directory to mount at /tmp
|
|
54
|
+
self.tmp_dir = tempfile.TemporaryDirectory(dir="/tmp")
|
|
55
|
+
|
|
56
|
+
# Convert rootfs_path to Path if provided, otherwise None (which triggers caching)
|
|
57
|
+
rootfs_path_obj = Path(rootfs_path) if rootfs_path is not None else None
|
|
58
|
+
|
|
59
|
+
self.rootfs_dir = setup_rootfs(str(rootfs), rootfs_path_obj)
|
|
60
|
+
|
|
61
|
+
async def run(self, command: str, allow_network: bool = False, timeout: float = 10.0) -> tuple[bytes, bytes]:
|
|
62
|
+
"""Runs a shell command in the sandbox. Returns (stdout, stderr) if the command succeeds, otherwise raises an exception.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
command: Shell command to run
|
|
66
|
+
allow_network: Whether to allow network access
|
|
67
|
+
timeout: Command timeout in seconds
|
|
68
|
+
"""
|
|
69
|
+
built_command: list[str] = [
|
|
70
|
+
"bwrap",
|
|
71
|
+
"--unshare-all",
|
|
72
|
+
"--die-with-parent",
|
|
73
|
+
# Make sure we're using the 'sandbox' user.
|
|
74
|
+
"--unshare-user",
|
|
75
|
+
"--uid", "1000",
|
|
76
|
+
# Bind root fs and work dir
|
|
77
|
+
"--ro-bind", shlex.quote(str(self.rootfs_dir.absolute())), "/",
|
|
78
|
+
"--bind", shlex.quote(str(self.work_dir.absolute())), "/home/sandbox",
|
|
79
|
+
# Bind new /dev/ and /proc/ dirs - must happen after rootfs mount
|
|
80
|
+
"--dev", "/dev",
|
|
81
|
+
"--proc", "/proc",
|
|
82
|
+
# Mount the temp dir at /tmp. We can't use --tmpfs because it doesn't persist between invocations of bwrap.
|
|
83
|
+
"--bind", shlex.quote(str(self.tmp_dir.name)), "/tmp",
|
|
84
|
+
# Set home directory and path
|
|
85
|
+
"--setenv", "HOME", "/home/sandbox",
|
|
86
|
+
"--setenv", "PATH", "/usr/bin:/bin:/usr/local/bin",
|
|
87
|
+
"--chdir", "/home/sandbox",
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
if allow_network:
|
|
91
|
+
# Bind system DNS config and allow network access
|
|
92
|
+
built_command.extend(["--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf", "--share-net"])
|
|
93
|
+
|
|
94
|
+
built_command.extend(
|
|
95
|
+
["bash", "-c", command]
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
process = await asyncio.create_subprocess_exec(
|
|
99
|
+
*built_command,
|
|
100
|
+
stdout=subprocess.PIPE,
|
|
101
|
+
stderr=subprocess.PIPE
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
stdout, stderr = await asyncio.wait_for(
|
|
106
|
+
process.communicate(),
|
|
107
|
+
timeout=timeout
|
|
108
|
+
)
|
|
109
|
+
except asyncio.TimeoutError:
|
|
110
|
+
process.kill()
|
|
111
|
+
await process.wait()
|
|
112
|
+
raise TimeoutError(f"Command execution exceeded {timeout} seconds")
|
|
113
|
+
|
|
114
|
+
return stdout or b"", stderr or b""
|
|
115
|
+
|
|
116
|
+
async def run_python(self, code: str, allow_network: bool = False, timeout: float = 10.0) -> tuple[bytes, bytes]:
|
|
117
|
+
"""Runs a Python script in the sandbox. Returns (stdout, stderr) if the code succeeds, otherwise raises an exception.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
code: Python code to run
|
|
121
|
+
allow_network: Whether to allow network access
|
|
122
|
+
timeout: Command timeout in seconds
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
script_path = self.work_dir / "script.py"
|
|
126
|
+
with open(script_path, "w") as f:
|
|
127
|
+
f.write(code)
|
|
128
|
+
|
|
129
|
+
return await self.run("python script.py", allow_network, timeout)
|
|
130
|
+
|
|
131
|
+
def __del__(self):
|
|
132
|
+
"""Cleanup the sandbox work directory if it's temporary."""
|
|
133
|
+
# Cleanup temporary directory if it was created and persistence is disabled
|
|
134
|
+
if self._temp_dir is not None and not self.persist_session:
|
|
135
|
+
self._temp_dir.cleanup()
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pybubble
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: A Python package for running sandboxed code.
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Requires-Python: >=3.12
|
|
7
|
+
Provides-Extra: test
|
|
8
|
+
Requires-Dist: pytest-asyncio>=0.25.2; extra == 'test'
|
|
9
|
+
Requires-Dist: pytest>=8.0; extra == 'test'
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# pybubble
|
|
13
|
+
|
|
14
|
+
A simple wrapper around `bwrap` to create sandbox environments for executing code. It works without Docker or other daemon-based container runtimes, using shared read-only root filesystems for quick (1-2ms) setup times.
|
|
15
|
+
|
|
16
|
+
While these environments are sandboxed and provide protection from accidental modification of your host system by overzealous LLMs, **pybubble is not an acceptable substitute for virtualization when running untrusted code**. If you are giving untrusted people access to this, either directly or via an LLM frontend, consider using more production-ready sandboxing or virtualization tools with pybubble just isolating environment state.
|
|
17
|
+
|
|
18
|
+
Feel free to submit bug reports and pull requests via GitHub, but note that Arcee is not committing to long-term maintenence of this software. This is just a small library I built in my spare time and thought everyone else would find useful.
|
|
19
|
+
|
|
20
|
+
Due to relying on Linux kernel features to operate, pybubble is not compatible with macOS or Windows.
|
|
21
|
+
|
|
22
|
+
## Setup
|
|
23
|
+
|
|
24
|
+
Install `bwrap`. On Ubuntu, do:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
sudo apt-get install bubblewrap
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Then, add `pybubble` to your project.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
uv add pybubble
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Root filesystem archives
|
|
37
|
+
|
|
38
|
+
If all you need is basic Python code execution, consider using the provided root filesystem archive under our GitHub release. It comes preinstalled with:
|
|
39
|
+
|
|
40
|
+
- Python
|
|
41
|
+
- uv
|
|
42
|
+
- bash
|
|
43
|
+
- ripgrep
|
|
44
|
+
- cURL & wget
|
|
45
|
+
- numpy
|
|
46
|
+
- pandas
|
|
47
|
+
- httpx & requests
|
|
48
|
+
- pillow
|
|
49
|
+
- ImageMagick
|
|
50
|
+
|
|
51
|
+
If you need more tools or want to run a leaner environment, follow [this guide](docs/build-rootfs.md) to build one yourself.
|
|
52
|
+
|
|
53
|
+
## Run code
|
|
54
|
+
|
|
55
|
+
Create a sandbox by doing:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from pybubble import Sandbox
|
|
59
|
+
import asyncio
|
|
60
|
+
|
|
61
|
+
async def main():
|
|
62
|
+
s = Sandbox("path/to/rootfs.tgz")
|
|
63
|
+
|
|
64
|
+
stdout, stderr = await s.run("ping -c 1 google.com", allow_network=True)
|
|
65
|
+
|
|
66
|
+
print(stdout.decode("utf-8")) # ping output
|
|
67
|
+
|
|
68
|
+
stdout, stderr = await s.run_python("print('hello, world')", timeout=5.0)
|
|
69
|
+
|
|
70
|
+
print(stdout.decode("utf-8")) # "hello, world"
|
|
71
|
+
|
|
72
|
+
if __name__ == "__main__":
|
|
73
|
+
asyncio.run(main())
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
To learn more about the features available in `Sandbox`, see [this page](docs/sandbox.md).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
pybubble/__cli__.py,sha256=18128AFGghY9ikPCoswl1imyVJz4F8W234aE15UYBIw,6344
|
|
2
|
+
pybubble/__init__.py,sha256=4nKJ3TUQ6b1iX8mfh9bSF7Z2sKt9GnCyhzRurNKzXQA,388
|
|
3
|
+
pybubble/data.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
pybubble/rootfs.py,sha256=BY2HN4ljc0t-2zzKAYpKivBmAmOVqa9fzdO_lqkSRlM,2890
|
|
5
|
+
pybubble/sandbox.py,sha256=X9ZS3tvW3X8hOzTCJ-nxJW5iuDay4WcpPVF4aQyqVDU,5619
|
|
6
|
+
pybubble-0.1.1.dist-info/METADATA,sha256=MOWcE-RJivAmnPQHcCmdWpBBaM3bPXud4KcwW7fMlow,2457
|
|
7
|
+
pybubble-0.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
8
|
+
pybubble-0.1.1.dist-info/entry_points.txt,sha256=1wvtl7t5bn0PfuCioGYlQVAj6YH9rN6iS-5yzLvnBWs,51
|
|
9
|
+
pybubble-0.1.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
10
|
+
pybubble-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|