Python
Windows sandbox: credential grants in the account mode; Settings names the provider
Rohit C Prasad1b899acf650e
diff --git a/coworker/sandbox/credentials.py b/coworker/sandbox/credentials.pyindex bec827ed..ea0947d0 100644--- a/coworker/sandbox/credentials.py+++ b/coworker/sandbox/credentials.py@@ -16,6 +16,7 @@ from __future__ import annotationsimport osimport shutilimport stat+import sysfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Optional, Sequence@@ -171,6 +172,8 @@ def copy_in(home: Optional[str] = None,proxy_port: Optional[int] = None,ssh_proxy_command: Optional[str] = None,+ inside_home: Optional[str] = None,+ windows: Optional[bool] = None,) -> CopiedCredentials:"""Make the sandbox's private home under `runtime_dir` with the granted files inside.Returns the environment the sandbox needs so each tool finds its copy. With no grants@@ -178,40 +181,50 @@ def copy_in(`ssh_proxy_command`: when the sandbox can only reach the network through the proxy, a`ProxyCommand` for ssh (with `%h` and `%p`), put first in the copied ssh config so it wins.+ `inside_home`: the path the copy will have from the sandbox's side when a provider moves+ it there after this (the Windows account's own profile); every path written into the+ copy and into the environment uses it. Default: the copy stays where it is made.+ `windows`: write Windows wrappers (`ssh.cmd`, `ssh.exe`); default: this platform."""home = os.path.realpath(home or os.path.expanduser("~"))sandbox_home = os.path.join(os.path.realpath(runtime_dir), "home")if sandbox_home == home or sandbox_home.startswith(home + os.sep) and os.path.realpath(runtime_dir) == home:raise ValueError("the sandbox's runtime folder cannot be the home folder itself")+ seen = sandbox_home if inside_home is None else inside_home+ on_windows = (sys.platform == "win32") if windows is None else windowsos.makedirs(sandbox_home, mode=stat.S_IRWXU, exist_ok=True)for rel in _GIT_SETTINGS:src = os.path.join(home, rel)if os.path.exists(src):_copy_private(src, os.path.join(sandbox_home, rel))- env: dict[str, str] = {"HOME": sandbox_home}+ env: dict[str, str] = {"HOME": seen}hosts: list[str] = []path_dirs: list[str] = []for g in grants:dst = os.path.join(sandbox_home, g.relative)+ inside = os.path.join(seen, g.relative)_copy_private(g.path, dst)hosts += g.hostsif g.name == "ssh":# 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)+ env.update(_prepare_ssh(dst, bin_dir, ssh_proxy_command, inside_dir=inside, windows=on_windows))+ env["OPENWORKER_PATH_PREPEND"] = os.path.join(seen, "bin") # the runner daemon puts it first on PATH+ path_dirs.append(os.path.join(seen, "bin"))elif g.name == "gh":- env["GH_CONFIG_DIR"] = dst+ env["GH_CONFIG_DIR"] = insideelif g.name == "aws":- env["AWS_CONFIG_FILE"] = os.path.join(dst, "config")- env["AWS_SHARED_CREDENTIALS_FILE"] = os.path.join(dst, "credentials")+ env["AWS_CONFIG_FILE"] = os.path.join(inside, "config")+ env["AWS_SHARED_CREDENTIALS_FILE"] = os.path.join(inside, "credentials")elif g.name == "kube":- env["KUBECONFIG"] = os.path.join(dst, "config")+ env["KUBECONFIG"] = os.path.join(inside, "config")return CopiedCredentials(home=sandbox_home, env=env, hosts=sorted(set(hosts)), grants=list(grants), path_dirs=path_dirs)-def _prepare_ssh(ssh_dir: str, bin_dir: str, proxy_command: Optional[str]) -> dict[str, str]:+_WINDOWS_SSH = r"C:\Windows\System32\OpenSSH\ssh.exe"+++def _prepare_ssh(ssh_dir: str, bin_dir: str, proxy_command: Optional[str], *, inside_dir: Optional[str] = None, windows: bool = False) -> dict[str, str]:"""Make the copied `.ssh` usable from inside the sandbox.ssh reads its config and expands `~` from the ACCOUNT's home folder, not from `$HOME`,@@ -220,29 +233,42 @@ def _prepare_ssh(ssh_dir: str, bin_dir: str, proxy_command: Optional[str]) -> dioption) naming the copied known_hosts and every private key in the copy, with no agent(the real agent's socket is not reachable from inside, and sockets are not copied);a tiny `ssh` wrapper first on PATH passes `-F <copy>/config`; and `GIT_SSH_COMMAND` does- the same for git. With `proxy_command`, connections go through the proxy."""+ the same for git. With `proxy_command`, connections go through the proxy. `inside_dir`+ is the copy's path as the sandbox will see it (default: as it is here)."""+ seen = inside_dir or ssh_dirconfig = os.path.join(ssh_dir, "config")existing = Path(config).read_text(encoding="utf-8", errors="replace") if os.path.exists(config) else ""keys = sorted(- os.path.join(ssh_dir, name)- for name in os.listdir(ssh_dir)- if os.path.isfile(os.path.join(ssh_dir, name + ".pub")) and os.path.isfile(os.path.join(ssh_dir, name))+ name for name in os.listdir(ssh_dir) if os.path.isfile(os.path.join(ssh_dir, name + ".pub")) and os.path.isfile(os.path.join(ssh_dir, name)))lines = ["# Added by OpenWorker: this is a copy of your .ssh inside the sandbox", "Host *"]if proxy_command:lines.append(f" ProxyCommand {proxy_command}")- lines.append(f" UserKnownHostsFile {os.path.join(ssh_dir, 'known_hosts')}")+ lines.append(f" UserKnownHostsFile {_ssh_path(os.path.join(seen, 'known_hosts'), windows)}")lines.append(" IdentityAgent none")lines.append(" AddKeysToAgent no")- lines += [f" IdentityFile {key}" for key in keys]+ lines += [f" IdentityFile {_ssh_path(os.path.join(seen, key), windows)}" for key in keys]Path(config).write_text("\n".join(lines) + "\n\n" + existing, encoding="utf-8")os.chmod(config, stat.S_IRUSR | stat.S_IWUSR)Path(os.path.join(ssh_dir, "known_hosts")).touch(mode=stat.S_IRUSR | stat.S_IWUSR)os.makedirs(bin_dir, mode=stat.S_IRWXU, exist_ok=True)+ seen_config = os.path.join(seen, "config")+ if windows:+ wrapper = os.path.join(bin_dir, "ssh.cmd")+ Path(wrapper).write_text(f'@"{_WINDOWS_SSH}" -F "{seen_config}" %*\r\n', encoding="utf-8")+ return {"GIT_SSH_COMMAND": f'"{_WINDOWS_SSH}" -F "{seen_config}"'}wrapper = os.path.join(bin_dir, "ssh")- Path(wrapper).write_text(f'#!/bin/sh\nexec /usr/bin/ssh -F "{config}" "$@"\n', encoding="utf-8")+ Path(wrapper).write_text(f'#!/bin/sh\nexec /usr/bin/ssh -F "{seen_config}" "$@"\n', encoding="utf-8")os.chmod(wrapper, stat.S_IRWXU)- return {"GIT_SSH_COMMAND": f'/usr/bin/ssh -F "{config}"'}+ return {"GIT_SSH_COMMAND": f'/usr/bin/ssh -F "{seen_config}"'}+++def _ssh_path(path: str, windows: bool) -> str:+ """A path in an ssh config: quoted when it has spaces; forward slashes on Windows, which+ Windows OpenSSH reads and which keeps backslashes from being taken as escapes."""+ if windows:+ path = path.replace("\\", "/")+ return f'"{path}"' if " " in path else pathdef mac_ssh_proxy_command(port: int) -> str:@@ -250,6 +276,11 @@ def mac_ssh_proxy_command(port: int) -> str:return f"/usr/bin/nc -X connect -x 127.0.0.1:{int(port)} %h %p"+def windows_ssh_proxy_command(python: str, runner: str, port: int) -> str:+ """Windows ships no nc: the runner's own `connect` command is the ProxyCommand."""+ return f'"{python}" -S "{runner}" connect 127.0.0.1 {int(port)} %h %p'++def context_lines(copied: Optional[CopiedCredentials]) -> str:"""What the agent is told about the credentials it was given (ruling 21: the agent knowsits environment). Empty when nothing was granted."""diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.pyindex 9356c127..5ec145a3 100644--- a/coworker/sandbox/providers/windows.py+++ b/coworker/sandbox/providers/windows.py@@ -33,6 +33,7 @@ nothing.from __future__ import annotations+import base64import osimport shutilimport subprocess@@ -131,6 +132,8 @@ class WindowsProvider:self._token: Any = Noneself._desktop: Any = Noneself._granted: list[tuple[str, str]] = [] # (folder, "write" | "read") entries that exist right now+ self._runner_inside: Path = self._runner # where the sandbox sees the runner file+ self.notes: list[str] = [] # what the agent must be told beyond the credentials list# -- what it is ---------------------------------------------------------------------def describe(self) -> dict[str, Any]:@@ -147,6 +150,7 @@ class WindowsProvider:"mode": self.mode,"reason": reason,"credentials": self.copied.describe() if self.copied is not None else [],+ "notes": list(self.notes),}# -- start ------------------------------------------------------------------------@@ -161,8 +165,9 @@ class WindowsProvider:preflight()from .. import winsec+ hosts = sorted({h for g in self.grants for h in g.hosts})if self.network:- self._proxy = netproxy.shared(self.profile)+ self._proxy = netproxy.AllowListProxy(self.profile, extra_hosts=hosts) if hosts else netproxy.shared(self.profile)for root in self.roots:self._grant(root["path"], "write" if root["writable"] else "read")self._grant(self._dir, "write")@@ -172,17 +177,30 @@ class WindowsProvider:assert self._account is not Nonename, sid, password = self._account# The runner file lives in the user's state folder, which the account cannot see.- runner = Path(self._dir) / self._runner.name- shutil.copy2(self._runner, runner)+ self._runner_inside = Path(self._dir) / self._runner.name+ shutil.copy2(self._runner, self._runner_inside)env_args = [arg for k, v in self._environment(full=True).items() for arg in ("--env", f"{k}={v}")]serve = serve_arguments(self.socket_path, self._dir, also_sids=[sid])- argv = [*runner_command(runner), "serve", *serve, *env_args, "--cwd", self.cwd, "--exit-with-parent"]+ argv = [*runner_command(self._runner_inside), "serve", *serve, *env_args, "--cwd", self.cwd, "--exit-with-parent"]self._daemon = winsec.spawn_as_account(argv, account=name, password=password, desktop=self._desktop, cwd=self.cwd, stderr_path=log)else:+ self._runner_inside = self._runner+ env = self._environment(full=False)+ # Same user: Windows OpenSSH does its work under a write-restricted token but+ # never exits, and git's MSYS shell cannot start at all (no signal pipe), so an+ # ssh grant cannot be honoured here; the agent is told. The other grants are+ # files plus environment variables and work.+ usable = [g for g in self.grants if g.name != "ssh"]+ if len(usable) != len(self.grants):+ self.notes.append("The shared SSH key is not available in this sandbox: on Windows it needs the full sandbox (`openworker machine sandbox setup`).")+ if usable:+ self.copied = creds.copy_in(usable, self._dir, proxy_port=self._proxy.port if self._proxy else None)+ winsec.private_acl(self.copied.home) # the copy is this user's alone+ env.update(self.copied.env)self._token = winsec.RestrictedToken(self.session_sid)serve = serve_arguments(self.socket_path, self._dir, also_sids=[self.session_sid])argv = [*runner_command(self._runner), "serve", *serve, "--cwd", self.cwd, "--exit-with-parent"]- self._daemon = winsec.spawn(argv, token=self._token, desktop=self._desktop, cwd=self.cwd, env=self._environment(full=False), stderr_path=log)+ self._daemon = winsec.spawn(argv, token=self._token, desktop=self._desktop, cwd=self.cwd, env=env, stderr_path=log)try:wait_for_runner(self.socket_path, self._daemon)except RuntimeError as exc:@@ -204,6 +222,48 @@ class WindowsProvider:env.update(netproxy.environment(self._proxy))return env+ def _ssh_proxy_command(self) -> Optional[str]:+ if self._proxy is None:+ return None+ return creds.windows_ssh_proxy_command(sys.executable, str(self._runner_inside), self._proxy.port)++ _CLEARED = (".ssh", ".config/gh", ".aws", ".kube", "bin")++ def provision(self, client: Any) -> None:+ """Full mode: the copies of granted credentials go into the ACCOUNT's own profile,+ written by the daemon so that the account owns them (Windows OpenSSH refuses a key+ file owned by someone else). Whatever an earlier sandbox left there is removed+ first; the daemon removes them again when it leaves."""+ if self.mode != FULL:+ return+ from ..runner.protocol import RunnerError++ home_inside = str(client.hello.get("home") or "")+ if not home_inside:+ raise WindowsUnavailable("the sandboxed runner did not report its home folder")+ for rel in self._CLEARED:+ try:+ client.call("fs.remove", {"path": os.path.join(home_inside, rel), "recursive": True}, timeout=30)+ except RunnerError:+ pass # nothing there+ if not self.grants:+ return+ staging = tempfile.mkdtemp(prefix="owc-")+ try:+ self.copied = creds.copy_in(self.grants, staging, inside_home=home_inside, ssh_proxy_command=self._ssh_proxy_command(), windows=True)+ shipped: list[str] = []+ for folder, _dirs, files in os.walk(self.copied.home):+ rel_folder = os.path.relpath(folder, self.copied.home)+ for name in files:+ rel = name if rel_folder == "." else os.path.join(rel_folder, name)+ data = Path(folder, name).read_bytes()+ client.call("fs.write", {"path": os.path.join(home_inside, rel), "data_b64": base64.b64encode(data).decode(), "make_parents": True}, timeout=30)+ shipped.append(rel.split(os.sep)[0])+ client.call("runner.cleanup_at_exit", {"paths": sorted({os.path.join(home_inside, top) for top in shipped})}, timeout=15)+ client.call("env.set", {"vars": self.copied.env}, timeout=15)+ finally:+ shutil.rmtree(staging, ignore_errors=True)+def open_runner(self) -> Transport:argv = [*runner_command(self._runner), "attach", "--socket", self.socket_path]if self._relay_silence is not None:@@ -301,6 +361,9 @@ class WindowsProvider:if thing is not None:thing.close()self._token = self._desktop = None+ if self._proxy is not None and self._proxy is not netproxy._proxies.get(self.profile):+ self._proxy.close() # this session's own proxy; the shared one stays+ self._proxy = None# The job's last processes (cmd holding the log) may still be going; give them a moment.for _ in range(20):shutil.rmtree(self._dir, ignore_errors=True)diff --git a/coworker/sandbox/runner/__main__.py b/coworker/sandbox/runner/__main__.pyindex 44c7f2da..8f617622 100644--- a/coworker/sandbox/runner/__main__.py+++ b/coworker/sandbox/runner/__main__.py@@ -28,7 +28,16 @@ def main(argv: list[str] | None = None) -> int:attach = sub.add_parser("attach", help="connect this process's stdin/stdout to the daemon")attach.add_argument("--socket", required=True)attach.add_argument("--silence-seconds", type=float, default=None, help="leave after this much client silence (0 = never)")+ connect = sub.add_parser("connect", help="a tunnel through the allow-list proxy on stdin/stdout (ssh ProxyCommand)")+ connect.add_argument("proxy_host")+ connect.add_argument("proxy_port", type=int)+ connect.add_argument("host")+ connect.add_argument("port", type=int)args = parser.parse_args(argv)+ if args.command == "connect":+ from .connect import run as run_connect++ return run_connect(args.proxy_host, args.proxy_port, args.host, args.port)if args.command == "serve":for item in args.env:name, sep, value = item.partition("=")diff --git a/coworker/sandbox/runner/connect.py b/coworker/sandbox/runner/connect.pynew file mode 100644index 00000000..96238992--- /dev/null+++ b/coworker/sandbox/runner/connect.py@@ -0,0 +1,75 @@+"""`connect`: an HTTP CONNECT client for ssh's ProxyCommand where there is no `nc`.++`runner connect <proxy host> <proxy port> <host> <port>` opens a tunnel to host:port+through the allow-list proxy and copies bytes between it and stdin/stdout. Windows ships+no netcat, and ssh on every platform can run a ProxyCommand; this is that command.+Standard library only, like the rest of the runner.+"""++from __future__ import annotations++import os+import socket+import sys+import threading+++def run(proxy_host: str, proxy_port: int, host: str, port: int) -> int:+ if sys.platform == "win32":+ import msvcrt++ msvcrt.setmode(0, os.O_BINARY)+ msvcrt.setmode(1, os.O_BINARY)+ try:+ sock = socket.create_connection((proxy_host, proxy_port), timeout=20)+ except OSError as exc:+ print(f"connect: cannot reach the proxy at {proxy_host}:{proxy_port}: {exc}", file=sys.stderr)+ return 2+ sock.sendall(f"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n\r\n".encode())+ reply = b""+ while b"\r\n\r\n" not in reply:+ chunk = sock.recv(4096)+ if not chunk:+ break+ reply += chunk+ status = reply.split(b"\r\n", 1)[0].decode(errors="replace")+ if " 200" not in status:+ print(f"connect: the proxy refused {host}:{port}: {status}", file=sys.stderr)+ sock.close()+ return 3+ sock.settimeout(None)+ done = threading.Event()++ def upstream() -> None:+ try:+ while True:+ data = os.read(0, 65536)+ if not data:+ break+ sock.sendall(data)+ sock.shutdown(socket.SHUT_WR)+ except OSError:+ pass+ done.set()++ def downstream() -> None:+ try:+ while True:+ data = sock.recv(65536)+ if not data:+ break+ view = memoryview(data)+ while view:+ view = view[os.write(1, view):]+ except OSError:+ pass+ done.set()++ threading.Thread(target=upstream, daemon=True).start()+ threading.Thread(target=downstream, daemon=True).start()+ done.wait()+ try:+ sock.close()+ except OSError:+ pass+ return 0diff --git a/coworker/sandbox/runner/daemon.py b/coworker/sandbox/runner/daemon.pyindex 5a24e9de..18a867f5 100644--- a/coworker/sandbox/runner/daemon.py+++ b/coworker/sandbox/runner/daemon.py@@ -125,6 +125,7 @@ class Daemon:self._gap = False # a result fell off the log before it was acknowledgedself._requests: "collections.OrderedDict[str, Optional[bytes]]" = collections.OrderedDict()self._conn: Optional[_Conn] = None+ self._cleanup: list[str] = []self._stop = threading.Event()# -- outgoing ---------------------------------------------------------------------@@ -199,9 +200,33 @@ class Daemon:"python": platform.python_version(),"shell": "powershell.exe" if sys.platform == "win32" else "/bin/bash","cwd": self.default_cwd,+ "home": os.path.expanduser("~"),"shells": sorted(self._shells),}+ def _env_set(self, params: dict[str, Any]) -> dict[str, Any]:+ """Variables for the shells started from now on (a provider that could not pass an+ environment at start, or learned a path only after connecting). `OPENWORKER_PATH_PREPEND`+ goes first on PATH, as at start."""+ variables = params.get("vars")+ if not isinstance(variables, dict):+ raise ValueError("'vars' must be an object")+ for name, value in variables.items():+ if name == "OPENWORKER_PATH_PREPEND":+ os.environ["PATH"] = str(value) + os.pathsep + os.environ.get("PATH", "")+ else:+ os.environ[str(name)] = str(value)+ return {"set": sorted(str(k) for k in variables)}++ def _cleanup_at_exit(self, params: dict[str, Any]) -> dict[str, Any]:+ """Paths this daemon removes when it shuts down (copies it was given that live where+ the server cannot delete them)."""+ paths = params.get("paths")+ if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths):+ raise ValueError("'paths' must be a list of strings")+ self._cleanup.extend(paths)+ return {"paths": list(self._cleanup)}+def _resume(self, params: dict[str, Any]) -> dict[str, Any]:last = int(params.get("last_seq") or 0)with self._out_lock:@@ -271,6 +296,10 @@ class Daemon:def _dispatch(self, req_id: str, method: str, params: dict[str, Any]) -> dict[str, Any]:if method == "runner.hello":return self._hello(params)+ if method == "env.set":+ return self._env_set(params)+ if method == "runner.cleanup_at_exit":+ return self._cleanup_at_exit(params)if method == "session.resume":return self._resume(params)if method == "shell.open":@@ -408,6 +437,14 @@ class Daemon:for task_id in list(shell.executor._bg_tasks):shell.executor.background_kill(task_id)shell.executor.close()+ for path in self._cleanup:+ try:+ if os.path.isdir(path) and not os.path.islink(path):+ shutil.rmtree(path, ignore_errors=True)+ elif os.path.lexists(path):+ os.remove(path)+ except OSError:+ passif not self.is_pipe:try:os.unlink(self.socket_path)diff --git a/coworker/sandbox/winsec.py b/coworker/sandbox/winsec.pyindex 575fb884..5f8267d6 100644--- a/coworker/sandbox/winsec.py+++ b/coworker/sandbox/winsec.py@@ -439,18 +439,18 @@ def spawn_as_account(return Process(info, job)-def _explicit(sid: _Sid, mode: int, permissions: int = 0) -> "EXPLICIT_ACCESS_W":+def _explicit(sid: _Sid, mode: int, permissions: int = 0, inherit: bool = True) -> "EXPLICIT_ACCESS_W":entry = EXPLICIT_ACCESS_W()entry.grfAccessPermissions = permissions or _FILE_GENERIC_MODIFYentry.grfAccessMode = mode- entry.grfInheritance = _CONTAINER_INHERIT_ACE | _OBJECT_INHERIT_ACE+ entry.grfInheritance = (_CONTAINER_INHERIT_ACE | _OBJECT_INHERIT_ACE) if inherit else 0entry.Trustee.TrusteeForm = _TRUSTEE_IS_SIDentry.Trustee.TrusteeType = 0 # TRUSTEE_IS_UNKNOWN: it is no accountentry.Trustee.ptstrName = sid.pointer.valuereturn entry-def _change_dacl(folder: str, sid_text: str, mode: int, permissions: int = 0) -> None:+def _change_dacl(folder: str, sid_text: str, mode: int, permissions: int = 0, inherit: bool = True) -> None:sid = _Sid(sid_text)old = ctypes.c_void_p()descriptor = ctypes.c_void_p()@@ -459,7 +459,7 @@ def _change_dacl(folder: str, sid_text: str, mode: int, permissions: int = 0) ->raise OSError(status, f"GetNamedSecurityInfo {folder}: {ctypes.FormatError(status).strip()}")try:new = ctypes.c_void_p()- entry = _explicit(sid, mode, permissions)+ entry = _explicit(sid, mode, permissions, inherit)status = _adv.SetEntriesInAclW(1, ctypes.byref(entry), old, ctypes.byref(new))if status:raise OSError(status, f"SetEntriesInAcl {folder}: {ctypes.FormatError(status).strip()}")@@ -473,10 +473,11 @@ def _change_dacl(folder: str, sid_text: str, mode: int, permissions: int = 0) ->_k32.LocalFree(descriptor)-def grant_write(folder: str, sid_text: str) -> None:+def grant_write(folder: str, sid_text: str, *, inherit: bool = True) -> None:"""One inheritable Modify entry for the SID on the folder (what `icacls /grant- *SID:(OI)(CI)M` would do, without the account lookup that icacls insists on)."""- _change_dacl(folder, sid_text, _GRANT_ACCESS)+ *SID:(OI)(CI)M` would do, without the account lookup that icacls insists on).+ `inherit=False` for one file."""+ _change_dacl(folder, sid_text, _GRANT_ACCESS, inherit=inherit)def grant_read(folder: str, sid_text: str) -> None:@@ -489,6 +490,24 @@ def revoke(folder: str, sid_text: str) -> None:_change_dacl(folder, sid_text, _REVOKE_ACCESS)+def private_acl(path: str) -> None:+ """Make a folder (and what is under it) readable by this user, administrators and+ SYSTEM only, with no inheritance: what Windows OpenSSH demands of a key file."""+ import subprocess++ # The folder gets the three entries and stops inheriting; everything under it is then+ # reset to inherit from the folder. (One `/T` pass instead would leave the files with+ # an EMPTY list: the inheritable flags are not valid on a file and the grant is dropped.)+ steps = [+ ["icacls", path, "/inheritance:r", "/grant:r", f"*{current_user_sid()}:(OI)(CI)F", "/grant:r", "*S-1-5-18:(OI)(CI)F", "/grant:r", "*S-1-5-32-544:(OI)(CI)F", "/Q"],+ ["icacls", os.path.join(path, "*"), "/reset", "/T", "/Q"],+ ] # fmt: skip+ for argv in steps:+ done = subprocess.run(argv, capture_output=True, text=True)+ if done.returncode != 0:+ raise OSError(done.returncode, f"{' '.join(argv[:2])}: {(done.stderr or done.stdout).strip()}")++def entries_for(folder: str, sid_text: str) -> bool:"""Whether the folder's own DACL still names the SID (for tests and clean-up checks)."""import subprocessdiff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.pyindex ce36adeb..1e071029 100644--- a/coworker/sandbox/workspace.py+++ b/coworker/sandbox/workspace.py@@ -93,9 +93,7 @@ class RunnerWorkspace(Workspace):try:self.client = RunnerClient(provider.open_runner)self.hello = self.client.connect()- verify = getattr(provider, "verify", None)- if verify is not None:- verify(self.client) # e.g. every folder is really reachable inside+ self._after_connect()except Exception:provider.destroy()raise@@ -139,12 +137,25 @@ class RunnerWorkspace(Workspace):regrant(wanted)if restarts:self.client.connect() # a new runner: the client notes the restart- verify = getattr(self.provider, "verify", None)- if verify is not None:- verify(self.client)+ self._after_connect()+ else:+ verify = getattr(self.provider, "verify", None)+ if verify is not None:+ verify(self.client)self._record()return RESTART_NOTICE if restarts else REGRANT_NOTICE+ def _after_connect(self) -> None:+ """What a provider does once it can talk to its runner: prove the wall is up, then+ put in what it could not put in before the runner existed (copies that must be+ owned by the sandbox's own account)."""+ verify = getattr(self.provider, "verify", None)+ if verify is not None:+ verify(self.client) # e.g. every folder is really reachable inside+ provision = getattr(self.provider, "provision", None)+ if provision is not None:+ provision(self.client)+@propertydef executor(self) -> Executor:return self._executor@@ -153,7 +164,9 @@ class RunnerWorkspace(Workspace):"""What the agent is told about this sandbox each turn (ruling 21)."""from .credentials import context_lines- return context_lines(getattr(self.provider, "copied", None))+ text = context_lines(getattr(self.provider, "copied", None))+ notes = getattr(self.provider, "notes", None) or []+ return "\n".join(part for part in [text, *notes] if part)def describe(self) -> dict[str, Any]:return {**self.provider.describe(), "runner": {k: self.hello.get(k) for k in ("runner_version", "os", "machine", "instance_id")}}@@ -162,6 +175,13 @@ class RunnerWorkspace(Workspace):try:self._executor.close()finally:+ try:+ # Ask the daemon to leave by itself first: it ends its shells and removes+ # what only it can (its folder, copies it was handed). The provider's+ # destroy() is the hard stop behind it.+ self.client.call("runner.shutdown", timeout=5)+ except Exception:+ passself.client.close()self.provider.destroy()if self.registry is not None and self._registered:diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsxindex 01cf5790..f6f17652 100644--- a/surfaces/gui/src/components/SettingsView.tsx+++ b/surfaces/gui/src/components/SettingsView.tsx@@ -748,6 +748,7 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {const providerNames: Record<string, [string, string]> = {direct: [t("settingsx.sandbox.provider_direct"), t("settingsx.sandbox.provider_direct_desc")],seatbelt: [t("settingsx.sandbox.provider_seatbelt"), t("settingsx.sandbox.provider_seatbelt_desc")],+ windows: [t("settingsx.sandbox.provider_windows"), t("settingsx.sandbox.provider_windows_desc")],openshell: [t("settingsx.sandbox.provider_openshell"), t("settingsx.sandbox.provider_openshell_desc")],};const chosen = cfg.provider || cfg.effective_provider || "direct";@@ -769,7 +770,7 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {<div className={FIELD_LABEL + " mb-2"}>{t("settingsx.sandbox.run_in")}</div><div className={CARD + " mb-1 divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.run_in")}>{cfg.providers- .filter((p) => p.name !== "seatbelt" || cfg.platform === "darwin")+ .filter((p) => (p.name !== "seatbelt" || cfg.platform === "darwin") && (p.name !== "windows" || cfg.platform === "win32")).map((p) => {const [label, desc] = providerNames[p.name] ?? [p.name, ""];const active = chosen === p.name;diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 5bda529e..472edb76 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -2276,6 +2276,8 @@"provider_direct_desc": "Commands run as you, with no limits. Fastest. The default until you choose otherwise.","provider_seatbelt": "macOS sandbox","provider_seatbelt_desc": "Commands can read and write only the session's folders and reach only the network hosts on the allow list. Your other files and logins are hidden.",+ "provider_windows": "Windows sandbox",+ "provider_windows_desc": "Commands run as a hidden local account that cannot see your profile, and reach only the network hosts on the allow list. Without the one-time setup (openworker machine sandbox setup), writes are limited to the session's folders and nothing else is.","provider_openshell": "OpenShell (NVIDIA)","provider_openshell_desc": "One Linux container per agent, with the session's folders mounted. Needs OpenShell and Docker on this machine.","status_default": "default",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 8eb9980b..bb972e86 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -2236,6 +2236,8 @@"provider_direct_desc": "命令以你的身份运行,没有限制。最快。在你另作选择前为默认。","provider_seatbelt": "macOS 沙箱","provider_seatbelt_desc": "命令只能读写会话的文件夹,只能访问允许列表中的网络主机。你的其他文件和登录信息被隐藏。",+ "provider_windows": "Windows 沙箱",+ "provider_windows_desc": "命令以一个看不到你的用户配置文件的隐藏本地账户运行,只能访问允许列表中的网络主机。未做一次性设置(openworker machine sandbox setup)时,只限制写入到会话的文件夹,其他不受限制。","provider_openshell": "OpenShell(NVIDIA)","provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要这台机器上装有 OpenShell 和 Docker。","status_default": "默认",diff --git a/tests/test_sandbox_credentials.py b/tests/test_sandbox_credentials.pyindex d49b8297..1d6bf2a7 100644--- a/tests/test_sandbox_credentials.py+++ b/tests/test_sandbox_credentials.py@@ -93,10 +93,14 @@ def test_copy_in_makes_a_private_home_and_the_tools_environment(tmp_path):assert not (sb / "Documents").exists() # nothing that was not grantedconfig = (sb / ".ssh" / "config").read_text()assert config.startswith("# Added by OpenWorker") and "ProxyCommand /usr/bin/nc -X connect -x 127.0.0.1:4545 %h %p" in config- assert f"IdentityFile {sb / '.ssh' / 'id_ed25519'}" in config and "IdentityAgent none" in config+ key_path = str(sb / ".ssh" / "id_ed25519").replace("\\", "/") if sys.platform == "win32" else str(sb / ".ssh" / "id_ed25519")+ assert f"IdentityFile {key_path}" in config and "IdentityAgent none" in config+ ssh_exe = r'"C:\Windows\System32\OpenSSH\ssh.exe"' if sys.platform == "win32" else "/usr/bin/ssh"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 (sb / "bin" / "ssh").read_text().startswith("#!/bin/sh") and copied.env["OPENWORKER_PATH_PREPEND"] == str(sb / "bin")+ assert copied.env["GIT_SSH_COMMAND"] == f'{ssh_exe} -F "{sb / ".ssh" / "config"}"'+ wrapper = (sb / "bin" / "ssh.cmd") if sys.platform == "win32" else (sb / "bin" / "ssh")+ assert wrapper.read_text().startswith("@" if sys.platform == "win32" else "#!/bin/sh")+ assert 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")diff --git a/tests/test_sandbox_windows.py b/tests/test_sandbox_windows.pyindex 63cfeafa..bbfee96a 100644--- a/tests/test_sandbox_windows.py+++ b/tests/test_sandbox_windows.py@@ -118,6 +118,109 @@ def test_the_provider_is_known_to_selection_and_settings(monkeypatch, tmp_path):assert names["windows"]["usable"] and "seatbelt" not in names+# -- credential grants ---------------------------------------------------------------------+++def _fake_home(tmp_path):+ """A home with a real (throwaway) ssh key, made by Windows' own ssh-keygen."""+ import subprocess++ home = tmp_path / "home"+ (home / ".ssh").mkdir(parents=True)+ subprocess.run([r"C:\Windows\System32\OpenSSH\ssh-keygen.exe", "-q", "-t", "ed25519", "-N", "", "-f", str(home / ".ssh" / "id_ed25519")], check=True, capture_output=True)+ (home / ".gitconfig").write_text("[user]\n\tname = Sam\n\temail = [email protected]\n")+ return home+++def _ssh_probe(ws) -> str:+ """Reaches GitHub over SSH through whatever the sandbox provides. A throwaway key gets+ "Permission denied (publickey)": the tunnel, the config and the key all worked. Through+ cmd, because PowerShell 5 turns a native command's first stderr line into an error+ record and drops the rest of its output."""+ return ws.executor.run('cmd.exe /d /c "ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -T [email protected] 2>&1"')["output"]+++@full+def test_a_granted_ssh_key_reaches_github_through_the_proxy(tmp_path):+ from coworker.sandbox import credentials as creds+ from coworker.sandbox.providers.windows import WindowsProvider++ home = _fake_home(tmp_path)+ grants = creds.granted([{"name": "ssh", "enabled": True}], home=str(home))+ project = tmp_path / "project"+ project.mkdir()+ zipapp = build_runner_zipapp(tmp_path / "dist")+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=True, credentials=grants, force_mode="full")+ ws = RunnerWorkspace(provider, cwd=project)+ ws.executor.default_timeout = 90+ try:+ assert ws.describe()["credentials"][0]["name"] == "ssh"+ config = ws.executor.run("Get-Content (Join-Path $env:USERPROFILE '.ssh\\config')")["output"]+ assert "ProxyCommand" in config and "connect 127.0.0.1" in config and "IdentityFile" in config+ said = _ssh_probe(ws)+ assert "Permission denied (publickey)" in said, said+ inside = ws.executor.run("Join-Path $env:USERPROFILE '.ssh'")["output"].strip()+ assert inside.lower().startswith(r"c:\users\openworkersandbox")+ finally:+ ws.close()+++def test_the_same_user_mode_refuses_an_ssh_grant_and_says_so(tmp_path):+ """Windows OpenSSH does not exit under a write-restricted token and git's MSYS shell+ cannot start there, so the same-user mode keeps the other grants and tells the agent."""+ from coworker.sandbox import credentials as creds+ from coworker.sandbox.providers.windows import WindowsProvider++ home = _fake_home(tmp_path)+ (home / ".config" / "gh").mkdir(parents=True)+ (home / ".config" / "gh" / "hosts.yml").write_text("github.com:\n oauth_token: gho_x\n")+ grants = creds.granted([{"name": "ssh", "enabled": True}, {"name": "gh", "enabled": True}], home=str(home))+ project = tmp_path / "project"+ project.mkdir()+ zipapp = build_runner_zipapp(tmp_path / "dist")+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=False, credentials=grants, force_mode="partial")+ ws = RunnerWorkspace(provider, cwd=project)+ ws.executor.default_timeout = 60+ try:+ assert [c["name"] for c in ws.describe()["credentials"]] == ["gh"]+ assert "needs the full sandbox" in ws.context()+ assert "gho_x" in ws.executor.run("Get-Content (Join-Path $env:GH_CONFIG_DIR 'hosts.yml')")["output"]+ assert ws.executor.run("Test-Path (Join-Path $env:HOME '.ssh')")["output"].strip() == "False"+ finally:+ ws.close()+ assert not os.path.exists(provider._dir) # the copy went with the private folder+++@full+def test_full_mode_removes_the_copies_when_the_sandbox_ends(tmp_path):+ """The account's profile persists between sandboxes; the copies must not."""+ from coworker.sandbox import credentials as creds+ from coworker.sandbox.providers.windows import WindowsProvider++ home = _fake_home(tmp_path)+ grants = creds.granted([{"name": "ssh", "enabled": True}], home=str(home))+ project = tmp_path / "project"+ project.mkdir()+ zipapp = build_runner_zipapp(tmp_path / "dist")++ def open_one(with_grants):+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=False, credentials=grants if with_grants else (), force_mode="full")+ ws = RunnerWorkspace(provider, cwd=project)+ ws.executor.default_timeout = 60+ return ws++ ws = open_one(True)+ try:+ assert ws.executor.run("Test-Path (Join-Path $env:USERPROFILE '.ssh\\id_ed25519')")["output"].strip() == "True"+ finally:+ ws.close()+ ws = open_one(False)+ try:+ assert ws.executor.run("Test-Path (Join-Path $env:USERPROFILE '.ssh')")["output"].strip() == "False"+ finally:+ ws.close()++# -- setup and the full mode ---------------------------------------------------------------