Repository navigation
Studio: approved host calls keep chat-installed packages, helper modules and CLIs - #14543
Conversation
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. |
|
The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins. |
… again (#14544) `pre-commit.ci` is red on every PR opened or pushed since #14490 merged (#14510, #14515, #14543 so far), and it cannot push its autofix ("a conflict occurred when applying fixes to the pr"). #14490 landed `_run_single_flight(*args, _run = run, _lock = lock, **kwargs)` in `unsloth/kernels/moe/grouped_gemm/interface.py` on one line, which is not what `ruff-format-with-kwargs` produces, and pre-commit.ci runs the hook over all files. Running the hook over all 4525 tracked Python files on main changes only this one signature. This PR is that formatter output and nothing else. It is a fixed point: running the hook again leaves it unchanged. ## Testing - `tests/test_formatter_fixed_point.py` on main: fails, naming `unsloth/kernels/moe/grouped_gemm/interface.py`. - Same test on this branch: 16 passed.
…ed CLIs, appended last [skip ci]
|
@codex review |
|
@codex security review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7efdd5514e
ℹ️ 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".
| scripts = os.path.join(packages, "Scripts" if os.name == "nt" else "bin") | ||
| env["PATH"] = os.pathsep.join(part for part in (env.get("PATH", ""), scripts) if part) | ||
| # Helper modules written into the chat folder stay importable, appended after the session packages. | ||
| env["_UNSLOTH_HOST_WORKDIR"] = plan.workdir |
There was a problem hiding this comment.
Disable user customization before appending the workdir
When a chat has no .unsloth-packages directory, PYTHONNOUSERSITE is not set, but this variable still causes sitecustomize to append the sandbox-writable workdir during interpreter startup. Python subsequently imports usercustomize, so a usercustomize.py planted by an earlier sandboxed call executes implicitly in an approved Python host-access call before the approved script, with access to host paths. Set PYTHONNOUSERSITE unconditionally whenever _UNSLOTH_HOST_WORKDIR is exposed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 868a2da. The chat folder is no longer put on sys.path. A finder appended at the end of sys.meta_path serves top-level helper modules from it and never resolves sitecustomize or usercustomize, so a planted usercustomize.py cannot run even with the user site enabled. PYTHONNOUSERSITE stays as it was, so ~/.local packages keep working for Terminal Python. Covered by test_chat_folder_never_supplies_startup_hooks, which fails on the previous commit.
There was a problem hiding this comment.
🛡️ Codex Security Review
Here are some automated security review suggestions for this pull request.
Reviewed commit: 7efdd5514e
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
| os.environ.get("_UNSLOTH_HOST_SESSION_PACKAGES"), | ||
| os.environ.get("_UNSLOTH_HOST_WORKDIR"), | ||
| ): | ||
| if _host_path and _host_path not in sys.path: | ||
| sys.path.append(_host_path) |
There was a problem hiding this comment.
🛡️ Codex Security Review
Security: Keep chat paths out of approved host Python
Condition: in an owner chat, after the user approves a host-reaching Terminal call that launches a Python CLI. These lines append model-writable .unsloth-packages and the chat directory to every descendant interpreter. Appending last prevents simple shadowing, but not plugin enumeration or imports of missing names: a planted pytest11 entry point was auto-loaded by the trusted system pytest binary and read an unrelated host file, while the parent-equivalent environment did not. Because this approved path has no OS isolation, implicit code gets broader host access than the command the user reviewed. Keep writable paths out of host launches; instead, confine the process to only approved host resources.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one as is. After the later commits the chat folder only supplies helper modules the approved script imports by name, and chat CLIs only resolve when the call names them. What remains is the packages folder for Python an approved call starts, appended after everything else, with no .pth processing. That folder is what the user installed in the chat for exactly these calls (for example an approved python analyze.py ~/data.xlsx whose script imports a chat-installed openpyxl), so scoping it to names in the command text would break that flow again. The remaining case needs a host tool that scans for plugins plus a planted entry point in an approved owner call.
…ever supplies startup hooks [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 868a2dade4
ℹ️ 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 path is not None or name in self._skip: | ||
| return None | ||
| import importlib.machinery | ||
| return importlib.machinery.PathFinder.find_spec(name, [self._workdir]) |
There was a problem hiding this comment.
Restrict the finder to explicitly requested helpers
When an approved script imports a trusted library that probes an absent optional top-level dependency, this process-wide fallback supplies a same-named module planted in the chat directory by an earlier sandboxed call. The planted module then executes with the approved process's host access even though the approved script never imported that helper directly; placing the finder last only prevents shadowing dependencies that already exist. Limit this fallback to helper names explicitly imported by the approved script, rather than resolving every otherwise-missing top-level import.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 32a220f. The approved Python tool call now passes only the top-level module names its script imports (parsed with ast), and the finder resolves only those names from the chat folder. A library probing an optional import never reaches the folder. Checked by hand: a planted optional_dep.py loaded before this change and does not now, while an imported helper still loads. Terminal calls no longer get the finder at all; their python -c already has the chat folder as cwd, as before.
…imports [skip ci]
|
@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: 32a220f2b8
ℹ️ 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".
| except (SyntaxError, ValueError): | ||
| return [] | ||
| names = set() | ||
| for node in ast.walk(tree): |
There was a problem hiding this comment.
Scope helper authorization to imports executed by the script
The new ast.walk allowlist is fresh evidence that optional-import injection remains possible: when an approved script merely mentions import optional_dep inside an uncalled function or a false platform/TYPE_CHECKING branch, the name is still enabled process-wide. If a trusted library later probes that absent dependency, the finder executes a planted optional_dep.py from the chat workdir with the approved process's host access even though the script never executed that import. Scope workdir resolution to import requests actually initiated by the approved script rather than every syntactically mentioned name.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this as is. It needs the approved script to name the module itself, in a branch that never runs, and a library to then probe for that same missing name. The user reviewed a script that names the module, and a library probing for an unnamed module is already blocked by the allowlist.
| env["PYTHONNOUSERSITE"] = "1" | ||
| # Chat-installed CLIs resolve too, but only after every system executable. | ||
| scripts = os.path.join(packages, "Scripts" if os.name == "nt" else "bin") | ||
| env["PATH"] = os.pathsep.join(part for part in (env.get("PATH", ""), scripts) if part) |
There was a problem hiding this comment.
Restrict chat CLI lookup to commands the approved call requests
In both approved Python and Terminal launches, appending the sandbox-writable scripts directory to PATH also exposes it to every trusted descendant process. If a trusted library or system executable probes an optional command that is absent from the system path—for example, a conversion library spawning ffmpeg—a binary planted earlier in .unsloth-packages/bin is selected and runs with host access even though the approved script or shell command never requested that chat CLI; placing the directory last prevents shadowing but not this missing-command injection. Limit this fallback to CLI names explicitly requested by the approved call rather than adding the whole directory process-wide.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 16de984. The chat bin folder is no longer added to PATH. Only the chat-installed CLIs whose names appear as words in the approved command or script are copied into the call's private directory, and that directory goes last on PATH. A tool probing for a command the call never names (the test builds the name at run time and uses command -v) misses the chat folder. The CLI the user ran still works.
|
@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: 16de984971
ℹ️ 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".
| _host_packages = os.environ.get("_UNSLOTH_HOST_SESSION_PACKAGES") | ||
| if _host_packages and _host_packages not in sys.path: | ||
| sys.path.append(_host_packages) |
There was a problem hiding this comment.
Restrict approved imports from the session package directory
Appending the entire sandbox-writable .unsloth-packages directory makes every otherwise-missing module importable during an approved host call. If a trusted dependency probes an absent optional module, an earlier sandboxed call can plant that module in this directory and have it execute with host access even though the approved script never named it; placing the directory last prevents shadowing existing modules but not missing-module injection. Restrict session-package resolution to packages actually authorized by the approved script.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this as is: .unsloth-packages holds what pip installed in the chat for exactly these approved calls, and a module there cannot be told apart from a package the user installed; the Python tool already appended this folder on the merge base. Restricting it to names in the script would break scripts whose installed packages import their own dependencies.
| words = set(re.findall(r"[\w.+-]+", text)) | ||
| copied = False | ||
| for entry in entries: | ||
| stem = os.path.splitext(entry)[0] if os.name == "nt" else entry | ||
| source = os.path.join(scripts, entry) | ||
| if (entry in words or stem in words) and os.path.isfile(source): |
There was a problem hiding this comment.
Parse executable positions before authorizing chat CLIs
Fresh evidence in this revision is that CLI authorization is derived from every word in the complete command or Python source, including comments, string literals, option values, and file names. If an approved script merely mentions ffmpeg in a comment or data value and a trusted dependency subsequently probes for ffmpeg, a planted chat executable is copied into the private PATH and runs with host access despite never being requested as a command. Identify actual executable invocations rather than treating arbitrary words as authorization.
Useful? React with 👍 / 👎.
| if path is not None or name not in self._names: | ||
| return None |
There was a problem hiding this comment.
Support sibling imports from approved chat helpers
When an approved script imports a chat-local helper.py that in turn uses an absolute import of another chat-local module such as import constants, the dependency is absent from the main script's allowlist, so this finder rejects it and the helper fails with ModuleNotFoundError. This breaks common multi-file helpers that worked when the chat directory was on sys.path; resolve or recursively authorize local dependencies reached while loading an explicitly approved helper.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 901db10: when the finder serves a requested chat helper, that helper's own absolute imports are allowed too, so helper.py importing config.py works (test covers it).
…hat folder [skip ci]
|
@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: 901db10889
ℹ️ 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".
| # Copies of just those: a tool probing for a command it lacks never reaches the rest of the folder. | ||
| requested = _requested_chat_clis( | ||
| os.path.join(packages, "Scripts" if os.name == "nt" else "bin"), | ||
| script if script is not None else " ".join(map(str, argv)), |
There was a problem hiding this comment.
Pass the original terminal command to CLI selection
For a non-owner account using UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS on a host without account confinement, _shell_argv stores the command in .studio_cmd_*.sh, leaving plan.argv with only the shell and generated filename. Scanning the joined argv here therefore never sees a chat CLI named by the approved command, so that CLI is not copied into the private PATH and the call fails with command-not-found. Pass the original terminal command to the selector instead.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this as is: it needs a non-owner account on a host without account confinement plus the UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS opt-in. Owners and confined accounts keep the command in argv, so named chat CLIs resolve there.
| for entry in entries: | ||
| stem = os.path.splitext(entry)[0] if os.name == "nt" else entry | ||
| source = os.path.join(scripts, entry) | ||
| if (entry in words or stem in words) and os.path.isfile(source): |
There was a problem hiding this comment.
Match chat CLI names case-insensitively on Windows
On Windows, executable lookup is case-insensitive, but this membership check compares the command words and directory entries case-sensitively. If the chat package contains ruff.exe and the approved command invokes RUFF (or otherwise varies casing), the executable is not copied, while the original Scripts directory is intentionally absent from PATH, so the approved call fails with command-not-found. Normalize both the candidate names and command words for Windows before comparing them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 402f3d0: on Windows the command words and the Scripts entries are compared case-folded, with a test.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
|
pre-commit.ci run |
…ved host calls (unslothai#14948) Follows up unslothai#14543. ### What was wrong Approved host launches (the Python tool and Terminal) set `_UNSLOTH_HOST_SESSION_PACKAGES`, and the sandbox `sitecustomize.py` appended the whole chat `.unsloth-packages` folder to `sys.path`. Appending it last stopped it from overriding the standard library or installed packages, but its `*.dist-info` became visible to `importlib.metadata`. Tools that load plugins from entry points then imported code from that folder that the approved command never asked for: an approved `python -m pytest -q test_ok.py` loaded a `pytest11` plugin the chat had installed, and in the repro that plugin read a file outside the chat folder. ### Fix The folder is no longer put on `sys.path`. `sitecustomize.py` appends a last-resort meta path finder, `_HostPackagesFinder`, that: - serves top-level modules from the folder only after every other finder has missed, so it never overrides anything the host has, and skips `sitecustomize` / `usercustomize`; - leaves submodules to the package's own `__path__`; - answers `importlib.metadata` only for an exact distribution name with no explicit `path` (so `version("pkg")` still works; a lookup scoped to explicit paths is left to the stock path finder) and returns nothing for name-less scans such as `distributions()` and `entry_points()`, which plugin discovery relies on. Explicit imports of chat-installed packages from an approved script or from Terminal-started Python keep working as they did after unslothai#14543. Visible change: tools that list installed packages by scanning (`pip list` style, `pkgutil.iter_modules`) no longer see chat-installed packages during an approved call, and `pkg_resources.get_distribution()` no longer finds them (pkg_resources reads only `sys.path`; `importlib.metadata.version()` still works). A Python started with `-S` skips `sitecustomize` and could not import chat-installed packages before this change either; that is unchanged. Submodules a chat installs into a namespace package the host already provides resolve from the chat's portion after the host's. Once one is served, that portion directory is appended to the namespace's `__path__` (PEP 420, and pkgutil-style or pkg_resources-style packages whose `__init__.py` declares `__path__ = extend_path(__path__, __name__)` or `declare_namespace(__name__)` at module level), so `importlib.resources` and `pkgutil.iter_modules` on the namespace see it. Limit: a PEP 420 `__path__` is recomputed from `sys.path` whenever `sys.path` changes, which drops the appended portion until the next submodule is served from it. ### Tests - New `test_an_approved_pytest_call_does_not_autoload_chat_installed_plugins` plants a `pytest11` entry point in the session package folder and runs an approved Terminal pytest; it fails on main and passes here. - New `test_an_approved_script_still_imports_chat_installed_packages` checks that a package, its submodule and `importlib.metadata.version` still resolve in an approved script, and that the entry point scan stays empty. - `test_tool_sandbox_hardening.py`, `test_tool_sandbox_wiring.py`, `test_sandbox_sitecustomize.py`, `test_sandbox_tools.py`, `test_sandbox_files_and_storage_roots.py`, `test_full_access_tool_prompt.py`: 1478 passed, 2 skipped (and 1130 passed, 2 skipped for the four sandbox files after the namespace and metadata-path fixes). - Checked on Python 3.10, 3.11, 3.12 and 3.13: the folder no longer shows up in `distributions()` or the `pytest11` entry points, and explicit imports still work. Not run: a full Studio approval flow against a live server, the macOS and Windows sandbox wrappers (the new tests are POSIX only and ran on Linux). --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Follow-up to #14429.
Problem. If a call reaches a host path (for example, a command that reads a file in the user's home) and the user approves it, it runs outside the chat sandbox with a private HOME. #14429 also stopped loading anything from the chat folder in these calls, because sandboxed calls can write there. That broke three things that worked before #14429:
.unsloth-packages). In an owner chat, installopenpyxlthrough Terminal, then approvepython -c "import openpyxl ..." ~/sales.xlsx: it failed withModuleNotFoundError. Studio: harden the tool sandbox around host launches, probes and workdir paths #14429 restored these packages for the Python tool through a small launcher, but the launcher only exists when there is a script.import helperfor ahelper.pythat an earlier call wrote into the chat folder. The script now runs from a private dir withPYTHONSAFEPATH=1, so the chat folder is not onsys.path..unsloth-packages/bin(for exampleblack file.py) were no longer found in approved calls (command not found).Change.
_UNSLOTH_HOST_SESSION_PACKAGESand the chat folder in_UNSLOTH_HOST_WORKDIR. The existing sandboxsitecustomize, which is already first on that launch's PYTHONPATH, appends the packages folder to the end ofsys.pathafter normal site setup. The chat folder is not put onsys.path. For an approved Python tool call, the launch passes the top-level module names the script itself imports (parsed withast), and a finder appended at the end ofsys.meta_pathserves only those names from the chat folder, only when nothing else provides them, and neversitecustomizeorusercustomize. A library probing an optional import never reaches the chat folder. The packages folder works for the Python tool and for any Python a Terminal command starts, and it replaces the per-script launcher..unsloth-packages/bin(Scriptson Windows) resolve only when the approved command or script names them: those files are copied into the call's private directory, which goes last on PATH. The chat bin folder itself is never on PATH, so a tool probing for a command it lacks (for exampleffmpeg) never reaches it.json.pyoros.pyin the chat folder, or acatin.unsloth-packages/bin, is never picked up first, and an unnamed CLI there is never picked up at all. The approved script still runs from the private dir withPYTHONSAFEPATH=1. A plantedusercustomize.pynever runs:PYTHONNOUSERSITE=1is set when the packages folder exists, and the chat folder finder skips startup hooks, so~/.localpackages keep working for a system Python. HOME stays private.sitecustomizeskips a path that is already onsys.path, so repeat runs give the same result.Terminal commands still run with the chat folder as cwd. So
python -cin Terminal keeps its usual cwd-first imports, as #14429 left them.Testing.
test_an_approved_terminal_call_reuses_chat_packages_without_shadowing: an approved Terminalpython -cimports a chat-installed package and reads a host file, twice. A plantedusercustomize.pydoes not run. Fails on main, passes here.test_approved_calls_import_chat_helpers_without_shadowing_the_stdlib: an approved Python tool call importshelper.pyfrom the chat folder, twice. Plantedjson.py/os.pyin the chat folder are not loaded, andjsoncomes from the standard library. An approved Terminalpython -calso imports the helper. Fails without this change (ModuleNotFoundError: No module named 'helper'), passes with it.test_an_approved_terminal_call_runs_chat_clis_after_system_ones: an approved Terminal call runs a CLI from.unsloth-packages/bin. A plantedcatthere does not replace the systemcat. Fails without this change (chatcli: command not found), passes with it.test_an_approved_host_launch_env_drops_every_workdir_inputnow checks that the chatbinis only the last PATH entry.test_chat_folder_only_supplies_the_helpers_the_script_imports: checks the import-name parsing, and that with the chat folder exposed forhelper, neitherusercustomizenor an unrequestedoptional_depcan be found whilehelperimports, twice. Checked by hand against the previous finder: a plantedoptional_dep.pyloaded there and does not now.usercustomizecannot be found whilehelperstill imports, and the chat folder is not onsys.path. Fails if the chat folder is appended tosys.pathinstead. Also checked by hand with the system/usr/bin/python3(user site enabled): a plantedusercustomize.pyran before this change and does not now.test_tool_sandbox_hardening.py: 27 passed after the name allowlist. Withtest_managed_tool_confinement_hardening.pyandtest_sandbox_sitecustomize.py: 58 passed, 1 skipped.test_tool*.py,test_sandbox_linux.py,test_sandbox_probe.py,test_sandbox_sitecustomize.py(29 files): 1336 passed, 3 skipped.test_an_approved_terminal_call_runs_chat_clis_after_system_onesnow also checks that acommand -vprobe for a chat CLI the command never names misses the chat folder, andtest_an_approved_host_launch_env_drops_every_workdir_inputthat the chat bin folder is not on PATH. Both fail without the CLI scoping and pass with it;test_tool_sandbox_hardening.py: 27 passed.