tsugite-sandbox 0.17.0__tar.gz

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.
@@ -0,0 +1,184 @@
1
+ # ---> Python
2
+ # Byte-compiled / optimized / DLL files
3
+ __pycache__/
4
+ *.py[cod]
5
+ *$py.class
6
+
7
+ # C extensions
8
+ *.so
9
+
10
+ # Distribution / packaging
11
+ .Python
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ #Pipfile.lock
97
+
98
+ # poetry
99
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103
+ #poetry.lock
104
+
105
+ # pdm
106
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107
+ #pdm.lock
108
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109
+ # in version control.
110
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
111
+ .pdm.toml
112
+ .pdm-python
113
+ .pdm-build/
114
+
115
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116
+ __pypackages__/
117
+
118
+ # Celery stuff
119
+ celerybeat-schedule
120
+ celerybeat.pid
121
+
122
+ # SageMath parsed files
123
+ *.sage.py
124
+
125
+ # Environments
126
+ .env
127
+ .venv
128
+ env/
129
+ venv/
130
+ ENV/
131
+ env.bak/
132
+ venv.bak/
133
+
134
+ # Spyder project settings
135
+ .spyderproject
136
+ .spyproject
137
+
138
+ # Rope project settings
139
+ .ropeproject
140
+
141
+ # mkdocs documentation
142
+ /site
143
+
144
+ # mypy
145
+ .mypy_cache/
146
+ .dmypy.json
147
+ dmypy.json
148
+
149
+ # Pyre type checker
150
+ .pyre/
151
+
152
+ # pytype static type analyzer
153
+ .pytype/
154
+
155
+ # Cython debug symbols
156
+ cython_debug/
157
+
158
+ # PyCharm
159
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
162
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163
+ #.idea/
164
+
165
+ .env
166
+ .env
167
+ benchmark_results/
168
+ test_output/
169
+ .claude/settings.local.json
170
+ std*.txt
171
+ secrets/*
172
+
173
+
174
+ # TODO: temp - I need to clean up the docs
175
+ docs-old/
176
+ docs/design/
177
+ examples/*
178
+ !examples/tsugite-example-plugin/
179
+ agents/
180
+ .claude/
181
+ .tsugite/
182
+ benchmarks/
183
+ docker-compose.test.yml
184
+ #### TODO ^^^
@@ -0,0 +1,6 @@
1
+ Metadata-Version: 2.4
2
+ Name: tsugite-sandbox
3
+ Version: 0.17.0
4
+ Summary: Tsugite plugin: bubblewrap sandbox backend (default-installed)
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: tsugite-cli==0.17.0
@@ -0,0 +1,25 @@
1
+ [project]
2
+ name = "tsugite-sandbox"
3
+ version = "0.17.0"
4
+ description = "Tsugite plugin: bubblewrap sandbox backend (default-installed)"
5
+ requires-python = ">=3.11"
6
+ dependencies = ["tsugite-cli==0.17.0"]
7
+
8
+ [project.entry-points."tsugite.sandbox"]
9
+ bwrap = "tsugite_sandbox:BubblewrapSandbox"
10
+
11
+ [build-system]
12
+ requires = ["hatchling"]
13
+ build-backend = "hatchling.build"
14
+
15
+ [tool.hatch.build.targets.wheel]
16
+ packages = ["tsugite_sandbox"]
17
+
18
+ [tool.hatch.build.targets.sdist]
19
+ include = [
20
+ "/tsugite_sandbox",
21
+ "/pyproject.toml",
22
+ ]
23
+
24
+ [tool.uv.sources]
25
+ tsugite-cli = { workspace = true }
@@ -0,0 +1,292 @@
1
+ """Tsugite plugin: bubblewrap (bwrap) sandbox backend.
2
+
3
+ Builds bwrap command lines for isolating agent subprocess execution with filesystem
4
+ restrictions and network namespace isolation. Registered under the `tsugite.sandbox`
5
+ entry-point group as `bwrap`; core resolves it via `tsugite.core.sandbox.get_sandbox_class`.
6
+ """
7
+
8
+ import os
9
+ import shlex
10
+ import shutil
11
+ import sys
12
+ import textwrap
13
+ from pathlib import Path
14
+ from typing import List, Optional
15
+
16
+ from tsugite.core.sandbox import SandboxConfig
17
+
18
+ # bwrap otherwise inherits the parent's full environment (API keys, tokens, ssh-agent
19
+ # socket, ...). We --clearenv and re-add only this safe set, so agent code in the sandbox
20
+ # can reach secrets only through the allowlisted, masked get_secret tool.
21
+ _ENV_ALLOWLIST = (
22
+ "PATH",
23
+ "HOME",
24
+ "USER",
25
+ "LOGNAME",
26
+ "TERM",
27
+ "TZ",
28
+ "LANG",
29
+ "LANGUAGE",
30
+ "PYTHONPATH",
31
+ "PYTHONHOME",
32
+ "PYTHONIOENCODING",
33
+ "PYTHONDONTWRITEBYTECODE",
34
+ "VIRTUAL_ENV",
35
+ "SSL_CERT_FILE",
36
+ "SSL_CERT_DIR",
37
+ "REQUESTS_CA_BUNDLE",
38
+ )
39
+
40
+ # TCP->UDS bridge script: listens on localhost, forwards to UDS proxy socket.
41
+ # Runs as a background process inside the sandbox so HTTP_PROXY works.
42
+ _TCP_UDS_BRIDGE = textwrap.dedent("""\
43
+ import socket, threading, sys
44
+ PROXY_SOCK = '/run/proxy.sock'
45
+ LISTEN_PORT = 12345
46
+
47
+ def handle(client):
48
+ try:
49
+ upstream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
50
+ upstream.connect(PROXY_SOCK)
51
+ def relay(src, dst):
52
+ try:
53
+ while True:
54
+ data = src.recv(8192)
55
+ if not data:
56
+ break
57
+ dst.sendall(data)
58
+ except Exception:
59
+ pass
60
+ finally:
61
+ try: dst.shutdown(socket.SHUT_WR)
62
+ except Exception: pass
63
+ t1 = threading.Thread(target=relay, args=(client, upstream), daemon=True)
64
+ t2 = threading.Thread(target=relay, args=(upstream, client), daemon=True)
65
+ t1.start(); t2.start()
66
+ t1.join(); t2.join()
67
+ except Exception:
68
+ pass
69
+ finally:
70
+ client.close()
71
+
72
+ srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
73
+ srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
74
+ srv.bind(('127.0.0.1', LISTEN_PORT))
75
+ srv.listen(16)
76
+ while True:
77
+ c, _ = srv.accept()
78
+ threading.Thread(target=handle, args=(c,), daemon=True).start()
79
+ """)
80
+
81
+ # SSH ProxyCommand helper: connects to the HTTP CONNECT proxy to tunnel SSH.
82
+ # Usage: ssh -o ProxyCommand='python3 _ssh_proxy.py %h %p' user@host
83
+ _SSH_PROXY_CONNECT = textwrap.dedent("""\
84
+ import socket, sys
85
+ host, port = sys.argv[1], sys.argv[2]
86
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
87
+ s.connect(('127.0.0.1', 12345))
88
+ s.sendall(f'CONNECT {host}:{port} HTTP/1.1\\r\\nHost: {host}:{port}\\r\\n\\r\\n'.encode())
89
+ resp = b''
90
+ while b'\\r\\n\\r\\n' not in resp:
91
+ resp += s.recv(4096)
92
+ if b'200' not in resp.split(b'\\r\\n')[0]:
93
+ sys.exit(1)
94
+ import os, select
95
+ while True:
96
+ r, _, _ = select.select([sys.stdin.buffer, s], [], [])
97
+ if sys.stdin.buffer in r:
98
+ data = os.read(sys.stdin.buffer.fileno(), 8192)
99
+ if not data: break
100
+ s.sendall(data)
101
+ if s in r:
102
+ data = s.recv(8192)
103
+ if not data: break
104
+ sys.stdout.buffer.write(data)
105
+ sys.stdout.buffer.flush()
106
+ """)
107
+
108
+
109
+ class BubblewrapSandbox:
110
+ """Wraps a command with bubblewrap for filesystem and network isolation.
111
+
112
+ Args:
113
+ config: Sandbox configuration
114
+ proxy_socket: Path to the HTTP proxy Unix domain socket
115
+ workspace_dir: Working directory for the sandboxed process
116
+ state_dir: Directory for harness temp files (read-write)
117
+ """
118
+
119
+ def __init__(
120
+ self,
121
+ config: SandboxConfig,
122
+ proxy_socket: Optional[Path] = None,
123
+ workspace_dir: Optional[Path] = None,
124
+ state_dir: Optional[Path] = None,
125
+ ):
126
+ self.config = config
127
+ self.proxy_socket = proxy_socket
128
+ self.workspace_dir = workspace_dir or Path.cwd()
129
+ self.state_dir = state_dir
130
+
131
+ @property
132
+ def _use_proxy(self) -> bool:
133
+ """Whether to set up network proxy (socket provided and network not fully disabled)."""
134
+ return bool(self.proxy_socket and not self.config.no_network)
135
+
136
+ def build_command(self, inner_cmd: List[str]) -> List[str]:
137
+ """Wrap inner command with bwrap arguments.
138
+
139
+ Args:
140
+ inner_cmd: The command to run inside the sandbox
141
+
142
+ Returns:
143
+ Full command list starting with 'bwrap'
144
+ """
145
+ cmd = ["bwrap"]
146
+
147
+ cmd += ["--unshare-pid", "--die-with-parent"]
148
+ if self.config.no_network or self.proxy_socket:
149
+ cmd += ["--unshare-net"]
150
+
151
+ # Default-deny the environment. Set the XDG defaults first (isolated, writable tmpfs
152
+ # dirs - otherwise --clearenv drops XDG_* and in-child tools fall back to the operator's
153
+ # real, unbound, read-only home). Then re-add the safe allowlist plus any names the
154
+ # operator opted into via config.pass_env (values read from the parent env, so secret
155
+ # values never live in config). The allowlist/pass_env pass comes last, so passing an
156
+ # XDG var through naturally overrides its default (bwrap --setenv is last-wins).
157
+ cmd += [
158
+ "--clearenv",
159
+ "--setenv",
160
+ "XDG_CONFIG_HOME",
161
+ "/tmp/.config",
162
+ "--setenv",
163
+ "XDG_CACHE_HOME",
164
+ "/tmp/.cache",
165
+ "--setenv",
166
+ "XDG_DATA_HOME",
167
+ "/tmp/.local/share",
168
+ "--setenv",
169
+ "XDG_STATE_HOME",
170
+ "/tmp/.local/state",
171
+ ]
172
+ for _k, _v in os.environ.items():
173
+ if _k in _ENV_ALLOWLIST or _k in self.config.pass_env or _k.startswith("LC_"):
174
+ cmd += ["--setenv", _k, _v]
175
+
176
+ # Basic filesystem
177
+ cmd += ["--tmpfs", "/tmp", "--proc", "/proc", "--dev", "/dev"]
178
+
179
+ # System read-only binds
180
+ for sys_dir in ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc/ssl", "/etc/resolv.conf"]:
181
+ p = Path(sys_dir)
182
+ if p.exists():
183
+ cmd += ["--ro-bind", sys_dir, sys_dir]
184
+
185
+ # CA certificates: resolve symlinks to find the real path (varies by distro).
186
+ # Check both bundle files and the cert.pem symlink (Arch/EndeavourOS uses
187
+ # /etc/ssl/cert.pem -> /etc/ca-certificates/extracted/tls-ca-bundle.pem).
188
+ for cert_path in [
189
+ "/etc/ssl/cert.pem",
190
+ "/etc/ssl/certs/ca-certificates.crt",
191
+ "/etc/ssl/certs/ca-bundle.crt",
192
+ "/etc/pki/tls/certs/ca-bundle.crt",
193
+ ]:
194
+ p = Path(cert_path)
195
+ if p.exists():
196
+ real = p.resolve().parent
197
+ if real.exists() and not any(str(real).startswith(d) for d in ["/usr", "/etc/ssl"]):
198
+ cmd += ["--ro-bind", str(real), str(real)]
199
+ break
200
+
201
+ # Python venv (read-only)
202
+ venv_path = Path(sys.prefix)
203
+ if venv_path.exists():
204
+ cmd += ["--ro-bind", str(venv_path), str(venv_path)]
205
+
206
+ # If venv is a symlink or different from base prefix, bind base too
207
+ base_prefix = Path(sys.base_prefix)
208
+ if base_prefix != venv_path and base_prefix.exists():
209
+ cmd += ["--ro-bind", str(base_prefix), str(base_prefix)]
210
+
211
+ # Editable installs: venv .pth files reference the project source directory.
212
+ # Bind all sys.path entries so imports work inside the sandbox.
213
+ bound = {str(venv_path), str(base_prefix), str(self.workspace_dir)}
214
+ for p in sys.path:
215
+ if not p or p in bound:
216
+ continue
217
+ pp = Path(p)
218
+ if pp.exists() and str(pp) not in bound:
219
+ cmd += ["--ro-bind", str(pp), str(pp)]
220
+ bound.add(str(pp))
221
+
222
+ # Project/workspace directory (read-write)
223
+ cmd += ["--bind", str(self.workspace_dir), str(self.workspace_dir)]
224
+
225
+ # State directory for harness files (read-write)
226
+ if self.state_dir:
227
+ cmd += ["--bind", str(self.state_dir), str(self.state_dir)]
228
+
229
+ if self._use_proxy:
230
+ cmd += ["--ro-bind", str(self.proxy_socket), "/run/proxy.sock"]
231
+
232
+ # Extra binds
233
+ for path in self.config.extra_ro_binds:
234
+ if path.exists():
235
+ cmd += ["--ro-bind", str(path), str(path)]
236
+ for path in self.config.extra_rw_binds:
237
+ if path.exists():
238
+ cmd += ["--bind", str(path), str(path)]
239
+
240
+ # Working directory
241
+ cmd += ["--chdir", str(self.workspace_dir)]
242
+
243
+ if self._use_proxy:
244
+ scripts_dir = self.state_dir or Path("/tmp")
245
+
246
+ # Write bridge + SSH proxy scripts (state_dir is bind-mounted into sandbox)
247
+ bridge_path = scripts_dir / "_bridge.py"
248
+ bridge_path.write_text(_TCP_UDS_BRIDGE)
249
+ ssh_proxy_path = scripts_dir / "_ssh_proxy.py"
250
+ ssh_proxy_path.write_text(_SSH_PROXY_CONNECT)
251
+
252
+ cmd += [
253
+ "--setenv",
254
+ "HTTP_PROXY",
255
+ "http://127.0.0.1:12345",
256
+ "--setenv",
257
+ "HTTPS_PROXY",
258
+ "http://127.0.0.1:12345",
259
+ # Lowercase variants too (curl/libcurl and many tools only read these).
260
+ "--setenv",
261
+ "http_proxy",
262
+ "http://127.0.0.1:12345",
263
+ "--setenv",
264
+ "https_proxy",
265
+ "http://127.0.0.1:12345",
266
+ # Don't route loopback (incl. the in-sandbox bridge) through the egress proxy.
267
+ "--setenv",
268
+ "NO_PROXY",
269
+ "localhost,127.0.0.1,::1",
270
+ "--setenv",
271
+ "no_proxy",
272
+ "localhost,127.0.0.1,::1",
273
+ "--setenv",
274
+ "GIT_SSH_COMMAND",
275
+ f"ssh -o StrictHostKeyChecking=accept-new -o ProxyCommand='python3 {ssh_proxy_path} %h %p'",
276
+ ]
277
+ actual_cmd = shlex.join(inner_cmd)
278
+ # Start bridge in background, wait for it to bind, then run harness
279
+ cmd += [
280
+ "sh",
281
+ "-c",
282
+ f"python3 {bridge_path} & sleep 0.1; exec {actual_cmd}",
283
+ ]
284
+ else:
285
+ cmd += inner_cmd
286
+
287
+ return cmd
288
+
289
+ @staticmethod
290
+ def check_available() -> bool:
291
+ """Check if bwrap is installed."""
292
+ return shutil.which("bwrap") is not None