Python
Tool runner on Windows: the daemon listens on a named pipe
Rohit C Prasad42f71f8abd84
diff --git a/coworker/sandbox/launch.py b/coworker/sandbox/launch.pyindex cc79d561..062e88f5 100644--- a/coworker/sandbox/launch.py+++ b/coworker/sandbox/launch.py@@ -11,8 +11,14 @@ Mac binary cannot run there.from __future__ import annotationsimport os+import subprocessimport sys+import tempfile+import timefrom pathlib import Path+from typing import Optional++from .runner import winpipedef frozen() -> bool:@@ -39,6 +45,54 @@ def read_paths() -> list[str]:return sorted(p for p in paths if p)+def runner_dir(base: Optional[str] = None) -> tuple[str, str]:+ """A private folder for one runner and the address its daemon listens on: a socket+ file inside the folder, or on Windows a named pipe carrying the folder's name.+ A Unix socket path is limited to about 100 bytes and temp folders on macOS are long,+ so the folder is short and under `/tmp` there."""+ if sys.platform == "win32":+ folder = tempfile.mkdtemp(prefix="owr-")+ return folder, winpipe.pipe_name(os.path.basename(folder))+ folder = tempfile.mkdtemp(prefix="owr-", dir=base or ("/tmp" if os.path.isdir("/tmp") else None))+ return folder, os.path.join(folder, "r.sock")+++def serve_arguments(address: str, folder: str) -> list[str]:+ """The `serve` options that tell the daemon where it lives and who may connect."""+ args = ["--socket", address, "--dir", folder]+ if winpipe.is_pipe(address):+ from . import winsec++ args += ["--allow-sid", winsec.current_user_sid()]+ return args+++def spawn_kwargs() -> dict:+ """How a daemon or relay is started so that it shares neither our session nor our+ console: its own session on POSIX, its own process group and no window on Windows."""+ if sys.platform == "win32":+ return {"creationflags": winpipe.default_creation_flags()}+ return {"start_new_session": True}+++def wait_for_runner(address: str, daemon: subprocess.Popen, *, seconds: float = 15, said: Optional[str] = None) -> None:+ """Block until the daemon listens at `address`; raise when it exits first or is late."""+ deadline = time.monotonic() + seconds+ while not _listening(address):+ if daemon.poll() is not None:+ tail = f" {said[-400:]}" if said else ""+ raise RuntimeError(f"the tool runner exited at once (code {daemon.returncode}).{tail}")+ if time.monotonic() > deadline:+ raise RuntimeError(f"the tool runner did not come up in {seconds:g} seconds")+ time.sleep(0.02)+++def _listening(address: str) -> bool:+ if winpipe.is_pipe(address):+ return winpipe.wait_ready(address)+ return os.path.exists(address)++def maybe_run_runner(argv: list[str]) -> bool:"""`openworker-server sandbox-runner <serve|attach> ...`: run the runner and exit.Returns False when argv is anything else. Imports only the runner package, so thediff --git a/coworker/sandbox/providers/runner_local.py b/coworker/sandbox/providers/runner_local.pyindex 770f2a05..79e47dd8 100644--- a/coworker/sandbox/providers/runner_local.py+++ b/coworker/sandbox/providers/runner_local.py@@ -10,14 +10,12 @@ from __future__ import annotationsimport osimport shutilimport subprocess-import sys-import tempfile-import timefrom pathlib import Pathfrom typing import Any, Optionalfrom ..bundle import build_runner_zipapp-from ..launch import runner_command+from ..launch import runner_command, runner_dir, serve_arguments, spawn_kwargs, wait_for_runner+from ..runner import winpipefrom ..transport import PipeTransport, Transport@@ -28,10 +26,7 @@ class RunnerLocalProvider:self.cwd = str(Path(cwd).expanduser().resolve())self._runner = Path(runner_path) if runner_path is not None else build_runner_zipapp()self._relay_silence = relay_silence_seconds- # A Unix socket path is limited to about 100 bytes, and temp folders on macOS are- # long, so the socket gets a short folder of its own.- self._dir = tempfile.mkdtemp(prefix="owr-", dir="/tmp" if os.path.isdir("/tmp") else None)- self.socket_path = os.path.join(self._dir, "r.sock")+ self._dir, self.socket_path = runner_dir()self._daemon: Optional[subprocess.Popen] = Nonedef describe(self) -> dict[str, Any]:@@ -39,26 +34,20 @@ class RunnerLocalProvider:def create(self) -> None:self._daemon = subprocess.Popen(- [*runner_command(self._runner), "serve", "--socket", self.socket_path, "--cwd", self.cwd, "--exit-with-parent"],+ [*runner_command(self._runner), "serve", *serve_arguments(self.socket_path, self._dir), "--cwd", self.cwd, "--exit-with-parent"],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,- start_new_session=True,+ **spawn_kwargs(),)- deadline = time.monotonic() + 15- while not os.path.exists(self.socket_path):- if self._daemon.poll() is not None:- raise RuntimeError(f"the tool runner exited at once (code {self._daemon.returncode})")- if time.monotonic() > deadline:- raise RuntimeError("the tool runner did not come up in 15 seconds")- time.sleep(0.02)+ wait_for_runner(self.socket_path, self._daemon)def open_runner(self) -> Transport:argv = [*runner_command(self._runner), "attach", "--socket", self.socket_path]if self._relay_silence is not None:argv += ["--silence-seconds", str(self._relay_silence)]return PipeTransport(- subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0)+ subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0, **spawn_kwargs()))def restart_daemon(self) -> None:@@ -73,10 +62,11 @@ class RunnerLocalProvider:self._daemon.wait(timeout=5)except subprocess.TimeoutExpired:self._daemon.kill()- try:- os.unlink(self.socket_path)- except OSError:- pass+ if not winpipe.is_pipe(self.socket_path):+ try:+ os.unlink(self.socket_path)+ except OSError:+ passdef destroy(self) -> None:self._stop_daemon()diff --git a/coworker/sandbox/registry.py b/coworker/sandbox/registry.pyindex 490fb77b..28071387 100644--- a/coworker/sandbox/registry.py+++ b/coworker/sandbox/registry.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport jsonimport os+import sysimport sqlite3import threadingimport time@@ -48,6 +49,11 @@ class SandboxLimitReached(RuntimeError):def _alive(pid: int) -> bool:+ if sys.platform == "win32":+ # `os.kill(pid, 0)` is TerminateProcess on Windows, not a probe.+ from .runner import winpipe++ return not winpipe.process_is_gone(pid)try:os.kill(pid, 0)except ProcessLookupError:diff --git a/coworker/sandbox/runner/__main__.py b/coworker/sandbox/runner/__main__.pyindex 58c829cb..fee4e5cf 100644--- a/coworker/sandbox/runner/__main__.py+++ b/coworker/sandbox/runner/__main__.py@@ -19,9 +19,11 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--version", action="version", version=RUNNER_VERSION)sub = parser.add_subparsers(dest="command", required=True)serve = sub.add_parser("serve", help="run the daemon (the sandbox's main process)")- serve.add_argument("--socket", required=True, help="path of the Unix socket file to listen on")+ serve.add_argument("--socket", required=True, help="path of the Unix socket file to listen on (Windows: a \\\\.\\pipe\\ name)")serve.add_argument("--cwd", default=None, help="folder new shells start in (default: current folder)")serve.add_argument("--exit-with-parent", action="store_true", help="stop when the starting process is gone (local use)")+ serve.add_argument("--dir", default=None, help="this runner's own folder, removed at shutdown (default: the socket's folder)")+ serve.add_argument("--allow-sid", action="append", default=[], help="Windows: an account that may connect to the pipe (repeatable)")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)")@@ -32,7 +34,7 @@ def main(argv: list[str] | None = None) -> int: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()+ Daemon(args.socket, args.cwd, args.exit_with_parent, runtime_dir=args.dir, allow_sids=args.allow_sid).serve_forever()return 0if args.silence_seconds is None:return run_relay(args.socket)diff --git a/coworker/sandbox/runner/daemon.py b/coworker/sandbox/runner/daemon.pyindex ef81a016..5a24e9de 100644--- a/coworker/sandbox/runner/daemon.py+++ b/coworker/sandbox/runner/daemon.py@@ -31,9 +31,9 @@ import threadingimport timeimport uuidfrom pathlib import Path-from typing import Any, Callable, Optional+from typing import Any, Callable, Iterator, Optional, Sequence-from . import fsops, protocol as P, toolcalls+from . import fsops, protocol as P, toolcalls, winpipefrom .executor import LocalExecutorRUNNER_VERSION = "0.1.0"@@ -41,11 +41,34 @@ _RESULT_LOG_MAX = 5000_REQUEST_MEMORY_MAX = 5000-class _Conn:- """One attached client (through a relay). Writes are serialized."""+class _SocketStream:+ """A connected Unix socket, in the shape `_Conn` needs (winpipe.PipeStream is the other)."""def __init__(self, sock: socket.socket) -> None:self.sock = sock++ def sendall(self, data: bytes) -> None:+ self.sock.sendall(data)++ def lines(self) -> Iterator[bytes]:+ return iter(self.sock.makefile("rb"))++ def close(self) -> None:+ try:+ self.sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ self.sock.close()+ except OSError:+ pass+++class _Conn:+ """One attached client (through a relay). Writes are serialized."""++ def __init__(self, stream: Any) -> None:+ self.stream = streamself._lock = threading.Lock()self.alive = True@@ -54,7 +77,7 @@ class _Conn:return Falsetry:with self._lock:- self.sock.sendall(frame)+ self.stream.sendall(frame)return Trueexcept OSError:self.alive = False@@ -62,14 +85,7 @@ class _Conn:def close(self) -> None:self.alive = False- try:- self.sock.shutdown(socket.SHUT_RDWR)- except OSError:- pass- try:- self.sock.close()- except OSError:- pass+ self.stream.close()class _Shell:@@ -80,8 +96,23 @@ class _Shell:class Daemon:- def __init__(self, socket_path: str, default_cwd: Optional[str] = None, exit_with_parent: bool = False) -> None:+ def __init__(+ self,+ socket_path: str,+ default_cwd: Optional[str] = None,+ exit_with_parent: bool = False,+ *,+ runtime_dir: Optional[str] = None,+ allow_sids: Sequence[str] = (),+ ) -> None:+ """`socket_path` is a Unix socket file, or on Windows a `\\\\.\\pipe\\` name.+ `runtime_dir` is this runner's own folder (temporary files, the log), removed at+ shutdown; for a socket it defaults to the socket's folder. `allow_sids` (Windows)+ are the accounts that may connect to the pipe."""self.socket_path = socket_path+ self.is_pipe = winpipe.is_pipe(socket_path)+ self.runtime_dir = runtime_dir if runtime_dir is not None else (None if self.is_pipe else os.path.dirname(socket_path))+ self.allow_sids = list(allow_sids)# Outside a sandbox nothing else ends this process when its server goes away.self._parent = os.getppid() if exit_with_parent else Noneself.default_cwd = str(Path(default_cwd or os.getcwd()).expanduser().resolve())@@ -332,9 +363,8 @@ class Daemon:old, self._conn = self._conn, connif old is not None:old.close() # the newest connection wins- reader = conn.sock.makefile("rb")try:- for line in reader:+ for line in conn.stream.lines():frame = P.decode(line)if frame is None:continue@@ -378,11 +408,14 @@ class Daemon:for task_id in list(shell.executor._bg_tasks):shell.executor.background_kill(task_id)shell.executor.close()- try:- os.unlink(self.socket_path)- except OSError:- pass- folder = os.path.dirname(self.socket_path)+ if not self.is_pipe:+ try:+ os.unlink(self.socket_path)+ except OSError:+ pass+ folder = self.runtime_dir+ if not folder:+ returntry:if os.path.basename(folder).startswith("owr-"):# A folder a provider made for this one runner (socket, temporary files, log).@@ -393,8 +426,21 @@ class Daemon:except OSError:pass- def serve_forever(self) -> None:+ def _parent_is_gone(self) -> bool:+ if self._parent is None:+ return False+ if sys.platform == "win32":+ return winpipe.process_is_gone(self._parent)+ return os.getppid() != self._parent++ def _listen(self) -> Callable[[float], Optional[Any]]:+ """Start listening; the result takes a timeout and gives the next client's stream,+ or None when nobody came in time. Closing is `self._close_listener`."""path = self.socket_path+ if self.is_pipe:+ listener = winpipe.Listener(path, self.allow_sids)+ self._close_listener = listener.close+ return listener.acceptPath(path).parent.mkdir(parents=True, exist_ok=True)try:os.unlink(path)@@ -407,21 +453,34 @@ class Daemon:finally:os.umask(old_mask)server.listen(16)- server.settimeout(0.5)- print(f"openworker tool runner {RUNNER_VERSION} ready on {path} (instance {self.instance_id})", file=sys.stderr, flush=True)+ self._close_listener = server.close++ def accept(timeout: float) -> Optional[_SocketStream]:+ server.settimeout(timeout)+ try:+ sock, _ = server.accept()+ except socket.timeout:+ return None+ return _SocketStream(sock)++ return accept++ def serve_forever(self) -> None:+ accept = self._listen()+ print(f"openworker tool runner {RUNNER_VERSION} ready on {self.socket_path} (instance {self.instance_id})", file=sys.stderr, flush=True)try:while not self._stop.is_set():try:- sock, _ = server.accept()- except socket.timeout:- if self._parent is not None and os.getppid() != self._parent:- break # the server that started us is gone- continue+ stream = accept(0.5)except OSError:break- threading.Thread(target=self._serve_conn, args=(_Conn(sock),), daemon=True).start()+ if stream is None:+ if self._parent_is_gone():+ break # the server that started us is gone+ continue+ threading.Thread(target=self._serve_conn, args=(_Conn(stream),), daemon=True).start()finally:- server.close()+ self._close_listener()self._shutdown()diff --git a/coworker/sandbox/runner/relay.py b/coworker/sandbox/runner/relay.pyindex f650dd66..4329e374 100644--- a/coworker/sandbox/runner/relay.py+++ b/coworker/sandbox/runner/relay.py@@ -15,18 +15,32 @@ import sysimport threadingimport time+from . import winpipefrom .protocol import RELAY_SILENCE_SECONDS+def _connect(socket_path: str):+ """The daemon's end: a Unix socket, or on Windows a named pipe (same three calls)."""+ if winpipe.is_pipe(socket_path):+ return winpipe.connect(socket_path)+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ sock.connect(socket_path)+ return sock++def run(socket_path: str, silence_seconds: float = RELAY_SILENCE_SECONDS) -> int:# Keep the pipe clean: move the real stdout to a private descriptor and point# descriptor 1 at stderr, so a stray print can never land inside a frame.out_fd = os.dup(1)os.dup2(2, 1)+ if sys.platform == "win32":+ import msvcrt++ msvcrt.setmode(0, os.O_BINARY) # frames are bytes; no newline translation+ msvcrt.setmode(out_fd, os.O_BINARY)- sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)try:- sock.connect(socket_path)+ sock = _connect(socket_path)except OSError as exc:print(f"attach: cannot reach the runner at {socket_path}: {exc}", file=sys.stderr)return 2diff --git a/coworker/sandbox/runner/winpipe.py b/coworker/sandbox/runner/winpipe.pynew file mode 100644index 00000000..3ff74814--- /dev/null+++ b/coworker/sandbox/runner/winpipe.py@@ -0,0 +1,198 @@+"""The runner's pipe on Windows: a named pipe instead of a Unix socket file.++Windows Python has no `AF_UNIX`, so when the daemon's address starts with `\\\\.\\pipe\\` it+listens on a named pipe and the relay connects to one. Both ends are the standard library's+`multiprocessing.connection.PipeConnection` (message mode, overlapped I/O, cancellable from+another thread); on top of that this module gives the daemon and the relay the same small+shape the socket has: `sendall`, `recv`, `lines`, `close`.++The pipe's security descriptor is the one thing that matters for a sandbox: when the daemon+runs as the sandbox account, only the server's user may connect. `listen(address,+allow_sids=[...])` writes exactly those accounts into the descriptor; with no list, the+pipe keeps Windows' default (the creator, Administrators and SYSTEM may use it).+"""++from __future__ import annotations++import ctypes+import sys+from typing import Any, Iterator, Optional, Sequence++PIPE_PREFIX = "\\\\.\\pipe\\"+_BUFSIZE = 65536+++def is_pipe(address: str) -> bool:+ return address.startswith(PIPE_PREFIX)+++def pipe_name(tag: str) -> str:+ return PIPE_PREFIX + tag+++class PipeStream:+ """One connected end. `recv` returns b"" once the other side is gone."""++ def __init__(self, conn: Any) -> None:+ self._conn = conn++ def sendall(self, data: bytes) -> None:+ self._conn.send_bytes(data)++ def recv(self, _size: int = _BUFSIZE) -> bytes:+ try:+ return self._conn.recv_bytes()+ except (EOFError, OSError):+ return b""++ def lines(self) -> Iterator[bytes]:+ """Lines as the socket's `makefile("rb")` yields them: a message from the other+ side may hold part of a line or several, so they are cut here."""+ buffer = b""+ while True:+ chunk = self.recv()+ if not chunk:+ break+ buffer += chunk+ while True:+ cut = buffer.find(b"\n")+ if cut < 0:+ break+ yield buffer[: cut + 1]+ buffer = buffer[cut + 1 :]+ if buffer:+ yield buffer++ def close(self) -> None:+ try:+ self._conn.close()+ except OSError:+ pass+++def connect(address: str) -> PipeStream:+ from multiprocessing.connection import PipeClient++ return PipeStream(PipeClient(address))+++class Listener:+ """The daemon's side. `accept(timeout)` returns a stream or None when nobody came."""++ def __init__(self, address: str, allow_sids: Sequence[str] = ()) -> None:+ import _winapi++ self._winapi = _winapi+ self.address = address+ self._security = _SecurityAttributes(allow_sids) if allow_sids else None+ self._pending: Optional[tuple[int, Any]] = None # (handle, overlapped connect)+ self._closed = False+ self._new_instance(first=True)++ def _new_instance(self, first: bool = False) -> None:+ w = self._winapi+ flags = w.PIPE_ACCESS_DUPLEX | w.FILE_FLAG_OVERLAPPED+ if first:+ flags |= w.FILE_FLAG_FIRST_PIPE_INSTANCE # fail if the name is already taken+ handle = w.CreateNamedPipe(+ self.address,+ flags,+ w.PIPE_TYPE_MESSAGE | w.PIPE_READMODE_MESSAGE | w.PIPE_WAIT,+ w.PIPE_UNLIMITED_INSTANCES,+ _BUFSIZE,+ _BUFSIZE,+ w.NMPWAIT_WAIT_FOREVER,+ self._security.pointer if self._security is not None else w.NULL,+ )+ self._pending = (handle, w.ConnectNamedPipe(handle, overlapped=True))++ def accept(self, timeout: float) -> Optional[PipeStream]:+ from multiprocessing.connection import PipeConnection++ w = self._winapi+ if self._pending is None:+ raise OSError("the listener is closed")+ handle, overlapped = self._pending+ if w.WaitForSingleObject(overlapped.event, int(timeout * 1000)) == w.WAIT_TIMEOUT:+ return None+ try:+ overlapped.GetOverlappedResult(True)+ except OSError:+ if self._closed:+ raise+ w.CloseHandle(handle) # a client that went away before we looked+ self._new_instance()+ return None+ self._new_instance() # the next instance waits while this one is served+ return PipeStream(PipeConnection(handle))++ def close(self) -> None:+ self._closed = True+ pending, self._pending = self._pending, None+ if pending is not None:+ handle, overlapped = pending+ try:+ overlapped.cancel()+ except OSError:+ pass+ self._winapi.CloseHandle(handle)+++class _SecurityAttributes:+ """A SECURITY_ATTRIBUTES whose descriptor grants full access to the given accounts and+ nothing to anyone else (the creator keeps the owner's right to read and change it)."""++ def __init__(self, sids: Sequence[str]) -> None:+ from ctypes import wintypes++ sddl = "D:P" + "".join(f"(A;;GA;;;{sid})" for sid in sids)+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)+ convert = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW+ convert.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.ULONG)]+ descriptor = ctypes.c_void_p()+ size = wintypes.ULONG()+ ok = convert(sddl, 1, ctypes.byref(descriptor), ctypes.byref(size)) # 1 = SDDL_REVISION_1+ if not ok:+ raise OSError(ctypes.get_last_error(), f"cannot build the pipe's security descriptor from {sddl!r}")+ self._descriptor = descriptor # LocalAlloc'd; lives as long as this object++ class SECURITY_ATTRIBUTES(ctypes.Structure):+ _fields_ = [("nLength", wintypes.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wintypes.BOOL)]++ self._attributes = SECURITY_ATTRIBUTES(ctypes.sizeof(SECURITY_ATTRIBUTES), descriptor, False)+ self.pointer = ctypes.addressof(self._attributes)+++def process_is_gone(pid: int) -> bool:+ """Whether the process with this id has exited. `os.getppid()` on Windows keeps+ returning the old parent's id after it dies, so the daemon asks the process itself."""+ import _winapi++ try:+ handle = _winapi.OpenProcess(_winapi.SYNCHRONIZE, False, pid)+ except OSError:+ return True # no such process any more (or nothing we may look at: treat as gone)+ try:+ return _winapi.WaitForSingleObject(handle, 0) == _winapi.WAIT_OBJECT_0+ finally:+ _winapi.CloseHandle(handle)+++def wait_ready(address: str, timeout_ms: int = 50) -> bool:+ """Whether a server instance of the pipe exists (without connecting to it)."""+ import _winapi++ try:+ _winapi.WaitNamedPipe(address, timeout_ms)+ return True+ except OSError:+ return False+++def default_creation_flags() -> int:+ """For a child that must not share our console or our Ctrl-C (subprocess kwargs)."""+ if sys.platform != "win32":+ return 0+ import subprocess++ return subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOWdiff --git a/coworker/sandbox/winsec.py b/coworker/sandbox/winsec.pynew file mode 100644index 00000000..cbeb5156--- /dev/null+++ b/coworker/sandbox/winsec.py@@ -0,0 +1,52 @@+"""Windows account facts the sandbox providers need, through ctypes (no pywin32).++Only the server side imports this; the runner package stays standard library and does not+need to know who its server is beyond the SIDs it is handed.+"""++from __future__ import annotations++import ctypes+import sys+from functools import lru_cache+++@lru_cache(maxsize=1)+def current_user_sid() -> str:+ """The SID of the account this process runs as, as a string (`S-1-5-21-...`)."""+ if sys.platform != "win32":+ raise OSError("Windows only")+ from ctypes import wintypes++ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ # Handles are pointer-sized: without these, the current process's pseudo handle (-1)+ # is cut to 32 bits on the way in and comes back as "invalid handle".+ kernel32.GetCurrentProcess.restype = wintypes.HANDLE+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.LocalFree.argtypes = [ctypes.c_void_p]+ advapi32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]+ advapi32.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]+ advapi32.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_wchar_p)]+ TOKEN_QUERY = 0x0008+ TokenUser = 1++ token = wintypes.HANDLE()+ if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), TOKEN_QUERY, ctypes.byref(token)):+ raise ctypes.WinError(ctypes.get_last_error())+ try:+ needed = wintypes.DWORD()+ advapi32.GetTokenInformation(token, TokenUser, None, 0, ctypes.byref(needed))+ buffer = ctypes.create_string_buffer(needed.value)+ if not advapi32.GetTokenInformation(token, TokenUser, buffer, needed, ctypes.byref(needed)):+ raise ctypes.WinError(ctypes.get_last_error())+ sid = ctypes.c_void_p.from_buffer(buffer).value # TOKEN_USER starts with SID_AND_ATTRIBUTES.Sid+ text = ctypes.c_wchar_p()+ if not advapi32.ConvertSidToStringSidW(ctypes.c_void_p(sid), ctypes.byref(text)):+ raise ctypes.WinError(ctypes.get_last_error())+ try:+ return text.value or ""+ finally:+ kernel32.LocalFree(text)+ finally:+ kernel32.CloseHandle(token)diff --git a/tests/test_sandbox_credentials.py b/tests/test_sandbox_credentials.pyindex 06460389..d49b8297 100644--- a/tests/test_sandbox_credentials.py+++ b/tests/test_sandbox_credentials.py@@ -86,8 +86,9 @@ def test_copy_in_makes_a_private_home_and_the_tools_environment(tmp_path):sb = Path(copied.home)assert sb == run / "home"assert (sb / ".ssh" / "id_ed25519").read_text() == "PRIVATE KEY\n"- assert stat.S_IMODE((sb / ".ssh" / "id_ed25519").stat().st_mode) == 0o600- assert stat.S_IMODE((sb / ".ssh").stat().st_mode) == 0o700+ if sys.platform != "win32": # Windows has no mode bits; the copy's ACL is the Windows provider's job+ assert stat.S_IMODE((sb / ".ssh" / "id_ed25519").stat().st_mode) == 0o600+ assert stat.S_IMODE((sb / ".ssh").stat().st_mode) == 0o700assert (sb / ".gitconfig").exists() # git's settings always come alongassert not (sb / "Documents").exists() # nothing that was not grantedconfig = (sb / ".ssh" / "config").read_text()@@ -207,6 +208,7 @@ def test_ssh_and_gh_copies_work_inside_seatbelt_and_ssh_goes_through_the_proxy(tassert not Path(provider.copied.home).exists() # the copies died with the sandbox[email protected](sys.platform == "win32", reason="the Seatbelt provider keeps its folder under /tmp")def test_a_failed_creation_leaves_no_copied_credential_behind(tmp_path, monkeypatch):from coworker.sandbox.providers import seatbeltdiff --git a/tests/test_sandbox_openshell.py b/tests/test_sandbox_openshell.pyindex ce28688d..5a42573b 100644--- a/tests/test_sandbox_openshell.py+++ b/tests/test_sandbox_openshell.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport osimport subprocess+import sysimport threadingimport timefrom pathlib import Path@@ -121,7 +122,7 @@ def test_registry_reaps_rows_of_a_server_that_is_gone(tmp_path, monkeypatch):reg = registry_mod.SandboxRegistry(tmp_path / "registry.db")reg.record("owr-local-1", provider="runner-local", session_id="s1")reg.record("owr-local-2", provider="runner-local", session_id="s2")- gone = subprocess.Popen(["true"])+ gone = subprocess.Popen([sys.executable, "-c", "pass"])gone.wait()with reg._connect() as db:db.execute("UPDATE sandboxes SET server_pid = ? WHERE name = ?", (gone.pid, "owr-local-1"))diff --git a/tests/test_sandbox_runner.py b/tests/test_sandbox_runner.pyindex eb55f90c..77d26958 100644--- a/tests/test_sandbox_runner.py+++ b/tests/test_sandbox_runner.py@@ -2,13 +2,16 @@These run the real thing end to end: the runner packed into its single file, a daemonprocess, an attach relay per pipe, and the client. No sandbox technology is involved-(`runner-local`), so what is tested here is the protocol and its delivery rules.+(`runner-local`), so what is tested here is the protocol and its delivery rules. The+daemon listens on a Unix socket, or on Windows a named pipe; the shell is bash there and+PowerShell here, so the commands come in two spellings."""from __future__ import annotationsimport astimport base64+import shutilimport sysimport threadingimport time@@ -17,16 +20,33 @@ from pathlib import Pathimport pytest-pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="the tool runner needs Unix sockets")--from coworker.sandbox.bundle import build_runner_zipapp # noqa: E402-from coworker.sandbox.client import RunnerClient # noqa: E402-from coworker.sandbox.executor import RunnerExecutor # noqa: E402-from coworker.sandbox.providers.runner_local import RunnerLocalProvider # noqa: E402-from coworker.sandbox.runner import protocol as P # noqa: E402-from coworker.sandbox.workspace import DirectWorkspace, RunnerWorkspace, open_workspace # noqa: E402+from coworker.sandbox.bundle import build_runner_zipapp+from coworker.sandbox.client import RunnerClient+from coworker.sandbox.executor import RunnerExecutor+from coworker.sandbox.providers.runner_local import RunnerLocalProvider+from coworker.sandbox.runner import protocol as P+from coworker.sandbox.workspace import DirectWorkspace, RunnerWorkspace, open_workspaceRUNNER_DIR = Path(__file__).resolve().parents[1] / "coworker" / "sandbox" / "runner"+_WIN = sys.platform == "win32"+posix_only = pytest.mark.skipif(_WIN, reason="bash syntax")+++def _sleep(seconds: float) -> str:+ # `Start-Sleep 0.4` would sleep 0 s: its `-Seconds` is an integer in PowerShell 5.+ return f"Start-Sleep -Milliseconds {int(seconds * 1000)}" if _WIN else f"sleep {seconds}"+++def _cd_and_set(folder: str, name: str, value: str) -> str:+ return f"cd {folder}; $env:{name}='{value}'" if _WIN else f"cd {folder} && export {name}={value}"+++def _echo_var_and_leaf(name: str) -> str:+ """Prints the variable and the current folder's last component."""+ return f'echo "$env:{name} $(Split-Path -Leaf (Get-Location))"' if _WIN else f"echo ${name} $(basename $PWD)"+++LEAF = "Split-Path -Leaf (Get-Location)" if _WIN else "basename $PWD"@pytest.fixture@@ -86,6 +106,7 @@ def test_lines_that_are_not_frames_are_dropped():assert P.decode(b"\xff\xfe\n") is None+@posix_onlydef test_multi_line_output_and_shell_syntax_survive_the_pipe(runner, tmp_path):_, client = runnerex = RunnerExecutor(client, cwd=str(tmp_path))@@ -119,8 +140,9 @@ def test_results_look_the_same_as_the_in_process_executor(runner, tmp_path):_, client = runnerdirect = DirectWorkspace(cwd=tmp_path)try:- ours = RunnerExecutor(client, cwd=str(tmp_path)).run("echo hi; false")- theirs = direct.executor.run("echo hi; false")+ command = "echo hi; cmd /c exit 1" if _WIN else "echo hi; false"+ ours = RunnerExecutor(client, cwd=str(tmp_path)).run(command)+ theirs = direct.executor.run(command)finally:direct.close()assert ours == theirs@@ -132,17 +154,17 @@ def test_each_shell_keeps_its_own_folder_and_variables(runner, tmp_path):(tmp_path / "b").mkdir()one = RunnerExecutor(client, cwd=str(tmp_path), shell="agent-1")two = RunnerExecutor(client, cwd=str(tmp_path), shell="agent-2")- one.run("cd a && export WHO=one")- two.run("cd b && export WHO=two")- assert one.run("echo $WHO $(basename $PWD)")["output"].split() == ["one", "a"]- assert two.run("echo $WHO $(basename $PWD)")["output"].split() == ["two", "b"]+ one.run(_cd_and_set("a", "WHO", "one"))+ two.run(_cd_and_set("b", "WHO", "two"))+ assert one.run(_echo_var_and_leaf("WHO"))["output"].split() == ["one", "a"]+ assert two.run(_echo_var_and_leaf("WHO"))["output"].split() == ["two", "b"]def test_a_slow_shell_does_not_block_another(runner, tmp_path):_, client = runnerslow = RunnerExecutor(client, cwd=str(tmp_path), shell="slow")fast = RunnerExecutor(client, cwd=str(tmp_path), shell="fast")- worker = threading.Thread(target=lambda: slow.run("sleep 2"))+ worker = threading.Thread(target=lambda: slow.run(_sleep(2)))worker.start()time.sleep(0.3)started = time.monotonic()@@ -154,7 +176,7 @@ def test_a_slow_shell_does_not_block_another(runner, tmp_path):def test_one_shell_runs_one_command_at_a_time(runner, tmp_path):_, client = runnerex = RunnerExecutor(client, cwd=str(tmp_path))- worker = threading.Thread(target=lambda: ex.run("sleep 1.5"))+ worker = threading.Thread(target=lambda: ex.run(_sleep(1.5)))worker.start()time.sleep(0.3)second = ex.run("echo too-soon")@@ -168,7 +190,8 @@ def test_live_output_is_a_view_and_the_result_is_the_record(runner, tmp_path):ex = RunnerExecutor(client, cwd=str(tmp_path), on_output=seen.append)fast = ex.run("echo instant")assert fast["output"].startswith("instant") and seen == [] # too quick for a live frame- slow = ex.run("for i in 1 2 3; do echo tick $i; sleep 0.4; done")+ ticks = f'foreach ($i in 1..3) {{ "tick $i"; {_sleep(0.4)} }}' if _WIN else "for i in 1 2 3; do echo tick $i; sleep 0.4; done"+ slow = ex.run(ticks)assert "tick 1" in "".join(seen) # the view arrived while it ranassert all(f"tick {i}" in slow["output"] for i in (1, 2, 3)) # the record is complete@@ -184,10 +207,10 @@ def test_user_stop_ends_the_command_and_the_session_carries_on(runner, tmp_path)ex.run("cd work")threading.Timer(0.5, ex.interrupt_now).start()started = time.monotonic()- stopped = ex.run("sleep 20", timeout=30)+ stopped = ex.run(_sleep(20), timeout=30)assert time.monotonic() - started < 10assert stopped["error"] == "interrupted by user"- assert ex.run("basename $PWD")["output"].strip() == "work"+ assert ex.run(LEAF)["output"].strip() == "work"# -- delivery after a break -------------------------------------------------------------@@ -195,24 +218,26 @@ def test_user_stop_ends_the_command_and_the_session_carries_on(runner, tmp_path)def test_a_cut_stream_resumes_and_no_result_is_lost(runner, tmp_path):provider, client = runner+ (tmp_path / "away").mkdir()ex = RunnerExecutor(client, cwd=str(tmp_path))- ex.run("cd /tmp && export KEEP=yes")+ ex.run(_cd_and_set("away", "KEEP", "yes"))instance = client.instance_idbox: dict = {}- worker = threading.Thread(target=lambda: box.update(ex.run("sleep 1.5; echo finished-while-away")))+ worker = threading.Thread(target=lambda: box.update(ex.run(f"{_sleep(1.5)}; echo finished-while-away")))worker.start()time.sleep(0.4)client._transport.proc.kill() # the stream is cut while the command runsworker.join(timeout=20)assert "finished-while-away" in box.get("output", "") # delivered after the resumeassert client.instance_id == instance and client.restarts == 0 # same daemon- assert ex.run("echo $KEEP $PWD")["output"].split() == ["yes", "/tmp"] # same shell+ assert ex.run(_echo_var_and_leaf("KEEP"))["output"].split() == ["yes", "away"] # same shelldef test_the_same_request_id_runs_once(runner, tmp_path):_, client = runnertarget = tmp_path / "count.txt"- frame = P.encode(P.request("r-fixed", "shell.run", {"shell": "main", "command": f"echo x >> {target}", "cwd": str(tmp_path)}))+ append = f"Add-Content -Path '{target}' -Value x" if _WIN else f"echo x >> {target}"+ frame = P.encode(P.request("r-fixed", "shell.run", {"shell": "main", "command": append, "cwd": str(tmp_path)}))for _ in range(3):client._send(client._transport, frame)deadline = time.monotonic() + 10@@ -226,16 +251,16 @@ def test_a_restarted_sandbox_fails_the_running_command_and_reopens_in_the_last_fprovider, client = runner(tmp_path / "work").mkdir()ex = RunnerExecutor(client, cwd=str(tmp_path))- ex.run("cd work && export GONE=soon")+ ex.run(_cd_and_set("work", "GONE", "soon"))box: dict = {}- worker = threading.Thread(target=lambda: box.update(ex.run("sleep 30", timeout=60)))+ worker = threading.Thread(target=lambda: box.update(ex.run(_sleep(30), timeout=60)))worker.start()time.sleep(0.4)provider.restart_daemon() # a new runner instance, as after a sandbox restartworker.join(timeout=30)assert "outcome of this command is unknown" in box["error"] # never re-sent by the clientassert client.restarts == 1- after = ex.run("echo [$GONE] $(basename $PWD)")+ after = ex.run(f'echo "[$env:GONE] $({LEAF})"' if _WIN else "echo [$GONE] $(basename $PWD)")assert after["output"].split() == ["[]", "work"] # variables lost, folder kept@@ -264,7 +289,7 @@ def test_a_relay_left_behind_goes_away_by_itself(tmp_path):def test_files_are_read_in_pages_and_written_with_a_precondition(runner, tmp_path):_, client = runnerbig = tmp_path / "out.log"- big.write_text("".join(f"line {i}\n" for i in range(1, 1001)))+ big.write_bytes("".join(f"line {i}\n" for i in range(1, 1001)).encode()) # the same bytes on Windowspage = client.call("fs.read", {"path": str(big), "offset_line": 10, "limit_lines": 3}, timeout=10)assert page["text"] == "line 10\nline 11\nline 12\n"assert (page["start_line"], page["end_line"], page["total_lines"], page["eof"]) == (10, 12, 1000, False)@@ -286,17 +311,52 @@ def test_files_are_read_in_pages_and_written_with_a_precondition(runner, tmp_patdef test_a_relative_path_resolves_against_the_shells_folder(runner, tmp_path):_, client = runner(tmp_path / "sub").mkdir()- RunnerExecutor(client, cwd=str(tmp_path), shell="agent-1").run("cd sub && echo hello > here.txt")+ write = "cd sub; Set-Content -Path here.txt -Value hello" if _WIN else "cd sub && echo hello > here.txt"+ RunnerExecutor(client, cwd=str(tmp_path), shell="agent-1").run(write)got = client.call("fs.read", {"path": "here.txt", "shell": "agent-1"}, timeout=10)- assert got["text"] == "hello\n"+ assert got["text"].splitlines() == ["hello"]listing = client.call("fs.list", {"path": ".", "shell": "agent-1"}, timeout=10)assert [e["name"] for e in listing["entries"]] == ["here.txt"]def test_proc_run_takes_an_argument_list_without_a_shell(runner, tmp_path):_, client = runner- done = client.call("proc.run", {"argv": ["printf", "%s|", "a b", "$HOME"], "cwd": str(tmp_path)}, timeout=10)- assert done["exit_code"] == 0 and done["stdout"] == "a b|$HOME|" # no shell: nothing expanded+ argv = [sys.executable, "-c", "import sys; print('|'.join(sys.argv[1:]))", "a b", "$HOME"]+ done = client.call("proc.run", {"argv": argv, "cwd": str(tmp_path)}, timeout=30)+ assert done["exit_code"] == 0 and done["stdout"].strip() == "a b|$HOME" # no shell: nothing expanded++[email protected](not _WIN, reason="the named pipe's security descriptor is Windows only")+def test_the_pipe_admits_only_the_listed_accounts(tmp_path):+ """On Windows the daemon may run as another account; its pipe must admit exactly the+ accounts it was given (the server's user). A pipe that lists only the Anonymous+ account refuses us, one that lists our own account does not."""+ import subprocess++ from coworker.sandbox import launch, winsec+ from coworker.sandbox.runner import winpipe++ zipapp = build_runner_zipapp(tmp_path / "dist")+ for sid, expect_refused in ((winsec.current_user_sid(), False), ("S-1-5-7", True)):+ folder, address = launch.runner_dir()+ daemon = subprocess.Popen(+ [*launch.runner_command(zipapp), "serve", "--socket", address, "--dir", folder, "--allow-sid", sid, "--cwd", str(tmp_path)],+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, **launch.spawn_kwargs(),+ ) # fmt: skip+ try:+ launch.wait_for_runner(address, daemon)+ try:+ stream = winpipe.connect(address)+ except PermissionError:+ refused = True+ else:+ refused = False+ stream.close()+ assert refused is expect_refused, f"pipe for {sid}: refused={refused}"+ finally:+ daemon.kill()+ daemon.wait(timeout=10)+ shutil.rmtree(folder, ignore_errors=True)# -- choosing a workspace ---------------------------------------------------------------diff --git a/tests/test_sandbox_seatbelt.py b/tests/test_sandbox_seatbelt.pyindex a046331e..25112b71 100644--- a/tests/test_sandbox_seatbelt.py+++ b/tests/test_sandbox_seatbelt.py@@ -24,6 +24,10 @@ from coworker.sandbox.selection import select# -- the profile ----------------------------------------------------------------------+posix_paths = pytest.mark.skipif(sys.platform == "win32", reason="the profile is written for macOS paths")+++@posix_pathsdef test_profile_lists_the_folders_and_nothing_else_under_home(tmp_path):home = tmp_path / "home"(home / ".nvm").mkdir(parents=True)@@ -48,6 +52,7 @@ def test_profile_lists_the_folders_and_nothing_else_under_home(tmp_path):assert "remote tcp" not in text # no proxy port given: no network at all+@posix_pathsdef test_profile_allows_only_the_proxy_port_and_quotes_paths(tmp_path):odd = tmp_path / 'has "quotes" and spaces'odd.mkdir()diff --git a/tests/test_shell.py b/tests/test_shell.pyindex 6bb1bf2b..99b60de9 100644--- a/tests/test_shell.py+++ b/tests/test_shell.py@@ -24,6 +24,7 @@ ECHO_ENV = "echo $env:GREETING" if _WIN else "echo $GREETING"EXIT_OK = "cmd /c exit 0" if _WIN else "true"EXIT_FAIL = "cmd /c exit 1" if _WIN else "false"SLEEP_5 = "Start-Sleep -Seconds 5" if _WIN else "sleep 5"+PWD = "(Get-Location).Path" if _WIN else "pwd" # PowerShell's `pwd` is a table that cuts long pathsPRINT_1000 = ('foreach ($i in 1..1000) { "line$i" }'if _WIN@@ -32,9 +33,9 @@ PRINT_1000 = (# Every behaviour below is checked twice: on the in-process executor (direct mode) and on-# the same contract served by a tool runner in another process (the sandbox path). The two-# must not drift apart. The runner needs Unix sockets, so it is skipped on Windows.-_EXECUTORS = ["direct"] if _WIN else ["direct", "runner"]+# the same contract served by a tool runner in another process (the sandbox path, over a+# Unix socket or a Windows named pipe). The two must not drift apart.+_EXECUTORS = ["direct", "runner"]if sys.platform == "darwin":_EXECUTORS.append("seatbelt") # the same runner, inside the macOS sandbox@@ -76,7 +77,7 @@ def _runner_zipapp(tmp_path):def test_cwd_persists_across_calls(executor, tmp_path):(tmp_path / "sub").mkdir()executor.run("cd sub")- result = executor.run("pwd")+ result = executor.run(PWD)assert result["exit_code"] == 0assert "sub" in result["output"]assert executor.cwd.endswith("sub")