Repository navigation
studio: tighten sandbox blocklist precision (bash, hf upload, NOFILE) - #5487
Conversation
Three precision fixes in core/inference/tools.py. Same security boundary; fewer false positives that broke legitimate sandbox use. bash blocklist: The per-token loop introduced in #5375 fired on any blocklist word in any token position, so the entirely benign `grep -r curl .`, `echo source the data`, and `ls /usr/bin/curl` were rejected with "blocked command 'curl'". The position-anchored regex already covers real command-position invocations, including `;rm`, `&&wget`, `$(rm)`, `<(rm)`, backticked subshells, and `/usr/bin/sudo`. The token loop is re-scoped: it only fires when the previous shlex token is a shell separator (or at start of line), so split-quoting obfuscations like `r''m -rf /` are still caught (shlex collapses them to a single command-position token) while argument-position blocklist words pass through. Trailing meta-chars glued to a shlex token (`rm;`) are stripped before basename matching. hf upload AST gate: `_method_call_is_hf_upload` previously matched any method named `upload_file` / `upload_folder` / `upload_large_folder` / `create_commit` on any receiver, so paramiko.SFTPClient.upload_file, boto3.create_commit, and similar non-HF SDK methods were rejected. The fallback now requires an `import huggingface_hub` / `import hf_api` / `from huggingface_hub import ...` somewhere in the same module. Fully-qualified huggingface_hub.upload_file(...) calls are unchanged. NOFILE env knob: `RLIMIT_NOFILE = (1024, 1024)` was the only sandbox rlimit without an env override. 1024 is below Linux's typical soft default and below what multi-shard safetensors mmap chains need on Llama-3 70B-class loads. Default is now 16384 with UNSLOTH_STUDIO_SANDBOX_NOFILE, parity with the other rlimits. 15 new bash-blocklist-position tests pin both the false-positive fixes and the still-blocked invariants (semicolon, &&, subshell, backtick, split-quote, /usr/bin/ prefix, nested bash -c). 4 new hf-upload-import-gate tests pin both the false-positive allowances and that HF-imported uses are still blocked. 1 new pin asserts the NOFILE env var is wired.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11f0ac5179
ℹ️ 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".
| base = _token_basename(token) | ||
| if base in _BLOCKED_COMMANDS: | ||
| blocked.add(base) | ||
| prev_is_separator = token in _SHELL_SEPARATORS |
There was a problem hiding this comment.
Treat env assignments as command-prefix tokens
When a bash command starts with a POSIX environment assignment, e.g. X=1 rm -rf /tmp/x or HTTPS_PROXY=... curl https://..., bash executes the word after the assignment as the command, but this loop marks the assignment token as consuming command position and then skips the following blocked command; the regex also misses it because the blocked word is not at start or after a separator. This creates a direct bypass of the sandbox blocklist for every blocked command that can be prefixed with VAR=value.
Useful? React with 👍 / 👎.
| """True for HfApi upload method names when huggingface_hub is imported.""" | ||
| return ( | ||
| isinstance(node.func, ast.Attribute) | ||
| _hf_in_scope |
There was a problem hiding this comment.
Preserve HF upload blocking for dynamic imports
For code that dynamically imports Hugging Face, such as __import__('huggingface_hub').HfApi().upload_file(...) or __import__('huggingface_hub').upload_file(...), _hf_in_scope remains false because there is no Import/ImportFrom node, so this new gate suppresses the upload-method fallback. Since Hugging Face hosts are allowlisted elsewhere, these calls can perform the uploads this check is intended to block.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request refines the command blocklist logic to only target tokens in the command position, preventing false positives for arguments. It also makes the sandbox file limit (RLIMIT_NOFILE) tunable via an environment variable and restricts Hugging Face upload detection to cases where the library is explicitly imported. A review comment pointed out a tautological assertion in the test suite that needs to be corrected to ensure the code is properly validated.
| def test_echo_source_allowed(self): | ||
| assert self._find()("echo source the data") == set() | ||
|
|
||
| def test_cat_with_word_source_allowed(self): |
There was a problem hiding this comment.
This assertion is a tautology (... == set() or True) and will always pass regardless of the actual output of _find(). It should be corrected to properly validate that no blocked commands are found in this scenario.
| def test_cat_with_word_source_allowed(self): | |
| assert self._find()("cat README.md && echo source") == set() |
870d8b4 to
dfa1e26
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dfa1e2612f
ℹ️ 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 prev_is_separator and not token.startswith("-"): | ||
| base = _token_basename(token) | ||
| if base in _BLOCKED_COMMANDS: | ||
| blocked.add(base) | ||
| prev_is_separator = token in _SHELL_SEPARATORS |
There was a problem hiding this comment.
Treat shell command wrappers as command position
When a blocked command is preceded by a shell command wrapper such as command, exec, time, env, or nohup, bash still executes the following word as the command, but this loop consumes the wrapper as the only command-position token and then treats rm/curl as an argument. For example, _bash_exec("command rm -rf /tmp/x") or env curl https://... reaches bash -c with an empty blocked set, so the new argument-position filtering creates a direct bypass for commands that were previously caught by scanning every token.
Useful? React with 👍 / 👎.
…E clamp
Reviewer follow-ups to the sandbox blocklist precision change.
Command-position scanner missed Bash command-prefix wrappers and inline
shell assignments. shlex tokenised `env curl`, `time curl`, `nohup rm`,
`FOO=bar curl`, `sudo rm`, etc. with the prefix at command position and
the real command at argument position, so the position-anchored check
returned set() while pre-PR's per-token scan caught them. Likewise the
position-anchored regex requires `^` or a shell separator before the
command, so `env curl` slipped through.
Reworked the scanner to track an expect_command flag plus a
prefix_pending flag:
- assignments (FOO=bar) keep expect_command=True for the next token,
- flags ('-oL', '--') keep it intact while prefix_pending is set,
- numeric duration args ('timeout 1 cmd') skip without breaking
expect_command,
- known wrappers (env, command, builtin, exec, time, nohup, nice,
setsid, stdbuf, timeout, ionice, chroot, sudo, doas, su, xargs)
set prefix_pending so the wrapper's command is still checked,
- shell separators now include `{`, `}`, `)`, `then`, `do`,
`else`, `elif` so brace groups and if/then/while/do bodies are
recognised as command positions.
Also lex with `shlex.shlex(punctuation_chars=";&|()`")` so split-quote
forms like `echo done; r''m -rf /tmp/x` and `echo done;r''m` tokenise
as `[..., ';', 'rm', ...]` and the command position check fires.
Added a small `find -exec CMD ... ;` / `-execdir CMD ... ;` pass so
`find . -exec rm -f {} +` and friends are caught even though the
direct token is at argument position to `find`.
Dynamic Hugging Face imports were treated as no-HF-in-scope. The
upload-method gate now also resolves `__import__('huggingface_hub')`,
`importlib.import_module('huggingface_hub')`, and bare
`import_module('huggingface_hub')` (via `from importlib import
import_module`) as HF imports, so HfApi().upload_file via dynamic
import is still blocked.
RLIMIT_NOFILE: setrlimit(NOFILE, (16384, 16384)) silently failed if
the parent's hard cap is below the requested value; the broad
except swallowed the OSError and left the sandbox at the parent's
default. Clamp the requested value to the inherited hard limit
before calling setrlimit.
Test cleanup: the existing test_cat_with_word_source_allowed had
`assert ... or True` so it could not fail; rewrote it to assert the
actual return value plus the two membership checks. Added
parametrised coverage for shell prefix wrappers, find -exec / xargs,
brace groups, if/then, while/do, split-quote command-name forms, and
dynamic HF import upload patterns.
Test:
- python -m pytest studio/backend/tests/test_sandbox_tools.py -q
-> 90 passed (was 67 before this commit)
- full studio/backend/tests/ minus llama_cpp_load_progress_live and
GPU CUDA_VISIBLE_DEVICES tests (pre-existing isolation flake)
-> 1063 passed
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa0d03fb58
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if token.startswith("-"): | ||
| # Flags belong to the active command. While a wrapper prefix is | ||
| # waiting for its command (`stdbuf -oL cmd`, `xargs -- cmd`), | ||
| # keep expect_command intact. | ||
| if not prefix_pending: |
There was a problem hiding this comment.
Consume wrapper option args before command-position matching
The wrapper-state logic keeps expect_command open for flags but does not account for flags that require a following argument, so that argument is misclassified as the wrapped command. I checked local CLI semantics: env --help shows -u NAME / -C DIR, and xargs --help shows -a FILE; with inputs like env -u PATH rm -rf /tmp/x or xargs -a /tmp/list rm, this loop consumes PATH or /tmp/list as the command and never evaluates rm, and the regex pass cannot recover because rm is now in argument position. That creates a blocked-command bypass introduced by this rewrite.
Useful? React with 👍 / 👎.
| if not (isinstance(arg0, ast.Constant) and isinstance(arg0.value, str)): | ||
| continue | ||
| if arg0.value.split(".", 1)[0] not in _HF_IMPORT_MODULES: | ||
| continue |
There was a problem hiding this comment.
Detect HF imports when module name is indirect
The HF import gate only treats dynamic imports as in-scope when the first argument is a literal string constant, so name='huggingface_hub'; hf=__import__(name); hf.HfApi().upload_file(...) leaves _hf_in_scope false and bypasses _method_call_is_hf_upload. Since this commit changed method-name blocking from unconditional to import-gated, this is a real regression: a trivial variable indirection now avoids the HF upload block.
Useful? React with 👍 / 👎.
`from huggingface_hub import upload_file; upload_file(...)` is a canonical HF call shape that the previous Attribute-only check missed: the bare-name call lands as ast.Name (not ast.Attribute), so the fuzzy gate skipped it. Extend _method_call_is_hf_upload to also match ast.Name when HF is in scope. Same import-gating discipline as the Attribute branch, so paramiko/boto3 and locally-defined `def upload_file(...)` helpers without HF imports still pass. Pins: 4 new TestHfUploadImportGate cases (upload_file/folder/create_commit bare-name imports blocked; local upload_file without HF import allowed).
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9cfe5b8265
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if token.startswith("-"): | ||
| # Flags belong to the active command. While a wrapper prefix is | ||
| # waiting for its command (`stdbuf -oL cmd`, `xargs -- cmd`), | ||
| # keep expect_command intact. | ||
| if not prefix_pending: | ||
| expect_command = False | ||
| continue |
There was a problem hiding this comment.
Skip wrapper option args before matching the real command
This parser keeps expect_command open for wrapper prefixes but never consumes option arguments, so values for options like env -u NAME / -C DIR, xargs -a FILE, and timeout -s SIGNAL are misclassified as the wrapped command and the actual command token is never checked. I verified the CLI semantics from local --help output and reproduced the bypass against this implementation (env -u PATH rm -rf /tmp/x, xargs -a /tmp/list rm, timeout -s TERM rm -rf /tmp/x all fail to report rm), which means blocked commands can pass through when preceded by these wrapper forms.
Useful? React with 👍 / 👎.
| if not (isinstance(arg0, ast.Constant) and isinstance(arg0.value, str)): | ||
| continue | ||
| if arg0.value.split(".", 1)[0] not in _HF_IMPORT_MODULES: |
There was a problem hiding this comment.
Recognize indirect HF module names in dynamic imports
The HF-import gate only accepts dynamic imports when the first argument is a literal string, so __import__(name) / import_module(name) with name = 'huggingface_hub' leaves _hf_in_scope false and disables _method_call_is_hf_upload. Since this commit moved upload-method blocking behind that gate, this is a real bypass for HF uploads with simple variable indirection. Fresh evidence from the current logic: name='huggingface_hub'; hf=__import__(name); hf.HfApi().upload_file(...) does not trigger the upload block.
Useful? React with 👍 / 👎.
… leaks The previous gate dropped every HF upload call. Two refinements make it precise enough to allow legitimate sandbox->HF uploads while still catching credential / file exfil: - path_or_fileobj / folder_path / create_commit operation paths must be sandbox-local relative-path literals (no '/', '~', drive letter, or '..' segments). Variable / dynamic paths are rejected. - Any positional or keyword argument that statically resolves to os.environ / os.environ.get / os.getenv / bare getenv / subprocess shape readers is rejected (env-var exfil). - token / hf_token / api_token / api_key / auth_token / access_token / password / secret kwargs are always rejected; sandbox env strips all parent credentials by construction, so any value here is hard-coded or lifted. Recursive subtree walk in _reads_env_or_secret catches wrapper shapes (str(os.environ), json.dumps(os.environ.items()), etc.). Add TestSandboxEnvIsolation: pin that _build_safe_env builds the env from a whitelist, not by stripping. Cover Linux/macOS/WSL/Windows secret shapes. The whitelist is PATH / HOME / TMPDIR / LANG / TERM / PYTHONIOENCODING (+ VIRTUAL_ENV / SystemRoot when applicable); HOME points at the sandbox workdir, so HF / wandb / aws SDKs cannot reach the operator's ~/.cache credentials. Test classes added: - TestHfUploadSandboxLocalPaths (relative literals allowed; absolute, drive-letter, '~', '..', mid-path traversal, dynamic vars, and open() of unsafe paths blocked, including create_commit recursion). - TestHfUploadEnvAndSecretLeakBlock (os.environ subscript/get/getenv, bare getenv, subprocess.check_output, str(os.environ), token=, hf_token=, api_key=, and create_commit operations referencing env). - TestSandboxEnvIsolation (no parent secret leaks into sandbox env). 131 tests in test_sandbox_tools.py pass.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 85bca3afae
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| "xargs", | ||
| } | ||
| ) | ||
| _ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=") |
There was a problem hiding this comment.
Expand assignment-prefix detection beyond NAME= syntax
The command-position parser only treats tokens matching ^[A-Za-z_][A-Za-z0-9_]*= as environment assignments, so valid Bash assignment prefixes like X+=1 rm -rf /tmp/x (and array-form assignments such as A[0]=1 rm ...) are misclassified as the command token and cause the real command to be skipped. Because the regex fallback only matches command words at explicit separators, rm/curl in these forms are never detected, creating a direct blocklist bypass for shell-exec paths introduced by this rewrite.
Useful? React with 👍 / 👎.
| if kw.arg == "operations" and isinstance(kw.value, ast.List): | ||
| for elt in kw.value.elts: |
There was a problem hiding this comment.
Validate non-literal create_commit operations payloads
The create_commit branch validates upload paths only when operations is an inline ast.List; if operations is passed via a variable or other expression (for example ops=[CommitOperationAdd(path_or_fileobj='/etc/passwd', ...)] then create_commit(..., operations=ops)), this branch does no path checks and returns allow. Since this commit changed HF upload handling from unconditional block to conditional allow, that creates a new exfiltration bypass for absolute/host paths hidden behind non-literal operations values.
Useful? React with 👍 / 👎.
Summary
Three precision fixes on top of #5375's sandbox hardening. Same security boundary, fewer false positives that broke legitimate sandbox use.
Bash blocklist (per-token loop scoped to command position)
The per-token loop in
_find_blocked_commandsfired on any blocklist word in any token position. That rejected:grep -r curl .-> blocked as'curl'echo source the data-> blocked as'source'ls /usr/bin/curl-> blocked as'curl'cat README.md && echo source-> blocked as'source'The position-anchored regex below it already covers real command-position invocations (start of string,
;,|,&&,||, backticks,$(),<(), newlines, with optional/usr/bin/orC:\Windows\...prefix). The token loop is rescoped: it only fires when the previous shlex token is a shell separator (or at start of line), so split-quoting obfuscations liker''m -rf /are still caught (shlex collapses them to one command-position token) while argument-position blocklist words pass through. Trailing meta-chars on a shlex token (rm;) are stripped before basename matching.HF upload AST gate (require huggingface_hub import in scope)
_method_call_is_hf_uploadpreviously matched any method namedupload_file/upload_folder/upload_large_folder/create_commiton any receiver. That rejected unrelated SDK methods (paramiko SFTP, boto3, internal libraries). The fallback now requires animport huggingface_hub/from huggingface_hub import .../import hf_apisomewhere in the snippet. Fully-qualifiedhuggingface_hub.upload_file(...)is unchanged.NOFILE env knob
RLIMIT_NOFILE = (1024, 1024)was the only sandbox rlimit without an env override. 1024 is below Linux's typical soft default and well below what multi-shardsafetensorsmmap chains need on 70B-class loads. Default is now 16384, env-tunable viaUNSLOTH_STUDIO_SANDBOX_NOFILE, matching the other rlimits.Test plan
studio/backend/tests/test_sandbox_tools.py-- 67 tests pass, including all 38 pre-existing security testsTestBashBlocklistPositiontests pin both the false-positive fixes (6) and the still-blocked invariants (9): semicolon,&&, subshell$(), backtick, split-quote,/usr/bin/prefix, nestedbash -cTestHfUploadImportGatetests pin the import-gate behaviour:paramiko.upload_fileand bareclient.create_commitpass without HF imports;huggingface_hub.upload_fileandHfApi().upload_fileare still rejectedTestSandboxCpuRlimitDefault::test_nofile_env_tunableasserts the env var is wired