@useconvoy/cli 0.108.0 → 0.113.1
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.
- package/README.md +4 -2
- package/dist/src/agent/app/runner.d.ts +6 -0
- package/dist/src/agent/app/runner.js +20 -2
- package/dist/src/agent/app/runner.js.map +1 -1
- package/dist/src/agent/runtimes/registry.js +2 -1
- package/dist/src/agent/runtimes/registry.js.map +1 -1
- package/dist/src/commands/connect/workflow.js +15 -4
- package/dist/src/commands/connect/workflow.js.map +1 -1
- package/dist/src/commands/environment/command.d.ts +3 -0
- package/dist/src/commands/environment/command.js +5 -5
- package/dist/src/commands/environment/command.js.map +1 -1
- package/dist/src/commands/environment/index.d.ts +13 -0
- package/dist/src/commands/environment/index.js +4 -0
- package/dist/src/commands/environment/index.js.map +1 -1
- package/dist/src/commands/environment/projects.d.ts +1 -1
- package/dist/src/commands/environment/validators.d.ts +1 -6
- package/dist/src/commands/environment/validators.js +1 -1
- package/dist/src/commands/environment/validators.js.map +1 -1
- package/dist/src/commands/environment/workflow.d.ts +1 -2
- package/dist/src/commands/environment/workflow.js +0 -5
- package/dist/src/commands/environment/workflow.js.map +1 -1
- package/dist/src/commands/keys/workflow.d.ts +2 -0
- package/dist/src/commands/project/command.js +36 -4
- package/dist/src/commands/project/command.js.map +1 -1
- package/dist/src/commands/project/formatters.d.ts +30 -0
- package/dist/src/commands/project/formatters.js +77 -0
- package/dist/src/commands/project/formatters.js.map +1 -0
- package/dist/src/commands/project/launcher.d.ts +21 -3
- package/dist/src/commands/project/launcher.js +37 -15
- package/dist/src/commands/project/launcher.js.map +1 -1
- package/dist/src/commands/project/validators.d.ts +55 -1
- package/dist/src/commands/project/validators.js +14 -0
- package/dist/src/commands/project/validators.js.map +1 -1
- package/dist/src/commands/project/workflow.d.ts +5 -1
- package/dist/src/commands/project/workflow.js +72 -2
- package/dist/src/commands/project/workflow.js.map +1 -1
- package/dist/src/commands/remote/command.js +3 -3
- package/dist/src/commands/remote/command.js.map +1 -1
- package/dist/src/commands/remote/index.d.ts +1 -1
- package/dist/src/commands/remote/index.js +1 -1
- package/dist/src/commands/remote/index.js.map +1 -1
- package/dist/src/commands/remote/ssh.d.ts +8 -2
- package/dist/src/commands/remote/ssh.js +41 -15
- package/dist/src/commands/remote/ssh.js.map +1 -1
- package/dist/src/commands/remote/workflow.d.ts +83 -0
- package/dist/src/commands/remote/workflow.js +48 -0
- package/dist/src/commands/remote/workflow.js.map +1 -0
- package/dist/src/commands/service/client.js +2 -1
- package/dist/src/commands/service/client.js.map +1 -1
- package/dist/src/commands/service/formatters.js +3 -0
- package/dist/src/commands/service/formatters.js.map +1 -1
- package/dist/src/commands/service/server.js +1 -1
- package/dist/src/commands/service/server.js.map +1 -1
- package/dist/src/commands/service/validators.d.ts +14 -0
- package/dist/src/commands/service/validators.js +4 -0
- package/dist/src/commands/service/validators.js.map +1 -1
- package/dist/src/commands/service/workflow.js +28 -1
- package/dist/src/commands/service/workflow.js.map +1 -1
- package/dist/src/commands/tui/actions/app.js +8 -6
- package/dist/src/commands/tui/actions/app.js.map +1 -1
- package/dist/src/commands/tui/actions/formatters.js +6 -1
- package/dist/src/commands/tui/actions/formatters.js.map +1 -1
- package/dist/src/commands/tui/actions/validators.d.ts +3 -1
- package/dist/src/commands/tui/actions/validators.js +2 -1
- package/dist/src/commands/tui/actions/validators.js.map +1 -1
- package/dist/src/commands/tui/actions/workflow.d.ts +3 -1
- package/dist/src/commands/tui/actions/workflow.js +51 -13
- package/dist/src/commands/tui/actions/workflow.js.map +1 -1
- package/dist/src/commands/tui/app.js +6 -4
- package/dist/src/commands/tui/app.js.map +1 -1
- package/dist/src/commands/tui/credentials/app.js +9 -1
- package/dist/src/commands/tui/credentials/app.js.map +1 -1
- package/dist/src/commands/tui/environments/app.js +4 -7
- package/dist/src/commands/tui/environments/app.js.map +1 -1
- package/dist/src/commands/tui/formatters.d.ts +3 -0
- package/dist/src/commands/tui/formatters.js +6 -0
- package/dist/src/commands/tui/formatters.js.map +1 -1
- package/dist/src/commands/tui/onboarding/app.js +4 -3
- package/dist/src/commands/tui/onboarding/app.js.map +1 -1
- package/dist/src/commands/tui/resolution.d.ts +7 -2
- package/dist/src/commands/tui/resolution.js +10 -6
- package/dist/src/commands/tui/resolution.js.map +1 -1
- package/dist/src/commands/tui/validators.d.ts +1 -1
- package/dist/src/commands/tui/workflow.d.ts +2 -0
- package/dist/src/lib/connect-events.d.ts +6 -0
- package/dist/src/lib/connect-events.js.map +1 -1
- package/dist/templates/project-isolation/README.md +28 -13
- package/dist/templates/project-isolation/__pycache__/install.cpython-311.pyc +0 -0
- package/dist/templates/project-isolation/__pycache__/launcher.cpython-311.pyc +0 -0
- package/dist/templates/project-isolation/environment.py +2 -55
- package/dist/templates/project-isolation/environment.test.py +1 -1
- package/dist/templates/project-isolation/install.py +39 -6
- package/dist/templates/project-isolation/install.test.py +32 -0
- package/dist/templates/project-isolation/launcher.py +224 -18
- package/dist/templates/project-isolation/launcher.test.py +179 -2
- package/package.json +1 -1
- package/dist/templates/project-isolation/__pycache__/environment.cpython-311.pyc +0 -0
|
@@ -10,15 +10,23 @@ import pwd
|
|
|
10
10
|
import re
|
|
11
11
|
import selectors
|
|
12
12
|
import select
|
|
13
|
+
import shutil
|
|
13
14
|
import signal
|
|
14
15
|
import stat
|
|
15
16
|
import subprocess
|
|
16
17
|
import sys
|
|
18
|
+
import tempfile
|
|
17
19
|
import time
|
|
18
20
|
from urllib.parse import urlparse
|
|
19
21
|
|
|
20
22
|
CONFIG = Path("/etc/convoy-projects.json")
|
|
21
23
|
SAFE_ENV = {"PATH": "/usr/local/bin:/usr/bin:/bin", "LANG": "C.UTF-8"}
|
|
24
|
+
# Runtimes Convoy has tested inside the boundary: binary, label, login command, config folder, login file.
|
|
25
|
+
RUNTIMES = {"codex": ("codex", "Codex", "codex login --device-auth", ".codex", "auth.json"),
|
|
26
|
+
"claude-code": ("claude", "Claude Code", "claude auth login", ".claude", ".credentials.json")}
|
|
27
|
+
# Who holds a project lease, as written into its lease file.
|
|
28
|
+
HOLDERS = {"service": "the project service", "connect": "a foreground connection", "shell": "a private project shell",
|
|
29
|
+
"login": "a runtime login", "registration": "a registration", "unknown": "another connection or shell"}
|
|
22
30
|
|
|
23
31
|
|
|
24
32
|
def require(condition, message):
|
|
@@ -95,13 +103,47 @@ def lock_file(config, name, nonblocking=False, control=None):
|
|
|
95
103
|
raise
|
|
96
104
|
|
|
97
105
|
|
|
98
|
-
|
|
106
|
+
class ProjectActive(ValueError):
|
|
107
|
+
def __init__(self, holder):
|
|
108
|
+
self.holder = holder
|
|
109
|
+
super().__init__(f"Project is in use by {HOLDERS[holder]}. Stop it before continuing.")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def read_holder(config, identity):
|
|
113
|
+
try:
|
|
114
|
+
fd = os.open(Path(config["state"]) / (identity + ".lease"), os.O_RDONLY | os.O_NOFOLLOW)
|
|
115
|
+
except OSError:
|
|
116
|
+
return "unknown"
|
|
117
|
+
try:
|
|
118
|
+
holder = os.read(fd, 32).decode(errors="replace")
|
|
119
|
+
finally:
|
|
120
|
+
os.close(fd)
|
|
121
|
+
return holder if holder in HOLDERS else "unknown"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def take_lease(config, identity, holder):
|
|
125
|
+
"""Take the project lease and record who holds it; a conflict names the holder."""
|
|
126
|
+
try:
|
|
127
|
+
fd = lock_file(config, identity + ".lease", True)
|
|
128
|
+
except ValueError:
|
|
129
|
+
raise ProjectActive(read_holder(config, identity)) from None
|
|
130
|
+
os.ftruncate(fd, 0)
|
|
131
|
+
os.pwrite(fd, holder.encode(), 0)
|
|
132
|
+
return fd
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def lease_holder(config, identity):
|
|
136
|
+
"""None while the lease is free, otherwise its recorded holder."""
|
|
99
137
|
try:
|
|
100
138
|
fd = lock_file(config, identity + ".lease", True)
|
|
101
139
|
except ValueError:
|
|
102
|
-
return
|
|
140
|
+
return read_holder(config, identity)
|
|
103
141
|
os.close(fd)
|
|
104
|
-
return
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def is_active(config, identity):
|
|
146
|
+
return lease_holder(config, identity) is not None
|
|
105
147
|
|
|
106
148
|
|
|
107
149
|
def validate_target(config, registry, identity, target):
|
|
@@ -168,6 +210,20 @@ def drop_privileges(uid):
|
|
|
168
210
|
os.umask(0o077)
|
|
169
211
|
|
|
170
212
|
|
|
213
|
+
def runtime_homes(home, uid):
|
|
214
|
+
"""Create runtime config folders in a project HOME without following project-made links."""
|
|
215
|
+
fd = os.open(home, os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
216
|
+
try:
|
|
217
|
+
for name in [item[3] for item in RUNTIMES.values()]:
|
|
218
|
+
try:
|
|
219
|
+
os.mkdir(name, 0o700, dir_fd=fd)
|
|
220
|
+
except FileExistsError:
|
|
221
|
+
continue
|
|
222
|
+
os.chown(name, uid, uid, dir_fd=fd, follow_symlinks=False)
|
|
223
|
+
finally:
|
|
224
|
+
os.close(fd)
|
|
225
|
+
|
|
226
|
+
|
|
171
227
|
def write_identity_files(config, entry):
|
|
172
228
|
uid = entry["uid"]
|
|
173
229
|
records = {
|
|
@@ -181,6 +237,55 @@ def write_identity_files(config, entry):
|
|
|
181
237
|
stream.write(content)
|
|
182
238
|
|
|
183
239
|
|
|
240
|
+
def sandbox_path(config):
|
|
241
|
+
return f"{config['installation_root']}/node_modules/.bin:{config['package_root']}/dist/bin:/home/convoy/.local/bin:/usr/local/bin:/usr/bin:/bin"
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def runtime_states(config):
|
|
245
|
+
"""Each tested runtime: ready (administrator-owned binary), untrusted or missing; checked at every launch."""
|
|
246
|
+
shared = ":".join(item for item in sandbox_path(config).split(":") if not item.startswith("/home/"))
|
|
247
|
+
states = {}
|
|
248
|
+
for name, (binary, *_) in RUNTIMES.items():
|
|
249
|
+
located = shutil.which(binary, path=shared)
|
|
250
|
+
states[name] = "missing"
|
|
251
|
+
try:
|
|
252
|
+
if located:
|
|
253
|
+
states[name] = "untrusted"
|
|
254
|
+
trusted_path(Path(located).resolve())
|
|
255
|
+
states[name] = "ready"
|
|
256
|
+
except (ValueError, OSError):
|
|
257
|
+
pass
|
|
258
|
+
return states
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def detect_runtimes(config):
|
|
262
|
+
return [name for name, state in runtime_states(config).items() if state == "ready"]
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def runtime_files(home):
|
|
266
|
+
"""Per runtime, whether its config folder and login file exist, without following project-made links."""
|
|
267
|
+
found = {name: (False, False) for name in RUNTIMES}
|
|
268
|
+
try:
|
|
269
|
+
fd = os.open(home, os.O_DIRECTORY | os.O_NOFOLLOW)
|
|
270
|
+
except OSError:
|
|
271
|
+
return found
|
|
272
|
+
try:
|
|
273
|
+
for name, (*_, folder, login) in RUNTIMES.items():
|
|
274
|
+
try:
|
|
275
|
+
sub = os.open(folder, os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
|
|
276
|
+
except OSError:
|
|
277
|
+
continue
|
|
278
|
+
try:
|
|
279
|
+
found[name] = (True, stat.S_ISREG(os.stat(login, dir_fd=sub, follow_symlinks=False).st_mode))
|
|
280
|
+
except OSError:
|
|
281
|
+
found[name] = (True, False)
|
|
282
|
+
finally:
|
|
283
|
+
os.close(sub)
|
|
284
|
+
finally:
|
|
285
|
+
os.close(fd)
|
|
286
|
+
return found
|
|
287
|
+
|
|
288
|
+
|
|
184
289
|
def sandbox_args(config, entry):
|
|
185
290
|
args = ["/usr/bin/bwrap", "--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts",
|
|
186
291
|
"--die-with-parent", "--new-session", "--cap-drop", "ALL", "--clearenv"]
|
|
@@ -192,21 +297,23 @@ def sandbox_args(config, entry):
|
|
|
192
297
|
args += ["--ro-bind", item, item]
|
|
193
298
|
for suffix in ["passwd", "group"]:
|
|
194
299
|
args += ["--ro-bind", str(Path(config["state"]) / (entry["identity"] + "." + suffix)), "/etc/" + suffix]
|
|
195
|
-
cli = config["package_root"]
|
|
196
300
|
installation = config["installation_root"]
|
|
197
301
|
if not installation.startswith("/usr/"):
|
|
198
302
|
args += ["--ro-bind", installation, installation]
|
|
199
303
|
home = str(Path(config["state"]) / entry["identity"])
|
|
304
|
+
states, files = runtime_states(config), runtime_files(home)
|
|
200
305
|
args += ["--bind", home, "/home/convoy", "--bind", entry["path"], entry["path"],
|
|
201
306
|
"--bind", entry["path"] + "-worktrees", entry["path"] + "-worktrees",
|
|
202
307
|
"--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--dir", "/run/user"]
|
|
203
|
-
env = {**SAFE_ENV, "PATH":
|
|
308
|
+
env = {**SAFE_ENV, "PATH": sandbox_path(config),
|
|
204
309
|
"HOME": "/home/convoy", "USER": "convoy-project", "LOGNAME": "convoy-project",
|
|
205
310
|
"TMPDIR": "/tmp", "XDG_RUNTIME_DIR": "/run/user", "XDG_CONFIG_HOME": "/home/convoy/.config",
|
|
206
311
|
"XDG_CACHE_HOME": "/home/convoy/.cache", "XDG_DATA_HOME": "/home/convoy/.local/share",
|
|
207
312
|
"CODEX_HOME": "/home/convoy/.codex", "CLAUDE_CONFIG_DIR": "/home/convoy/.claude",
|
|
208
313
|
"CONVOY_PROJECT_IDENTITY": entry["identity"], "TERM": "xterm-256color",
|
|
209
|
-
"CONVOY_PROJECT_RUNTIMES": ",".join(
|
|
314
|
+
"CONVOY_PROJECT_RUNTIMES": ",".join(name for name, state in states.items() if state == "ready"),
|
|
315
|
+
"CONVOY_PROJECT_UNTRUSTED": ",".join(name for name, state in states.items() if state == "untrusted"),
|
|
316
|
+
"CONVOY_PROJECT_LOGGED_OUT": ",".join(name for name, state in states.items() if state == "ready" and not files[name][1])}
|
|
210
317
|
for key, value in env.items():
|
|
211
318
|
args += ["--setenv", key, value]
|
|
212
319
|
return args + ["--chdir", entry["path"]]
|
|
@@ -220,6 +327,72 @@ def run_bounded(config, entry, command):
|
|
|
220
327
|
require(result.returncode == 0, "Project preparation failed inside the Linux boundary. Check user namespaces, bubblewrap and HTTPS clone access. Private files were retained.")
|
|
221
328
|
|
|
222
329
|
|
|
330
|
+
PROBE = """import os, pathlib
|
|
331
|
+
assert os.getuid() == 65000, 'the project UID was not applied'
|
|
332
|
+
assert not os.getgroups(), 'supplementary groups were retained'
|
|
333
|
+
s = pathlib.Path('/proc/self/status').read_text()
|
|
334
|
+
assert 'NoNewPrivs:\\t1' in s, 'privilege escalation is still allowed'
|
|
335
|
+
assert int(s.split('CapEff:\\t')[1].splitlines()[0], 16) == 0, 'capabilities were retained'
|
|
336
|
+
for path in os.environ['HIDDEN'].split(':'):
|
|
337
|
+
assert not pathlib.Path(path).exists(), path + ' is visible inside the boundary'
|
|
338
|
+
pathlib.Path('probe.txt').write_text('private')
|
|
339
|
+
"""
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def check_boundary(config):
|
|
343
|
+
"""Run the boundary probes under a throwaway UID. Raises ValueError naming the cause."""
|
|
344
|
+
uid = 65000 # Outside the project UID range and never registered.
|
|
345
|
+
made = []
|
|
346
|
+
|
|
347
|
+
def temporary(root, prefix="convoy-probe-"):
|
|
348
|
+
made.append(Path(tempfile.mkdtemp(prefix=prefix, dir=root)))
|
|
349
|
+
return made[-1]
|
|
350
|
+
try:
|
|
351
|
+
workspace, other, home = temporary(config["workspace"]), temporary(config["workspace"], "convoy-other-"), temporary(config["state"])
|
|
352
|
+
made.append(Path(str(workspace) + "-worktrees"))
|
|
353
|
+
made[-1].mkdir()
|
|
354
|
+
entry = {"uid": uid, "identity": home.name, "path": str(workspace)}
|
|
355
|
+
for path in [workspace, made[-1], home]:
|
|
356
|
+
os.chown(path, uid, uid)
|
|
357
|
+
path.chmod(0o700)
|
|
358
|
+
write_identity_files(config, entry)
|
|
359
|
+
hidden = [str(other), pwd.getpwuid(config["control_uid"]).pw_dir, "/var/run/docker.sock"]
|
|
360
|
+
result = subprocess.run(sandbox_args(config, entry) + ["--setenv", "HIDDEN", ":".join(hidden), "python3", "-I", "-c", PROBE],
|
|
361
|
+
env=SAFE_ENV, preexec_fn=lambda: drop_privileges(uid), stdin=subprocess.DEVNULL,
|
|
362
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, timeout=60, close_fds=True)
|
|
363
|
+
finally:
|
|
364
|
+
for path in made:
|
|
365
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
366
|
+
for suffix in ["passwd", "group"]:
|
|
367
|
+
(Path(config["state"]) / (path.name + "." + suffix)).unlink(missing_ok=True)
|
|
368
|
+
if result.returncode:
|
|
369
|
+
cause = (result.stderr.strip().splitlines() or ["no output"])[-1]
|
|
370
|
+
hint = (" On Ubuntu, AppArmor can block bubblewrap's user namespaces:"
|
|
371
|
+
" https://docs.convoy.build/docs/cli/isolated-projects#ubuntu-apparmor-prerequisite") \
|
|
372
|
+
if cause.startswith("bwrap:") and ("Permission denied" in cause or "Operation not permitted" in cause) else ""
|
|
373
|
+
raise ValueError(f"Sandbox check failed: {cause}.{hint}")
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def check(config, entry):
|
|
377
|
+
"""Read-only preconditions for project check; the probes use a throwaway UID."""
|
|
378
|
+
try:
|
|
379
|
+
check_boundary(config)
|
|
380
|
+
sandbox = None
|
|
381
|
+
except ValueError as error:
|
|
382
|
+
sandbox = str(error)
|
|
383
|
+
except (OSError, subprocess.SubprocessError) as error:
|
|
384
|
+
sandbox = f"Sandbox check could not run: {error}."
|
|
385
|
+
files = runtime_files(Path(config["state"]) / entry["identity"])
|
|
386
|
+
return {"sandbox": sandbox, "holder": lease_holder(config, entry["identity"]),
|
|
387
|
+
"runtimes": {name: {"state": state, "home": files[name][0], "loggedIn": files[name][1]}
|
|
388
|
+
for name, state in runtime_states(config).items()}}
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def emit_failure(reason, **fields):
|
|
392
|
+
"""A service worker's status event; the service maps the fixed code to its own guidance."""
|
|
393
|
+
print(json.dumps({"v": 1, "ts": int(time.time() * 1000), "event": "status", "status": "failed", "reason": reason, **fields}), flush=True)
|
|
394
|
+
|
|
395
|
+
|
|
223
396
|
def add(config, registry, request):
|
|
224
397
|
identity = request["identity"]
|
|
225
398
|
target = validate_target(config, registry, identity, request["path"])
|
|
@@ -300,19 +473,31 @@ def supervise(config, entry, request, shell=False):
|
|
|
300
473
|
require(entry["uid"] not in {item.pw_uid for item in pwd.getpwall()} and
|
|
301
474
|
entry["uid"] not in {item.gr_gid for item in grp.getgrall()},
|
|
302
475
|
"Retained UID/GID now belongs to a system account; administrator intervention required")
|
|
303
|
-
|
|
304
|
-
|
|
476
|
+
login = request.get("login")
|
|
477
|
+
if login:
|
|
478
|
+
require(login in RUNTIMES, "Unsupported runtime")
|
|
479
|
+
require(login in detect_runtimes(config),
|
|
480
|
+
f"{RUNTIMES[login][1]} is not installed system-wide. Install it root-owned, for example under /usr/local/bin, then retry.")
|
|
305
481
|
private_directory(entry["path"], entry["uid"])
|
|
306
482
|
private_directory(entry["path"] + "-worktrees", entry["uid"])
|
|
307
|
-
|
|
483
|
+
home = Path(config["state"]) / entry["identity"]
|
|
484
|
+
private_directory(home, entry["uid"])
|
|
485
|
+
runtime_homes(home, entry["uid"])
|
|
308
486
|
write_identity_files(config, entry)
|
|
309
487
|
# Allocate the controlling terminal inside the boundary, after --new-session.
|
|
488
|
+
# A worker's shell writes one byte once the sandbox is up, so a bwrap failure is told apart.
|
|
489
|
+
started, ready = os.pipe() if not shell else (None, None)
|
|
310
490
|
command = ["/usr/bin/script", "--quiet", "--return", "--command",
|
|
311
|
-
"/bin/bash --noprofile --norc", "/dev/null"] if shell else
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
491
|
+
RUNTIMES[login][2] if login else "/bin/bash --noprofile --norc", "/dev/null"] if shell else \
|
|
492
|
+
["/bin/sh", "-c", f'printf 1 >&{ready} && exec {ready}>&- "$0" "$@"', config["node"], config["cli"]]
|
|
493
|
+
try:
|
|
494
|
+
child = subprocess.Popen(sandbox_args(config, entry) + command, env=SAFE_ENV,
|
|
495
|
+
preexec_fn=lambda: drop_privileges(entry["uid"]),
|
|
496
|
+
stdin=None if shell else subprocess.PIPE, close_fds=True,
|
|
497
|
+
pass_fds=() if shell else (ready,), start_new_session=not shell)
|
|
498
|
+
finally:
|
|
499
|
+
if ready is not None:
|
|
500
|
+
os.close(ready)
|
|
316
501
|
stopping = False
|
|
317
502
|
deadline = None
|
|
318
503
|
|
|
@@ -343,8 +528,17 @@ def supervise(config, entry, request, shell=False):
|
|
|
343
528
|
time.sleep(0.1)
|
|
344
529
|
if deadline and time.monotonic() >= deadline:
|
|
345
530
|
child.kill()
|
|
531
|
+
if not stopping and child.returncode and request.get("holder") == "service":
|
|
532
|
+
os.set_blocking(started, False)
|
|
533
|
+
try:
|
|
534
|
+
if not os.read(started, 1):
|
|
535
|
+
emit_failure("sandbox-failed")
|
|
536
|
+
except BlockingIOError:
|
|
537
|
+
pass
|
|
346
538
|
return 0 if stopping else child.returncode
|
|
347
539
|
finally:
|
|
540
|
+
if started is not None:
|
|
541
|
+
os.close(started)
|
|
348
542
|
selector.close()
|
|
349
543
|
if child.poll() is None:
|
|
350
544
|
child.kill()
|
|
@@ -353,16 +547,16 @@ def supervise(config, entry, request, shell=False):
|
|
|
353
547
|
|
|
354
548
|
def main():
|
|
355
549
|
config = load_config()
|
|
356
|
-
shell = len(sys.argv) == 3 and sys.argv[1] == "shell"
|
|
550
|
+
shell = len(sys.argv) == 3 and sys.argv[1] == "shell" or len(sys.argv) == 4 and sys.argv[1] == "login"
|
|
357
551
|
if shell:
|
|
358
|
-
request = {"action": "shell", "identity": sys.argv[2]}
|
|
552
|
+
request = {"action": "shell", "identity": sys.argv[2], **({"login": sys.argv[3]} if len(sys.argv) == 4 else {})}
|
|
359
553
|
else:
|
|
360
554
|
require(len(sys.argv) == 1, "Unsupported launcher arguments")
|
|
361
555
|
raw = sys.stdin.buffer.readline(65537)
|
|
362
556
|
require(len(raw) <= 65536, "Request too large")
|
|
363
557
|
request = json.loads(raw)
|
|
364
558
|
action = request.get("action")
|
|
365
|
-
require(action in {"list", "add", "remove", "connect", "shell"}, "Unsupported operation")
|
|
559
|
+
require(action in {"list", "add", "remove", "connect", "shell", "check"}, "Unsupported operation")
|
|
366
560
|
identity = request.get("identity")
|
|
367
561
|
if action != "list":
|
|
368
562
|
require(isinstance(identity, str) and re.fullmatch(r"[a-f0-9]{64}", identity), "Invalid project identity")
|
|
@@ -378,8 +572,20 @@ def main():
|
|
|
378
572
|
"status": "pending" if not entry.get("ready") else "stopped" if entry.get("enabled", True) else "removed"}
|
|
379
573
|
for key, entry in registry.items()
|
|
380
574
|
]}
|
|
575
|
+
elif action == "check":
|
|
576
|
+
require(identity in registry and registry[identity].get("ready"), "Project is not registered; repeat project add")
|
|
577
|
+
os.close(registry_lock)
|
|
578
|
+
registry_lock = None
|
|
579
|
+
result = check(config, registry[identity])
|
|
381
580
|
else:
|
|
382
|
-
|
|
581
|
+
holder = {"shell": "login" if request.get("login") else "shell",
|
|
582
|
+
"connect": request.get("holder") if request.get("holder") in ("service", "connect") else "connect"}.get(action, "registration")
|
|
583
|
+
try:
|
|
584
|
+
lease = take_lease(config, identity, holder)
|
|
585
|
+
except ProjectActive as error:
|
|
586
|
+
if action == "connect" and holder == "service":
|
|
587
|
+
emit_failure("project-active", holder=error.holder)
|
|
588
|
+
raise
|
|
383
589
|
if action == "add":
|
|
384
590
|
result = {**add(config, registry, request), "active": False}
|
|
385
591
|
else:
|
|
@@ -9,6 +9,7 @@ import subprocess
|
|
|
9
9
|
from pathlib import Path
|
|
10
10
|
import tempfile
|
|
11
11
|
import unittest
|
|
12
|
+
import unittest.mock
|
|
12
13
|
from unittest.mock import patch
|
|
13
14
|
|
|
14
15
|
spec = importlib.util.spec_from_file_location("launcher", Path(__file__).with_name("launcher.py"))
|
|
@@ -148,10 +149,11 @@ class LauncherPolicyTests(unittest.TestCase):
|
|
|
148
149
|
|
|
149
150
|
def test_worker_pipe_stays_open_until_stop_without_terminating_bwrap(self):
|
|
150
151
|
entry = {"identity": self.identity, "uid": 20001, "path": str(self.root / "a")}
|
|
151
|
-
config = self.config | {"node": "/usr/bin/node", "cli": "/cli.js"
|
|
152
|
+
config = self.config | {"node": "/usr/bin/node", "cli": "/cli.js"}
|
|
152
153
|
pipe = io.BytesIO()
|
|
153
154
|
observed = []
|
|
154
155
|
with patch.object(launcher, "private_directory"), patch.object(launcher, "write_identity_files"), \
|
|
156
|
+
patch.object(launcher, "runtime_homes"), \
|
|
155
157
|
patch.object(launcher.pwd, "getpwall", return_value=[]), patch.object(launcher.grp, "getgrall", return_value=[]), \
|
|
156
158
|
patch.object(launcher.signal, "signal"), patch.object(launcher.os, "read", return_value=b""), \
|
|
157
159
|
patch.object(launcher.selectors, "DefaultSelector") as selector, \
|
|
@@ -168,10 +170,185 @@ class LauncherPolicyTests(unittest.TestCase):
|
|
|
168
170
|
child.terminate.assert_not_called()
|
|
169
171
|
self.assertTrue(spawn.call_args.kwargs.get("start_new_session"))
|
|
170
172
|
|
|
173
|
+
def test_runtimes_are_detected_at_launch_from_trusted_binaries(self):
|
|
174
|
+
binaries = {"codex": "/usr/local/bin/codex", "claude": "/home/x/claude"}
|
|
175
|
+
|
|
176
|
+
def trusted(path, owners=(0,)):
|
|
177
|
+
if str(path).startswith("/home/"):
|
|
178
|
+
raise ValueError("untrusted")
|
|
179
|
+
return Path(path)
|
|
180
|
+
with patch.object(launcher.shutil, "which", side_effect=lambda name, path=None: binaries.get(name)), \
|
|
181
|
+
patch.object(launcher.Path, "resolve", lambda self, strict=False: self), \
|
|
182
|
+
patch.object(launcher, "trusted_path", side_effect=trusted):
|
|
183
|
+
self.assertEqual(launcher.detect_runtimes(self.config), ["codex"])
|
|
184
|
+
args = launcher.sandbox_args(self.config | {"verified_runtimes": ["claude-code"]}, {"identity": self.identity, "path": str(self.root / "a")})
|
|
185
|
+
self.assertEqual(args[args.index("CONVOY_PROJECT_RUNTIMES") + 1], "codex")
|
|
186
|
+
|
|
187
|
+
def test_skipped_runtimes_and_missing_logins_reach_the_worker(self):
|
|
188
|
+
binaries = {"codex": "/usr/local/bin/codex", "claude": "/opt/claude"}
|
|
189
|
+
home = self.root / self.identity
|
|
190
|
+
(home / ".codex").mkdir(parents=True)
|
|
191
|
+
|
|
192
|
+
def trusted(path, owners=(0,)):
|
|
193
|
+
if str(path) == "/opt/claude":
|
|
194
|
+
raise ValueError("untrusted")
|
|
195
|
+
return Path(path)
|
|
196
|
+
with patch.object(launcher.shutil, "which", side_effect=lambda name, path=None: binaries.get(name)), \
|
|
197
|
+
patch.object(launcher.Path, "resolve", lambda self, strict=False: self), \
|
|
198
|
+
patch.object(launcher, "trusted_path", side_effect=trusted):
|
|
199
|
+
self.assertEqual(launcher.runtime_states(self.config), {"codex": "ready", "claude-code": "untrusted"})
|
|
200
|
+
args = launcher.sandbox_args(self.config, {"identity": self.identity, "path": str(self.root / "a")})
|
|
201
|
+
self.assertEqual(args[args.index("CONVOY_PROJECT_UNTRUSTED") + 1], "claude-code")
|
|
202
|
+
self.assertEqual(args[args.index("CONVOY_PROJECT_LOGGED_OUT") + 1], "codex")
|
|
203
|
+
(home / ".codex" / "auth.json").write_text("{}")
|
|
204
|
+
args = launcher.sandbox_args(self.config, {"identity": self.identity, "path": str(self.root / "a")})
|
|
205
|
+
self.assertEqual(args[args.index("CONVOY_PROJECT_LOGGED_OUT") + 1], "")
|
|
206
|
+
|
|
207
|
+
def test_login_files_are_found_without_following_project_links(self):
|
|
208
|
+
home, outside = self.root / "home", self.root / "outside"
|
|
209
|
+
(home / ".claude").mkdir(parents=True)
|
|
210
|
+
outside.mkdir()
|
|
211
|
+
(outside / ".credentials.json").write_text("{}")
|
|
212
|
+
(home / ".codex").symlink_to(outside)
|
|
213
|
+
(home / ".claude" / ".credentials.json").symlink_to(outside / ".credentials.json")
|
|
214
|
+
self.assertEqual(launcher.runtime_files(home), {"codex": (False, False), "claude-code": (True, False)})
|
|
215
|
+
(home / ".claude" / ".credentials.json").unlink()
|
|
216
|
+
(home / ".claude" / ".credentials.json").write_text("{}")
|
|
217
|
+
self.assertEqual(launcher.runtime_files(home)["claude-code"], (True, True))
|
|
218
|
+
self.assertEqual(launcher.runtime_files(self.root / "absent"), {"codex": (False, False), "claude-code": (False, False)})
|
|
219
|
+
|
|
220
|
+
def test_a_held_lease_names_its_holder(self):
|
|
221
|
+
fd = launcher.take_lease(self.config, self.identity, "shell")
|
|
222
|
+
try:
|
|
223
|
+
with self.assertRaisesRegex(ValueError, "in use by a private project shell") as raised:
|
|
224
|
+
launcher.take_lease(self.config, self.identity, "service")
|
|
225
|
+
self.assertEqual(raised.exception.holder, "shell")
|
|
226
|
+
self.assertEqual(launcher.lease_holder(self.config, self.identity), "shell")
|
|
227
|
+
finally:
|
|
228
|
+
os.close(fd)
|
|
229
|
+
self.assertIsNone(launcher.lease_holder(self.config, self.identity))
|
|
230
|
+
(self.root / (self.identity + ".lease")).write_text("anything")
|
|
231
|
+
fd = launcher.lock_file(self.config, self.identity + ".lease", True)
|
|
232
|
+
try:
|
|
233
|
+
self.assertEqual(launcher.lease_holder(self.config, self.identity), "unknown")
|
|
234
|
+
finally:
|
|
235
|
+
os.close(fd)
|
|
236
|
+
|
|
237
|
+
def test_service_connect_reports_a_held_lease_as_an_event(self):
|
|
238
|
+
launcher.save_registry(self.config, {self.identity: {"identity": self.identity, "uid": 20001, "path": str(self.root / "a"), "ready": True}})
|
|
239
|
+
fd = launcher.take_lease(self.config, self.identity, "login")
|
|
240
|
+
read, write = os.pipe()
|
|
241
|
+
os.write(write, (json.dumps({"action": "connect", "identity": self.identity, "holder": "service", "config": {}}) + "\n").encode())
|
|
242
|
+
output = io.StringIO()
|
|
243
|
+
try:
|
|
244
|
+
with open(read, "r") as stdin, patch.object(launcher, "load_config", return_value=self.config), \
|
|
245
|
+
patch.object(launcher.sys, "argv", ["launcher"]), patch.object(launcher.sys, "stdin", stdin), \
|
|
246
|
+
patch.object(launcher.sys, "stdout", output):
|
|
247
|
+
with self.assertRaisesRegex(ValueError, "runtime login"):
|
|
248
|
+
launcher.main()
|
|
249
|
+
finally:
|
|
250
|
+
os.close(fd)
|
|
251
|
+
os.close(write)
|
|
252
|
+
event = json.loads(output.getvalue())
|
|
253
|
+
self.assertEqual({key: event[key] for key in ["event", "status", "reason", "holder"]},
|
|
254
|
+
{"event": "status", "status": "failed", "reason": "project-active", "holder": "login"})
|
|
255
|
+
|
|
256
|
+
def test_service_worker_reports_a_sandbox_that_never_started(self):
|
|
257
|
+
entry = {"identity": self.identity, "uid": 20001, "path": str(self.root / "a")}
|
|
258
|
+
config = self.config | {"node": "/usr/bin/node", "cli": "/cli.js"}
|
|
259
|
+
for started, expected in [(False, ["sandbox-failed"]), (True, [])]:
|
|
260
|
+
output = io.StringIO()
|
|
261
|
+
|
|
262
|
+
def spawn(args, **kwargs):
|
|
263
|
+
if started:
|
|
264
|
+
os.write(kwargs["pass_fds"][0], b"1")
|
|
265
|
+
child = unittest.mock.MagicMock()
|
|
266
|
+
child.poll.return_value = 1
|
|
267
|
+
child.returncode = 1
|
|
268
|
+
return child
|
|
269
|
+
with patch.object(launcher, "private_directory"), patch.object(launcher, "write_identity_files"), \
|
|
270
|
+
patch.object(launcher, "runtime_homes"), patch.object(launcher, "sandbox_args", return_value=[]), \
|
|
271
|
+
patch.object(launcher.pwd, "getpwall", return_value=[]), patch.object(launcher.grp, "getgrall", return_value=[]), \
|
|
272
|
+
patch.object(launcher.signal, "signal"), patch.object(launcher.selectors, "DefaultSelector"), \
|
|
273
|
+
patch.object(launcher.subprocess, "Popen", side_effect=spawn), patch.object(launcher.sys, "stdout", output):
|
|
274
|
+
self.assertEqual(launcher.supervise(config, entry, {"config": {}, "holder": "service"}), 1)
|
|
275
|
+
self.assertEqual([json.loads(line)["reason"] for line in output.getvalue().splitlines()], expected)
|
|
276
|
+
|
|
277
|
+
def test_check_reports_each_precondition_without_changing_the_project(self):
|
|
278
|
+
entry = {"identity": self.identity, "uid": 20001, "path": str(self.root / "a")}
|
|
279
|
+
home = self.root / self.identity
|
|
280
|
+
(home / ".codex").mkdir(parents=True)
|
|
281
|
+
(home / ".codex" / "auth.json").write_text("{}")
|
|
282
|
+
fd = launcher.take_lease(self.config, self.identity, "service")
|
|
283
|
+
try:
|
|
284
|
+
with patch.object(launcher, "check_boundary", side_effect=ValueError("Sandbox check failed: bwrap: denied.")), \
|
|
285
|
+
patch.object(launcher, "runtime_states", return_value={"codex": "ready", "claude-code": "missing"}):
|
|
286
|
+
result = launcher.check(self.config, entry)
|
|
287
|
+
finally:
|
|
288
|
+
os.close(fd)
|
|
289
|
+
self.assertEqual(result, {"sandbox": "Sandbox check failed: bwrap: denied.", "holder": "service", "runtimes": {
|
|
290
|
+
"codex": {"state": "ready", "home": True, "loggedIn": True},
|
|
291
|
+
"claude-code": {"state": "missing", "home": False, "loggedIn": False}}})
|
|
292
|
+
self.assertFalse((home / ".claude").exists())
|
|
293
|
+
|
|
294
|
+
def test_runtime_homes_are_created_without_following_symlinks(self):
|
|
295
|
+
home, outside = self.root / "home", self.root / "outside"
|
|
296
|
+
home.mkdir()
|
|
297
|
+
outside.mkdir(mode=0o755)
|
|
298
|
+
(home / ".claude").symlink_to(outside)
|
|
299
|
+
launcher.runtime_homes(home, os.getuid())
|
|
300
|
+
self.assertEqual((home / ".codex").stat().st_mode & 0o777, 0o700)
|
|
301
|
+
self.assertTrue((home / ".claude").is_symlink())
|
|
302
|
+
self.assertEqual(outside.stat().st_mode & 0o777, 0o755)
|
|
303
|
+
|
|
304
|
+
def test_login_runs_only_the_detected_runtime_login(self):
|
|
305
|
+
entry = {"identity": self.identity, "uid": 20001, "path": str(self.root / "a")}
|
|
306
|
+
with patch.object(launcher, "private_directory"), patch.object(launcher, "write_identity_files"), \
|
|
307
|
+
patch.object(launcher, "runtime_homes"), patch.object(launcher, "sandbox_args", return_value=[]), \
|
|
308
|
+
patch.object(launcher.pwd, "getpwall", return_value=[]), patch.object(launcher.grp, "getgrall", return_value=[]), \
|
|
309
|
+
patch.object(launcher.signal, "signal"), patch.object(launcher.subprocess, "Popen") as spawn:
|
|
310
|
+
spawn.return_value.poll.return_value = 0
|
|
311
|
+
spawn.return_value.returncode = 0
|
|
312
|
+
with patch.object(launcher, "detect_runtimes", return_value=["codex"]):
|
|
313
|
+
launcher.supervise(self.config, entry, {"login": "codex"}, shell=True)
|
|
314
|
+
self.assertIn("codex login --device-auth", spawn.call_args.args[0])
|
|
315
|
+
with self.assertRaisesRegex(ValueError, "Claude Code is not installed system-wide"):
|
|
316
|
+
launcher.supervise(self.config, entry, {"login": "claude-code"}, shell=True)
|
|
317
|
+
|
|
318
|
+
def test_boundary_check_explains_a_user_namespace_denial(self):
|
|
319
|
+
failed = subprocess.CompletedProcess([], 1, "", "bwrap: setting up uid map: Permission denied\n")
|
|
320
|
+
with patch.object(launcher, "write_identity_files"), patch.object(launcher, "sandbox_args", return_value=[]), \
|
|
321
|
+
patch.object(launcher.os, "chown"), patch.object(launcher.subprocess, "run", return_value=failed):
|
|
322
|
+
with self.assertRaisesRegex(ValueError, "uid map: Permission denied.*AppArmor"):
|
|
323
|
+
launcher.check_boundary(self.config | {"control_uid": os.getuid()})
|
|
324
|
+
|
|
325
|
+
def test_boundary_check_keeps_the_apparmor_hint_off_other_bwrap_errors(self):
|
|
326
|
+
failed = subprocess.CompletedProcess([], 1, "", "bwrap: Creating new namespace failed: nesting depth or /proc/sys/user/max_*_namespaces exceeded (ENOSPC)\n")
|
|
327
|
+
with patch.object(launcher, "write_identity_files"), patch.object(launcher, "sandbox_args", return_value=[]), \
|
|
328
|
+
patch.object(launcher.os, "chown"), patch.object(launcher.subprocess, "run", return_value=failed):
|
|
329
|
+
with self.assertRaises(ValueError) as raised:
|
|
330
|
+
launcher.check_boundary(self.config | {"control_uid": os.getuid()})
|
|
331
|
+
self.assertIn("ENOSPC", str(raised.exception))
|
|
332
|
+
self.assertNotIn("AppArmor", str(raised.exception))
|
|
333
|
+
|
|
334
|
+
def test_boundary_check_removes_its_folders_when_setup_fails(self):
|
|
335
|
+
real = launcher.tempfile.mkdtemp
|
|
336
|
+
calls = iter([real, real, OSError("disk full")])
|
|
337
|
+
|
|
338
|
+
def mkdtemp(**kwargs):
|
|
339
|
+
step = next(calls)
|
|
340
|
+
if isinstance(step, Exception):
|
|
341
|
+
raise step
|
|
342
|
+
return step(**kwargs)
|
|
343
|
+
with patch.object(launcher.tempfile, "mkdtemp", side_effect=mkdtemp):
|
|
344
|
+
with self.assertRaises(OSError):
|
|
345
|
+
launcher.check_boundary(self.config | {"control_uid": os.getuid()})
|
|
346
|
+
self.assertEqual(list(self.root.iterdir()), [])
|
|
347
|
+
|
|
171
348
|
def test_private_shell_has_job_control_in_a_detached_session(self):
|
|
172
349
|
entry = {"identity": self.identity, "uid": 20001, "path": str(self.root / "a")}
|
|
173
350
|
with patch.object(launcher, "private_directory"), patch.object(launcher, "write_identity_files"), \
|
|
174
|
-
patch.object(launcher, "sandbox_args", return_value=[]), \
|
|
351
|
+
patch.object(launcher, "sandbox_args", return_value=[]), patch.object(launcher, "runtime_homes"), \
|
|
175
352
|
patch.object(launcher.pwd, "getpwall", return_value=[]), \
|
|
176
353
|
patch.object(launcher.grp, "getgrall", return_value=[]), \
|
|
177
354
|
patch.object(launcher.signal, "signal"), patch.object(launcher.subprocess, "Popen") as spawn:
|
package/package.json
CHANGED
|
Binary file
|