Repository navigation
Studio: grant MXC Tier 3 read access to runtime folders once, not per launch - #12121
Conversation
Scan the whole tree for credential files and links before granting, never take over an existing entry for the group, lock the record across processes, keep the retry when a rollback fails, check folder identity before revoking, and revoke from the capability check when the DACL tier is turned off.
Refuse a launch while another process may be mid-grant or an unfinished grant cannot be checked, keep records whose folder identity cannot be read, never adopt or roll back a folder that replaced the granted one, and keep cleanup from blocking a launch when only the record write fails.
The Windows unit suites run with the DACL opt-in set; stub the persistent read grant there so they neither run icacls on the host Python nor trip the host-launch assertions. The native suite keeps the real grant.
… grant actions/setup-python ships python3.exe as a symlink to python.exe in the same folder, so the whole interpreter was refused and kept the per-launch walk. A symlink or junction whose final target resolves inside the granted tree exposes nothing new; links that leave it and other reparse tags still refuse the grant.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ 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. |
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 177f922df0
ℹ️ 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 not os.path.isdir(key): | ||
| record.pop(key) | ||
| return "dropped" |
There was a problem hiding this comment.
Preserve grant records when the original path disappears
When a granted runtime directory is renamed or moved on the same volume, key stops being a directory, but the same NTFS object retains the explicit ALL APPLICATION PACKAGES ACE at its new path. This branch deletes the only record containing its file identity, so opting out and every later cleanup permanently lose the ability to revoke the machine-wide read grant. A missing original path must not be treated as proof that the granted object no longer exists; retain the record or resolve the stored identity before dropping it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Studio never moves or renames these runtime folders, and a moved one is no longer a path Studio launches from. The entry it keeps is read-only on a tree that passed the credential and link scan, so this is not something the opt-out needs to chase.
| if not enabled(): | ||
| revoke_recorded() | ||
| return () |
There was a problem hiding this comment.
Fail closed when opt-out cleanup cannot acquire the lock
When UNSLOTH_MXC_PERSISTENT_READ_GRANTS=0 while another Studio process still holds the grant transaction, revoke_recorded() suppresses the lock timeout and this branch returns normally, allowing the DACL launch to proceed. If the other process is still propagating or rolling back an ACE, WXC can observe the covered root and skip its per-launch grant while descendants remain unreadable—the same unknown state for which the enabled path raises ReadGrantError. The launch-time opt-out path should propagate lock contention and refuse the launch rather than treating deferred cleanup as success.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Needs two Studio processes running at once with opposite settings for this variable. Even then the outcome is a launch that cannot read some files, not access outside the policy, and the next launch retries the cleanup.
| "Install the pinned Microsoft WXC runtime and enable BaseContainer/PSEC. On Windows " | ||
| f"builds without it, set {mxc_policy.DACL_FALLBACK_ENV}=1 to use the AppContainer " | ||
| "tier: it adds temporary permission entries to the granted host folders, removed " | ||
| "on exit, and needs a one-time administrator host preparation plus one per reboot." | ||
| "on exit, and needs a one-time administrator host preparation plus one per reboot. " | ||
| "Studio's own Python runtime folders get a permanent read-only entry instead, so " | ||
| f"launches stay fast; set {mxc_read_grants.PERSISTENT_GRANTS_ENV}=0 to keep every " | ||
| "entry temporary." |
There was a problem hiding this comment.
Show the persistent-grant opt-out in the DACL remediation
The new disclosure and opt-out instructions are in the else branch, so they are shown only when DACL fallback is disabled. Once UNSLOTH_MXC_ALLOW_DACL_FALLBACK=1 is active and Studio is actually adding permanent runtime ACEs, the elif dacl branch omits both that behavior and UNSLOTH_MXC_PERSISTENT_READ_GRANTS=0, leaving affected users without the promised remediation. Include this text in the active DACL branch as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Wording only. The note is there for users deciding whether to enable the tier; the DACL branch is remediation for a host where it is unavailable.
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e8119a5c0d
ℹ️ 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".
| data = json.loads(record_path().read_text(encoding = "utf-8")) | ||
| except (OSError, ValueError): | ||
| return {} |
There was a problem hiding this comment.
Fail closed when the grant record cannot be loaded
When this JSON is malformed or temporarily unreadable, returning an empty record makes every existing persistent ACE invisible. revoke_recorded() will then leave those machine-wide grants in place, and if the same invocation grants another root, _save_record() replaces the original record without the lost identities, permanently preventing opt-out cleanup. Treat an unreadable or invalid record as an unknown security state and preserve/refuse it rather than continuing with {}.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The record is only ever written by an atomic replace while holding its lock, so a malformed file needs something outside Studio to corrupt it. A missing file, the normal case, correctly reads as no grants.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e8119a5c0d
ℹ️ 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".
| identity = _identity(root) | ||
| if identity is None: |
There was a problem hiding this comment.
Revalidate the scanned identity before granting
If a runtime root is atomically replaced between the initial identity read/eligibility scan and this second _identity call, identity refers to a directory that never passed the deep credential and reparse-point scan, yet it is immediately recorded and granted. A replacement after this read but before icacls resolves the path similarly leaves a grant on an unscanned object while the record retains the old identity and later cleanup drops it as mismatched. Fresh evidence beyond the previously discussed post-grant rename is that this second identity is never compared with current; restart eligibility when it changes and verify it again after _grant succeeds.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Replacing a runtime root needs write access to its parent, which the container never has; only the host user can do it, and that user can already read everything the grant exposes.
| done = subprocess.run( | ||
| [icacls, root, *args, "/Q"], | ||
| capture_output = True, | ||
| text = True, | ||
| # icacls writes the console (OEM) codepage to a pipe; the codec exists only on Windows. | ||
| encoding = "oem" if os.name == "nt" else "utf-8", | ||
| errors = "replace", | ||
| timeout = GRANT_TIMEOUT_SECONDS, |
There was a problem hiding this comment.
Make the one-time ACL operation cancellable
During the first grant or a pending-grant retry, this blocking subprocess.run receives no cancellation signal even though the surrounding capability probe and tool launch accept a cancel_event. If icacls stalls on a large or problematic runtime tree, cancelling the tool or probe still blocks for up to GRANT_TIMEOUT_SECONDS (15 minutes); propagate cancellation into this operation and terminate the child rather than waiting only for the timeout.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
One-time operation on a Studio runtime folder that finishes in seconds and is bounded by the timeout; not a correctness issue.
| for root in roots: | ||
| if _ensure_root(record, root): | ||
| covered.append(root) |
There was a problem hiding this comment.
Recheck every recorded root for newly unsafe content
When the selected runtime or trusted terminal PATH changes, previously granted roots remain in the record but disappear from the roots argument, and this loop never calls _ensure_root for them. Consequently, adding even a top-level .env or outward junction to such an old runtime is never detected or revoked, including after a Studio restart, while its machine-wide read ACE remains indefinitely; sweep recorded entries for unsafe or retired roots in addition to checking the current roots.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Needs someone to drop a credential file into a runtime Studio no longer uses. Sweeping every retired root with a deep scan on each launch would cost what this PR removes; opting out still revokes them all.
| if dacl_fallback_enabled(): | ||
| mxc_read_grants.ensure(runtime_roots) |
There was a problem hiding this comment.
Roll back grants when capability qualification fails
On a DACL-opted host with WXC installed but missing host preparation, or whose live isolation controls fail, the capability probe reaches build_launch_request and this call persists the runtime ACEs before WXC reports the capability unavailable. capability_snapshot then permits the software-safeguard fallback without another cleanup, so merely probing an unusable backend leaves machine-wide runtime access with no successful MXC launch; revoke grants added by a failed probe or defer persistence until qualification succeeds.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The read-only entry on Studio's runtime folders is the documented cost of the DACL opt-in, not tied to one launch succeeding, and it only covers trees that passed the credential and link scan. Opting out revokes it.
| if entry.name.casefold() in CREDENTIAL_FILES: | ||
| return f"it holds a credential file ({entry.path})" | ||
| if deep and entry.is_dir(follow_symlinks = False): | ||
| pending.append(entry.path) |
There was a problem hiding this comment.
Reject hard links that escape the runtime tree
The deep scan accepts every non-reparse regular file without checking its link count, so a benignly named file inside the runtime can be hard-linked to a credential or other host file outside the root. On NTFS those names share one file object and security descriptor, so propagating the ALL APPLICATION PACKAGES ACE through the runtime exposes the external object as well; the existing workdir scanner explicitly accounts for st_nlink, and persistent runtime grants need the same outward-hard-link rejection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
uv installs packages on Windows with hard links to its cache by default (link-mode hardlink), so nlink > 1 is the normal case in a Studio venv and rejecting it would disable the grant everywhere. Those links point at the same package files; a hard link to a credential file has to be made by the user.
…he read grant scan
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f55c792afb
ℹ️ 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".
| for key in list(record): | ||
| if _revoke_recorded_root(record, key) == "revoked": | ||
| restored.append(key) | ||
| # A failed revoke keeps its entry, so the next launch or capability check retries it. | ||
| _save_quietly(record) |
There was a problem hiding this comment.
Reject opt-out launches when ACL revocation fails
When opt-out or DACL-off cleanup reaches a recorded directory but _revoke() returns false—for example, because icacls persistently reports Access Denied—this loop retains the entry but returns normally. Both the disabled branch of ensure() and the non-DACL branch of build_launch_request() ignore that result, so launches continue while the machine-wide ALL APPLICATION PACKAGES ACE remains, and repeated retries may never honor the opt-out. This is fresh evidence beyond the earlier lock-contention case: the transaction is successfully acquired, but a completed revocation failure is still swallowed; propagate that failure instead of treating cleanup as successful.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The entry that stays behind is read-only on Studio's own runtime folders, which passed the credential and link scan; every later launch retries the revoke. Refusing launches over it would turn a preference into an outage.
|
|
||
|
|
||
| def _grant(root: str) -> tuple[bool, str]: | ||
| return _icacls(root, "/grant", f"*{ALL_APPLICATION_PACKAGES}:(OI)(CI)(RX)") |
There was a problem hiding this comment.
Cover descendants with protected DACL inheritance
When a runtime contains a descendant whose DACL has inheritance disabled and does not already grant this SID, granting only the root succeeds and is recorded as complete, but that descendant receives no ACE. The inheritable root ACE then makes WXC skip its normal recursive grant, so importing or executing that descendant fails inside the container. Microsoft's icacls reference documents /T as applying the operation to files in the specified directory and its subdirectories; this invocation omits it. Detect protected descendants and retain the per-launch path, or otherwise verify descendant coverage before recording completion.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Venvs made by uv or pip inherit their parent's ACL; a protected descendant needs someone to set one by hand, and the effect would be an import failing inside the container, not access beyond the policy.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f55c792afb
ℹ️ 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".
| deep = key not in _scanned or _scanned[key] != current | ||
| reason = ineligible_reason(root, deep = deep) |
There was a problem hiding this comment.
Rescan descendants after an in-place tree change
After the first successful scan, an ordinary mutation beneath the runtime leaves the root's file identity unchanged, so deep remains false and subsequent launches inspect only the root directory. For example, adding Lib/site-packages/pkg/.env or a nested outward junction after the grant will not be detected or revoked until Studio restarts, while the persistent inheritable ACE makes the new content readable by every AppContainer. The replacement fix does not cover this scenario because creating or changing descendants does not change the root's volume/file ID; the cache needs a content-change invalidation mechanism rather than relying only on directory identity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
By design: the deep scan runs once per Studio process and every new process scans again; rescanning the whole runtime on each launch is the cost this PR removes. The container cannot write under these folders, so only the host user or an install they run can add content there.
| if not (mxc_policy.dacl_fallback_enabled() and mxc_read_grants.enabled()): | ||
| # Here too: a host with only the DACL tier stops at this capability and never builds a launch. | ||
| mxc_read_grants.revoke_recorded() |
There was a problem hiding this comment.
Run opt-out cleanup when isolation is bypassed
If Studio previously created persistent grants and the user then sets UNSLOTH_MXC_PERSISTENT_READ_GRANTS=0 or disables the DACL tier while using Bypass Permissions, this cleanup is never reached: os_sandbox.prepare_tool_launch() returns early for requested_mode == "full", and the production callers do not otherwise invoke capability_snapshot(). Consequently the recorded machine-wide ACEs remain indefinitely despite the opt-out, potentially even across a restart configured directly into full mode. Trigger revocation from an unconditional startup/preparation path rather than only the MXC capability path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
In Full access nothing launches in a container, and the revoke runs the next time Studio goes through MXC. Until then what remains is a read-only entry on Studio's own scanned runtime folders.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f55c792afb
ℹ️ 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".
| def _revoke(root: str) -> tuple[bool, str]: | ||
| return _icacls(root, "/remove:g", f"*{ALL_APPLICATION_PACKAGES}") |
There was a problem hiding this comment.
Preserve grants added after Studio's ACE
When another ACL manager adds a separate explicit grant for S-1-15-2-1 after Studio records its own—for example, a differently scoped or broader permission—opt-out cleanup invokes /remove:g and deletes that grant as well. The initial explicit check only protects entries present before Studio's grant; it does not protect later changes. Microsoft documents /remove:g as removing all occurrences of granted rights for the SID, so cleanup should remove only the ACE Studio added or restore a safely recorded ACL delta. Microsoft icacls documentation
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Needs another tool to add its own ALL APPLICATION PACKAGES entry on Studio's private runtime folder after Studio granted it. Nothing ships that does, and entries present before Studio's grant are already left alone.
… launch (unslothai#12121) * Studio: grant MXC Tier 3 read access to runtime folders once, not per launch * Studio: harden the persistent MXC read grant Scan the whole tree for credential files and links before granting, never take over an existing entry for the group, lock the record across processes, keep the retry when a rollback fails, check folder identity before revoking, and revoke from the capability check when the DACL tier is turned off. * Studio: settle MXC read grants that are in an unknown state Refuse a launch while another process may be mid-grant or an unfinished grant cannot be checked, keep records whose folder identity cannot be read, never adopt or roll back a folder that replaced the granted one, and keep cleanup from blocking a launch when only the record write fails. * Studio: keep MXC unit tests off real ACLs The Windows unit suites run with the DACL opt-in set; stub the persistent read grant there so they neither run icacls on the host Python nor trip the host-launch assertions. The native suite keeps the real grant. * Studio: allow links that stay inside a runtime folder in the MXC read grant actions/setup-python ships python3.exe as a symlink to python.exe in the same folder, so the whole interpreter was refused and kept the per-launch walk. A symlink or junction whose final target resolves inside the granted tree exposes nothing new; links that leave it and other reparse tags still refuse the grant. * Studio: name the icacls output encoding * Studio: use a non-executable name in the read grant link test * Studio: rescan a runtime folder replaced at an already scanned path * Studio: check credential names before accepting an internal link in the read grant scan
On Windows builds that only have MXC's AppContainer + DACL tier (Windows 11 24H2 and 25H2 today, opted into with
UNSLOTH_MXC_ALLOW_DACL_FALLBACK=1), every sandboxed tool call spends 10 to 15 seconds rewriting file permissions before the command even starts. This PR makes that a one-time cost.Why each call is slow
For every
readonlyPathsentry, wxc-exec adds an inheritable ACE for the container withSetNamedSecurityInfoW, so Windows rewrites the security descriptor of every file under it, then reverts all of it on exit (mxc/src/core/wxc_common/src/filesystem_dacl.rs). Studio grants its whole Python environment on every launch, which is tens of thousands of files. Upstream tracks the same cost in microsoft/mxc#572 (about 35 s per run for a Python install there).wxc-exec already skips a path whose DACL grants the needed access to ALL APPLICATION PACKAGES (
filter_paths_needing_grantindispatcher.rs). That is whyC:\Windowscosts nothing: Windows ships it, like Program Files, readable by AppContainers.What changes
New
studio/backend/core/inference/mxc_read_grants.py, called frommxc_policy.build_launch_request(so probes and launches both benefit):S-1-15-2-1) an inheritable read and execute entry once on its runtime read roots (the Python prefix and base prefix, site-packages,sandbox_site, the shell folder). Every later launch skips the walk.pip.ini,pip.conf,uv.toml,.pypirc,.netrc,.env) or a reparse point anywhere below it. A symlink or junction whose final target stays inside the same folder is fine (actions/setup-pythonshipspython3.exeas a link topython.exe). The deep scan runs once per Studio process; every launch rechecks the top level, and a granted folder that gains one is revoked.mxc-runtime/persistent-read-grants.json(locked across Studio processes) tracks each grant as pending or complete, with the folder's volume and file id. An interrupted grant is redone; a failed grant is rolled back; a revoke only happens when the folder is still the one Studio granted.UNSLOTH_MXC_PERSISTENT_READ_GRANTS=0. Opting out, or turning the DACL tier off, revokes every recorded grant, also from the capability check so hosts that never build a launch are cleaned up.sandbox_windows_mxc.pyadds themxc_tier3_persistent_runtime_read_grantslimitation and states the behaviour and the opt-out in the remediation text.No UAC prompt: Studio's venv lives under the user's own profile, and the owner can always change its DACL. MXC's per-launch grant needs the same right on the same folders.
Results
GitHub
windows-latestrunner (Windows Server 2025, 24H2, build 26100.33438), pinned MXC v0.8.0,--prepare-host, DACL opt-in, sandboxedpython -c "import json, ssl"throughbuild_launch_requestandmxc_adapter.spawn. Same workflow and runner image for both arms;mainat a9982dc vs this branch.UNSLOTH_MXC_PERSISTENT_READ_GRANTS=0), medianAfter the first launch the Python prefix carries the inheritable ALL APPLICATION PACKAGES entry and wxc-exec skips it; after opting out the entry is gone again.
Isolation controls, both arms: reading a file outside the workdir is denied, writing outside is denied, writing into the Python environment is denied.
MXC test suites on the same runners (non-native and
native_mxc):mainhas 5 failures, this PR 3, all of them also failing onmain:test_mxc_windows_backend.py::test_selected_python_spelling_is_preserved_in_trusted_policytest_mxc_windows_backend.py::test_terminal_policy_preserves_constructed_shell_argvtest_mxc_native_windows.py::test_native_mxc_powershell_variants_pass_live_terminal_controls[powershell.exe]The two native timeout tests (
test_native_mxc_timeout_reclaims_child_and_grandchild_tree,test_native_cmd_timeout_reclaims_terminal_child_and_grandchild) fail onmainand pass here, since the launch no longer spends most of the timeout rewriting ACLs.Linux: 1697 passed, 17 skipped across
tests/test_mxc_*.py,tests/test_sandbox*.pyandtests/test_tool_sandbox_wiring.py, including 39 new tests intests/test_mxc_read_grants.py.Not covered