Python
Windows sandbox provider, same-user mode: writes limited by a write-restricted token
Rohit C Prasad750ae3489bdd
diff --git a/coworker/sandbox/launch.py b/coworker/sandbox/launch.pyindex 062e88f5..766815f4 100644--- a/coworker/sandbox/launch.py+++ b/coworker/sandbox/launch.py@@ -16,7 +16,7 @@ import sysimport tempfileimport timefrom pathlib import Path-from typing import Optional+from typing import Optional, Sequencefrom .runner import winpipe@@ -57,13 +57,16 @@ def runner_dir(base: Optional[str] = None) -> tuple[str, str]: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."""+def serve_arguments(address: str, folder: str, *, also_sids: Sequence[str] = ()) -> list[str]:+ """The `serve` options that tell the daemon where it lives and who may connect: this+ user (the server), plus `also_sids` (a sandbox's own session SID, so that a daemon+ under a write-restricted token may open further instances of its own pipe)."""args = ["--socket", address, "--dir", folder]if winpipe.is_pipe(address):from . import winsec- args += ["--allow-sid", winsec.current_user_sid()]+ for sid in (winsec.current_user_sid(), *also_sids):+ args += ["--allow-sid", sid]return argsdiff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.pynew file mode 100644index 00000000..234094b3--- /dev/null+++ b/coworker/sandbox/providers/windows.py@@ -0,0 +1,232 @@+"""`windows`: the tool runner on Windows, confined by a write-restricted token.++Same runner, same protocol. The wall, in this first mode (`partial`), is Windows' own+restricted-token rule: the daemon runs as the current user but its token carries a+made-up session SID as a RESTRICTING SID with `WRITE_RESTRICTED`, so any write must be+allowed for that SID as well as for the user. The session's writable folders and the+sandbox's private folder get one inheritable Modify entry for the SID; nothing else on the+disk has one. The entries are removed when the sandbox closes. Every process the daemon+starts inherits the token; no program can take it off.++What this mode does NOT do (and says so in `describe()`): reads are the user's reads, so a+key under the profile can be read; the network is the user's network, the allow-list proxy+is only offered through the proxy variables. Folders that grant Everyone a write (the drive+root's "create folder", `C:\\Users\\Public`, `C:\\Windows\\Temp`) stay writable, as in every+write-restricted sandbox. The full mode (a hidden sandbox account, firewall and loopback+filters) needs `openworker machine sandbox setup` and comes next (design doc, section 7).++Learned on the VM (2026-09-22): the restricting list must hold the LOGON SID or no process+starts at all (0xC0000142); the token's default DACL must name the session SID or the+process cannot start children (error 5); a console is fine once both hold.+"""++from __future__ import annotations++import os+import shutil+import subprocess+import sys+import uuid+from pathlib import Path+from typing import Any, Optional, Sequence++from .. import credentials as creds+from .. import netproxy, network_profiles+from ..bundle import build_runner_zipapp+from ..launch import runner_command, runner_dir, serve_arguments, spawn_kwargs, wait_for_runner+from ..transport import PipeTransport, Transport+from .seatbelt import _CACHE_VARIABLES, clean_environment++PARTIAL_REASON = (+ "Windows write-restricted token: writes limited to the session's folders; reads and the network are NOT limited"+ " (run `openworker machine sandbox setup` for the full sandbox)"+)+_EVERYONE_WRITABLE = ("the drive root (new folders only)", r"C:\Users\Public", r"C:\Windows\Temp")+++class WindowsUnavailable(RuntimeError):+ """The Windows sandbox cannot be used here. The message says why."""+++def preflight() -> None:+ if sys.platform != "win32":+ raise WindowsUnavailable("The Windows sandbox exists only on Windows.")+ from .. import winsec++ try:+ winsec.current_user_sid()+ winsec.logon_sid()+ except OSError as exc:+ raise WindowsUnavailable(f"cannot read this process's token: {exc}") from None+++class WindowsProvider:+ name = "windows"++ def __init__(+ self,+ *,+ roots: Sequence[dict[str, Any]],+ cwd: str | Path,+ profile: str = network_profiles.DEFAULT_PROFILE,+ network: bool = True,+ runner_path: Optional[Path] = None,+ relay_silence_seconds: Optional[float] = None,+ credentials: Sequence[creds.Grant] = (),+ ) -> None:+ self.roots = _clean_roots(roots)+ self.grants = list(credentials)+ self.copied: Optional[creds.CopiedCredentials] = None+ self.cwd = os.path.realpath(str(cwd))+ self.profile = network_profiles.check(profile)+ self.network = network+ self._runner = Path(runner_path) if runner_path is not None else build_runner_zipapp()+ self._relay_silence = relay_silence_seconds+ self.sandbox = f"sb-{uuid.uuid4().hex[:12]}"+ self.mode = "partial"+ self._dir, self.socket_path = runner_dir()+ self._daemon: Any = None+ self._proxy: Optional[netproxy.AllowListProxy] = None+ self._token: Any = None+ self._desktop: Any = None+ self._granted: list[str] = [] # folders that carry an entry for the session SID right now+ from .. import winsec++ self.session_sid = winsec.session_sid()++ def describe(self) -> dict[str, Any]:+ network = f"advisory: the '{self.profile}' profile through the proxy variables only" if self.network else "the user's own"+ return {+ "provider": self.name,+ "sandbox": self.sandbox,+ "enforcement": self.mode,+ "reason": f"{PARTIAL_REASON}. Network: {network}. Still writable by anyone: {', '.join(_EVERYONE_WRITABLE)}",+ "credentials": self.copied.describe() if self.copied is not None else [],+ }++ # -- start ------------------------------------------------------------------------+ def create(self) -> None:+ try:+ self._create()+ except BaseException:+ self.destroy() # nothing of a failed sandbox stays behind (entries, folder, token)+ raise++ def _environment(self) -> dict[str, str]:+ env = clean_environment()+ temp = os.path.join(self._dir, "tmp")+ os.makedirs(temp, exist_ok=True)+ env["TEMP"] = env["TMP"] = temp+ for name, folder in _CACHE_VARIABLES.items():+ env[name] = os.path.join(self._dir, "cache", folder)+ if self._proxy is not None:+ env.update(netproxy.environment(self._proxy))+ return env++ def _create(self) -> None:+ preflight()+ from .. import winsec++ if self.network:+ self._proxy = netproxy.shared(self.profile)+ for folder in [r["path"] for r in self.roots if r["writable"]] + [self._dir]:+ winsec.grant_write(folder, self.session_sid)+ self._granted.append(folder)+ self._token = winsec.RestrictedToken(self.session_sid)+ self._desktop = winsec.Desktop(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"]+ log = os.path.join(self._dir, "daemon.log")+ self._daemon = winsec.spawn(argv, token=self._token, desktop=self._desktop, cwd=self.cwd, env=self._environment(), stderr_path=log)+ try:+ wait_for_runner(self.socket_path, self._daemon)+ except RuntimeError as exc:+ said = Path(log).read_text(errors="replace").strip() if os.path.exists(log) else ""+ raise WindowsUnavailable(f"the sandboxed tool runner did not start: {exc} {said[-400:]}".strip()) from None++ 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, **spawn_kwargs())+ )++ def verify(self, client: Any) -> None:+ """Every folder is reachable inside, and the wall is really up: a write into the+ user's profile, which no session is given as a whole, must fail."""+ from ..runner.protocol import RunnerError++ for root in self.roots:+ client.call("fs.list", {"path": root["path"], "limit": 1}, timeout=15)+ home = os.path.realpath(os.path.expanduser("~"))+ if any(home == r["path"] or home.startswith(r["path"] + os.sep) for r in self.roots if r["writable"]):+ return # the user granted the home folder itself; nothing to prove+ probe = os.path.join(home, f"owr-verify-{uuid.uuid4().hex[:8]}.txt")+ try:+ client.call("fs.write", {"path": probe, "text": "probe\n"}, timeout=15)+ except RunnerError:+ return+ try:+ os.remove(probe)+ except OSError:+ pass+ raise WindowsUnavailable("the sandbox did not take effect: a file could be written into the home folder from inside")++ # -- changes ------------------------------------------------------------------------+ def regrant(self, roots: Sequence[dict[str, Any]]) -> None:+ """The session's folders changed. The token is per sandbox, not per folder, so the+ entries move and the daemon stays: a new folder is usable at once, a removed one+ is closed at once."""+ from .. import winsec++ self.roots = _clean_roots(roots)+ wanted = [r["path"] for r in self.roots if r["writable"]] + [self._dir]+ for folder in list(self._granted):+ if folder not in wanted:+ winsec.revoke(folder, self.session_sid)+ self._granted.remove(folder)+ for folder in wanted:+ if folder not in self._granted:+ winsec.grant_write(folder, self.session_sid)+ self._granted.append(folder)++ restarts_on_regrant = False++ def restart_daemon(self) -> None:+ """Tests only: what a sandbox restart looks like from the client's side."""+ self._stop_daemon()+ self._create()++ # -- stop ---------------------------------------------------------------------------+ def _stop_daemon(self) -> None:+ daemon, self._daemon = self._daemon, None+ if daemon is None:+ return+ if daemon.poll() is None:+ daemon.terminate()+ try:+ daemon.wait(timeout=5)+ except subprocess.TimeoutExpired:+ pass+ daemon.close()++ def destroy(self) -> None:+ from .. import winsec++ self._stop_daemon()+ for folder in list(self._granted):+ try:+ winsec.revoke(folder, self.session_sid)+ except OSError:+ pass # a folder that is gone has no entry to remove+ self._granted.remove(folder)+ for thing in (self._token, self._desktop):+ if thing is not None:+ thing.close()+ self._token = self._desktop = None+ shutil.rmtree(self._dir, ignore_errors=True)+++def _clean_roots(roots: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:+ return [{"path": os.path.realpath(r["path"]), "writable": bool(r.get("writable"))} for r in roots]diff --git a/coworker/sandbox/runner/winpipe.py b/coworker/sandbox/runner/winpipe.pyindex 3ff74814..fea8f11b 100644--- a/coworker/sandbox/runner/winpipe.py+++ b/coworker/sandbox/runner/winpipe.py@@ -170,8 +170,10 @@ def process_is_gone(pid: int) -> bool: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)+ except OSError as exc:+ # 87 (invalid parameter) is "no such process". Anything else (access denied from+ # inside a restricted token, say) means the process is there but not ours to open.+ return getattr(exc, "winerror", None) == 87try:return _winapi.WaitForSingleObject(handle, 0) == _winapi.WAIT_OBJECT_0finally:diff --git a/coworker/sandbox/selection.py b/coworker/sandbox/selection.pyindex 309fcd4c..60e101a3 100644--- a/coworker/sandbox/selection.py+++ b/coworker/sandbox/selection.py@@ -16,10 +16,10 @@ import timefrom dataclasses import dataclassfrom typing import Optional-from .workspace import DIRECT, OPENSHELL, PROVIDER_ENV, RUNNER_LOCAL, SEATBELT+from .workspace import DIRECT, OPENSHELL, PROVIDER_ENV, RUNNER_LOCAL, SEATBELT, WINDOWSHEADLESS_ENV = "OPENWORKER_HEADLESS" # set by `openworker up` / `join` for their process-KNOWN = (DIRECT, SEATBELT, OPENSHELL, RUNNER_LOCAL)+KNOWN = (DIRECT, SEATBELT, WINDOWS, OPENSHELL, RUNNER_LOCAL)_PROBE_SECONDS = 30.0_probe_lock = threading.Lock()@@ -80,6 +80,15 @@ def select(configured: Optional[str] = None, *, headless: Optional[bool] = None)raise seatbelt.SeatbeltUnavailable(f"This machine is set to run agents in the macOS sandbox (Seatbelt), and it cannot be used right now, so no session will start. {exc}") from None+ if chosen == WINDOWS:+ from .providers import windows++ try:+ windows.preflight()+ except windows.WindowsUnavailable as exc:+ raise windows.WindowsUnavailable(+ f"This machine is set to run agents in the Windows sandbox, and it cannot be used right now, so no session will start. {exc}"+ ) from Nonereturn Selection(chosen, explicit=True)if headless if headless is not None else is_headless():problem = openshell_problem()diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.pyindex 46c30e65..a211bb37 100644--- a/coworker/sandbox/settings.py+++ b/coworker/sandbox/settings.py@@ -10,7 +10,7 @@ from typing import Any, Optionalfrom .. import config as app_configfrom . import credentials, network_profiles-from .workspace import DIRECT, OPENSHELL, SEATBELT+from .workspace import DIRECT, OPENSHELL, SEATBELT, WINDOWSdef _availability(name: str) -> tuple[bool, str]:@@ -32,9 +32,24 @@ def _availability(name: str) -> tuple[bool, str]:problem = openshell_problem()return (problem is None), (problem or "")+ if name == WINDOWS:+ if sys.platform != "win32":+ return False, "Windows only"+ from .providers import windows++ try:+ windows.preflight()+ return True, ""+ except windows.WindowsUnavailable as exc:+ return False, str(exc)return False, "unknown"+def native_sandbox() -> str:+ """The operating system's own sandbox provider: the middle option on the page."""+ return WINDOWS if sys.platform == "win32" else SEATBELT++def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:cfg = cfg or app_config.load_config()from .selection import select@@ -45,7 +60,7 @@ def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:except Exception as exc: # an explicit choice that cannot be used: sessions are refusedeffective, refused = "", str(exc)providers = []- for name in (DIRECT, SEATBELT, OPENSHELL):+ for name in (DIRECT, native_sandbox(), OPENSHELL):usable, why = _availability(name)providers.append({"name": name, "usable": usable, "why": why})return {@@ -84,7 +99,7 @@ def update(body: dict[str, Any]) -> dict[str, Any]:body = body or {}if "provider" in body:provider = str(body.get("provider") or "").strip().lower()- if provider and provider not in (DIRECT, SEATBELT, OPENSHELL):+ if provider and provider not in (DIRECT, SEATBELT, WINDOWS, OPENSHELL):return {"ok": False, "error": f"unknown sandbox provider: {provider}"}app_config.set_global_value("sandbox_provider", provider) if provider else _unset("sandbox_provider")from .selection import openshell_problemdiff --git a/coworker/sandbox/winsec.py b/coworker/sandbox/winsec.pyindex cbeb5156..b6c207d2 100644--- a/coworker/sandbox/winsec.py+++ b/coworker/sandbox/winsec.py@@ -1,14 +1,189 @@-"""Windows account facts the sandbox providers need, through ctypes (no pywin32).+"""Windows security plumbing for the sandbox providers, through ctypes (no pywin32).Only the server side imports this; the runner package stays standard library and does notneed to know who its server is beyond the SIDs it is handed.++What is here, in the order a provider uses it:+- `current_user_sid()`, `logon_sid()`: who we are.+- `session_sid()`: a made-up SID for one sandbox. It is no account and never looked up; it is+ what the write-restricted token and the folder entries have in common.+- `write_restricted_token(session)`: our own token, restricted so that a WRITE is allowed only+ where the session SID (or the logon SID, or Everyone) is allowed too. Reads are not+ affected. The token's default DACL names the session SID as well, or the process could not+ open its own token and children (found 2026-09-22: error 5 on every CreateProcess).+- `Desktop`: a window station and desktop of our own, so the sandbox never touches the+ person's windows and clipboard, and so it starts at all from a process with no desktop.+- `spawn(...)`: CreateProcessAsUser with the token, on that desktop, inside a job object that+ ends every descendant when the job closes. Returns a `Process` with the Popen calls the+ providers use (`poll`, `wait`, `terminate`, `kill`, `pid`, `returncode`).+- `grant_write(folder, sid)` / `revoke(folder, sid)`: one inheritable Modify entry for the SID+ on a folder, and its removal."""from __future__ import annotationsimport ctypes+import os+import randomimport sysfrom functools import lru_cache+from typing import Optional, Sequence++if sys.platform == "win32":+ from ctypes import wintypes++ _adv = ctypes.WinDLL("advapi32", use_last_error=True)+ _k32 = ctypes.WinDLL("kernel32", use_last_error=True)+ _u32 = ctypes.WinDLL("user32", use_last_error=True)++ class SID_AND_ATTRIBUTES(ctypes.Structure):+ _fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wintypes.DWORD)]++ class SECURITY_ATTRIBUTES(ctypes.Structure):+ _fields_ = [("nLength", wintypes.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wintypes.BOOL)]++ class STARTUPINFOW(ctypes.Structure):+ _fields_ = [+ ("cb", wintypes.DWORD), ("lpReserved", wintypes.LPWSTR), ("lpDesktop", wintypes.LPWSTR), ("lpTitle", wintypes.LPWSTR),+ ("dwX", wintypes.DWORD), ("dwY", wintypes.DWORD), ("dwXSize", wintypes.DWORD), ("dwYSize", wintypes.DWORD),+ ("dwXCountChars", wintypes.DWORD), ("dwYCountChars", wintypes.DWORD), ("dwFillAttribute", wintypes.DWORD),+ ("dwFlags", wintypes.DWORD), ("wShowWindow", wintypes.WORD), ("cbReserved2", wintypes.WORD), ("lpReserved2", ctypes.c_void_p),+ ("hStdInput", wintypes.HANDLE), ("hStdOutput", wintypes.HANDLE), ("hStdError", wintypes.HANDLE),+ ] # fmt: skip++ class PROCESS_INFORMATION(ctypes.Structure):+ _fields_ = [("hProcess", wintypes.HANDLE), ("hThread", wintypes.HANDLE), ("dwProcessId", wintypes.DWORD), ("dwThreadId", wintypes.DWORD)]++ class TOKEN_DEFAULT_DACL(ctypes.Structure):+ _fields_ = [("DefaultDacl", ctypes.c_void_p)]++ class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):+ _fields_ = [+ ("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64), ("LimitFlags", wintypes.DWORD),+ ("MinimumWorkingSetSize", ctypes.c_size_t), ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),+ ("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD), ("SchedulingClass", wintypes.DWORD),+ ] # fmt: skip++ class IO_COUNTERS(ctypes.Structure):+ _fields_ = [(name, ctypes.c_uint64) for name in ("ReadOperationCount", "WriteOperationCount", "OtherOperationCount", "ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]++ class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):+ _fields_ = [+ ("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION), ("IoInfo", IO_COUNTERS), ("ProcessMemoryLimit", ctypes.c_size_t),+ ("JobMemoryLimit", ctypes.c_size_t), ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t),+ ] # fmt: skip++ class TRUSTEE_W(ctypes.Structure):+ _fields_ = [("pMultipleTrustee", ctypes.c_void_p), ("MultipleTrusteeOperation", ctypes.c_int), ("TrusteeForm", ctypes.c_int), ("TrusteeType", ctypes.c_int), ("ptstrName", ctypes.c_void_p)]++ class EXPLICIT_ACCESS_W(ctypes.Structure):+ _fields_ = [("grfAccessPermissions", wintypes.DWORD), ("grfAccessMode", ctypes.c_int), ("grfInheritance", wintypes.DWORD), ("Trustee", TRUSTEE_W)]++ _k32.GetCurrentProcess.restype = wintypes.HANDLE+ _k32.CloseHandle.argtypes = [wintypes.HANDLE]+ _k32.LocalFree.argtypes = [ctypes.c_void_p]+ _k32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]+ _k32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]+ _k32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]+ _k32.ResumeThread.argtypes = [wintypes.HANDLE]+ _k32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]+ _k32.CreateJobObjectW.restype = wintypes.HANDLE+ _k32.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]+ _k32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]+ _k32.TerminateJobObject.argtypes = [wintypes.HANDLE, wintypes.UINT]+ _adv.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]+ _adv.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]+ _adv.SetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]+ _adv.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_wchar_p)]+ _adv.ConvertStringSidToSidW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p)]+ _adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.ULONG)]+ _adv.GetSecurityDescriptorDacl.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.BOOL), ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.BOOL)]+ _adv.CreateRestrictedToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(SID_AND_ATTRIBUTES), wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(SID_AND_ATTRIBUTES), ctypes.POINTER(wintypes.HANDLE)]+ _adv.CreateProcessAsUserW.argtypes = [wintypes.HANDLE, wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, wintypes.BOOL, wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(STARTUPINFOW), ctypes.POINTER(PROCESS_INFORMATION)]+ _adv.GetNamedSecurityInfoW.argtypes = [wintypes.LPCWSTR, ctypes.c_int, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]+ _adv.SetNamedSecurityInfoW.argtypes = [wintypes.LPWSTR, ctypes.c_int, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]+ _adv.SetEntriesInAclW.argtypes = [wintypes.ULONG, ctypes.POINTER(EXPLICIT_ACCESS_W), ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]+ _u32.CreateWindowStationW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p]+ _u32.CreateWindowStationW.restype = wintypes.HANDLE+ _u32.CreateDesktopW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p]+ _u32.CreateDesktopW.restype = wintypes.HANDLE+ _u32.GetProcessWindowStation.restype = wintypes.HANDLE+ _u32.SetProcessWindowStation.argtypes = [wintypes.HANDLE]+ _u32.CloseWindowStation.argtypes = [wintypes.HANDLE]+ _u32.CloseDesktop.argtypes = [wintypes.HANDLE]++_TOKEN_ALL_ACCESS = 0xF01FF+_TOKEN_QUERY = 0x0008+_TokenUser, _TokenDefaultDacl, _TokenLogonSid = 1, 6, 28+_WRITE_RESTRICTED = 0x8+_SDDL_REVISION_1 = 1+_WINSTA_ALL_ACCESS = 0x37F+_DESKTOP_ALL_ACCESS = 0x1FF | 0x000F0000+CREATE_SUSPENDED = 0x4+CREATE_NEW_PROCESS_GROUP = 0x200+CREATE_UNICODE_ENVIRONMENT = 0x400+CREATE_NO_WINDOW = 0x08000000+_STARTF_USESTDHANDLES = 0x100+_JobObjectExtendedLimitInformation = 9+_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000+_SE_FILE_OBJECT = 1+_DACL_SECURITY_INFORMATION = 0x4+_TRUSTEE_IS_SID = 0+_GRANT_ACCESS, _REVOKE_ACCESS = 1, 4+_CONTAINER_INHERIT_ACE, _OBJECT_INHERIT_ACE = 0x2, 0x1+_FILE_GENERIC_MODIFY = 0x1301BF # icacls "M": read, write, execute, delete+_INFINITE = 0xFFFFFFFF+_WAIT_OBJECT_0 = 0+++def _fail(what: str) -> OSError:+ err = ctypes.get_last_error()+ return OSError(err, f"{what}: {ctypes.FormatError(err).strip()}")+++def _token_info(token: int, kind: int) -> ctypes.Array:+ needed = wintypes.DWORD()+ _adv.GetTokenInformation(token, kind, None, 0, ctypes.byref(needed))+ buffer = ctypes.create_string_buffer(needed.value)+ if not _adv.GetTokenInformation(token, kind, buffer, needed, ctypes.byref(needed)):+ raise _fail("GetTokenInformation")+ return buffer+++def _sid_text(sid: int) -> str:+ text = ctypes.c_wchar_p()+ if not _adv.ConvertSidToStringSidW(ctypes.c_void_p(sid), ctypes.byref(text)):+ raise _fail("ConvertSidToStringSid")+ try:+ return text.value or ""+ finally:+ _k32.LocalFree(text)+++class _Sid:+ """A binary SID from its text, kept alive as long as the object."""++ def __init__(self, text: str) -> None:+ self.text = text+ self.pointer = ctypes.c_void_p()+ if not _adv.ConvertStringSidToSidW(text, ctypes.byref(self.pointer)):+ raise _fail(f"ConvertStringSidToSid {text!r}")++ def __del__(self) -> None:+ if getattr(self, "pointer", None) and self.pointer.value:+ _k32.LocalFree(self.pointer)+++class _OwnToken:+ def __init__(self, access: int) -> None:+ self.handle = wintypes.HANDLE()+ if not _adv.OpenProcessToken(_k32.GetCurrentProcess(), access, ctypes.byref(self.handle)):+ raise _fail("OpenProcessToken")++ def close(self) -> None:+ if self.handle:+ _k32.CloseHandle(self.handle)+ self.handle = wintypes.HANDLE()@lru_cache(maxsize=1)@@ -16,37 +191,253 @@ 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+ token = _OwnToken(_TOKEN_QUERY)+ try:+ buffer = _token_info(token.handle, _TokenUser) # TOKEN_USER starts with SID_AND_ATTRIBUTES.Sid+ return _sid_text(ctypes.c_void_p.from_buffer(buffer).value)+ finally:+ token.close()- 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())++@lru_cache(maxsize=1)+def logon_sid() -> str:+ """The SID of this logon session (`S-1-5-5-X-Y`); the desktop and other per-session+ objects grant it, so a restricted token must carry it or nothing starts."""+ token = _OwnToken(_TOKEN_QUERY)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())+ buffer = _token_info(token.handle, _TokenLogonSid) # TOKEN_GROUPS: count, then the entries+ entry = SID_AND_ATTRIBUTES.from_buffer(buffer, ctypes.sizeof(ctypes.c_void_p))+ return _sid_text(entry.Sid)+ finally:+ token.close()+++def session_sid() -> str:+ """A SID for one sandbox. Made up, unique, never an account. Windows accepts only its+ own authorities as restricting SIDs (an app-capability SID `S-1-15-...` is refused), so+ it has the shape of a domain account that no domain issues."""+ return "S-1-5-21-%d-%d-%d-%d" % tuple(random.SystemRandom().randrange(1 << 20, 1 << 31) for _ in range(4))+++def _descriptor(sddl: str) -> ctypes.c_void_p:+ descriptor = ctypes.c_void_p()+ size = wintypes.ULONG()+ if not _adv.ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, _SDDL_REVISION_1, ctypes.byref(descriptor), ctypes.byref(size)):+ raise _fail(f"security descriptor from {sddl!r}")+ return descriptor+++class RestrictedToken:+ """A write-restricted copy of our own token (see the module docstring)."""++ def __init__(self, session: str, *, restrict_to: Sequence[str] = ()) -> None:+ self.session = session+ self._sids = [_Sid(s) for s in (session, logon_sid(), "S-1-1-0", *restrict_to)] # S-1-1-0 = Everyone+ own = _OwnToken(_TOKEN_ALL_ACCESS)+ try:+ restrict = (SID_AND_ATTRIBUTES * len(self._sids))()+ for i, sid in enumerate(self._sids):+ restrict[i].Sid = sid.pointer.value+ restrict[i].Attributes = 0+ self.handle = wintypes.HANDLE()+ if not _adv.CreateRestrictedToken(own.handle, _WRITE_RESTRICTED, 0, None, 0, None, len(self._sids), restrict, ctypes.byref(self.handle)):+ raise _fail("CreateRestrictedToken")+ finally:+ own.close()+ # Objects the sandbox creates (its token, its processes, its pipes) get this DACL.+ self._default = _descriptor(f"D:(A;;GA;;;{current_user_sid()})(A;;GA;;;{session})(A;;GA;;;SY)")+ present, dacl, defaulted = wintypes.BOOL(), ctypes.c_void_p(), wintypes.BOOL()+ if not _adv.GetSecurityDescriptorDacl(self._default, ctypes.byref(present), ctypes.byref(dacl), ctypes.byref(defaulted)):+ raise _fail("GetSecurityDescriptorDacl")+ info = TOKEN_DEFAULT_DACL(dacl)+ if not _adv.SetTokenInformation(self.handle, _TokenDefaultDacl, ctypes.byref(info), ctypes.sizeof(info)):+ raise _fail("SetTokenInformation(TokenDefaultDacl)")++ def close(self) -> None:+ if self.handle:+ _k32.CloseHandle(self.handle)+ self.handle = wintypes.HANDLE()+++class Desktop:+ """A window station and desktop of our own that the user, the session SID and this+ logon may open. `name` is what goes into STARTUPINFO.lpDesktop."""++ def __init__(self, session: str) -> None:+ sddl = f"D:(A;;GA;;;{current_user_sid()})(A;;GA;;;{session})(A;;GA;;;{logon_sid()})"+ self._descriptor = _descriptor(sddl)+ attributes = SECURITY_ATTRIBUTES(ctypes.sizeof(SECURITY_ATTRIBUTES), self._descriptor, False)+ self.station_name = "owsb-%08x" % random.SystemRandom().getrandbits(32)+ self.station = _u32.CreateWindowStationW(self.station_name, 0, _WINSTA_ALL_ACCESS, ctypes.byref(attributes))+ if not self.station:+ raise _fail("CreateWindowStation")+ previous = _u32.GetProcessWindowStation()+ _u32.SetProcessWindowStation(self.station) # CreateDesktop works on the process's station+ try:+ self.desktop = _u32.CreateDesktopW("default", None, None, 0, _DESKTOP_ALL_ACCESS, ctypes.byref(attributes))+ finally:+ _u32.SetProcessWindowStation(previous)+ if not self.desktop:+ _u32.CloseWindowStation(self.station)+ raise _fail("CreateDesktop")+ self.name = f"{self.station_name}\\default"++ def close(self) -> None:+ if getattr(self, "desktop", None):+ _u32.CloseDesktop(self.desktop)+ self.desktop = None+ if getattr(self, "station", None):+ _u32.CloseWindowStation(self.station)+ self.station = None+++class Process:+ """A process started by `spawn`, with the calls a provider uses on a Popen."""++ def __init__(self, info: "PROCESS_INFORMATION", job: int) -> None:+ self._handle = info.hProcess+ self._job = job+ self.pid = int(info.dwProcessId)+ self.returncode: Optional[int] = None+ _k32.CloseHandle(info.hThread)++ def poll(self) -> Optional[int]:+ if self.returncode is None and _k32.WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:+ code = wintypes.DWORD()+ _k32.GetExitCodeProcess(self._handle, ctypes.byref(code))+ self.returncode = int(code.value)+ return self.returncode++ def wait(self, timeout: Optional[float] = None) -> int:+ ms = _INFINITE if timeout is None else int(timeout * 1000)+ if _k32.WaitForSingleObject(self._handle, ms) != _WAIT_OBJECT_0:+ import subprocess++ raise subprocess.TimeoutExpired("sandbox daemon", timeout or 0)+ code = self.poll()+ assert code is not None+ return code++ def terminate(self) -> None:+ """Ends the whole job: the daemon, its shells and everything they started."""+ if self.poll() is None:+ _k32.TerminateJobObject(self._job, 1)++ kill = terminate++ def close(self) -> None:+ if self._handle:+ _k32.CloseHandle(self._handle)+ self._handle = None+ if self._job:+ _k32.CloseHandle(self._job) # kill-on-close: whatever is left in the job ends here+ self._job = None+++def spawn(+ argv: Sequence[str],+ *,+ token: RestrictedToken,+ desktop: Desktop,+ cwd: str,+ env: dict[str, str],+ stderr_path: Optional[str] = None,+) -> Process:+ """Start `argv` under the token, on the desktop, in a job that ends with the Process.+ A hidden console is created (the daemon's shells need one). stdin is closed; stdout+ goes nowhere; stderr to `stderr_path` when given."""+ import subprocess++ job = _k32.CreateJobObjectW(None, None)+ if not job:+ raise _fail("CreateJobObject")+ limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()+ limits.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+ if not _k32.SetInformationJobObject(job, _JobObjectExtendedLimitInformation, ctypes.byref(limits), ctypes.sizeof(limits)):+ raise _fail("SetInformationJobObject")++ startup = STARTUPINFOW()+ startup.cb = ctypes.sizeof(startup)+ startup.lpDesktop = desktop.name+ handles = []+ try:+ nul = os.open(os.devnull, os.O_RDWR)+ handles.append(nul)+ err_fd = os.open(stderr_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC) if stderr_path else nul+ if stderr_path:+ handles.append(err_fd)+ import msvcrt++ startup.dwFlags = _STARTF_USESTDHANDLES+ startup.hStdInput = msvcrt.get_osfhandle(nul)+ startup.hStdOutput = msvcrt.get_osfhandle(nul)+ startup.hStdError = msvcrt.get_osfhandle(err_fd)+ for h in (startup.hStdInput, startup.hStdError):+ _k32.SetHandleInformation(wintypes.HANDLE(h), 1, 1) # HANDLE_FLAG_INHERIT+ command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))+ block = ctypes.create_unicode_buffer("".join(f"{k}={v}\0" for k, v in sorted(env.items())) + "\0")+ info = PROCESS_INFORMATION()+ flags = CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW+ if not _adv.CreateProcessAsUserW(token.handle, None, command, None, None, True, flags, block, cwd, ctypes.byref(startup), ctypes.byref(info)):+ raise _fail("CreateProcessAsUser")+ finally:+ for fd in handles:+ os.close(fd)+ if not _k32.AssignProcessToJobObject(job, info.hProcess):+ _k32.TerminateProcess(info.hProcess, 1)+ raise _fail("AssignProcessToJobObject")+ _k32.ResumeThread(info.hThread)+ return Process(info, job)+++def _explicit(sid: _Sid, mode: int) -> "EXPLICIT_ACCESS_W":+ entry = EXPLICIT_ACCESS_W()+ entry.grfAccessPermissions = _FILE_GENERIC_MODIFY+ entry.grfAccessMode = mode+ entry.grfInheritance = _CONTAINER_INHERIT_ACE | _OBJECT_INHERIT_ACE+ entry.Trustee.TrusteeForm = _TRUSTEE_IS_SID+ entry.Trustee.TrusteeType = 0 # TRUSTEE_IS_UNKNOWN: it is no account+ entry.Trustee.ptstrName = sid.pointer.value+ return entry+++def _change_dacl(folder: str, sid_text: str, mode: int) -> None:+ sid = _Sid(sid_text)+ old = ctypes.c_void_p()+ descriptor = ctypes.c_void_p()+ status = _adv.GetNamedSecurityInfoW(folder, _SE_FILE_OBJECT, _DACL_SECURITY_INFORMATION, None, None, ctypes.byref(old), None, ctypes.byref(descriptor))+ if status:+ raise OSError(status, f"GetNamedSecurityInfo {folder}: {ctypes.FormatError(status).strip()}")+ try:+ new = ctypes.c_void_p()+ entry = _explicit(sid, mode)+ status = _adv.SetEntriesInAclW(1, ctypes.byref(entry), old, ctypes.byref(new))+ if status:+ raise OSError(status, f"SetEntriesInAcl {folder}: {ctypes.FormatError(status).strip()}")try:- return text.value or ""+ status = _adv.SetNamedSecurityInfoW(folder, _SE_FILE_OBJECT, _DACL_SECURITY_INFORMATION, None, None, new, None)+ if status:+ raise OSError(status, f"SetNamedSecurityInfo {folder}: {ctypes.FormatError(status).strip()}")finally:- kernel32.LocalFree(text)+ _k32.LocalFree(new)finally:- kernel32.CloseHandle(token)+ _k32.LocalFree(descriptor)+++def grant_write(folder: str, sid_text: str) -> 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)+++def revoke(folder: str, sid_text: str) -> None:+ """Remove every entry for the SID from the folder (the children inherit the removal)."""+ _change_dacl(folder, sid_text, _REVOKE_ACCESS)+++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 subprocess++ done = subprocess.run(["icacls", folder], capture_output=True, text=True)+ return sid_text in done.stdoutdiff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.pyindex 7b2a80f1..ce36adeb 100644--- a/coworker/sandbox/workspace.py+++ b/coworker/sandbox/workspace.py@@ -24,7 +24,9 @@ DIRECT = "direct"RUNNER_LOCAL = "runner-local"OPENSHELL = "openshell"SEATBELT = "seatbelt"+WINDOWS = "windows"+REGRANT_NOTICE = "The session's folders changed; the sandbox now covers the current list. Shells and variables were kept."RESTART_NOTICE = ("The sandbox was restarted because the session's folders changed. The shell started again: ""variables and background tasks from before are gone, files are untouched."@@ -131,14 +133,17 @@ class RunnerWorkspace(Workspace):wanted = [{"path": str(r.path), "writable": bool(r.writable)} for r in self._live_roots]if not wanted or _same_roots(wanted, getattr(self.provider, "roots", [])):return None- self.client.detach()+ restarts = getattr(self.provider, "restarts_on_regrant", True)+ if restarts:+ self.client.detach()regrant(wanted)- self.client.connect() # a new runner: the client notes the restart+ if restarts:+ self.client.connect() # a new runner: the client notes the restartverify = getattr(self.provider, "verify", None)if verify is not None:verify(self.client)self._record()- return RESTART_NOTICE+ return RESTART_NOTICE if restarts else REGRANT_NOTICE@propertydef executor(self) -> Executor:@@ -230,4 +235,16 @@ def open_workspace(agent=agent,live_roots=roots,)- raise ValueError(f"unknown sandbox provider: {name!r} (known: {DIRECT}, {SEATBELT}, {OPENSHELL}, {RUNNER_LOCAL})")+ if name == WINDOWS:+ from .providers.windows import WindowsProvider+ from .registry import SandboxRegistry++ return RunnerWorkspace(+ WindowsProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile),+ cwd=cwd,+ registry=SandboxRegistry(),+ session_id=session_id,+ agent=agent,+ live_roots=roots,+ )+ raise ValueError(f"unknown sandbox provider: {name!r} (known: {DIRECT}, {SEATBELT}, {WINDOWS}, {OPENSHELL}, {RUNNER_LOCAL})")diff --git a/tests/test_sandbox_settings.py b/tests/test_sandbox_settings.pyindex 9ec4d77b..a05939cd 100644--- a/tests/test_sandbox_settings.py+++ b/tests/test_sandbox_settings.py@@ -2,6 +2,7 @@from __future__ import annotations+import sysfrom pathlib import Pathimport pytest@@ -21,7 +22,8 @@ def config_file(tmp_path, monkeypatch):def test_snapshot_reports_the_default_rule_and_the_shipped_entries(config_file):snap = settings.snapshot()assert snap["provider"] == "" and snap["effective_provider"] == "direct" and snap["refused"] == ""- assert [p["name"] for p in snap["providers"]] == ["direct", "seatbelt", "openshell"]+ native = "windows" if sys.platform == "win32" else "seatbelt" # the operating system's own sandbox+ assert [p["name"] for p in snap["providers"]] == ["direct", native, "openshell"]assert next(p for p in snap["providers"] if p["name"] == "direct")["usable"]assert snap["network_profile"] == "strict" and [n["name"] for n in snap["network_profiles"]] == ["strict", "standard"]assert [(e["name"], e["enabled"]) for e in snap["credentials"]] == [("ssh", False), ("gh", False), ("aws", False), ("kube", False)]diff --git a/tests/test_sandbox_windows.py b/tests/test_sandbox_windows.pynew file mode 100644index 00000000..60daa903--- /dev/null+++ b/tests/test_sandbox_windows.py@@ -0,0 +1,97 @@+"""The Windows sandbox provider (design doc `sandbox-windows-design.md`, section 7).++Live tests: they run only on Windows, as the current user, with no setup. What they prove+is the write-restricted mode: a write outside the session's folders fails, one inside+works, the entries the provider adds are gone when it closes.+"""++from __future__ import annotations++import os+import sys++import pytest++pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="the Windows sandbox exists only on Windows")++from coworker.sandbox.bundle import build_runner_zipapp # noqa: E402+from coworker.sandbox.workspace import RunnerWorkspace # noqa: E402+++def sandbox(tmp_path):+ from coworker.sandbox.providers.windows import WindowsProvider++ project = tmp_path / "project"+ project.mkdir()+ (project / "a.txt").write_text("hello\n")+ zipapp = build_runner_zipapp(tmp_path / "dist")+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=False)+ ws = RunnerWorkspace(provider, cwd=project)+ ws.executor.default_timeout = 60+ yield ws, provider, project+ ws.close()+++def test_writes_are_limited_to_the_sessions_folders(sandbox, tmp_path):+ ws, provider, project = sandbox+ assert ws.describe()["enforcement"] == "partial"+ inside = ws.executor.run("Set-Content -Path new.txt -Value made; Get-Content new.txt")+ assert inside["exit_code"] == 0 and "made" in inside["output"]+ beside = ws.executor.run(f"Set-Content -Path '{tmp_path / 'beside.txt'}' -Value x") # the parent, never granted+ assert beside["exit_code"] != 0 and not (tmp_path / "beside.txt").exists()+ home = ws.executor.run("Set-Content -Path (Join-Path $env:USERPROFILE 'owr-probe.txt') -Value x")+ assert home["exit_code"] != 0 and not os.path.exists(os.path.expanduser("~/owr-probe.txt"))+ # Reads are the user's reads in this mode, and the statement says so.+ assert ws.executor.run(f"(Get-ChildItem '{tmp_path}').Count")["exit_code"] == 0+ assert "reads and the network are NOT limited" in ws.describe()["reason"]+++def test_the_entries_come_and_go_with_the_sandbox(sandbox, tmp_path):+ from coworker.sandbox import winsec++ ws, provider, project = sandbox+ assert winsec.entries_for(str(project), provider.session_sid)+ assert not winsec.entries_for(str(tmp_path), provider.session_sid)+ ws.close()+ assert not winsec.entries_for(str(project), provider.session_sid)+ assert not os.path.exists(provider._dir)+++def test_a_new_folder_is_usable_without_a_restart(sandbox, tmp_path):+ ws, provider, project = sandbox+ extra = tmp_path / "extra"+ extra.mkdir()+ before = ws.client.instance_id+ assert ws.executor.run(f"Set-Content -Path '{extra / 'x.txt'}' -Value x")["exit_code"] != 0+ provider.regrant([{"path": str(project), "writable": True}, {"path": str(extra), "writable": True}])+ assert ws.executor.run(f"Set-Content -Path '{extra / 'x.txt'}' -Value x")["exit_code"] == 0+ assert ws.client.instance_id == before # the same daemon, the same shells+ provider.regrant([{"path": str(project), "writable": True}])+ assert ws.executor.run(f"Set-Content -Path '{extra / 'y.txt'}' -Value x")["exit_code"] != 0+++def test_a_session_workspace_goes_through_the_registry(tmp_path, monkeypatch):+ from coworker.sandbox.registry import SandboxRegistry+ from coworker.sandbox.workspace import open_workspace++ monkeypatch.setenv("OPENWORKER_SANDBOX_PROVIDER", "windows")+ ws = open_workspace(cwd=tmp_path, session_id="s-win", agent="cowork")+ try:+ assert ws.describe()["provider"] == "windows" and ws.describe()["enforcement"] == "partial"+ assert ws.executor.run("echo via-sandbox")["output"].strip() == "via-sandbox"+ rows = SandboxRegistry().list()+ assert [r["session_id"] for r in rows] == ["s-win"] and rows[0]["enforcement"] == "partial"+ finally:+ ws.close()+ assert SandboxRegistry().list() == []+++def test_the_provider_is_known_to_selection_and_settings(monkeypatch, tmp_path):+ from coworker.sandbox import selection, settings++ monkeypatch.setenv("OPENWORKER_SANDBOX_PROVIDER", "windows")+ assert selection.select().provider == "windows"+ monkeypatch.delenv("OPENWORKER_SANDBOX_PROVIDER")+ names = {p["name"]: p for p in settings.snapshot()["providers"]}+ assert names["windows"]["usable"] and "seatbelt" not in names