Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend): contain exec_file paths within the sandbox base (#14750)

Bently789032fbc89d
diff --git a/autogpt_platform/backend/backend/blocks/slant3d/api_test.py b/autogpt_platform/backend/backend/blocks/slant3d/api_test.py
index 27b67af6fd..9436004521 100644
--- a/autogpt_platform/backend/backend/blocks/slant3d/api_test.py
+++ b/autogpt_platform/backend/backend/blocks/slant3d/api_test.py
@@ -1,3 +1,4 @@
+from pathlib import Path
from unittest.mock import ANY, AsyncMock, Mock, patch
import pytest
@@ -9,6 +10,7 @@ from backend.blocks.slant3d.order import (
Slant3DEstimateOrderBlock,
)
from backend.data.execution import ExecutionContext
+from backend.util import file as file_module
CUSTOMER = {
"name": "John Doe",
@@ -35,6 +37,15 @@ DRAFT = {
TEST_EXECUTION_CONTEXT = ExecutionContext(user_id="user-1", graph_exec_id="run-1")
+def _stage_exec_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Stage model.stl where store_media_file leaves it for this execution."""
+ monkeypatch.setattr(file_module, "TEMP_DIR", tmp_path)
+ source = tmp_path / "exec_file" / "run-1" / "model.stl"
+ source.parent.mkdir(parents=True)
+ source.write_bytes(b"STL bytes")
+ return source
+
+
async def test_v2_auth_and_response_envelope():
block = Slant3DFilamentBlock()
response = Mock(ok=True, status=200)
@@ -179,9 +190,10 @@ async def test_platform_selection_is_unambiguous(platforms, expected):
await block._resolve_platform_id("", "key")
-async def test_upload_confirms_exact_placeholder_without_forwarding_api_key(tmp_path):
- source = tmp_path / "model.stl"
- source.write_bytes(b"STL bytes")
+async def test_upload_confirms_exact_placeholder_without_forwarding_api_key(
+ tmp_path, monkeypatch
+):
+ source = _stage_exec_file(tmp_path, monkeypatch)
uploaded = []
async def put(url, **kwargs):
@@ -240,9 +252,8 @@ async def test_upload_confirms_exact_placeholder_without_forwarding_api_key(tmp_
assert api.await_args_list[1].kwargs["json"]["filePlaceholder"] is placeholder
-async def test_failed_upload_is_not_confirmed(tmp_path):
- source = tmp_path / "model.stl"
- source.write_bytes(b"STL bytes")
+async def test_failed_upload_is_not_confirmed(tmp_path, monkeypatch):
+ source = _stage_exec_file(tmp_path, monkeypatch)
block = Slant3DFilamentBlock()
with patch.object(
block,
diff --git a/autogpt_platform/backend/backend/util/exec_file_path_test.py b/autogpt_platform/backend/backend/util/exec_file_path_test.py
new file mode 100644
index 0000000000..a3dfe7d758
--- /dev/null
+++ b/autogpt_platform/backend/backend/util/exec_file_path_test.py
@@ -0,0 +1,118 @@
+"""Containment tests for :func:`backend.util.file.get_exec_file_path`.
+
+Every path handed to ``get_exec_file_path()`` is caller-supplied and must stay
+inside ``{temp}/exec_file/{graph_exec_id}``. See GitHub issue #14622.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from backend.util import file as file_module
+from backend.util.file import clean_exec_files, get_exec_file_path
+
+EXEC_ID = "e2d4f1aa-0000-4000-8000-000000000001"
+
+
+def exec_base(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Point TEMP_DIR at *tmp_path* and yield the execution's own folder."""
+ monkeypatch.setattr(file_module, "TEMP_DIR", tmp_path.resolve())
+ base = tmp_path.resolve() / "exec_file" / EXEC_ID
+ base.mkdir(parents=True)
+ return base
+
+
+class TestGetExecFilePathRejectsEscapes:
+ """Paths that resolve outside the execution folder are refused."""
+
+ def test_rejects_parent_traversal(self, exec_base: Path):
+ with pytest.raises(ValueError):
+ get_exec_file_path(EXEC_ID, "../../outside.txt")
+
+ def test_rejects_traversal_below_a_subdirectory(self, exec_base: Path):
+ with pytest.raises(ValueError):
+ get_exec_file_path(EXEC_ID, "nested/../../../outside.txt")
+
+ def test_rejects_absolute_path(self, exec_base: Path):
+ with pytest.raises(ValueError):
+ get_exec_file_path(EXEC_ID, "/etc/passwd")
+
+ def test_rejects_symlink_pointing_out_of_the_base(
+ self, exec_base: Path, tmp_path: Path
+ ):
+ elsewhere = tmp_path / "elsewhere"
+ elsewhere.mkdir()
+ (elsewhere / "secret.txt").write_text("outside the sandbox")
+ (exec_base / "link").symlink_to(elsewhere, target_is_directory=True)
+
+ with pytest.raises(ValueError):
+ get_exec_file_path(EXEC_ID, "link/secret.txt")
+
+ def test_rejects_sibling_folder_sharing_the_base_name_as_prefix(
+ self, exec_base: Path
+ ):
+ """``/tmp/exec_file/<id>_evil`` is not inside ``/tmp/exec_file/<id>``."""
+ (exec_base.parent / f"{EXEC_ID}_evil").mkdir()
+
+ with pytest.raises(ValueError):
+ get_exec_file_path(EXEC_ID, f"../{EXEC_ID}_evil/loot.txt")
+
+ def test_rejects_exec_id_that_leaves_the_exec_file_root(self, exec_base: Path):
+ with pytest.raises(ValueError):
+ get_exec_file_path("../..", "loot.txt")
+
+ def test_clean_exec_files_does_not_remove_anything_outside_the_base(
+ self, exec_base: Path, tmp_path: Path
+ ):
+ unrelated = tmp_path / "important"
+ unrelated.mkdir()
+ (unrelated / "data.txt").write_text("unrelated data")
+
+ with pytest.raises(ValueError):
+ clean_exec_files(EXEC_ID, "../..")
+
+ assert (unrelated / "data.txt").is_file()
+
+
+class TestGetExecFilePathAllowsOrdinaryPaths:
+ """Normal relative paths keep resolving to the same place they always did."""
+
+ def test_allows_plain_filename(self, exec_base: Path):
+ assert get_exec_file_path(EXEC_ID, "report.csv") == str(
+ exec_base / "report.csv"
+ )
+
+ def test_allows_dots_inside_the_filename(self, exec_base: Path):
+ assert get_exec_file_path(EXEC_ID, "report.2026.csv") == str(
+ exec_base / "report.2026.csv"
+ )
+
+ def test_allows_nested_subdirectories(self, exec_base: Path):
+ assert get_exec_file_path(EXEC_ID, "nested/dir/report.csv") == str(
+ exec_base / "nested" / "dir" / "report.csv"
+ )
+
+ def test_allows_current_directory_prefix(self, exec_base: Path):
+ assert get_exec_file_path(EXEC_ID, "./report.csv") == str(
+ exec_base / "report.csv"
+ )
+
+ def test_allows_traversal_that_stays_inside_the_base(self, exec_base: Path):
+ assert get_exec_file_path(EXEC_ID, "nested/../report.csv") == str(
+ exec_base / "report.csv"
+ )
+
+ def test_empty_path_returns_the_base_folder(self, exec_base: Path):
+ assert get_exec_file_path(EXEC_ID, "") == str(exec_base)
+
+ def test_allows_absolute_path_already_inside_the_base(self, exec_base: Path):
+ inside = exec_base / "report.csv"
+ assert get_exec_file_path(EXEC_ID, str(inside)) == str(inside)
+
+ def test_clean_exec_files_removes_the_execution_folder(self, exec_base: Path):
+ (exec_base / "report.csv").write_text("data")
+
+ clean_exec_files(EXEC_ID)
+
+ assert not exec_base.exists()
diff --git a/autogpt_platform/backend/backend/util/file.py b/autogpt_platform/backend/backend/util/file.py
index 2edf53403e..4c66949840 100644
--- a/autogpt_platform/backend/backend/util/file.py
+++ b/autogpt_platform/backend/backend/util/file.py
@@ -96,10 +96,17 @@ def sanitize_filename(filename: str) -> str:
def get_exec_file_path(graph_exec_id: str, path: str) -> str:
"""
Utility to build an absolute path in the {temp}/exec_file/{exec_id}/... folder.
+
+ *path* is interpreted relative to that folder, and the result has to stay
+ inside it: an absolute path, a ``..`` segment or a symlink inside the folder
+ that points out of it is rejected rather than silently escaping.
"""
+ exec_file_root = (TEMP_DIR / "exec_file").resolve()
+ base = exec_file_root / graph_exec_id
try:
- full_path = TEMP_DIR / "exec_file" / graph_exec_id / path
- return str(full_path)
+ # Resolve before comparing so symlinked components are followed first.
+ resolved_base = base.resolve()
+ full_path = (base / path).resolve()
except OSError as e:
if "File name too long" in str(e):
raise ValueError(
@@ -107,6 +114,15 @@ def get_exec_file_path(graph_exec_id: str, path: str) -> str:
) from e
raise ValueError(f"Invalid file path: {e}") from e
+ # is_relative_to() compares path components rather than string prefixes, so
+ # a sibling folder whose name merely starts with the base name is excluded.
+ if not resolved_base.is_relative_to(exec_file_root):
+ raise ValueError("Invalid execution ID: resolves outside the exec_file folder")
+ if not full_path.is_relative_to(resolved_base):
+ raise ValueError("Invalid file path: resolves outside the execution folder")
+
+ return str(full_path)
+
def clean_exec_files(graph_exec_id: str, file: str = "") -> None:
"""