Skip to content

Automate browser based workflows with AI

fix: restrict SendEmailBlock and UploadToS3Block to workflow download directory (SKY-7900) (#5221)

Shuchang Zheng6d1dc4259775
diff --git a/skyvern/forge/sdk/api/files.py b/skyvern/forge/sdk/api/files.py
index 3fb131ca3..58bc6f87d 100644
--- a/skyvern/forge/sdk/api/files.py
+++ b/skyvern/forge/sdk/api/files.py
@@ -272,6 +272,46 @@ def unzip_files(zip_file_path: str, output_dir: str) -> None:
zip_ref.extractall(output_dir)
+_REMOTE_URL_PREFIXES = ("http://", "https://", "s3://", "azure://", "www.")
+
+
+def is_remote_url(path: str) -> bool:
+ """Return True if the path is a remote URL (HTTP, S3, Azure) rather than a local filesystem path."""
+ return path.startswith(_REMOTE_URL_PREFIXES)
+
+
+def validate_local_file_path(candidate_path: str, run_id: str | None) -> str:
+ """Validate that a local file path is within the workflow's download directory.
+
+ Uses os.path.realpath() to resolve symlinks and '..' traversal before checking
+ containment. Raises PermissionError if the path resolves outside the allowed directory.
+
+ Returns the resolved canonical path on success.
+ """
+ if run_id is None:
+ raise PermissionError("File access denied: no workflow run ID provided")
+
+ if not candidate_path:
+ LOG.warning("Empty path provided for file access validation", run_id=run_id)
+ raise PermissionError(f"File access denied: path must not be empty for run {run_id}")
+
+ allowed_dir = os.path.realpath(os.path.join(settings.DOWNLOAD_PATH, str(run_id)))
+ resolved = os.path.realpath(candidate_path)
+
+ # The resolved path must be the allowed dir itself or a child of it
+ if resolved != allowed_dir and not resolved.startswith(allowed_dir + os.sep):
+ LOG.warning(
+ "Path traversal attempt blocked",
+ candidate_path=candidate_path,
+ resolved_path=resolved,
+ allowed_dir=allowed_dir,
+ run_id=run_id,
+ )
+ raise PermissionError(f"File access denied: path is outside the allowed download directory for run {run_id}")
+
+ return resolved
+
+
def get_path_for_workflow_download_directory(run_id: str | None) -> Path:
return Path(get_download_dir(run_id=run_id))
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 22d9137e5..a50f47b40 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -59,7 +59,9 @@ from skyvern.forge.sdk.api.files import (
download_file,
get_download_dir,
get_path_for_workflow_download_directory,
+ is_remote_url,
parse_uri_to_path,
+ validate_local_file_path,
)
from skyvern.forge.sdk.api.llm.api_handler import LLMAPIHandler
from skyvern.forge.sdk.api.llm.api_handler_factory import LLMAPIHandlerFactory
@@ -2833,31 +2835,38 @@ class UploadToS3Block(Block):
organization_id=organization_id,
)
- if not self.path or not os.path.exists(self.path):
- raise FileNotFoundError(f"UploadToS3Block: File not found at path: {self.path}")
+ if not self.path:
+ raise ValueError("UploadToS3Block: path is required")
+
+ context = skyvern_context.current()
+ run_id = context.run_id if context and context.run_id else workflow_run_id
+ resolved_path = validate_local_file_path(self.path, run_id)
+
+ if not os.path.exists(resolved_path):
+ raise FileNotFoundError(f"UploadToS3Block: File not found at path: {resolved_path}")
s3_uris = []
try:
client = self.get_async_aws_client()
# is the file path a file or a directory?
- if os.path.isdir(self.path):
+ if os.path.isdir(resolved_path):
# get all files in the directory, if there are more than 25 files, we will not upload them
- files = os.listdir(self.path)
+ files = os.listdir(resolved_path)
if len(files) > MAX_UPLOAD_FILE_COUNT:
raise ValueError("Too many files in the directory, not uploading")
for file in files:
# if the file is a directory, we will not upload it
- if os.path.isdir(os.path.join(self.path, file)):
+ if os.path.isdir(os.path.join(resolved_path, file)):
LOG.warning("UploadToS3Block: Skipping directory", file=file)
continue
- file_path = os.path.join(self.path, file)
+ file_path = os.path.join(resolved_path, file)
s3_uri = self._get_s3_uri(workflow_run_id, file_path)
s3_uris.append(s3_uri)
await client.upload_file_from_path(uri=s3_uri, file_path=file_path)
else:
- s3_uri = self._get_s3_uri(workflow_run_id, self.path)
+ s3_uri = self._get_s3_uri(workflow_run_id, resolved_path)
s3_uris.append(s3_uri)
- await client.upload_file_from_path(uri=s3_uri, file_path=self.path)
+ await client.upload_file_from_path(uri=s3_uri, file_path=resolved_path)
except Exception as e:
LOG.exception("UploadToS3Block: Failed to upload file to S3", file_path=self.path)
raise e
@@ -3216,6 +3225,8 @@ class SendEmailBlock(Block):
def _get_file_paths(self, workflow_run_context: WorkflowRunContext, workflow_run_id: str) -> list[str]:
file_paths = []
+ context = skyvern_context.current()
+ run_id = context.run_id if context and context.run_id else workflow_run_id
for path in self.file_attachments:
# if the file path is a parameter, get the value from the workflow run context first
if workflow_run_context.has_parameter(path):
@@ -3231,12 +3242,7 @@ class SendEmailBlock(Block):
if path == settings.WORKFLOW_DOWNLOAD_DIRECTORY_PARAMETER_KEY:
# if the path is WORKFLOW_DOWNLOAD_DIRECTORY_PARAMETER_KEY, use download directory for the workflow run
- context = skyvern_context.current()
- path = str(
- get_path_for_workflow_download_directory(
- context.run_id if context and context.run_id else workflow_run_id
- ).absolute()
- )
+ path = str(get_path_for_workflow_download_directory(run_id).absolute())
LOG.info(
"SendEmailBlock: Using download directory for the workflow run",
workflow_run_id=workflow_run_id,
@@ -3244,6 +3250,8 @@ class SendEmailBlock(Block):
)
path = self.format_block_parameter_template_from_workflow_run_context(path, workflow_run_context)
+ if not is_remote_url(path):
+ path = validate_local_file_path(path, run_id)
# if the file path is a directory, add all files in the directory, skip directories, limit to 10 files
if os.path.exists(path):
if os.path.isdir(path):
@@ -3256,14 +3264,7 @@ class SendEmailBlock(Block):
else:
# covers the case where the file path is a single file
file_paths.append(path)
- # check if path is a url, or an S3 uri
- elif (
- path.startswith("http://")
- or path.startswith("https://")
- or path.startswith("s3://")
- or path.startswith("azure://")
- or path.startswith("www.")
- ):
+ elif is_remote_url(path):
file_paths.append(path)
else:
LOG.warning("SendEmailBlock: File not found", file_path=path)
diff --git a/tests/unit/test_local_file_path_validation.py b/tests/unit/test_local_file_path_validation.py
new file mode 100644
index 000000000..6b1264f80
--- /dev/null
+++ b/tests/unit/test_local_file_path_validation.py
@@ -0,0 +1,146 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from skyvern.config import settings
+from skyvern.forge.sdk.api.files import is_remote_url, validate_local_file_path
+
+RUN_ID = "wr_test_run_123"
+
+
+def download_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """Set up a temporary download directory structure mimicking production."""
+ monkeypatch.setattr(settings, "DOWNLOAD_PATH", str(tmp_path))
+ run_dir = tmp_path / RUN_ID
+ run_dir.mkdir()
+ return run_dir
+
+
+def sample_file(download_dir: Path) -> Path:
+ """Create a sample file inside the download directory."""
+ f = download_dir / "report.pdf"
+ f.write_text("sample content")
+ return f
+
+
+def sample_subdir_file(download_dir: Path) -> Path:
+ """Create a sample file in a subdirectory of the download directory."""
+ subdir = download_dir / "subdir"
+ subdir.mkdir()
+ f = subdir / "nested.pdf"
+ f.write_text("nested content")
+ return f
+
+
+# ---------------------------------------------------------------------------
+# validate_local_file_path: happy path
+# ---------------------------------------------------------------------------
+
+
+class TestValidateLocalFilePath:
+ def test_accepts_file_within_download_dir(self, sample_file: Path) -> None:
+ """A file inside downloads/{run_id}/ should be accepted."""
+ result = validate_local_file_path(str(sample_file), RUN_ID)
+ assert result == str(sample_file.resolve())
+
+ def test_accepts_file_in_subdirectory(self, sample_subdir_file: Path) -> None:
+ """A file in a subdirectory of downloads/{run_id}/ should be accepted."""
+ result = validate_local_file_path(str(sample_subdir_file), RUN_ID)
+ assert result == str(sample_subdir_file.resolve())
+
+ def test_accepts_download_directory_itself(self, download_dir: Path) -> None:
+ """The download directory itself should be accepted (for SKYVERN_DOWNLOAD_DIRECTORY)."""
+ result = validate_local_file_path(str(download_dir), RUN_ID)
+ assert result == str(download_dir.resolve())
+
+ # ---------------------------------------------------------------------------
+ # validate_local_file_path: path traversal attacks
+ # ---------------------------------------------------------------------------
+
+ def test_rejects_path_traversal_with_dotdot(self, download_dir: Path) -> None:
+ """Path traversal via ../../ should be rejected."""
+ malicious = str(download_dir / ".." / ".." / "etc" / "passwd")
+ with pytest.raises(PermissionError, match="outside the allowed download directory"):
+ validate_local_file_path(malicious, RUN_ID)
+
+ def test_rejects_absolute_path_outside_download_dir(self, download_dir: Path) -> None:
+ """Absolute paths to sensitive files should be rejected."""
+ with pytest.raises(PermissionError, match="outside the allowed download directory"):
+ validate_local_file_path("/var/run/secrets/kubernetes.io/serviceaccount/token", RUN_ID)
+
+ def test_rejects_proc_self_environ(self, download_dir: Path) -> None:
+ """/proc/self/environ should be rejected."""
+ with pytest.raises(PermissionError, match="outside the allowed download directory"):
+ validate_local_file_path("/proc/self/environ", RUN_ID)
+
+ def test_rejects_symlink_escaping_sandbox(self, download_dir: Path) -> None:
+ """A symlink inside the download dir pointing outside should be rejected."""
+ # Create a symlink inside the sandbox that points to /etc/passwd
+ symlink_path = download_dir / "evil_link"
+ symlink_path.symlink_to("/etc/passwd")
+ with pytest.raises(PermissionError, match="outside the allowed download directory"):
+ validate_local_file_path(str(symlink_path), RUN_ID)
+
+ def test_rejects_relative_path_outside_download_dir(self, download_dir: Path) -> None:
+ """Relative paths that resolve outside the download dir should be rejected."""
+ with pytest.raises(PermissionError, match="outside the allowed download directory"):
+ validate_local_file_path("../../../etc/shadow", RUN_ID)
+
+ def test_rejects_empty_path(self, download_dir: Path) -> None:
+ """Empty path should be rejected."""
+ with pytest.raises(PermissionError, match="path must not be empty"):
+ validate_local_file_path("", RUN_ID)
+
+ def test_rejects_none_run_id(self, download_dir: Path) -> None:
+ """None run_id should be rejected immediately."""
+ with pytest.raises(PermissionError, match="no workflow run ID provided"):
+ validate_local_file_path("/some/path", None)
+
+ def test_rejects_path_to_different_run_id(self, download_dir: Path) -> None:
+ """A file belonging to a different workflow run should be rejected."""
+ other_run_dir = download_dir.parent / "wr_other_run_456"
+ other_run_dir.mkdir()
+ other_file = other_run_dir / "secret.pdf"
+ other_file.write_text("other tenant data")
+ with pytest.raises(PermissionError, match="outside the allowed download directory"):
+ validate_local_file_path(str(other_file), RUN_ID)
+
+ def test_accepts_absolute_path_within_download_dir(self, sample_file: Path) -> None:
+ """Absolute path like /app/downloads/wr_xxx/file.pdf should be accepted."""
+ absolute = str(sample_file.resolve())
+ result = validate_local_file_path(absolute, RUN_ID)
+ assert result == absolute
+
+
+class TestIsRemoteUrl:
+ """Tests for the is_remote_url() helper."""
+
+ def test_http_url(self) -> None:
+ assert is_remote_url("http://example.com/file.pdf") is True
+
+ def test_https_url(self) -> None:
+ assert is_remote_url("https://example.com/file.pdf") is True
+
+ def test_s3_uri(self) -> None:
+ assert is_remote_url("s3://bucket/key/file.pdf") is True
+
+ def test_azure_uri(self) -> None:
+ assert is_remote_url("azure://container/blob/file.pdf") is True
+
+ def test_local_path_not_remote(self) -> None:
+ assert is_remote_url("/app/downloads/wr_123/file.pdf") is False
+
+ def test_relative_path_not_remote(self) -> None:
+ assert is_remote_url("downloads/wr_123/file.pdf") is False
+
+ def test_www_prefix_is_remote(self) -> None:
+ """www. is treated as a remote URL for backward compatibility."""
+ assert is_remote_url("www.example.com/report.pdf") is True
+
+ def test_empty_string_not_remote(self) -> None:
+ assert is_remote_url("") is False