Repository navigation
Studio: add Windows MXC Preview sandboxing - #11390
Merged
danielhanchen merged 114 commits intoSep 25, 2026
Merged
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.
Found by reverting each functional hunk and re-running the suite. Both changes could be removed with all 133 tests still green, which is the same as not having made them: a later refactor reintroduces the per-launch cache walk or drops the TTL back to 60s and CI stays green either way. The memo test asserts the second launch does not re-walk the component, which is the whole behaviour: measured 2.1ms against an empty cache and 44.2ms at 15,000 entries, re-paid on every call before this. Two companion tests pin the invalidation direction, because a memo that never expires is a stale security verdict rather than an optimisation. One asserts a component changed through its root is re-inspected; the other asserts reset_cache_verdicts, which tools.py calls when a launch fails, actually drops the entry. The TTL test asserts the constant stays at or above ten minutes and that a seeded entry survives the 70s that used to expire it. Correctness never rested on the TTL, since the key carries the runtime identity and a failed launch invalidates outright, but the cost did: a call 70s after the last one measured 1.24s against 0.040s unsandboxed. Verified falsifiable: reverting the memo fails the memo test, reverting the TTL to 60 fails the TTL test. 137 passed with both in place.
…inutes Raising the probe TTL to 900s was about the hot path, where the verdict is available and the host is not changing underneath it. Applied to the negative verdict it works against the user: the cache key carries only the backend name and the runtime identity, and neither moves when bubblewrap is installed or the AppArmor profile is loaded, which is exactly what the remediation text tells the user to do. So `auto` kept running without OS isolation and `required` kept refusing calls for up to 15 minutes after the prerequisite was in place. An unavailable verdict now keeps the original 60s TTL and an available one keeps 900s, so the cost saving is unchanged and the remediation takes effect about as quickly as it did before. Verified to fail with the split reverted.
/opt is in the Linux read allowlist and the shipped Docker layout puts Studio's state inside it: docker/run.sh mounts the Studio volume at /opt/unsloth-studio and studio_launch.sh exports UNSLOTH_STUDIO_HOME to match. Binding /opt whole therefore hands auth/auth.db to model-authored Python and Terminal code read-only. That database holds the HS256 jwt_secret, and tools.py's guard is on the literal path, so building the path dynamically walks past it and the disclosure survives required mode, which is the mode that exists to prevent exactly this. Dropping /opt outright would take away toolchains that legitimately install there, so a system root that contains Studio's state is replaced by its children with the state directory left out, recursively and bounded. Everything else under the root stays readable and the state directory is never a bind source. Roots that do not contain Studio state are untouched, so no launch pays a listdir of /usr. Two tests, both verified to fail with the exclusion reverted. 883 passed, 4 skipped across the sandbox suites.
…fter a Seatbelt failure Two findings on the tools.py wiring. The mode check sat inside the planner, and a managed account's confinement is the outer launch contract and skips the planner entirely, so whether an unknown tool_execution_mode was refused depended on which account ran the call. It now happens in _requested_execution_mode, which both executors call before they branch on confinement, so the contract holds on both paths. No production caller passes the mode today, so this is a contract the PR states rather than a live regression, but the divergence is real in the code the PR adds and checking in one place is cheaper than having two answers. The launch-failure invalidation matched the literal prefix "bwrap: ". Seatbelt reports a rejected profile as "sandbox-exec: ", so on macOS a backend already known to be broken kept being launched for the whole positive probe TTL instead of re-probing and letting auto fall back. The marker is now keyed on the backend that actually ran, so each launcher's own refusal is recognised and a payload failing inside a correctly built sandbox still costs nothing. Two tests added, each verified to fail with its fix reverted. 885 passed, 4 skipped.
…acOS too Two follow-ups to keeping Studio's own state out of the sandbox read grants. The Linux descent is bounded, and the bound restored the ancestor it had just been descending into. A home more than four levels below a system root, say /opt/a/b/c/d/studio, therefore ended up binding /opt/a/b/c/d and handing over auth/auth.db exactly as binding /opt whole would have. At the cutoff the root is now dropped and the reason logged, so the bound fails closed. macOS had the same exposure by a different route. A Studio home under one of the optional read roots, a Homebrew prefix for instance, is recursively readable, so a script could construct the path to auth/auth.db and read the HS256 jwt_secret without ever spelling the literal path tools.py guards. The profile now denies the state root after the read allowances, Seatbelt being last-match-wins, and immediately restores the runtime paths inside it, since on a custom-home install the interpreter lives under the Studio root and a blanket deny would stop it being readable. The resolver both backends need is now one function in os_sandbox rather than a Linux-only helper, so the two platforms cannot answer differently. Three tests added, each verified to fail with its fix reverted. 888 passed, 4 skipped.
…he off Studio state Two consequences of the previous commit, both found before merge. Splitting a system root changed what a symlink under it means. Inside a whole-root bind a symlink is dormant: it resolves inside the jail, where its target is not mounted. Named as a bind source in its own right it resolves on the HOST, so a Studio home under /opt plus /opt/private pointing at /home/operator/private would have mounted that private directory into the sandbox precisely because the root was split, which the unsplit bind never did. A symlinked child is kept only when its target stays under the same root, so a toolchain that links within its own tree still works and nothing new becomes reachable. The writable model cache binds were a separate route to the same file. A configured HF_HUB_CACHE or HF_XET_CACHE at, or above, the Studio root shares auth/auth.db into the jail and shares it WRITABLE, and the hazard scan does not object because an ordinary file is not a host channel. A cache component that is, or contains, a Studio state root is now refused with a log line, and the other components are untouched. Three tests added, each verified to fail with its fix reverted. One of them drives _model_cache_binds itself rather than the predicate, since the guard is only worth anything if the bind list is what changes. 891 passed, 4 skipped.
A managed account on a host that cannot confine tool processes gets a Confinement whose mechanism is unconfined-by-owner when the installation owner has set UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS=1. It carries neither a pre-exec nor a wrapper, so it confines nothing; it only records that the owner allowed the call to run anyway. Both executors branched on "confinement is not None" and therefore treated it as the outer launch contract, skipped the generic sandbox planner entirely and executed even under tool_execution_mode="required". Required mode exists to refuse exactly that. They now ask whether the confinement confines, so the placeholder takes the planner path: auto falls back to software safeguards as it does for the owner, and required refuses. Nothing changes for a real Landlock or sandbox-exec confinement, which is still kept as the outer contract rather than having a generic sandbox stacked around it. Two tests added, one of them verified to fail with the condition reverted. Unrelated: three tests in test_account_tool_confinement.py fail on this workspace host (they assert against the real /run, /etc and /dev/nvidia*), and they fail identically with this change stashed, so they are not a regression from it.
HF_HUB_CACHE or HF_XET_CACHE configured as a broad path, /home/alice or a symlink resolving there, was accepted as a cache component and mounted WRITABLE into the sandbox. The host-channel scan does not object, because ordinary credential files are not host channels, so a tool call in required mode could read, change or delete the user's home. That is a misconfiguration rather than an attack, but the consequence is the boundary failing silently in the mode that exists to prevent it. A component is now refused when it is a filesystem root, the user's home or an ancestor of it, one of the obvious system directories, or a directory that already holds credentials such as .ssh, .aws or .git-credentials, since that is not a cache directory whatever it is called. Other components are untouched, so one bad setting costs one bind rather than the whole cache. Two tests, one verified to fail with the guard reverted.
The budget on the workdir host-channel walk exists so that one pip install cannot end a chat, and turning the refusal into a degradation was the right call for auto. It was the wrong call for required. The unvisited part of the walk could hold an external hard link or a host unix socket, both backends then grant the whole workdir read and write, and recording workdir_scan_incomplete in the execution record does not keep a boundary the caller asked to be guaranteed. required now fails closed on an incomplete scan and says what to do about it. auto is unchanged and still launches with the limitation carried, so the brick this budget was raised to fix stays fixed. The marker is a named constant now, since two places have to agree on it. Two tests, one for each half of the decision; the refusal is verified to fail with the check reverted.
…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.
…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.
shimmyshimmer
pushed a commit
to shimmyshimmer/unsloth-staging-4
that referenced
this pull request
Sep 25, 2026
…loading it apparmor-profiles ships bwrap-userns-restrict disabled under /usr/share/apparmor/extra-profiles, so apparmor_parser on the /etc path failed quietly and the confinement tests skipped on ubuntu-24.04. Same command the installer prints.
The interpreter is read-only inside the container, so a workload's pip install failed, and packages already in .unsloth-packages were not on PYTHONPATH or PATH. The launch now sets PIP_TARGET to the session packages and appends them to PYTHONPATH and PATH (Scripts and bin), matching the existing spelling of Path. Editable package directories are granted read-only through the same guard as model folders; a single-module editable install is a file and is skipped.
…sion and imports next call
bwrap is executed on the host, unconfined, while a launch is prepared, so a bwrap planted in a user-writable directory earlier on PATH would have run with Studio's own access and could answer the probe. The resolved binary and its directory must now be root-owned and writable only by root, the rule macOS already applies to sandbox-exec.
pip --target writes console scripts to Scripts on Windows, and the unisolated launch only appended bin, so a command installed into the session was lost on the next Terminal call. The helper moves to os_sandbox so a backend's own fallback can apply the same environment.
…indows MXC branch
When MXC qualified but failed before dispatch, the host fallback ran with the plain plan environment, so packages an earlier isolated call had installed disappeared for that call only. It now gets the same session-package environment as every other unisolated launch.
A second launch on the same workdir saw the first one's walk still running, took it for a walk a previous launch had given up on, and reported the workdir unchecked, which required mode refuses. It now waits out that walk's own deadline and reuses its verdict; a walk already past its deadline still reports incomplete at once.
--unshare-all adds the network namespace, which the sandbox never creates, so a host that only denies that one was told bubblewrap cannot build a sandbox.
Measured on windows-latest with the DACL opt-in: the fixed 0.5 s timer landed during the seconds before dispatch, so the call was cancelled correctly but never dispatched and left no record to check; and the code gate refuses a subprocess argv it cannot read as literal, so the pip test never reached pip.
… into the Windows MXC branch
…ng setup With ErrorActionPreference Stop and PowerShell 7's native-command preference on, a nonzero exit from install_mxc_prebuilt.py terminated setup before the software-safeguards fallback, reproduced locally in pwsh 7 with a failing installer. The call now runs under Continue with the native preference off, restored afterwards, like the llama.cpp installer.
… holds it System roots already bind their children instead when the Studio home is inside them, but a runtime or editable root containing it was bound whole, auth.db included. Those are now carved the same way; a runtime inside the Studio home, the managed venv, is unchanged.
…st path The approval classifier decodes $'...' and prompts for cat $'/home/u/x', but the check that lets an approved call leave the jail lexed the raw word as $/home/u/x, so the approved read still failed inside it.
Measured on windows-latest with the DACL opt-in: pip itself does not complete inside the container yet (its log and temp directories go through the path-remap shim and fail), so the native test now covers what this branch changes, packages already in .unsloth-packages being importable in an isolated call, and pip inside the container stays a documented limit.
Member
|
pre-commit.ci run |
shaojun
pushed a commit
to shaojun/unsloth
that referenced
this pull request
Sep 29, 2026
Adds a Windows MXC ProcessContainer backend beside bubblewrap and Seatbelt. setup.ps1 installs Microsoft's pinned @microsoft/mxc-sdk 0.8.0 wxc-exec.exe and wxc-host-prep.exe from npm with size and SHA-256 checks. Tools run through wxc-exec directly, with availability from a live probe. On builds without BaseContainer, the AppContainer DACL tier is opt-in via UNSLOTH_MXC_ALLOW_DACL_FALLBACK=1, with a Studio-owned restore journal replayed at every start and install_mxc_prebuilt.py --prepare-host for the one-time host preparation. Co-authored-by: Etherll <[email protected]> Co-authored-by: oobabooga <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Dependency
Builds on #11209, which is merged; this branch now carries only the Windows MXC backend on top of it.
Supersedes #10615, replacing its Windows SRT backend with the Microsoft MXC ProcessContainer integration described below.
Summary
Adds a Windows MXC ProcessContainer backend beside the Linux bubblewrap and macOS Seatbelt backends from #11209. Python and qualifying native Windows terminal commands use the shared
ToolLaunchPlanandPreparedSandboxLaunchflow.Studio downloads Microsoft's official
@microsoft/[email protected]npm tarball (25.9 MB, published by Microsoft), verifies the tarball and each executable's size and SHA-256 digest, and installs only the approved x86-64wxc-exec.exeandwxc-host-prep.exe. Both binaries are byte-identical to the ones in the 358 MB GitHub release zip, whose extra content is debug symbols only.setup.ps1runs the install, so it needs no separate step; a second run is a no-op. The backend sends a deterministic stable v0.8 request directly towxc-exec.exe, withui.disable=falseand, by default,fallback.allowDaclMutation=falsein the executed configuration.The integration preserves the selected Python or shell command, streams stdout and stderr, reclaims descendants on timeout or cancellation, and never replays the workload on the host after WXC dispatch may have started. Execution records report the backend, WXC revision and digest, configuration hash, cleanup state, and current Preview limitations. WXC v0.8.0 does not provide structured per-execution tier evidence, so the execution tier remains
unknown.Supported scope
wxc-execrefuses with "BaseContainer is unavailable on this system and DACL fallback is disabled", so tools keep running with software safeguards unless the opt-in below is set.mxc_compatibility_requested_unverified.Opt-in AppContainer DACL tier (current Windows builds)
UNSLOTH_MXC_ALLOW_DACL_FALLBACK=1lets MXC use its AppContainer tier, the only one shipping 23H2, 24H2 and 25H2 builds have. MXC adds temporary permission entries to the granted folders and removes them on exit. It is off by default.allowDaclMutation=trueonly when the opt-in is set at spawn time. The probe cache and capability fingerprint include the setting, so a probe under one setting never qualifies a launch under the other.wxc-execalways getsMXC_DACL_STATE_DIRunder the Studio home, opt-in or not. MXC journals every entry before applying it and replays the journal at every start, so a hard kill is repaired by the next launch or probe. A grant that would expose the journal refuses the launch.wxc-host-prep.exeis pinned from the same package (913,728 bytes, SHA-256a9b8b14a...e310) and installed next towxc-exec.exe.python studio/install_mxc_prebuilt.py --prepare-hostinstalls MXC if it is missing and runs the steps MXC reports missing, through a UAC prompt when not elevated. The elevated side copies the binary into a fresh folder under ProgramData that only Administrators and SYSTEM can write, rechecks its SHA-256 there, runs it, and deletes the folder, so a user-writable copy is never executed elevated.prepare-system-driveis one-time and takes minutes;prepare-null-deviceis undone by every reboot. Nothing is scheduled to run elevated.mxc_tier3_dacl_host_permission_changeswhen the opt-in is on.Measured on windows-latest (Windows Server 2025, 24H2 build 26100, no BaseContainer):
wxc-exec, tools use software safeguardsC:\WindowsandC:\Program Filestaskkill /Fonwxc-exec, then next startDACL recovery: 1 file(s), 4 ACE(s) restoredKnown limits on this tier: each launch costs about 10 seconds on that runner (MXC re-applies each granted tree), and a tool's timeout includes it; Windows PowerShell 5.1 does not autoload modules inside the container (
Write-Outputis not recognized until an explicitImport-Module Microsoft.PowerShell.Utility;PSModulePath, profile folders and the module analysis cache location make no difference), so its probe reports it unavailable, while pwsh 7 and cmd work.Fixes carried over from #11357
autorecordsworkdir_scan_incomplete,requiredrefuses, and the walk is wall-clock bounded. This is the rule Linux and macOS use.nlink > 1blocked the chat after one install.C:\Users\RUNNER~1are compared in their long form instead of being reported as reparse points.Execution cancelled.instead of an execution error.Launch safety
wxc-execstart, probe included, so orphaned entries are repaired before anything else runs. An elevated--prepare-hostprobes with an empty journal instead, so it never replays entries as Administrator.wxc-exec.Review fixes since the last description
PIP_TARGETpoints at.unsloth-packages, which is appended toPYTHONPATHandPATH(Scriptsandbin). The same environment is used whenautofalls back after a pre-dispatch MXC failure.setup.ps1keeps a failed optional MXC install non-fatal underStopand PowerShell 7's native-command preference (reproduced in pwsh 7).Known limit found while testing:
pip installinside the DACL tier does not complete yet. The network works inside the container and packages already in.unsloth-packagesimport, but pip's log and temp directories fail through the path-remap shim. Install from a normal call, or with the opt-in off, until that is fixed.Testing
ValidMicrosoft signatures;--prepare-hostexit 0 and a second run exit 0; 137 MXC unit tests passed. Inside the container the profile canary, the DACL journal and writes outside the workdir are denied; the workdir and stdlib imports work; aftertaskkill /Fthe next start restored the entries.git diff --checkpassed.