Repository navigation
Feat: support local provider for code exec component & remove some outdated models - #14637
Conversation
📝 WalkthroughWalkthroughThis PR introduces ChangesLocalProvider Sandbox with Configuration & Integration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (2)
agent/tools/code_exec.py (1)
380-382: ⚡ Quick winAdd a log on explicit provider-config failures
Line 380–382 returns immediately with
_ERRORbut does not log server-side context, which makes provider misconfiguration incidents harder to diagnose.As per coding guidelines `**/*.py`: Add logging for new flows.Proposed patch
except SandboxProviderConfigError as provider_error: + logging.warning(f"[CodeExec]: Provider configuration error: {provider_error}") self.set_output("_ERROR", str(provider_error)) return self.output()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@agent/tools/code_exec.py` around lines 380 - 382, The except block catching SandboxProviderConfigError currently sets self.set_output("_ERROR", str(provider_error)) and returns self.output() without server-side logging; update the handler in the method containing this except to also log the failure (e.g., use logger.error or self.logger.error) including the exception and any relevant context (provider name/config vars) before returning, while preserving the existing set_output("_ERROR", ...) and return self.output() behavior so diagnostics are recorded server-side for SandboxProviderConfigError.test/unit_test/agent/sandbox/test_local_provider.py (1)
23-23: ⚡ Quick winFail fast in test helper when provider initialization fails
Line 23 ignores the boolean return from
initialize, which can make downstream test failures less precise.Proposed patch
- provider.initialize(config) + assert provider.initialize(config), "LocalProvider failed to initialize in test setup"🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit_test/agent/sandbox/test_local_provider.py` at line 23, The test helper currently calls provider.initialize(config) and ignores its boolean result; update the helper to fail fast by checking the return value of provider.initialize and raising or asserting when it returns False (e.g., assert provider.initialize(config), "provider.initialize failed for <provider>") so tests stop immediately with a clear message; locate the call to provider.initialize in test_local_provider.py and replace the ignored call with a return-value check that fails the test on initialization failure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@agent/sandbox/providers/local.py`:
- Around line 69-86: The new Local sandbox provider lacks lifecycle logging: add
structured start/finish/error logs around initialize, execute, and destroy flows
to aid tracing without logging user code/PII. In the initialize method (and
similarly in execute and destroy), before and after key steps (e.g., entering
initialize, after setting python_bin/node_bin/work_dir/limits, after
self._validate_limits(), after work_dir.mkdir(), and when setting
self._initialized) emit structured logs via the module logger (include function
name like initialize/execute/destroy and non-sensitive config keys), and add
exception handling to log errors with context before re-raising; follow existing
logger conventions used elsewhere in the codebase for message format and log
level.
- Line 117: Replace direct dict indexing of self._instances with a guarded
lookup: before assigning instance_dir = self._instances[instance_id], check if
instance_id in self._instances (or use self._instances.get(instance_id)) and if
missing raise the provider's controlled error (e.g., raise ProviderError /
KeyedLookupError with a clear message) instead of allowing a raw KeyError;
update both places that set instance_dir from self._instances (the occurrences
referencing instance_dir and instance_id) to use this guarded pattern so callers
receive a predictable, descriptive error when an unknown/stale instance_id is
provided.
- Line 120: Compute and validate the effective timeout (exec_timeout) so it
cannot be non-positive before calling process.communicate: when calculating
exec_timeout (currently exec_timeout = min(int(timeout or self.timeout),
self.timeout)) clamp it to a positive value (e.g., exec_timeout = max(1, ...))
or explicitly check if exec_timeout <= 0 and raise a clear provider error (use
the provider's existing error type or a ValueError) with a descriptive message;
perform this validation just before the call to
process.communicate(timeout=exec_timeout) to ensure invalid inputs (like -1)
produce a clear, controlled failure.
- Around line 79-80: The assignment to self.max_artifacts uses a truthy fallback
which treats an explicit 0 as falsy and prevents zero from being configured;
update the logic around self.max_artifacts (and similarly
self.max_artifact_bytes if necessary) to check for None explicitly (e.g., use
config.get("max_artifacts") is not None) before falling back to os.environ or
the default so that 0 is preserved, and ensure subsequent lower-bound checks
against self.max_artifacts still behave correctly.
In `@agent/sandbox/result_protocol.py`:
- Around line 69-73: The code currently decodes and parses RESULT_MARKER_PREFIX
payloads into structured_result without guarding against malformed input; update
the block that handles lines starting with RESULT_MARKER_PREFIX to wrap
base64.b64decode(...) and json.loads(...) in a try/except, catch (ValueError,
binascii.Error, json.JSONDecodeError) (or a broad Exception if those types
aren't available), log the error using the module logger (create logger =
logging.getLogger(__name__) if none exists), skip the malformed marker (leave
structured_result unchanged) and continue processing instead of letting the
exception propagate. Reference the RESULT_MARKER_PREFIX check and the assignment
to payload_b64/payload/structured_result when making the change.
In `@agent/tools/base.py`:
- Line 60: Restore safe logging for tool invocation by truncating and sanitizing
inputs/results before logging: in the invoke function (where logging.info uses
name, arguments) call a sanitize helper (e.g., sanitize_arguments(arguments))
that redacts sensitive keys (patterns like *key, *token, *secret, password) and
then truncate the sanitized string to ~200 characters before logging; do the
same for the response (resp) logging path (the other logging.info at the resp
line) using sanitize_response(resp) then truncate. Ensure helpers are reusable
and clearly referenced in the invoke code so both the arguments and resp log
calls use sanitized+truncated values rather than raw payloads.
---
Nitpick comments:
In `@agent/tools/code_exec.py`:
- Around line 380-382: The except block catching SandboxProviderConfigError
currently sets self.set_output("_ERROR", str(provider_error)) and returns
self.output() without server-side logging; update the handler in the method
containing this except to also log the failure (e.g., use logger.error or
self.logger.error) including the exception and any relevant context (provider
name/config vars) before returning, while preserving the existing
set_output("_ERROR", ...) and return self.output() behavior so diagnostics are
recorded server-side for SandboxProviderConfigError.
In `@test/unit_test/agent/sandbox/test_local_provider.py`:
- Line 23: The test helper currently calls provider.initialize(config) and
ignores its boolean result; update the helper to fail fast by checking the
return value of provider.initialize and raising or asserting when it returns
False (e.g., assert provider.initialize(config), "provider.initialize failed for
<provider>") so tests stop immediately with a clear message; locate the call to
provider.initialize in test_local_provider.py and replace the ignored call with
a return-value check that fails the test on initialization failure.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fc13af08-4ecd-4bc4-8517-8540d24f6656
📒 Files selected for processing (11)
agent/sandbox/client.pyagent/sandbox/providers/__init__.pyagent/sandbox/providers/aliyun_codeinterpreter.pyagent/sandbox/providers/base.pyagent/sandbox/providers/local.pyagent/sandbox/result_protocol.pyagent/tools/base.pyagent/tools/code_exec.pyconf/llm_factories.jsondocker/.envtest/unit_test/agent/sandbox/test_local_provider.py
💤 Files with no reviewable changes (1)
- conf/llm_factories.json
| def initialize(self, config: Dict[str, Any]) -> bool: | ||
| if not _env_enabled("SANDBOX_LOCAL_ENABLED"): | ||
| raise SandboxProviderConfigError("Local code execution is disabled. Set SANDBOX_LOCAL_ENABLED=true to enable it.") | ||
|
|
||
| self.python_bin = str(config.get("python_bin") or os.environ.get("SANDBOX_LOCAL_PYTHON_BIN", "python3")) | ||
| self.node_bin = str(config.get("node_bin") or os.environ.get("SANDBOX_LOCAL_NODE_BIN", "node")) | ||
| self.work_dir = Path(config.get("work_dir") or os.environ.get("SANDBOX_LOCAL_WORK_DIR", "/tmp/ragflow-codeexec")).resolve() | ||
| self.timeout = int(config.get("timeout") or os.environ.get("SANDBOX_LOCAL_TIMEOUT", 30)) | ||
| self.max_memory_mb = int(config.get("max_memory_mb") or os.environ.get("SANDBOX_LOCAL_MAX_MEMORY_MB", 512)) | ||
| self.max_output_bytes = int(config.get("max_output_bytes") or os.environ.get("SANDBOX_LOCAL_MAX_OUTPUT_BYTES", 1024 * 1024)) | ||
| self.max_artifacts = int(config.get("max_artifacts") or os.environ.get("SANDBOX_LOCAL_MAX_ARTIFACTS", 20)) | ||
| self.max_artifact_bytes = int(config.get("max_artifact_bytes") or os.environ.get("SANDBOX_LOCAL_MAX_ARTIFACT_BYTES", 10 * 1024 * 1024)) | ||
|
|
||
| self._validate_limits() | ||
| self.work_dir.mkdir(parents=True, exist_ok=True, mode=0o700) | ||
| self._initialized = True | ||
| return True | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add lifecycle/execution logs for the new provider flow
New critical flows (initialize, execute, destroy) currently have no logging, which makes operational debugging and incident tracing difficult. Add structured logs at start/end/error boundaries (without logging user code/PII).
As per coding guidelines, **/*.py: "Add logging for new flows".
Also applies to: 105-167, 168-174
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/sandbox/providers/local.py` around lines 69 - 86, The new Local sandbox
provider lacks lifecycle logging: add structured start/finish/error logs around
initialize, execute, and destroy flows to aid tracing without logging user
code/PII. In the initialize method (and similarly in execute and destroy),
before and after key steps (e.g., entering initialize, after setting
python_bin/node_bin/work_dir/limits, after self._validate_limits(), after
work_dir.mkdir(), and when setting self._initialized) emit structured logs via
the module logger (include function name like initialize/execute/destroy and
non-sensitive config keys), and add exception handling to log errors with
context before re-raising; follow existing logger conventions used elsewhere in
the codebase for message format and log level.
| raise RuntimeError("Provider not initialized. Call initialize() first.") | ||
|
|
||
| normalized_lang = self._normalize_language(language) | ||
| instance_dir = self._instances[instance_id] |
There was a problem hiding this comment.
Guard unknown instance IDs instead of leaking KeyError
Lines 117 and 172 directly index self._instances[...]. If an invalid/stale instance_id is provided, the API raises raw KeyError instead of a controlled provider error, which hurts reliability and error handling.
Suggested fix
- instance_dir = self._instances[instance_id]
+ instance_dir = self._instances.get(instance_id)
+ if instance_dir is None:
+ raise RuntimeError(f"Sandbox instance not found: {instance_id}")
...
- instance_dir = self._instances.pop(instance_id)
+ instance_dir = self._instances.pop(instance_id, None)
+ if instance_dir is None:
+ raise RuntimeError(f"Sandbox instance not found: {instance_id}")Also applies to: 172-172
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/sandbox/providers/local.py` at line 117, Replace direct dict indexing
of self._instances with a guarded lookup: before assigning instance_dir =
self._instances[instance_id], check if instance_id in self._instances (or use
self._instances.get(instance_id)) and if missing raise the provider's controlled
error (e.g., raise ProviderError / KeyedLookupError with a clear message)
instead of allowing a raw KeyError; update both places that set instance_dir
from self._instances (the occurrences referencing instance_dir and instance_id)
to use this guarded pattern so callers receive a predictable, descriptive error
when an unknown/stale instance_id is provided.
| if line.startswith(RESULT_MARKER_PREFIX): | ||
| payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip() | ||
| payload = base64.b64decode(payload_b64, validate=True).decode("utf-8") | ||
| structured_result = json.loads(payload) | ||
| continue |
There was a problem hiding this comment.
Do not hard-fail on malformed result-marker lines
Line 69–73 decodes/parses marker payload without a guard. If user stdout contains an invalid __RAGFLOW_RESULT__: line, execution can fail with an exception instead of returning normal stdout.
Proposed patch
+import logging
import base64
import json
from typing import Any
+logger = logging.getLogger(__name__)
+
@@
for line in str(stdout).splitlines():
if line.startswith(RESULT_MARKER_PREFIX):
payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip()
- payload = base64.b64decode(payload_b64, validate=True).decode("utf-8")
- structured_result = json.loads(payload)
+ try:
+ payload = base64.b64decode(payload_b64, validate=True).decode("utf-8")
+ structured_result = json.loads(payload)
+ except Exception as e:
+ logger.warning(f"Invalid structured result marker payload ignored: {e}")
+ cleaned_lines.append(line)
continue
cleaned_lines.append(line)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if line.startswith(RESULT_MARKER_PREFIX): | |
| payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip() | |
| payload = base64.b64decode(payload_b64, validate=True).decode("utf-8") | |
| structured_result = json.loads(payload) | |
| continue | |
| if line.startswith(RESULT_MARKER_PREFIX): | |
| payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip() | |
| try: | |
| payload = base64.b64decode(payload_b64, validate=True).decode("utf-8") | |
| structured_result = json.loads(payload) | |
| except Exception as e: | |
| logger.warning(f"Invalid structured result marker payload ignored: {e}") | |
| cleaned_lines.append(line) | |
| continue |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/sandbox/result_protocol.py` around lines 69 - 73, The code currently
decodes and parses RESULT_MARKER_PREFIX payloads into structured_result without
guarding against malformed input; update the block that handles lines starting
with RESULT_MARKER_PREFIX to wrap base64.b64decode(...) and json.loads(...) in a
try/except, catch (ValueError, binascii.Error, json.JSONDecodeError) (or a broad
Exception if those types aren't available), log the error using the module
logger (create logger = logging.getLogger(__name__) if none exists), skip the
malformed marker (leave structured_result unchanged) and continue processing
instead of letting the exception propagate. Reference the RESULT_MARKER_PREFIX
check and the assignment to payload_b64/payload/structured_result when making
the change.
| async def tool_call_async(self, name: str, arguments: dict[str, Any]) -> Any: | ||
| assert name in self.tools_map, f"LLM tool {name} does not exist" | ||
| logging.info(f"[ToolCall] invoke name={name} arguments={str(arguments)[:200]}") | ||
| logging.info(f"[ToolCall] invoke name={name} arguments={str(arguments)}") |
There was a problem hiding this comment.
Risk: Unbounded logging may expose sensitive data and cause operational issues.
Removing the 200-character truncation on arguments and resp introduces two concerns:
- Privacy/compliance risk: Tool arguments and results may contain sensitive data (API keys, credentials, PII, user inputs). Logging them in full could violate privacy regulations or leak secrets.
- Operational risk: Large payloads (e.g., file contents, bulk data) can bloat log files, degrade performance, and make logs difficult to analyze.
Consider re-adding truncation and sanitizing sensitive fields before logging.
🔒 Suggested fix with truncation and sanitization placeholder
- logging.info(f"[ToolCall] invoke name={name} arguments={str(arguments)}")
+ # Truncate and sanitize arguments before logging
+ safe_args = str(arguments)[:500] # Adjust limit as needed
+ logging.info(f"[ToolCall] invoke name={name} arguments={safe_args}")- logging.info(f"[ToolCall] done name={name} elapsed={elapsed:.2f}s result={str(resp)}")
+ # Truncate result to prevent log bloat
+ safe_result = str(resp)[:500] # Adjust limit as needed
+ logging.info(f"[ToolCall] done name={name} elapsed={elapsed:.2f}s result={safe_result}")For production use, also implement sanitization to redact sensitive fields (e.g., keys matching patterns like *key, *token, *secret, password).
Also applies to: 84-84
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/tools/base.py` at line 60, Restore safe logging for tool invocation by
truncating and sanitizing inputs/results before logging: in the invoke function
(where logging.info uses name, arguments) call a sanitize helper (e.g.,
sanitize_arguments(arguments)) that redacts sensitive keys (patterns like *key,
*token, *secret, password) and then truncate the sanitized string to ~200
characters before logging; do the same for the response (resp) logging path (the
other logging.info at the resp line) using sanitize_response(resp) then
truncate. Ensure helpers are reusable and clearly referenced in the invoke code
so both the arguments and resp log calls use sanitized+truncated values rather
than raw payloads.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14637 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@agent/sandbox/providers/local.py`:
- Around line 141-147: The except block handling subprocess.TimeoutExpired
currently calls os.killpg(process.pid, signal.SIGKILL) which can raise
ProcessLookupError if the child already exited, preventing process.communicate()
and causing a leaked pipe and wrong exception; update the TimeoutExpired handler
in local.py to wrap the posix os.killpg call in a try/except ProcessLookupError
(ignore or log and continue), ensure process.communicate() is always invoked
(e.g., place it after the kill call or in a finally-like flow inside the except
block), and then raise the intended TimeoutError(f"Execution timed out after
{exec_timeout} seconds"); reference the symbols: process, exec_timeout,
os.killpg, signal.SIGKILL, process.communicate, and TimeoutError.
- Around line 258-287: The symlink check in _collect_artifacts is
TOCTOU-vulnerable; instead of relying on path.is_symlink() +
path.read_bytes()/path.stat(), open the file with O_NOFOLLOW and read via the
resulting fd so the open and read are atomic: use os.open(path, os.O_RDONLY |
os.O_NOFOLLOW), call os.fstat(fd) to get size (and enforce max_artifact_bytes),
read the content from the fd, then close it (handle OSError from os.open and
convert to the same RuntimeError messages used now). You may keep the initial
path.is_symlink() fast-path but make the O_NOFOLLOW open the authoritative
guard; preserve use of path.relative_to(artifacts_dir).as_posix() and
mimetypes.guess_type(path.name) when building the artifact dict.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 682705d0-eeb9-4cbf-bf0b-e08f734f625f
📒 Files selected for processing (2)
agent/sandbox/providers/local.pyagent/sandbox/result_protocol.py
✅ Files skipped from review due to trivial changes (1)
- agent/sandbox/result_protocol.py
| except subprocess.TimeoutExpired: | ||
| if os.name == "posix": | ||
| os.killpg(process.pid, signal.SIGKILL) | ||
| else: | ||
| process.kill() | ||
| process.communicate() | ||
| raise TimeoutError(f"Execution timed out after {exec_timeout} seconds") |
There was a problem hiding this comment.
os.killpg can raise ProcessLookupError, swallowing TimeoutError and leaking the pipe
If the child process exits naturally between TimeoutExpired being raised and os.killpg executing, the process group is already gone and os.killpg raises ProcessLookupError. At that point process.communicate() is never called (pipe stays open → potential zombie), and raise TimeoutError(...) is never reached — the caller receives ProcessLookupError instead.
🐛 Proposed fix
except subprocess.TimeoutExpired:
if os.name == "posix":
- os.killpg(process.pid, signal.SIGKILL)
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass # process group already gone; still need to drain pipes
else:
process.kill()
process.communicate()
raise TimeoutError(f"Execution timed out after {exec_timeout} seconds")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/sandbox/providers/local.py` around lines 141 - 147, The except block
handling subprocess.TimeoutExpired currently calls os.killpg(process.pid,
signal.SIGKILL) which can raise ProcessLookupError if the child already exited,
preventing process.communicate() and causing a leaked pipe and wrong exception;
update the TimeoutExpired handler in local.py to wrap the posix os.killpg call
in a try/except ProcessLookupError (ignore or log and continue), ensure
process.communicate() is always invoked (e.g., place it after the kill call or
in a finally-like flow inside the except block), and then raise the intended
TimeoutError(f"Execution timed out after {exec_timeout} seconds"); reference the
symbols: process, exec_timeout, os.killpg, signal.SIGKILL, process.communicate,
and TimeoutError.
| def _collect_artifacts(self, artifacts_dir: Path) -> list[dict[str, Any]]: | ||
| artifacts: list[dict[str, Any]] = [] | ||
| for path in sorted(artifacts_dir.rglob("*")): | ||
| if path.is_symlink(): | ||
| raise RuntimeError(f"Artifact symlinks are not allowed: {path.name}") | ||
| if path.is_dir(): | ||
| continue | ||
| if not path.is_file(): | ||
| raise RuntimeError(f"Unsupported artifact entry: {path.name}") | ||
|
|
||
| if len(artifacts) >= self.max_artifacts: | ||
| raise RuntimeError(f"Local execution produced more than {self.max_artifacts} artifacts.") | ||
|
|
||
| size = path.stat().st_size | ||
| if size > self.max_artifact_bytes: | ||
| raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {path.name}") | ||
|
|
||
| ext = path.suffix.lower() | ||
| if ext not in ALLOWED_ARTIFACT_EXTENSIONS: | ||
| raise RuntimeError(f"Unsupported artifact type: {path.name}") | ||
|
|
||
| artifacts.append( | ||
| { | ||
| "name": path.relative_to(artifacts_dir).as_posix(), | ||
| "content_b64": base64.b64encode(path.read_bytes()).decode("ascii"), | ||
| "mime_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream", | ||
| "size": size, | ||
| } | ||
| ) | ||
| return artifacts |
There was a problem hiding this comment.
TOCTOU: symlink check in _collect_artifacts can be raced to read arbitrary host files
path.is_symlink() (Line 261) is a stat-then-use pattern. A child process can atomically replace (rename) a regular file with a symlink between is_symlink() returning False and the subsequent path.stat() / path.read_bytes() calls, which both follow symlinks. This bypasses the guard and allows the child to exfiltrate arbitrary host-fs content (e.g., /etc/passwd, private keys) through the artifact channel.
The fix is to open each file with O_NOFOLLOW so the guard and the read are atomic:
🔒 Proposed fix
- size = path.stat().st_size
- if size > self.max_artifact_bytes:
- raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {path.name}")
-
ext = path.suffix.lower()
if ext not in ALLOWED_ARTIFACT_EXTENSIONS:
raise RuntimeError(f"Unsupported artifact type: {path.name}")
+ try:
+ fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW)
+ except OSError:
+ raise RuntimeError(f"Artifact symlinks are not allowed: {path.name}")
+ try:
+ raw = os.read(fd, self.max_artifact_bytes + 1)
+ finally:
+ os.close(fd)
+ size = len(raw)
+ if size > self.max_artifact_bytes:
+ raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {path.name}")
+
artifacts.append(
{
"name": path.relative_to(artifacts_dir).as_posix(),
- "content_b64": base64.b64encode(path.read_bytes()).decode("ascii"),
+ "content_b64": base64.b64encode(raw).decode("ascii"),
"mime_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
"size": size,
}
)The os.O_NOFOLLOW flag causes os.open to fail with OSError if path is a symlink at open time, making the check and the read atomic from the kernel's perspective. The early is_symlink() guard on Line 261 can be retained as a fast-path for clearly named symlinks, but the O_NOFOLLOW open is the authoritative safety net.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@agent/sandbox/providers/local.py` around lines 258 - 287, The symlink check
in _collect_artifacts is TOCTOU-vulnerable; instead of relying on
path.is_symlink() + path.read_bytes()/path.stat(), open the file with O_NOFOLLOW
and read via the resulting fd so the open and read are atomic: use os.open(path,
os.O_RDONLY | os.O_NOFOLLOW), call os.fstat(fd) to get size (and enforce
max_artifact_bytes), read the content from the fd, then close it (handle OSError
from os.open and convert to the same RuntimeError messages used now). You may
keep the initial path.is_symlink() fast-path but make the O_NOFOLLOW open the
authoritative guard; preserve use of path.relative_to(artifacts_dir).as_posix()
and mimetypes.guess_type(path.name) when building the artifact dict.
…tdated models (infiniflow#14637) ### What problem does this PR solve? Feat: support local provider for code exec component & remove some outdated models ### Type of change - [x] New Feature (non-breaking change which adds functionality)
…tdated models (infiniflow#14637) ### What problem does this PR solve? Feat: support local provider for code exec component & remove some outdated models ### Type of change - [x] New Feature (non-breaking change which adds functionality)
What problem does this PR solve?
Feat: support local provider for code exec component & remove some outdated models
Type of change