Skip to content
Python

Credential grants: the ssh wrapper lives in the copied home, so OpenShell carries it in

Devika Verma7792a417f634
diff --git a/coworker/sandbox/credentials.py b/coworker/sandbox/credentials.py
index 56944a1f..bec827ed 100644
--- a/coworker/sandbox/credentials.py
+++ b/coworker/sandbox/credentials.py
@@ -196,8 +196,11 @@ def copy_in(
_copy_private(g.path, dst)
hosts += g.hosts
if g.name == "ssh":
- env.update(_prepare_ssh(dst, os.path.join(os.path.realpath(runtime_dir), "bin"), ssh_proxy_command))
- path_dirs.append(os.path.join(os.path.realpath(runtime_dir), "bin"))
+ # The wrapper lives INSIDE the sandbox home, which every provider carries in.
+ bin_dir = os.path.join(sandbox_home, "bin")
+ env.update(_prepare_ssh(dst, bin_dir, ssh_proxy_command))
+ env["OPENWORKER_PATH_PREPEND"] = bin_dir # the runner daemon puts it first on PATH
+ path_dirs.append(bin_dir)
elif g.name == "gh":
env["GH_CONFIG_DIR"] = dst
elif g.name == "aws":
diff --git a/coworker/sandbox/providers/seatbelt.py b/coworker/sandbox/providers/seatbelt.py
index 50abf920..1bf339bc 100644
--- a/coworker/sandbox/providers/seatbelt.py
+++ b/coworker/sandbox/providers/seatbelt.py
@@ -141,8 +141,6 @@ class SeatbeltProvider:
env = clean_environment()
if self.copied is not None:
env.update(self.copied.env) # HOME is the sandbox's own; the copies live there
- if self.copied.path_dirs:
- env["PATH"] = os.pathsep.join([*self.copied.path_dirs, env.get("PATH", "")])
tmp = os.path.join(self._dir, "tmp")
env["TMPDIR"] = tmp + "/"
for variable, folder in _CACHE_VARIABLES.items():
diff --git a/coworker/sandbox/runner/__main__.py b/coworker/sandbox/runner/__main__.py
index e25ce7ad..58c829cb 100644
--- a/coworker/sandbox/runner/__main__.py
+++ b/coworker/sandbox/runner/__main__.py
@@ -7,6 +7,7 @@ Runs as `python -m coworker.sandbox.runner ...` from a checkout, or as
from __future__ import annotations
import argparse
+import os
import sys
from .daemon import RUNNER_VERSION, Daemon
@@ -26,6 +27,11 @@ def main(argv: list[str] | None = None) -> int:
attach.add_argument("--silence-seconds", type=float, default=None, help="leave after this much client silence (0 = never)")
args = parser.parse_args(argv)
if args.command == "serve":
+ # A provider may put a folder of its own first on PATH (the ssh wrapper that points
+ # at a copied credential, section 11b) without knowing the sandbox's own PATH.
+ prepend = os.environ.pop("OPENWORKER_PATH_PREPEND", "")
+ if prepend:
+ os.environ["PATH"] = prepend + os.pathsep + os.environ.get("PATH", "")
Daemon(args.socket, args.cwd, args.exit_with_parent).serve_forever()
return 0
if args.silence_seconds is None:
diff --git a/tests/test_sandbox_credentials.py b/tests/test_sandbox_credentials.py
index f9c43e5c..06460389 100644
--- a/tests/test_sandbox_credentials.py
+++ b/tests/test_sandbox_credentials.py
@@ -95,7 +95,7 @@ def test_copy_in_makes_a_private_home_and_the_tools_environment(tmp_path):
assert f"IdentityFile {sb / '.ssh' / 'id_ed25519'}" in config and "IdentityAgent none" in config
assert config.endswith("Host work\n HostName git.example.com\n") # the user's own config still there, after ours
assert copied.env["GIT_SSH_COMMAND"] == f'/usr/bin/ssh -F "{sb / ".ssh" / "config"}"'
- assert (run / "bin" / "ssh").read_text().startswith("#!/bin/sh") and copied.path_dirs == [str(run / "bin")]
+ assert (sb / "bin" / "ssh").read_text().startswith("#!/bin/sh") and copied.env["OPENWORKER_PATH_PREPEND"] == str(sb / "bin")
assert copied.env["HOME"] == str(sb)
assert copied.env["GH_CONFIG_DIR"] == str(sb / ".config" / "gh")
assert copied.env["AWS_SHARED_CREDENTIALS_FILE"] == str(sb / ".aws" / "credentials")
@@ -198,7 +198,7 @@ def test_ssh_and_gh_copies_work_inside_seatbelt_and_ssh_goes_through_the_proxy(t
assert ws.describe()["credentials"][0]["name"] == "ssh"
assert "SSH keys" in ws.context()
# ssh: the ProxyCommand in the copied config carries the connection through the proxy
- assert run("command -v ssh")["output"].strip() == os.path.join(provider._dir, "bin", "ssh") # the wrapper wins
+ assert run("command -v ssh")["output"].strip() == os.path.join(provider.copied.home, "bin", "ssh") # the wrapper wins
out = run("ssh -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=no -v [email protected] true 2>&1 | grep -i 'remote protocol version\\|proxy\\|banner' | head -3")
assert "SSH-2.0-OpenSSH_9.9 fake" in out["output"] or "Remote protocol version 2.0" in out["output"], out["output"]
finally:
diff --git a/tests/test_sandbox_openshell.py b/tests/test_sandbox_openshell.py
index 3848256c..ce28688d 100644
--- a/tests/test_sandbox_openshell.py
+++ b/tests/test_sandbox_openshell.py
@@ -242,3 +242,48 @@ def test_a_sandbox_left_behind_by_a_dead_server_is_removed(folder):
assert orphan.sandbox_name in names()
removed = SandboxRegistry().reap()
assert orphan.sandbox_name in removed and orphan.sandbox_name not in names()
+
+
+@live
+def test_credential_grants_are_copied_into_a_real_sandbox(folder):
+ """A fake `.ssh` and `.config/gh` under a made-up home are granted: inside, HOME is the
+ copy, the files are readable, git and ssh are pointed at the copy, the grant's hosts are
+ in the policy, and the real home stays hidden (design doc, section 11b)."""
+ from coworker.sandbox import credentials as creds
+
+ home = folder / "fakehome"
+ (home / ".ssh").mkdir(parents=True)
+ (home / ".ssh" / "id_ed25519").write_text("PRIVATE KEY\n")
+ (home / ".ssh" / "id_ed25519.pub").write_text("ssh-ed25519 AAAA test\n")
+ (home / ".config" / "gh").mkdir(parents=True)
+ (home / ".config" / "gh" / "hosts.yml").write_text("github.com:\n oauth_token: gho_x\n")
+ (home / ".gitconfig").write_text("[user]\n\tname = Sam\n\temail = [email protected]\n")
+ grants = creds.granted([{"name": "ssh", "enabled": True}, {"name": "gh", "enabled": True}], home=str(home))
+ project = folder / "project"
+ project.mkdir()
+ from coworker.roots import RootDir
+ from coworker.sandbox.providers.openshell import OpenShellProvider
+ from coworker.sandbox.workspace import RunnerWorkspace
+
+ provider = OpenShellProvider(roots=[{"path": str(project), "writable": True}], cwd=str(project), credentials=grants)
+ ws = RunnerWorkspace(provider, cwd=project, live_roots=[RootDir(path=project, writable=True)])
+ try:
+ ex = ws.executor
+ copy = provider.copied.home
+ assert ex.run("echo $HOME")["output"].strip() == copy
+ assert "PRIVATE KEY" in ex.run("cat ~/.ssh/id_ed25519")["output"]
+ assert "gho_x" in ex.run('cat "$GH_CONFIG_DIR/hosts.yml"')["output"]
+ assert "IdentityFile" in ex.run("cat ~/.ssh/config")["output"]
+ assert "-F" in ex.run("echo $GIT_SSH_COMMAND")["output"]
+ hidden = ex.run(f"ls {home}/.ssh 2>&1")["output"].lower()
+ assert "denied" in hidden or "no such file" in hidden # the real files stay hidden (not mounted at all)
+ assert "SSH keys" in ws.context() and ws.describe()["credentials"][0]["name"] == "ssh"
+ import yaml
+
+ policy = yaml.safe_load((Path(provider._tmp) / "policy.yaml").read_text())
+ hosts = {(e["host"], e["port"]) for e in policy["network_policies"]["credentials"]["endpoints"]}
+ assert ("github.com", 22) in hosts and ("api.github.com", 443) in hosts
+ assert copy in policy["filesystem_policy"]["read_write"]
+ finally:
+ ws.close()
+ assert not Path(copy).exists() # the copies died with the sandbox