Python
Windows sandbox: one mode only; traverse entries on the way to a granted folder
Rohit C Prasad388caf998ea0
diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.pyindex a7dad6a1..f686ec2a 100644--- a/coworker/sandbox/providers/windows.py+++ b/coworker/sandbox/providers/windows.py@@ -1,9 +1,8 @@"""`windows`: the tool runner on Windows, confined by Windows' own account boundary.-Same runner, same protocol. Two modes, chosen by whether `openworker machine sandbox-setup` has run (windows_setup.py):--FULL (after setup): the daemon is logged on as a hidden local account+Same runner, same protocol. The one-time setup (windows_setup.py) must have run; without+it the provider refuses (ruling 18: an explicit choice that cannot be honoured refuses,+it never runs open). The daemon is logged on as a hidden local account(CreateProcessWithLogonW, the secondary logon service; no privilege needed), chosen by thenetwork profile: `OWSandboxClosedNet` for the allow-list profiles, `OWSandboxOpenNet` for`open` (ruling 3d.2). Windows keeps both out of the person's profile: `.ssh`, `.aws`,@@ -17,13 +16,7 @@ session starts. The open account has no rules: any host, any local port, files sconfined. Folders outside the profile (`C:\\work`) are readable by any local account bydefault (spike finding A); that is stated, not hidden (ruling 3d.5).-SAME-USER (no setup): the daemon runs as the current user under a write-restricted token-whose restricting SID is a made-up session SID; writes are allowed only where that SID has-an entry (the session's writable folders, the private folder). Reads and the network are-the user's own. Everyone-writable places (the drive root's "new folder", `C:\\Users\\Public`,-`C:\\Windows\\Temp`) stay writable, as in every write-restricted sandbox.--In both modes the entries are removed at close, every process the daemon starts inherits+The entries are removed at close, every process the daemon starts inheritsthe confinement, and the daemon lives in a job object that ends with the sandbox.Learned on the VM (2026-09-22): the restricting list must hold the LOGON SID or no process@@ -49,18 +42,12 @@ from typing import Any, Optional, Sequencefrom .. import credentials as credsfrom .. import netproxy, network_profilesfrom ..bundle import build_runner_zipapp-from ..launch import runner_command, runner_dir, serve_arguments, spawn_kwargs, wait_for_runner+from ..launch import runner_command, serve_arguments, spawn_kwargs, wait_for_runnerfrom ..runner import winpipefrom ..transport import PipeTransport, Transportfrom . import windows_setup-from .seatbelt import _CACHE_VARIABLES, clean_environment-FULL, PARTIAL = "full", "partial"-_EVERYONE_WRITABLE = ("the drive root (new folders only)", r"C:\Users\Public", r"C:\Windows\Temp")-_PARTIAL_REASON = (- "Windows write-restricted token (setup not run): writes limited to the session's folders; reads and the network are"- " NOT limited (run `openworker machine sandbox setup` for the full sandbox)"-)+FULL = "full"_FULL_REASON = ("Windows sandbox account: the user's profile (keys, documents, OpenWorker's state) is out of reach; files limited to"" the session's folders plus what any local account may read outside profiles"@@ -72,20 +59,19 @@ class WindowsUnavailable(RuntimeError):def preflight() -> None:+ """Usable here: Windows, this process can read its token, setup of this version has run+ and this user can read the accounts' credentials. The message says what is missing."""if sys.platform != "win32":raise WindowsUnavailable("The Windows sandbox exists only on Windows.")from .. import winsectry:winsec.current_user_sid()- winsec.logon_sid()except OSError as exc:raise WindowsUnavailable(f"cannot read this process's token: {exc}") from None---def mode() -> str:- """`full` when setup has run and this user can read the accounts' credentials."""- return FULL if windows_setup.account(windows_setup.OPEN) and windows_setup.account(windows_setup.CLOSED) else PARTIAL+ problem = windows_setup.problem()+ if problem:+ raise WindowsUnavailable(problem)class WindowsProvider:@@ -101,15 +87,10 @@ class WindowsProvider:runner_path: Optional[Path] = None,relay_silence_seconds: Optional[float] = None,credentials: Sequence[creds.Grant] = (),- force_mode: Optional[str] = None,tool_dirs: Sequence[str] = (),) -> None:"""`credentials`: the grants (credentials.granted) to copy into the sandbox.- `tool_dirs`: developer tool folders under the profile the account may read (the- full mode; the same-user mode reads them anyway). `force_mode`: tests only;- `partial` on a machine where setup has run."""- from .. import winsec-+ `tool_dirs`: developer tool folders under the profile the account may read."""self.roots = _clean_roots(roots)self.grants = list(credentials)self.tool_dirs = [os.path.realpath(p) for p in tool_dirs]@@ -120,25 +101,22 @@ class WindowsProvider:self._runner = Path(runner_path) if runner_path is not None else build_runner_zipapp()self._relay_silence = relay_silence_secondsself.sandbox = f"sb-{uuid.uuid4().hex[:12]}"- self.mode = force_mode or mode()+ preflight()self.open_network = network and network_profiles.is_open(self.profile)# The account is the network mode: closed (allow list through the proxy) or open.self.kind = windows_setup.OPEN if self.open_network else windows_setup.CLOSED- self._account = windows_setup.account(self.kind) if self.mode == FULL else None- if self.mode == FULL and self._account is None:- raise WindowsUnavailable("the full Windows sandbox needs `openworker machine sandbox setup` first (or again: the accounts changed)")- # Who the entries and the pipe name: the hidden account, or the made-up session SID.- self.session_sid = self._account[1] if self._account else winsec.session_sid()- if self.mode == FULL:- windows_setup.SANDBOXES.mkdir(parents=True, exist_ok=True)- windows_setup.reap_private_folders() # what a server killed hard left behind- self._dir = tempfile.mkdtemp(prefix="owr-", dir=str(windows_setup.SANDBOXES))- self.socket_path = winpipe.pipe_name(os.path.basename(self._dir))- else:- self._dir, self.socket_path = runner_dir()+ account = windows_setup.account(self.kind)+ if account is None:+ raise WindowsUnavailable(windows_setup.problem() or f"the {self.kind} sandbox account is not usable; run `openworker machine sandbox setup` again")+ self._account = account+ # The entries on the folders and the pipe's descriptor name the account.+ self.session_sid = account[1]+ windows_setup.SANDBOXES.mkdir(parents=True, exist_ok=True)+ windows_setup.reap_private_folders() # what a server killed hard left behind+ self._dir = tempfile.mkdtemp(prefix="owr-", dir=str(windows_setup.SANDBOXES))+ self.socket_path = winpipe.pipe_name(os.path.basename(self._dir))self._daemon: Any = Noneself._proxy: Optional[netproxy.AllowListProxy] = None- self._token: Any = Noneself._desktop: Any = Noneself._granted: list[tuple[str, str]] = [] # (folder, "write" | "read") entries that exist right nowself._runner_inside: Path = self._runner # where the sandbox sees the runner file@@ -146,28 +124,18 @@ class WindowsProvider:# -- what it is ---------------------------------------------------------------------def describe(self) -> dict[str, Any]:- if self.mode == FULL:- if not self.network:- network = "blocked"- elif self.open_network:- network = "open (any host, any local port; the 'open' profile)"- else:- network = f"the '{self.profile}' profile through the allow-list proxy; the rest is blocked by the firewall and the loopback filters"- reason = f"{_FULL_REASON}. Network: {network}"+ if not self.network:+ network = "blocked"+ elif self.open_network:+ network = "open (any host, any local port; the 'open' profile)"else:- if not self.network:- network = "the user's own"- elif self.open_network:- network = "the user's own (the 'open' profile)"- else:- network = f"advisory: the '{self.profile}' profile through the proxy variables only"- reason = f"{_PARTIAL_REASON}. Network: {network}. Still writable by anyone: {', '.join(_EVERYONE_WRITABLE)}"+ network = f"the '{self.profile}' profile through the allow-list proxy; the rest is blocked by the firewall and the loopback filters"return {"provider": self.name,"sandbox": self.sandbox,- "enforcement": FULL if self.mode == FULL else PARTIAL,- "mode": self.mode,- "reason": reason,+ "enforcement": FULL,+ "account": self._account[0],+ "reason": f"{_FULL_REASON}. Network: {network}","credentials": self.copied.describe() if self.copied is not None else [],"notes": list(self.notes),}@@ -187,69 +155,35 @@ class WindowsProvider:hosts = sorted({h for g in self.grants for h in g.hosts})if self.network and not self.open_network: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")- if self.mode == FULL:- for folder in self.tool_dirs: # readable to the account, never writable- if os.path.isdir(folder):- self._grant(folder, "read")+ for entry in self._wanted_entries():+ self._grant(*entry)self._desktop = winsec.Desktop(self.session_sid)log = os.path.join(self._dir, "daemon.log")- if self.mode == FULL:- assert self._account is not None- name, sid, password = self._account- # The runner file lives in the user's state folder, which the account cannot see.- self._runner_inside = Path(self._dir) / self._runner.name- shutil.copy2(self._runner, self._runner_inside)- # The environment goes through a file in the private folder (the account reads- # it): CreateProcessWithLogonW allows 1024 characters of command line, and PATH- # alone can be longer than that.- import json-- env_file = os.path.join(self._dir, "env.json")- Path(env_file).write_text(json.dumps(self._environment(full=True)), encoding="utf-8")- serve = serve_arguments(self.socket_path, self._dir, also_sids=[sid])- argv = [*runner_command(self._runner_inside), "serve", *serve, "--env-file", env_file, "--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=env, stderr_path=log)+ name, sid, password = self._account+ # The runner file lives in the user's state folder, which the account cannot see.+ self._runner_inside = Path(self._dir) / self._runner.name+ shutil.copy2(self._runner, self._runner_inside)+ # The environment goes through a file in the private folder (the account reads it):+ # CreateProcessWithLogonW allows 1024 characters of command line, and PATH alone can+ # be longer than that.+ import json++ env_file = os.path.join(self._dir, "env.json")+ Path(env_file).write_text(json.dumps(self._environment()), encoding="utf-8")+ serve = serve_arguments(self.socket_path, self._dir, also_sids=[sid])+ argv = [*runner_command(self._runner_inside), "serve", *serve, "--env-file", env_file, "--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)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 _environment(self, *, full: bool) -> dict[str, str]:- """Same-user mode: the server's environment without secrets, temp and caches moved- into the private folder. Full mode: only what the account's own environment lacks- (the proxy), because the account has a profile, temp and caches of its own."""- env: dict[str, str] = {} if full else clean_environment()- if full:- # The account's own PATH knows nothing of the person's tools; the person's does.- env["PATH"] = os.environ.get("PATH", "")- if not full:- 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)+ def _environment(self) -> dict[str, str]:+ """Only what the account's own environment lacks: the person's PATH (the account's+ knows nothing of their tools) and the proxy. The account has a profile, temp and+ caches of its own."""+ env: dict[str, str] = {"PATH": os.environ.get("PATH", "")}if self._proxy is not None:env.update(netproxy.environment(self._proxy))return env@@ -262,12 +196,10 @@ class WindowsProvider:_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+ """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."""from ..runner.protocol import RunnerErrorhome_inside = str(client.hello.get("home") or "")@@ -305,8 +237,8 @@ class WindowsProvider:)def verify(self, client: Any) -> None:- """Every folder is reachable inside, and the wall is really up. Full mode: the- user's profile cannot be listed. Same-user mode: a file cannot be written into it."""+ """Every folder is reachable inside, and the wall is really up: the user's profile+ cannot be listed, and in the closed mode no local port but the proxy's is reachable."""from ..runner.protocol import RunnerErrorfor root in self.roots:@@ -314,23 +246,12 @@ class WindowsProvider:home = os.path.realpath(os.path.expanduser("~"))if any(home == r["path"] or home.startswith(r["path"] + os.sep) for r in self.roots):return # the user granted the home folder itself; nothing to prove- if self.mode == FULL:- try:- client.call("fs.list", {"path": home, "limit": 1}, timeout=15)- except RunnerError:- self._verify_loopback(client)- return- raise WindowsUnavailable("the sandbox did not take effect: the home folder can be listed from inside")- 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)+ client.call("fs.list", {"path": home, "limit": 1}, timeout=15)except RunnerError:+ self._verify_loopback(client)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")+ raise WindowsUnavailable("the sandbox did not take effect: the home folder can be listed from inside")def _verify_loopback(self, client: Any) -> None:"""The closed account may reach the proxy on loopback and nothing else there@@ -360,10 +281,28 @@ class WindowsProvider:raise WindowsUnavailable(f"the sandbox cannot reach the allow-list proxy on port {self._proxy.port}: {via.get('error')}")# -- the entries ----------------------------------------------------------------------+ def _wanted_entries(self) -> list[tuple[str, str]]:+ """Every entry this sandbox needs right now: Modify on writable roots and the+ private folder, Read on read-only roots and the tool folders, and Traverse (no+ listing) on each folder between a granted folder and the profile root, so a shell+ can enter a folder under the profile. The profile itself stays unlistable."""+ wanted = [(r["path"], "write" if r["writable"] else "read") for r in self.roots] + [(self._dir, "write")]+ wanted += [(folder, "read") for folder in self.tool_dirs if os.path.isdir(folder)]+ home = os.path.realpath(os.path.expanduser("~"))+ for folder, _kind in list(wanted):+ parent = os.path.dirname(folder)+ while parent.lower().startswith(home.lower()) and len(parent) >= len(home):+ if (parent, "traverse") not in wanted and not any(f.lower() == parent.lower() and k != "traverse" for f, k in wanted):+ wanted.append((parent, "traverse"))+ if parent.lower() == home.lower():+ break+ parent = os.path.dirname(parent)+ return wanted+def _grant(self, folder: str, kind: str) -> None:from .. import winsec- (winsec.grant_write if kind == "write" else winsec.grant_read)(folder, self.session_sid)+ {"write": winsec.grant_write, "read": winsec.grant_read, "traverse": winsec.grant_traverse}[kind](folder, self.session_sid)self._granted.append((folder, kind))def _revoke(self, folder: str, kind: str) -> None:@@ -383,9 +322,7 @@ class WindowsProvider:so the entries move and the daemon stays: a new folder is usable at once, a removedone is closed at once."""self.roots = _clean_roots(roots)- wanted = [(r["path"], "write" if r["writable"] else "read") for r in self.roots] + [(self._dir, "write")]- if self.mode == FULL:- wanted += [(folder, "read") for folder in self.tool_dirs if os.path.isdir(folder)]+ wanted = self._wanted_entries()for entry in list(self._granted):if entry not in wanted:self._revoke(*entry)@@ -419,10 +356,9 @@ class WindowsProvider:self._stop_daemon()for entry in list(self._granted):self._revoke(*entry)- for thing in (self._token, self._desktop):- if thing is not None:- thing.close()- self._token = self._desktop = None+ if self._desktop is not None:+ self._desktop.close()+ self._desktop = Noneif 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 staysself._proxy = Nonediff --git a/coworker/sandbox/providers/windows_setup.py b/coworker/sandbox/providers/windows_setup.pyindex 5a68e3f0..084a4e3c 100644--- a/coworker/sandbox/providers/windows_setup.py+++ b/coworker/sandbox/providers/windows_setup.py@@ -19,8 +19,8 @@ prompt) that:6. removes what an earlier setup or spike left (`OpenWorkerSandbox`, its rule), and recordswhat it changed in `setup.json`, so `remove` can undo exactly that.-The provider reads `account(kind)` at start: with it, full mode; without it, the same-user-mode labelled `partial: setup not run`.+The provider reads `account(kind)` at start; without it the sandbox is not usable and+sessions set to use it are refused (`problem()` says why). There is no weaker mode."""from __future__ import annotations@@ -202,6 +202,19 @@ def account(kind: str = CLOSED) -> Optional[tuple[str, str, str]]:return (name, sid, password) if password else None+def problem() -> Optional[str]:+ """Why the Windows sandbox cannot be used by this user right now, or None."""+ recorded = state()+ if not recorded:+ return "the one-time setup has not run on this PC (`openworker machine sandbox setup`)"+ if not current():+ return "an older setup is recorded on this PC; run `openworker machine sandbox setup` again"+ for kind in (OPEN, CLOSED):+ if account(kind) is None:+ return f"the sandbox account for the {kind} network mode is not usable by this user; run `openworker machine sandbox setup` again"+ return None++def filters_recorded() -> bool:recorded = state() or {}return bool((recorded.get("wfp") or {}).get("filters"))diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.pyindex 4339e3e9..0e21776a 100644--- a/coworker/sandbox/setup_cmd.py+++ b/coworker/sandbox/setup_cmd.py@@ -79,10 +79,13 @@ def windows_rows(print_fn: Callable[[str], None]) -> None:for what, ok, detail in windows_setup.checks():print_fn(f" [{'ok' if ok else '--'}] {what}" + (f" ({detail})" if detail and not ok else ""))- if app_config.load_config().sandbox_provider == "windows":- print_fn(f" the Windows sandbox runs in its {windows.mode()} mode here, and this machine is set to use it")+ problem = windows_setup.problem()+ if problem:+ print_fn(f" the Windows sandbox cannot be used yet: {problem}")+ elif app_config.load_config().sandbox_provider == "windows":+ print_fn(" the Windows sandbox is ready, and this machine is set to use it")else:- print_fn(f" the Windows sandbox runs in its {windows.mode()} mode here; to use it: set `sandbox_provider = \"windows\"` in {app_config.global_config_path()}")+ print_fn(f" the Windows sandbox is ready; to use it: set `sandbox_provider = \"windows\"` in {app_config.global_config_path()}")print_fn("\nOpenShell on this machine:")diff --git a/coworker/sandbox/winsec.py b/coworker/sandbox/winsec.pyindex 5f8267d6..4a87e5fd 100644--- a/coworker/sandbox/winsec.py+++ b/coworker/sandbox/winsec.py@@ -4,7 +4,7 @@ Only the server side imports this; the runner package stays standard library andneed 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.+- `current_user_sid()`, `logon_sid()`: who we are (the desktop's descriptor names both).- `session_sid()`: a made-up SID for one sandbox. It is no account and never looked up; it iswhat 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@@ -98,7 +98,6 @@ if sys.platform == "win32":_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]@@ -115,7 +114,6 @@ if sys.platform == "win32":_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@@ -133,6 +131,7 @@ _GRANT_ACCESS, _REVOKE_ACCESS = 1, 4_CONTAINER_INHERIT_ACE, _OBJECT_INHERIT_ACE = 0x2, 0x1_FILE_GENERIC_MODIFY = 0x1301BF # icacls "M": read, write, execute, delete_FILE_GENERIC_READ_EXECUTE = 0x1200A9 # icacls "RX"+_FILE_TRAVERSE_ONLY = 0x20 | 0x80 | 0x100000 # FILE_TRAVERSE, FILE_READ_ATTRIBUTES, SYNCHRONIZE: icacls "(X,RA,S)"_LOGON_WITH_PROFILE = 0x1_INFINITE = 0xFFFFFFFF_WAIT_OBJECT_0 = 0@@ -214,13 +213,6 @@ def logon_sid() -> str: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()@@ -229,38 +221,6 @@ def _descriptor(sddl: str) -> ctypes.c_void_p: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 thislogon may open. `name` is what goes into STARTUPINFO.lpDesktop."""@@ -336,62 +296,6 @@ class Process: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 spawn_as_account(argv: Sequence[str],*,@@ -480,6 +384,15 @@ def grant_write(folder: str, sid_text: str, *, inherit: bool = True) -> None:_change_dacl(folder, sid_text, _GRANT_ACCESS, inherit=inherit)+def grant_traverse(folder: str, sid_text: str) -> None:+ """Pass through the folder without listing it (one non-inheritable entry: traverse,+ read attributes, synchronize). Needed on every folder between a granted folder and the+ profile root: PowerShell resolves a path by reading each parent's attributes, and+ "bypass traverse checking" does not cover that, so without it a shell cannot enter+ a granted folder under the person's profile (found 2026-09-28)."""+ _change_dacl(folder, sid_text, _GRANT_ACCESS, _FILE_TRAVERSE_ONLY, inherit=False)++def grant_read(folder: str, sid_text: str) -> None:"""One inheritable Read-and-execute entry (icacls "RX") for the SID on the folder."""_change_dacl(folder, sid_text, _GRANT_ACCESS, _FILE_GENERIC_READ_EXECUTE)@@ -509,8 +422,10 @@ def private_acl(path: str) -> None: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)."""+ """Whether the folder's own DACL still names the SID (for tests and clean-up checks).+ `icacls /findsid` matches by SID, so a real account (which icacls would print by name)+ is found the same way as a made-up one."""import subprocess- done = subprocess.run(["icacls", folder], capture_output=True, text=True)- return sid_text in done.stdout+ done = subprocess.run(["icacls", folder, "/findsid", f"*{sid_text}"], capture_output=True, text=True)+ return "SID Found" in done.stdoutdiff --git a/docs/windows-sandbox.md b/docs/windows-sandbox.mdindex bc2f681f..4f118de5 100644--- a/docs/windows-sandbox.md+++ b/docs/windows-sandbox.md@@ -68,10 +68,12 @@ sandbox_network_profile = "open" # the Windows default; or "strict", "standarThe setting is per machine; a project's own config cannot change it.-The first time the Windows sandbox is selected, OpenWorker asks for administrator rights-and runs the one-time setup (the command line form is `openworker machine sandbox setup`).-If you skip it, or cannot elevate on this machine, sessions still run, in a weaker mode-that is labelled as such (see "Without setup" below), and you are asked again next time.+Choosing the Windows sandbox is choosing to set it up: OpenWorker shows what the one-time+setup changes and runs it on one administrator prompt (the command line form is+`openworker machine sandbox setup`). Until setup has run, the option cannot be used and the+machine stays on "No sandbox". There is no weaker mode. If setup is later found broken (an+account deleted, the rule or a filter gone), sessions on the machine are refused with the+way to set it up again, rather than run without the sandbox.## What the setup does@@ -151,6 +153,11 @@ Read only:account read those by default, and so can the sandbox. Keep what the agent must not seeunder your profile.+Passed through, not listed: the folders between a granted folder and your profile root.+A project under `C:\Users\<you>\code` needs the shell to step through `C:\Users\<you>`+and `code`; each gets a traverse-only entry for the session, which lets nothing be listed+or read there.+Read only, from your profile, so the agent can run your tools:- developer tools installed per user, from a list you control in Settings ▸ Sandbox:@@ -183,15 +190,6 @@ user"), never where a credential is kept. Short-lived cloud roles (AWS first) anencrypted wallet for keys that cannot be short-lived are the next additions; see thedesign notes.-## Without setup--If setup has not run, the Windows sandbox still limits writes: the runner starts as you,-under a write-restricted token, and can write only where the session's folders and its-private folder carry an entry for it. Reads and the network are yours. OpenWorker labels-this mode `partial` in every tool result and in Settings, and asks for setup again at the-next start. Shared SSH keys cannot be used in this mode (Windows OpenSSH does not finish-under a write-restricted token); the agent is told.-## Every agent, one accountAll sessions run under the same account (one per network mode). The goal is to keep yourdiff --git a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsxindex 82e8dfbc..40bd3cb0 100644--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx@@ -57,6 +57,7 @@ describe("Settings ▸ Sandbox", () => {await screen.findByTestId("sandbox-section");expect((screen.getByTestId("sandbox-provider-direct") as HTMLInputElement).checked).toBe(true);expect((screen.getByTestId("sandbox-provider-openshell") as HTMLInputElement).disabled).toBe(true);+ expect(screen.getByTestId("sandbox-provider-openshell-why").textContent).toBe("OpenShell is not installed");expect(screen.getByText("default")).toBeTruthy();expect((screen.getByTestId("sandbox-network-strict") as HTMLInputElement).checked).toBe(true);expect(screen.getByText("SSH keys")).toBeTruthy();diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsxindex 84b0218a..339698f2 100644--- a/surfaces/gui/src/components/SettingsView.tsx+++ b/surfaces/gui/src/components/SettingsView.tsx@@ -793,8 +793,11 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {<span className="flex-1 min-w-0"><span className="block text-ui text-ink">{label}</span><span className="block text-meta text-muted">{desc}</span>+ {!p.usable && p.why ? (+ <span className="block text-meta text-warnInk mt-1" data-testid={`sandbox-provider-${p.name}-why`}>{p.why}</span>+ ) : null}</span>- <span className={"text-meta shrink-0 " + (p.usable ? (active ? "text-success" : "text-muted") : "text-muted")} title={p.why || undefined}>+ <span className={"text-meta shrink-0 " + (p.usable ? (active ? "text-success" : "text-muted") : "text-muted")}>{p.name === "direct" && !cfg.provider? t("settingsx.sandbox.status_default"): p.usablediff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 34488d7f..f3bcbc62 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -2278,7 +2278,7 @@"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. The network is open, or limited to the allow list, as chosen below. Without the one-time setup (openworker machine sandbox setup), writes are limited to the session's folders and nothing else is.",+ "provider_windows_desc": "Commands run as a hidden local account that cannot see your profile. The network is open, or limited to the allow list, as chosen below. One-time setup, with one administrator prompt.","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 c74af46b..ee6b690a 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -2238,7 +2238,7 @@"provider_seatbelt": "macOS 沙箱","provider_seatbelt_desc": "命令只能读写会话的文件夹,只能访问允许列表中的网络主机。你的其他文件和登录信息被隐藏。","provider_windows": "Windows 沙箱",- "provider_windows_desc": "命令以一个看不到你的用户配置文件的隐藏本地账户运行。网络按下方的选择:开放,或仅限允许列表。未做一次性设置(openworker machine sandbox setup)时,只限制写入到会话的文件夹,其他不受限制。",+ "provider_windows_desc": "命令以一个看不到你的用户配置文件的隐藏本地账户运行。网络按下方的选择:开放,或仅限允许列表。一次性设置,只需一次管理员确认。","provider_openshell": "OpenShell(NVIDIA)","provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要这台机器上装有 OpenShell 和 Docker。","status_default": "默认",diff --git a/tests/test_sandbox_windows.py b/tests/test_sandbox_windows.pyindex bae360d2..fd35b462 100644--- a/tests/test_sandbox_windows.py+++ b/tests/test_sandbox_windows.py@@ -1,9 +1,9 @@"""The Windows sandbox provider (design doc `sandbox-windows-design.md`, section 7).-Live tests, Windows only. The same-user mode needs nothing; the full mode needs setup to-have run on the machine (`openworker machine sandbox setup`) and skips otherwise. Setup-itself is only exercised with OPENWORKER_TEST_WINDOWS_SETUP=1, because it changes the-machine (an account, a firewall rule, a folder under ProgramData).+Live tests, Windows only. They need setup to have run on the machine (`openworker machine+sandbox setup`) and skip otherwise; there is no weaker mode. Setup itself is only exercised+with OPENWORKER_TEST_WINDOWS_SETUP=1, because it changes the machine (two accounts, a+firewall rule, loopback filters, a folder under ProgramData)."""from __future__ import annotations@@ -27,10 +27,9 @@ def _has_setup() -> bool:return windows_setup.account("open") is not None and windows_setup.account("closed") is not None-full = pytest.mark.skipif(not _has_setup(), reason="needs `openworker machine sandbox setup` on this machine")-def _open(tmp_path, *, mode, extra_roots=(), network=False, profile="strict"):+def _open(tmp_path, *, extra_roots=(), network=False, profile="strict"):from coworker.sandbox.providers.windows import WindowsProviderproject = tmp_path / "project"@@ -38,78 +37,71 @@ def _open(tmp_path, *, mode, extra_roots=(), network=False, profile="strict"):(project / "a.txt").write_text("hello\n")zipapp = build_runner_zipapp(tmp_path / "dist")roots = [{"path": str(project), "writable": True}, *extra_roots]- provider = WindowsProvider(roots=roots, cwd=project, runner_path=zipapp, network=network, profile=profile, force_mode=mode)+ provider = WindowsProvider(roots=roots, cwd=project, runner_path=zipapp, network=network, profile=profile)ws = RunnerWorkspace(provider, cwd=project)ws.executor.default_timeout = 60return ws, provider, project-def sandbox(tmp_path):- ws, provider, project = _open(tmp_path, mode="partial")- yield ws, provider, project- ws.close()---# -- same-user mode ---------------------------------------------------------------------------def test_writes_are_limited_to_the_sessions_folders(sandbox, tmp_path):- ws, provider, project = sandbox- assert ws.describe()["mode"] == "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"]+full = pytest.mark.skipif(not _has_setup(), reason="needs `openworker machine sandbox setup` on this machine")-def test_the_entries_come_and_go_with_the_sandbox(sandbox, tmp_path):+@full+def test_writes_are_limited_to_the_sessions_folders_and_the_entries_come_and_go(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)+ ws, provider, project = _open(tmp_path)+ try:+ 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()+ assert winsec.entries_for(str(project), provider.session_sid)+ assert winsec.entries_for(str(tmp_path), provider.session_sid) # traverse only: the write above was refused+ assert winsec.entries_for(os.path.expanduser("~"), provider.session_sid)+ finally:+ ws.close()+ for folder in (str(project), str(tmp_path), os.path.expanduser("~")):+ assert not winsec.entries_for(folder, provider.session_sid), folderassert 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+@full+def test_a_new_folder_is_usable_without_a_restart(tmp_path):+ ws, provider, project = _open(tmp_path)+ try:+ 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+ finally:+ ws.close()+@fulldef test_a_session_workspace_goes_through_the_registry(tmp_path, monkeypatch):from coworker.sandbox.registry import SandboxRegistryfrom coworker.sandbox.workspace import open_workspacemonkeypatch.setenv("OPENWORKER_SANDBOX_PROVIDER", "windows")- expected = "full" if _has_setup() else "partial" # the default rule: full mode once setup has runws = open_workspace(cwd=tmp_path, session_id="s-win", agent="cowork")try:- assert ws.describe()["provider"] == "windows" and ws.describe()["enforcement"] == expected+ assert ws.describe()["provider"] == "windows" and ws.describe()["enforcement"] == "full"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"] == expected+ assert [r["session_id"] for r in rows] == ["s-win"] and rows[0]["enforcement"] == "full"assert rows[0]["profile"] == "open" # the Windows defaultfinally:ws.close()assert SandboxRegistry().list() == []+@fulldef test_the_provider_is_known_to_selection_and_settings(monkeypatch, tmp_path):from coworker.sandbox import selection, settings@@ -152,7 +144,7 @@ def test_a_granted_ssh_key_reaches_github_through_the_proxy(tmp_path):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")+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=True, credentials=grants)ws = RunnerWorkspace(provider, cwd=project)ws.executor.default_timeout = 90try:@@ -167,32 +159,6 @@ def test_a_granted_ssh_key_reaches_github_through_the_proxy(tmp_path):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--@fulldef test_full_mode_removes_the_copies_when_the_sandbox_ends(tmp_path):"""The account's profile persists between sandboxes; the copies must not."""@@ -206,7 +172,7 @@ def test_full_mode_removes_the_copies_when_the_sandbox_ends(tmp_path):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")+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=False, credentials=grants if with_grants else ())ws = RunnerWorkspace(provider, cwd=project)ws.executor.default_timeout = 60return ws@@ -226,6 +192,22 @@ def test_full_mode_removes_the_copies_when_the_sandbox_ends(tmp_path):# -- setup and the full mode ---------------------------------------------------------------+def test_without_setup_the_provider_refuses_and_settings_say_why(monkeypatch, tmp_path):+ """No weaker mode: an explicit choice that cannot be honoured refuses (ruling 18)."""+ from coworker.sandbox import selection, settings+ from coworker.sandbox.providers import windows, windows_setup++ monkeypatch.setattr(windows_setup, "state", lambda: None)+ with pytest.raises(windows.WindowsUnavailable, match="setup has not run"):+ windows.WindowsProvider(roots=[{"path": str(tmp_path), "writable": True}], cwd=tmp_path, runner_path=tmp_path / "r.pyz")+ monkeypatch.setenv("OPENWORKER_SANDBOX_PROVIDER", "windows")+ with pytest.raises(windows.WindowsUnavailable, match="no session will start"):+ selection.select()+ monkeypatch.delenv("OPENWORKER_SANDBOX_PROVIDER")+ row = next(p for p in settings.snapshot()["providers"] if p["name"] == "windows")+ assert not row["usable"] and "setup has not run" in row["why"]++@pytest.mark.skipif(os.environ.get("OPENWORKER_TEST_WINDOWS_SETUP") != "1", reason="changes the machine; OPENWORKER_TEST_WINDOWS_SETUP=1 to run")def test_setup_creates_the_two_hidden_accounts_and_status_reports_it():import subprocess@@ -254,12 +236,17 @@ def test_full_mode_hides_the_profile_and_gives_the_sessions_folders(tmp_path):reference = tmp_path / "reference"reference.mkdir()(reference / "ref.txt").write_text("read me\n")- ws, provider, project = _open(tmp_path, mode="full", extra_roots=[{"path": str(reference), "writable": False}])+ ws, provider, project = _open(tmp_path, extra_roots=[{"path": str(reference), "writable": False}])try:- assert ws.describe()["mode"] == "full"+ assert ws.describe()["enforcement"] == "full" and ws.describe()["account"] == "OWSandboxClosedNet"who = ws.executor.run("$env:USERNAME")["output"].strip()assert who.lower() == "owsandboxclosednet"- assert "made" in ws.executor.run("Set-Content -Path new.txt -Value made; Get-Content new.txt")["output"]+ # the project sits under the person's profile: the shell can enter it (traverse+ # entries on the parents), write there, and still not list the parents+ assert ws.executor.run("(Get-Location).Path")["output"].strip().lower() == str(project).lower()+ made = ws.executor.run("Set-Content -Path new.txt -Value made; Get-Content new.txt")+ assert made["exit_code"] == 0 and made["output"].strip() == "made", made+ assert ws.executor.run(f"Get-ChildItem '{tmp_path}'")["exit_code"] != 0assert "read me" in ws.executor.run(f"Get-Content '{reference / 'ref.txt'}'")["output"]assert ws.executor.run(f"Set-Content -Path '{reference / 'no.txt'}' -Value x")["exit_code"] != 0assert ws.executor.run("Get-ChildItem $env:USERPROFILE\\..\\Administrator")["exit_code"] != 0 # another account's profile@@ -272,6 +259,8 @@ def test_full_mode_hides_the_profile_and_gives_the_sessions_folders(tmp_path):assert not winsec.entries_for(str(project), provider.session_sid)assert not winsec.entries_for(str(reference), provider.session_sid)+ assert not winsec.entries_for(str(tmp_path), provider.session_sid) # the traverse entry is gone too+ assert not winsec.entries_for(os.path.expanduser("~"), provider.session_sid)assert not os.path.exists(provider._dir)@@ -282,7 +271,7 @@ def test_full_mode_blocks_the_network_except_the_proxy(tmp_path):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, force_mode="full")+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=True)ws = RunnerWorkspace(provider, cwd=project)ws.executor.default_timeout = 90# curl.exe (shipped with Windows) follows the proxy variables; PowerShell 5's@@ -316,7 +305,7 @@ def test_a_stale_private_folder_is_reaped_when_the_next_sandbox_starts(tmp_path)stale = windows_setup.SANDBOXES / "owr-stale0000"stale.mkdir(parents=True, exist_ok=True)(stale / "daemon.log").write_text("left behind\n")- ws, provider, project = _open(tmp_path, mode="full")+ ws, provider, project = _open(tmp_path)try:assert not stale.exists() # gone: no daemon listens on its pipeassert os.path.isdir(provider._dir) # the live one stays@@ -336,7 +325,7 @@ def test_full_mode_reads_the_toolchain_folders_it_is_given(tmp_path):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, force_mode="full", tool_dirs=[str(tools)])+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=False, tool_dirs=[str(tools)])ws = RunnerWorkspace(provider, cwd=project)ws.executor.default_timeout = 60try:@@ -353,7 +342,7 @@ def test_full_mode_reads_the_toolchain_folders_it_is_given(tmp_path):@fulldef test_the_open_profile_runs_as_the_open_account_with_the_network_open(tmp_path):- ws, provider, project = _open(tmp_path, mode="full", network=True, profile="open")+ ws, provider, project = _open(tmp_path, network=True, profile="open")ws.executor.default_timeout = 90try:assert provider.kind == "open" and provider._proxy is None