Repository navigation
Studio: Windows tool isolation through Microsoft's MXC, no Node runtime - #11357
danielhanchen wants to merge 56 commits into
Conversation
Three fixes to the Linux and macOS backends, all found by measuring the reviewed head rather than reading it. The workdir scan conflated two different things: a finding about the tree (a socket, a FIFO, a device node, a nested mount, a hard link from outside) and the scan simply running out of budget. Both refused the call. The second should not: the workdir only ever grows, one pip install batch reaches the 50,000-entry cap because packages are directed into .unsloth-packages, and the scan is also the thing that must run before a tool could delete anything, so a chat that crossed the cap could never run Python or Terminal again and could not clean itself up. Recovery meant deleting the chat. An overrun now builds the sandbox anyway and records workdir_scan_incomplete, which reaches the execution record. Findings stay fatal, verified by test: a planted socket, a FIFO and an external hard link all still refuse. The model cache walk was re-paid on every launch though the cache rarely changes between two of them: measured here, 2.1ms empty against 44.2ms at 15,000 entries, and it scales with the cache. It is now memoized per component on the root's identity and mtime, with a 5 minute ceiling, dropped when a launch fails for the same reason the capability probe is dropped there. The comment at the memo states what the key does not cover and why the residual window is narrow. The capability probe's 60s TTL made an idle chat pay the 353ms cold probe again on its next message. Correctness never rested on the TTL: the key carries the runtime identity, so a changed interpreter re-probes at once, and a failed launch invalidates the entry outright, which is what actually covers installing the AppArmor profile without a restart. Measured on this branch: 406 passed, 4 skipped in the six sandbox suites. Real confinement re-checked through prepare_tool_launch in a container where bubblewrap works, 13 of 13, every negative control paired with a host-side positive control proven first.
Adds the third backend behind the same duck-typed contract the bubblewrap and Seatbelt backends already satisfy: BACKEND_NAME, PROFILE_ID, LIMITATIONS and prepare(plan) -> PreparedSandboxLaunch. The two platform ladders in os_sandbox are the only dispatch that changes, so the probe, the record and tools.py are untouched. MXC (github.com/microsoft/mxc, MIT) ships wxc-exec.exe, a native Rust executor taking a JSON policy. It is driven with subprocess and nothing else. This is the difference from #10615, which vendored a pinned @anthropic-ai/sandbox-runtime Node helper plus npm and 11,243 lines; the executor here is one 9MB signed binary fetched at setup time from the published package, and nothing about it runs during a tool call except the process itself. Measured against the shipped 0.8.0 executor rather than assumed from its docs, using its Linux sibling lxc-exec in a container where bubblewrap works, since the CLI surface and schema are shared: - confinement is genuine, not nominal: 0 PIDs visible inside against 6 outside, /etc read-only, a planted credential canary unreadable with the host-side positive control proven first, and the workdir write landing on the host - exit codes pass the child's status through, and the first streamed chunk arrives in 17ms, so cancellation and live output work as the tool UI needs - the `-- argv` splice is Windows-only; lxc-exec rejects trailing arguments. The splice is why build_policy() emits no process.commandLine: that field is a single STRING, and rendering model-authored argv into a Windows command line in Python is an injection hazard. The Windows CI job verifies the splice on a real runner rather than trusting this - the schema pin is ours, not MXC's: 0.8.1-alpha was accepted despite the docs calling stable schemas exact-match contracts, though 9.9.9-alpha was rejected What this does NOT claim, and says so in LIMITATIONS rather than in a comment nobody reads. MXC's README states in bold that no MXC profile should be treated as a security boundary yet. Its os-version-support.md puts the kernel-native tier at build 26600+ and compiles out the brokered tier, so on 23H2, 24H2 and 25H2 the enforcing mechanism is an AppContainer SID plus temporary ACEs on real host paths. That is carried as windows_tier3_dacl and dropped only on a host that actually reaches the native tier. Network egress stays unconfined, the same contract Linux and macOS carry, because explicit CIDR rules are PSEC-only and unavailable on every build this runs on. Two documented T3 consequences are engineered around: the container id is unique per launch, because MXC warns that two concurrent runs sharing one revoke each other's ACEs, and cleanup reconciles the container on every path because a hard kill skips the executor's own revert. Windows isolation is opt-in while upstream calls itself preview. Eligibility is read from the environment Studio started with, never from a request, so a model-authored tool argument cannot select a backend or relax a policy. Tests: 18 new, running on every platform because they cover the policy this backend generates and when it engages. Whether Windows enforces that policy is a different question that only a Windows runner answers.
…e measured Adds the MXC executor installer, a cross-platform enforcement probe, and a workflow that runs the probe on real Linux, macOS and Windows kernels. The probe drives the real prepare_tool_launch and then inspects the host. Every negative control is paired with a positive control proven on the host first, because a read that fails for an unrelated reason proves nothing and a child that cannot start at all would otherwise look like a perfect sandbox. System write targets the host itself cannot write are dropped from the verdict rather than counted as confinement. It exits non-zero when no sandbox can be built, so such a host reports VOID rather than a pass. That last part is the reason the workflow exists. Backend CI installs bubblewrap on ubuntu-24.04 under a step named "Install bubblewrap, so the sandbox tests run instead of skipping", and then logs: File /etc/apparmor.d/bwrap-userns-restrict not found, skipping... bwrap: setting up uid map: Permission denied ::warning::bubblewrap cannot build a sandbox here; confinement tests will skip apparmor-profiles on 24.04 does not ship that profile at that path, so apparmor_parser finds nothing and the `|| true` swallows it. The run is green at 13,165 passed with every confinement test skipped. The Linux job here runs on ubuntu-22.04, which predates kernel.apparmor_restrict_unprivileged_userns, so an ordinary unprivileged user really can create the namespace bwrap needs. That is also the launch path a desktop user takes, which a privileged container is not. install_mxc_runtime.py takes the binaries from the npm tarball rather than the 358MB release zip: it is 26MB, carries the same signed per-arch executables, and is a gzipped tar the standard library can open, so Node is not required to install it any more than to run it. The version is pinned, tarball members are matched by exact name and written by basename so a crafted tarball cannot traverse out of the destination, and the recorded sha256 of the executor is printed for pinning. The Windows job proves the argv splice separately before measuring anything. build_policy() deliberately emits no process.commandLine, because that field is a single string and rendering model-authored argv into a Windows command line in Python is an injection hazard; it relies on MXC rendering the argv after `--`. The Linux sibling lxc-exec rejects trailing arguments, so the splice has to be proven on Windows rather than assumed from the documentation. Verified locally: VOID with exit 3 on this AppArmor-restricted host, and PASS with 13 of 13 checks through the real prepare_tool_launch in a container where bubblewrap works. The installer was run end to end and produced wxc-exec.exe sha256 6049c64723af1173c3739dc6cd6b2f33f6c021bb2832c4216233cba7f71aee9a.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsAdvisory findings (1)
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…e CI job Two fixes found by running the enforcement workflow on real runners rather than reasoning about it. The probe's positive controls were POSIX shaped. They open an AF_UNIX socketpair and pass a descriptor with multiprocessing.reduction.DupFd, which is the right control on Linux and macOS because that is what a Pool or a ProcessPoolExecutor rides. On Windows multiprocessing rides a named pipe and duplicates HANDLEs instead, so the socketpair tests winsock rather than the sandbox. On GitHub's windows-2025 and windows-11-arm runners it raises WinError 10106, the requested service provider could not be loaded, on the HOST, before any sandbox exists. The probe correctly refused to conclude and returned VOID, which is the designed behaviour and also useless here. The control is now the platform's own primitive: a duplex multiprocessing.Pipe on Windows, the socketpair and DupFd everywhere else. The Linux job installed structlog and pydantic but not pytest, so the unit suite step failed after the measurement step had already passed. The Linux measurement from that run is the one #11209 was missing. On an ordinary unprivileged ubuntu-22.04 runner, not a privileged container and not root: verdict PASS, effective_mode os_isolated, backend bubblewrap, all four credential canaries unreadable and the workdir positive controls satisfied. The system write targets came back as an empty set and were dropped from the verdict rather than counted as confinement, because the runner user cannot write /etc, /usr or / in the first place, which is exactly what pairing every negative control with a host side positive control is for.
Both found by the Windows CI job failing, which is what it is for. MXC grants nothing implicitly. Its policy doc is explicit: "Omitted = no filesystem access beyond the default sandbox root". The backend granted the interpreter tree and the workdir and nothing else, so python.exe could not resolve ntdll, kernel32 or the CRT and the launch failed before the payload ran. %SystemRoot% and %SystemRoot%\System32 are now granted read only, which is the same grant the Linux backend makes by binding /usr and /lib read only, and is already described by the system_paths_readable limitation. It widens what a tool call can read, not what it can write. Tier 3 also needs a one time elevated host preparation that the first version of this did not do. wxc-host-prep.exe applies minimum rights ACEs to the system drive root and MXC's managed descriptor to \Device\Null, and AppContainer plus DACL is the tier every shipping Windows build lands on, so this is not optional there. It is exposed as install_mxc_runtime.py --prepare-host and kept separate from the download on purpose: fetching a binary needs no privilege, and Studio should ask before changing host security state rather than doing it silently. The binary has requireAdministrator in its manifest and exits 65 when elevation is refused. Also adds huggingface_hub to the CI dependency list, since the repo's session scoped conftest imports it, and a failure only diagnostic step that re runs a minimal policy with --debug so the next failure reports why rather than that. Measured on real runners in the meantime, both of which are evidence #11209 did not have: Linux, ordinary unprivileged user on ubuntu-22.04, not root and not a privileged container: verdict PASS, effective_mode os_isolated, backend bubblewrap, four credential canaries unreadable. macOS, Apple Silicon macos-15: verdict PASS, backend macos-seatbelt, os_isolation true, four credential canaries unreadable, host file outside the workdir unmodified, every positive control satisfied. #11209 says of macOS that "the rest is still asserted about the generated SBPL text rather than about kernel behaviour". This measures the kernel behaviour. The Windows argv splice step passed on both windows-2025 and windows-11-arm, which confirms the design choice to emit no process.commandLine and let MXC render the argv.
wxc-host-prep.exe carries requireAdministrator in its manifest, so the Windows loader raises a UAC consent prompt at process start. With no interactive desktop to answer it the binary never returns rather than failing: on windows-2025 prepare-system-drive hung for the full 300 second timeout and took the job with it. prepare_host() now bounds each step and reports no response as a state instead of raising, because Studio setup has to be able to tell the user this needs their approval rather than appearing to freeze. The CI step is continue-on-error so the measurement still runs, which is how we learn whether Tier 3 works at all without the preparation instead of stopping at the prompt. Worth recording that MXC's own --probe diagnosed this before we did: AppContainer + DACL tier selected: AppContainer processes may be unable to read metadata of the system-drive root. Run `wxc-host-prep prepare-system-drive` (elevated) to grant the minimal metadata ACEs. AppContainer + DACL tier selected: AppContainer processes may be unable to open the NUL device, which the kernel resets to an AppContainer-hostile default at every boot. Run `wxc-host-prep prepare-null-device` (elevated). The probe also reports baseContainerApiPresent false, bfscfgPresent false and bfsCompiledIn false on build 26100, which is the os-version-support table confirmed on real hardware: T1 and T2 are both absent and T3 is the only tier available on a shipping Windows.
MXC replaces the environment rather than layering onto it; inheritDefaultEnv is 0.9 only. So whatever the policy carries is the entire environment the child gets, and a plan env without SystemRoot leaves python.exe unable to initialise. That is not a confinement result but it looks exactly like one from the outside, which is the failure mode the paired positive controls exist to catch. SystemRoot, SystemDrive, windir, COMSPEC, NUMBER_OF_PROCESSORS and PROCESSOR_ARCHITECTURE are now filled in from the host when the caller did not set them, so a deliberately overridden value still wins. They name system directories and the machine rather than carrying user data, and the POSIX backends pass their equivalents through for the same reason. The evidence this is the remaining gap: on windows-2025 the same executor, the same tier and the same argv splice run a minimal policy to completion. selected isolation tier: appcontainer-dacl AppContainerSID: S-1-15-2-2373689030-... Win32k mitigation applied to child process UI Job Object assigned to child process DIAG_OK Exit code: 0 (0x00000000) So ProcessContainer itself works on a shipping Windows build and the argv splice is confirmed on real hardware. What differs between that policy and ours is the environment, the timeout, the UI block and the capability list, and the environment is the only one of those that can stop an interpreter from starting.
MXC reports its stdio handling plainly in the debug output: "STDIO mode: passthrough (forwarding parent handles to child)". Its warnings therefore land on the same stdout as the workload. Two things break as a result. The capability probe requires its token alone on stdout, by design, so that a sandbox which merely prints something cannot be mistaken for one that ran the payload. With MXC's banner mixed in, the probe cannot conclude and reports the host as having no sandbox. That is the VOID the Windows job kept returning while the same executor, tier and argv splice ran a minimal policy to completion in the diagnostic step of the same job. The second is worse in normal use and would have outlived the probe: a tool call's visible output would carry MXC's warnings interleaved with the user's own program output, with no way to tell them apart. --log-file sends MXC's diagnostics to a file this launch owns and removes on cleanup, leaving stdout to the payload. The log path is registered as a cleanup callback rather than a cleanup path, because cleanup_paths rmtree's what it is handed and this is a file. The container id test now finds the config by flag instead of by argv index, since argv grows as the backend learns what MXC needs and a positional assumption breaks silently.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…he way there The macOS deny I added for Studio's own state was too wide in one specific way. On a default install the session workdir lives UNDER the Studio root, so denying file-read* on that root also denied stat on the directories leading to the workdir. os.makedirs then decided an existing ancestor was missing, tried to create it and failed with EPERM. macos-15 showed it: test_python_exec_mnt_data_open_is_remapped_into_workdir failed on the branch and passed on a base arm built from plain upstream main running the same job. The other 13 failures on that runner appear identically in both arms, so they are the runner's, not the branch's. The deny is now file-read-data and file-map-executable. A directory entry existing is not the secret; auth.db's contents are, and both reading a file and listing a directory are file-read-data, so the boundary that finding was about is unchanged. One test added for the traversal, verified to fail with the wider deny restored, and the two existing assertions about this rule updated to name the operation it now denies.
… read tool_path_approval treats the folders a user registered with Studio, and the well-known LM Studio and Ollama locations, as read-silent: "these hold weights, not documents, and reading them is the point of the app". The sandbox did not bind them, so the two halves of the product disagreed. A Python read or a cat from a registered model folder passed the approval gate without prompting, exactly as designed, and then failed inside the jail on every default auto launch on Linux and macOS. Both backends now grant those folders read only. Deliberately not the whole read-silent set: it also carries /etc and other system directories, where staying quiet at the approval gate is reasonable and binding the directory is not, since it would hand over /etc/ssl/private that the bind list excludes one file at a time. Measured, not assumed: binding the full set made test_no_private_key_directory_enters_the_jail_at_all fail. A registered folder that turns out to be a home, a system directory or Studio's own state is refused for the same reason. The write-silent half is not consulted at all; the sandbox keeps writes to the session workdir. Not fixed here, and left for the author: a path the user approves at the PROMPT is still not granted, because approval is a per-call yes or no and no resolved path set reaches ToolLaunchPlan. Carrying it needs a decision about what the approval is taken to authorise, which is the author's to make. Three tests, each verified to fail with its grant reverted. 901 passed, 4 skipped.
Parity with the Linux and macOS halves carried in the previous commit. The approval gate treats the folders a user registered with Studio, and the well-known LM Studio and Ollama locations, as read-silent, so a read from one never prompts and would then have failed inside the MXC container. Read only, never in readwritePaths, and it goes through the same filters as every other grant, so a folder inside the workdir or on another drive is handled the way it already was. One test, verified to fail with the grant reverted. 959 passed, 4 skipped.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a85e0529c6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if real == os.sep or not os.path.isdir(real): | ||
| continue | ||
| home = os.path.realpath(os.path.expanduser("~")) | ||
| # A registered folder that IS a home, a system directory, or that holds | ||
| # Studio's own state is a misconfiguration, and binding it would undo | ||
| # the rest of the profile. | ||
| if real == home or real in _NEVER_A_MODEL_LIBRARY: |
There was a problem hiding this comment.
Reject Windows drive roots as model libraries
On Windows, a canonical drive root such as C:\ is not equal to os.sep ("\\"), and none of the POSIX entries in _NEVER_A_MODEL_LIBRARY match it. If Studio's state is on another drive, registering C:\ (or an ancestor such as C:\Users) therefore survives these checks and is added recursively to MXC's readonlyPaths, exposing credentials and other files across that drive to model-authored code despite OS isolation. Detect filesystem roots with os.path.dirname(real) == real and add Windows system/home ancestors to the broad-directory rejection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it was reachable: scanning a whole drive for models is exactly how someone ends up with C:\ registered. Fixed in 357f7cf. Filesystem roots are now detected with os.path.dirname(path) == path, which is true at exactly the roots on every platform and covers C:\ and \server\share\ as well as /. The Windows system directories are read from the environment (SystemRoot, windir, ProgramFiles, ProgramFiles(x86), ProgramW6432, ProgramData, PUBLIC) rather than left out of the POSIX-only table, since the system drive letter and the Program Files location are both configurable. The parent of the user's home is rejected alongside the home itself, which is what /home and /Users were doing literally and is C:\Users on Windows.
test_a_windows_drive_root_is_not_a_model_library exercises the rule through an injected path module so it runs from any host, and the two environment cases have their own tests. All three fail with the hunk reverted.
…andbox Three things found while re-reading the workdir scan and the model library grant. A socket under the session workdir is fatal, and that is right everywhere except one directory. <workdir>/unsloth-tmp is created by Studio and is the child's TMPDIR, so a tool that used multiprocessing or any AF_UNIX server and was killed leaves its listener behind. Every later Python and Terminal call in that chat was then refused, and the scan is also what has to run before a tool could delete the socket, so the chat could not clean up after itself. The scan now removes sockets and FIFOs from that one directory before it walks. Removing is not a way past the check: the entry is gone rather than accepted, and anything that will not unlink is still a finding. The scan's five second budget was checked between entries, which is only a deadline while the walk is running. os.walk's scandir and the lstat per entry are uninterruptible, so a stalled NFS or FUSE mount under the workdir blocked inside one syscall and the call hung for the mount's timeout instead. The walk now runs on a worker and the budget is wall clock. Giving up reports the scan as unfinished, which auto carries and required refuses, and a second walk is not started for a root whose first one is still stuck. model_library_roots rejected a filesystem root by comparing against os.sep, which is true of POSIX / and of nothing on Windows: a folder registered as C:\, which is what scanning a whole drive for models produces, was granted. Roots are now detected with dirname(path) == path, the Windows system directories are read from the environment rather than left out of a POSIX-only table, and the parent of the user's home is rejected alongside the home itself, since /home and /Users were listed literally and the Windows equivalent is C:\Users under whichever drive Windows was installed on. Each fix has a test that fails when its hunk is reverted.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 357f7cfa6a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| try: | ||
| os.unlink(path) |
There was a problem hiding this comment.
Avoid deleting IPC endpoints without proving they are stale
When two tool calls run concurrently in the same session, the later call scans the shared unsloth-tmp directory and unconditionally unlinks sockets or FIFOs that the first call may still be using, breaking multiprocessing, distributed workers, or local IPC mid-execution. This can also delete host-owned endpoints when a project already contained a writable directory named unsloth-tmp, because _sandbox_temp_dir adopts such an existing directory without an ownership marker. Use per-call scratch directories or verify that no active call owns the endpoint before removing it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Both halves are right, and the concurrency one is the sharper of the two: two calls in a session share that directory, so a listener there can belong to a call that is still running. Fixed in 5941f11 (7f62713 on the source PR).
Staleness is now proved per endpoint rather than assumed. A socket is removed only when connecting to it is refused, a FIFO only when opening it for writing reports ENXIO. Anything live, or anything the probe cannot settle, is left alone; the walk then refuses that one launch, which ends when the other call does rather than lasting the rest of the chat. The long-path case is handled rather than treated as undecided, since sun_path is 108 bytes and a session workdir can be longer: the endpoint gets a short alias through a temporary symlink to its directory, and CPython raises its own path-too-long OSError with errno None, which would otherwise have read as live.
Ownership is checked too, for the adopted-directory case you describe: only a directory created the way _sandbox_temp_dir creates one, 0700 and owned by the user Studio runs as, is swept at all. I tried a marker file first and backed it out. The scratch directory is required to be empty when a call ends and its contents are listed to the user, so the marker put a file card on every call and made an otherwise empty sandbox look like it held the user's work.
One more from re-reading it: an endpoint with st_nlink > 1 is now left alone as well, since another name for it exists somewhere, the walk's hard-link rule is what should answer for it, and removing this name would hide the finding.
Per-call scratch directories were the other option you offered. I did not take it because TMPDIR is also where the user's own artifacts from a call land, and the listing and download routes address that path; changing its shape is a larger move than this bug needs.
The sweep that stops a killed tool's leftover listener from ending a chat removed sockets and FIFOs from the scratch directory unconditionally, and "left behind" was the whole justification for removing them. Two ways that was wrong. Two tool calls can run in one session and share that directory, so a live listener there may belong to a call that is still running, and unlinking it breaks multiprocessing or a local IPC server mid-execution. A socket is now removed only when connecting to it is refused, and a FIFO only when opening it for writing reports no reader. Anything live, or anything the probe cannot settle, is left alone, and the walk then refuses this launch, which ends when the other call does rather than lasting the rest of the chat. _sandbox_temp_dir adopts an existing unsloth-tmp rather than failing, so a project that already contained a directory by that name would have had its own endpoints swept. Only a directory created the way Studio creates one, 0700 and owned by the user Studio runs as, is touched. That is evidence rather than a marker file on purpose: the scratch directory is required to be empty when a call ends, so residue in it would show up as a file card on every call and would make an otherwise empty sandbox look like it held the user's work. An endpoint with more than one link is also left alone now. Another name for it exists somewhere, the walk's hard-link rule is the one that should answer for it, and removing this name would hide the finding. Three tests, each failing when its hunk is reverted: a live listener survives, a FIFO with a reader survives while a stale one is removed, and a scratch directory Studio did not create is not swept at all.
The sweep walks the same workdir the bounded scan does, so it can block on the same stalled NFS or FUSE mount. Running it on the caller's thread first put back exactly the hang the wall-clock bound exists to remove: the call would sit in the sweep's uninterruptible scandir for the mount's timeout before the budgeted walk was ever reached. It now runs on the same worker, under the same deadline, and the walk gets what is left of the budget rather than a fresh copy of it. Past the deadline the sweep stops and leaves the rest for the walk to refuse, which is the same answer an unfinished scan already gives: auto carries it and required refuses. Two tests, both failing on revert: a wedged sweep returns the caller inside the budget, and a sweep handed a deadline that has passed removes nothing while the same sweep without one removes the stale endpoint.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 25656e3f63
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| roots.append(os.path.dirname(resolved)) | ||
| # bash.exe lives in <git>\bin and its userland in <git>\usr\bin, so the | ||
| # install root covers both without guessing at either layout. | ||
| roots.append(os.path.dirname(os.path.dirname(resolved))) |
There was a problem hiding this comment.
Avoid widening non-Git launch paths to their grandparent
For a Windows Python launch outside the managed venv—for example C:\Python313\python.exe—this unconditionally adds C:\ to MXC's recursive readonlyPaths, exposing the entire drive, including user credentials, to model-authored code with unrestricted network access. The grandparent grant is only needed for the trusted Git-for-Windows Bash layout, so restrict it to that terminal executable and reject filesystem roots or home ancestors before adding any launch root.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 6024a9e. C:\Python313\python.exe has C:\ as its grandparent, readonlyPaths are recursive, and the launch does have unrestricted network, so that grant was the whole system drive including every user profile on it.
The grandparent is now added only for the Git for Windows layout, matched on both halves of it (bash.exe sitting in a directory named bin), since that is the only case the line existed for: bash cannot run without \usr\bin. Separately, every assembled read root is dropped if it is a filesystem root, the user's home, or the directory the homes live in, so a root that arrives some other way does not slip through either.
The Windows system directories are deliberately not in that rejection set. System32 is on the PATH of every launch and the container will not start without it, and it is already granted read-only by _system_roots.
Four tests; the two covering the fix fail when it is reverted. An interpreter outside Git does not reach its grandparent, Git bash still gets its install root, and the assembled grant drops a home on PATH while keeping an ordinary entry beside it.
Two separate holes in what the workdir scan and the cache memo were willing to assume. The stale-endpoint sweep removed FIFOs as well as sockets. A bound AF_UNIX path with nothing listening is garbage by construction, since bind refuses an existing path and a server has to unlink it before reusing it. A FIFO is the opposite: it is meant to outlive the processes at its ends, having no reader is its ordinary resting state, and 0700 plus ownership is evidence of who created the directory rather than proof. Launching a tool should not delete a user's idle named pipe, so FIFOs are no longer swept and one in the scratch directory refuses the launch exactly as it did before. The cache verdict was memoized against the component root's identity and mtime. A socket, a FIFO or a link created inside an existing nested directory leaves the root untouched, so a clean verdict could be reused for five minutes over exactly the channel the scan exists to reject. The verdict now carries every directory the scan visited and reuse re-stats all of them, which is one stat per directory against one lstat per entry: the saving that motivated the memo survives, and the invalidation answers for the whole tree. A walk that did not finish records no witness, so a partial scan is never reusable. What this still does not catch is a link created outside the tree to a file inside it, which changes no directory's mtime; that needs host write access to the cache's own files, which is access enough to change them directly. Also adds the macOS measurement for hard-link creation inside the workdir. file-link is its own SBPL operation rather than part of file-write*, so (deny default) should already refuse it, but the profile text is not the thing that decides: the test links on the host first as a positive control, then requires the same link to fail inside the sandbox. It runs on the Apple Silicon staging leg. Tests: a dormant FIFO survives and still refuses the launch, a socket planted deep inside a cached component invalidates its verdict, an unchanged cache is not walked again, and the macOS hard-link control. Each fails on revert.
…iner _launch_program_roots added the program's parent AND its grandparent. That is right for one layout only: Git for Windows puts bash.exe in <git>\bin and its userland in <git>\usr\bin, so the install root covers both. For an interpreter installed at C:\Python313\python.exe the grandparent is C:\, and MXC's readonlyPaths are recursive, so the container was handed the entire system drive, every user profile on it included, for model-authored code that also has unrestricted network access. The grandparent is now granted only for <git>\bin\bash.exe, matched on both halves of that layout, and every assembled read root is dropped if it is a filesystem root, the user's home, or the directory the homes live in. The Windows system directories are deliberately still granted: System32 is on the PATH of every launch and the container cannot start without it. Four tests, and the two that cover the fix fail when it is reverted: an interpreter outside Git does not reach its grandparent, Git bash still gets its install root, the helper rejects roots and homes, and the assembled grant drops a home on PATH while keeping an ordinary entry.
…macOS
Found by running the five test files that exist on main against plain upstream
main and against this head on the same macOS 15 runner: 13 failures are
identical in both arms and pre-date this work, and this one was new on the head.
The Studio-state deny emits every spelling a path has, /var and /private/var
both, because Seatbelt needs both. The list of paths to restore afterwards was
built with a plain prefix compare. On macOS /var, /tmp and /etc are symlinks
into /private, a session workdir arrives resolved and a configured Studio home
does not, so the two looked unrelated, the workdir was never restored, and the
deny that covered both spellings stood. The sandboxed interpreter then could
not open its own script and the tool call returned
Exit code 2: can't open file '<workdir>/studio_exec_xxxx.py':
[Errno 1] Operation not permitted
for every Python and Terminal call on that install. The failure was invisible
in the earlier runs because it needs a Studio home under one of those symlinked
prefixes, which is what the test fixture produces and what a custom
UNSLOTH_STUDIO_HOME under /var or /tmp produces too.
The restore list is now built across every spelling on both sides, the same way
the deny is. The test reproduces the shape with a symlink, so it runs on any
host, and it fails when the comparison is put back.
|
One of the reds here is stale rather than anything in this branch.
The others look like this branch's own: |
…lothai#11386) A pull_request run does not test the branch head. It tests refs/pull/N/merge, a merge of the branch into the base as the base stood when the run was created. GitHub does not rebuild that ref because the base later moved, and a re-run replays the same merge commit, so a fix that lands on main after a run starts stays invisible to that run until someone pushes to the branch. That cost real time today. unslothai#11372 gave three test files encoding = "utf-8" and merged at 14:35 UTC. Runs created at 13:39, 14:26 and 14:29 on unslothai#11375, unslothai#11357 and unslothai#11373 all went on failing tests/test_source_read_encoding.py on exactly those three lines, and all three were first read as defects in branches that had never touched the files. Adds .github/actions/merge-ref-age, which asks the compare endpoint how far the base branch has moved since this run's merge ref was built and prints a notice if the answer is not zero. It is wired into the two studio-backend-ci.yml jobs that run pytest, gated on failure(), so a green job never pays for it and it stays quiet when the base has not moved. It is advisory and cannot fail a job. A stale merge ref does not make a failure untrue: the merge really does fail. Deciding otherwise for the reader would be worse than the confusion it is fixing, so the script never exits non-zero and never emits ::error::. tests/studio/test_merge_ref_age_is_reported.py keeps both properties: every job in that workflow running pytest carries the step under failure(), and the action's script cannot fail the job it sits in. Each assertion was checked by reverting it individually against a green baseline. The repo's own test_workflow_guards_run_unfiltered caught the new guard missing from the unfiltered job, so it is registered in workflow-trigger-lint.yml too.
|
Closing in favour of #11390, which drives the same Microsoft MXC Two things this PR had that #11390 does not are being ported into #11390 rather than kept in a second MXC PR:
|
…lothai#11386) A pull_request run does not test the branch head. It tests refs/pull/N/merge, a merge of the branch into the base as the base stood when the run was created. GitHub does not rebuild that ref because the base later moved, and a re-run replays the same merge commit, so a fix that lands on main after a run starts stays invisible to that run until someone pushes to the branch. That cost real time today. unslothai#11372 gave three test files encoding = "utf-8" and merged at 14:35 UTC. Runs created at 13:39, 14:26 and 14:29 on unslothai#11375, unslothai#11357 and unslothai#11373 all went on failing tests/test_source_read_encoding.py on exactly those three lines, and all three were first read as defects in branches that had never touched the files. Adds .github/actions/merge-ref-age, which asks the compare endpoint how far the base branch has moved since this run's merge ref was built and prints a notice if the answer is not zero. It is wired into the two studio-backend-ci.yml jobs that run pytest, gated on failure(), so a green job never pays for it and it stays quiet when the base has not moved. It is advisory and cannot fail a job. A stale merge ref does not make a failure untrue: the merge really does fail. Deciding otherwise for the reader would be worse than the confusion it is fixing, so the script never exits non-zero and never emits ::error::. tests/studio/test_merge_ref_age_is_reported.py keeps both properties: every job in that workflow running pytest carries the step under failure(), and the action's script cannot fail the job it sits in. Each assertion was checked by reverting it individually against a green baseline. The repo's own test_workflow_guards_run_unfiltered caught the new guard missing from the unfiltered job, so it is registered in workflow-trigger-lint.yml too.
Summary
Adds Windows tool isolation for Studio's Python and Terminal calls, using Microsoft's MXC ProcessContainer. Linux bubblewrap and macOS Seatbelt from #11209 are untouched.
MXC ships
wxc-exec.exe, a native Rust executor that takes a JSON policy and runs one workload inside an AppContainer. It is driven withsubprocessand nothing else. No Node runtime, no npm at run time, no vendored JavaScript. That is the difference from #10615, which vendored a pinned@anthropic-ai/sandbox-runtimehelper plus an npm install and 11,243 lines. Here the executor is one 9MB signed binary fetched at setup time, and nothing about it runs during a tool call except the process itself.Depends on #11209
This branches from #11209 and retargets to
mainonce that lands. The files below are the only ones this PR adds on top of it:studio/backend/core/inference/sandbox_windows.pystudio/backend/tests/test_sandbox_windows.pystudio/backend/tests/sandbox_enforcement_probe.py.github/workflows/studio-sandbox-enforcement.ymlstudio/install_mxc_runtime.pystudio/backend/core/inference/os_sandbox.pyIt slots into the existing seam, it does not widen it
#11209's backend contract is duck typed: a module exposing
BACKEND_NAME,PROFILE_ID,LIMITATIONSandprepare(plan) -> PreparedSandboxLaunch.sandbox_linuxandsandbox_macosalready satisfy exactly that, andsandbox_probe.probe()takes the module as an opaque backend. So this adds a third module and extends the only two platform ladders that select one, incapability_snapshot()andprepare_tool_launch(). The probe, the execution record andtools.pyare unchanged.Measured against the shipped executor, not read off its docs
Validated with MXC's Linux sibling
lxc-execfrom the same 0.8.0 package, in a container where bubblewrap works. The CLI surface and the config schema are shared, so this establishes how the adapter talks to MXC. It establishes nothing about Windows enforcement; that is what the Windows CI job is for.Confinement is genuine rather than nominal:
/etcfrom insideTwo findings changed the design:
The
-- argvsplice is Windows only.lxc-execrejects trailing arguments. This matters becauseprocess.commandLineis a single string, and rendering model authored argv into a Windows command line in Python is an injection hazard with a long history.build_policy()therefore emits nocommandLineat all and relies on MXC rendering the argv itself. Since the Linux binary does not support it, the Windows CI job proves the splice on a real runner before it measures anything.The schema pin is ours, not MXC's. The docs describe stable schemas as immutable exact match contracts, but the shipped executor accepted
0.8.1-alpha(9.9.9-alphaand garbage were rejected). SoSCHEMA_VERSIONis pinned exactly on our side rather than trusted to be enforced upstream.What this does not claim
MXC's README says in bold that no MXC profile should be treated as a security boundary yet, and that current generated policies are known to be overly permissive. Its
docs/process-container/os-version-support.mdputs the kernel native tier (T1, PSEC) at build 26600 or newer, and the brokered tier (T2, BFS) is compiled out by default becausebfscfg.execan deadlock the host. The v0.8.0 release notes confirm it: "Windows 11 24H2 and 25H2 machines do not yet include all of the required OS side changes".So on 23H2, 24H2 and 25H2, which is every Windows that ships today, the enforcing mechanism is an AppContainer SID plus temporary DENY and ALLOW ACEs written onto real host paths and removed on exit. That is a real boundary and it is not a kernel sandbox. It is carried as the
windows_tier3_dacllimitation and dropped only on a host that actually reaches the native tier, so nothing is claimed that the host cannot back.Two documented consequences of that tier are engineered around rather than hoped about:
Network egress stays unconfined, the same contract Linux and macOS carry. Explicit CIDR and port rules exist in schema 0.8 but are PSEC only, so they are unavailable on every build this actually runs on, and claiming them would be false.
Off by default
Windows isolation is an opt in preview while upstream calls itself one. Eligibility is read from
UNSLOTH_WINDOWS_SANDBOX_PREVIEWin the environment Studio started with, never from a request, so a model authored tool argument cannot select a backend or relax a policy. Without it, Windows keeps today's behaviour exactly andcapability_snapshot()says why.The enforcement workflow, and why it exists
studio-sandbox-enforcement.ymlruns the probe on real Linux, macOS and Windows kernels, and every job fails when the sandbox cannot be built.That last part is the point. Backend CI added a step named "Install bubblewrap, so the sandbox tests run instead of skipping", and on
ubuntu-24.04it logs:apparmor-profileson 24.04 does not ship that profile at that path, soapparmor_parserfinds nothing and the|| trueswallows it. The run is green at 13,165 passed with every confinement test skipped. A suite that is green because it tested nothing is worse than a red one. The Linux job here runs onubuntu-22.04, which predateskernel.apparmor_restrict_unprivileged_userns, so an ordinary unprivileged user really can create the namespace bwrap needs. That is also the launch path a desktop user takes, which a privileged container is not.The probe pairs every negative control with a positive control proven on the host first, because a read that fails for an unrelated reason proves nothing and a child that cannot start at all would look like a perfect sandbox. System write targets the host itself cannot write are dropped from the verdict rather than counted as confinement.
Installation
install_mxc_runtime.pytakes the binaries from the npm tarball rather than the 358MB release zip. It is 26MB, carries the same signed per arch executables, and is a gzipped tar the standard library opens, so Node is not needed to install it any more than to run it. The version is pinned, tarball members are matched by exact name and written by basename so a crafted tarball cannot traverse out of the destination, and the sha256 of the executor is printed for pinning. It runs at setup time and never during a tool call, because a tool call that could download its own sandbox executor would be choosing its own boundary.Run end to end, it produced
wxc-exec.exesha2566049c64723af1173c3739dc6cd6b2f33f6c021bb2832c4216233cba7f71aee9a.Test plan
pytest studio/backend/tests/test_sandbox_windows.py, 18 passedtest_account_tool_confinement.pyare identical at the unmodified Studio: minimal OS sandbox for Python and Terminal tools on Linux and macOS #11209 head, so they predate thiswindows-2025andwindows-11-armmacos-15Not in scope
Windows Sandbox, WSLc, MicroVM, Hyperlight and IsolationSession are experimental MXC backends and are left for a separate evaluation. Removing the preview label is a separate decision that needs upstream to retract its warning and T1 to reach a shipping build.