Skip to content

Automate browser based workflows with AI

fix: restrict managed storage URI reads by organization (#5182)

Shuchang Zheng62ae173a3d09
diff --git a/skyvern/core/script_generations/real_skyvern_page_ai.py b/skyvern/core/script_generations/real_skyvern_page_ai.py
index d46fa6351..5a53820cc 100644
--- a/skyvern/core/script_generations/real_skyvern_page_ai.py
+++ b/skyvern/core/script_generations/real_skyvern_page_ai.py
@@ -445,7 +445,7 @@ class RealSkyvernPageAi(SkyvernPageAi):
except Exception:
LOG.exception(f"Failed to adapt value for upload file action on selector={selector}, file={files}")
- if public_url_only and not validate_download_url(files):
+ if public_url_only and not validate_download_url(files, organization_id=organization_id):
raise Exception("Only public URLs are allowed")
if action and organization_id and task and step:
diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.py
index 76fcd9da9..3e0b7fdde 100644
--- a/skyvern/core/script_generations/skyvern_page.py
+++ b/skyvern/core/script_generations/skyvern_page.py
@@ -929,7 +929,10 @@ class SkyvernPage(Page):
error_to_raise = None
if selector and files:
try:
- file_path = await download_file_from_url(files)
+ file_path = await download_file_from_url(
+ files,
+ organization_id=context.organization_id if context else None,
+ )
locator = self.page.locator(selector)
await locator.set_input_files(file_path, **kwargs)
except Exception as e:
@@ -964,7 +967,7 @@ class SkyvernPage(Page):
if not files:
raise ValueError("Parameter 'files' is required but was not provided")
- file_path = await download_file_from_url(files)
+ file_path = await download_file_from_url(files, organization_id=context.organization_id if context else None)
locator = self.page.locator(selector)
await locator.set_input_files(file_path, timeout=timeout, **kwargs)
return files
@@ -1131,7 +1134,12 @@ class SkyvernPage(Page):
# Use uuid as fallback for empty file_name, matching handler.py behavior
file_name = file_name or str(uuid.uuid4())
- file_path = await download_file_from_url(download_url, filename=file_name)
+ context = skyvern_context.current()
+ file_path = await download_file_from_url(
+ download_url,
+ filename=file_name,
+ organization_id=context.organization_id if context else None,
+ )
return file_path
@action_wrap(ActionType.RELOAD_PAGE)
diff --git a/skyvern/forge/sdk/api/files.py b/skyvern/forge/sdk/api/files.py
index b529e2862..3fb131ca3 100644
--- a/skyvern/forge/sdk/api/files.py
+++ b/skyvern/forge/sdk/api/files.py
@@ -18,21 +18,11 @@ from skyvern.config import settings
from skyvern.constants import BROWSER_DOWNLOAD_TIMEOUT, BROWSER_DOWNLOADING_SUFFIX, REPO_ROOT_DIR
from skyvern.exceptions import DownloadFileMaxSizeExceeded, DownloadFileMaxWaitingTime
from skyvern.forge import app
-from skyvern.forge.sdk.api.aws import AsyncAWSClient
from skyvern.utils.url_validators import encode_url
LOG = structlog.get_logger()
-async def download_from_s3(client: AsyncAWSClient, s3_uri: str) -> str:
- downloaded_bytes = await client.download_file(uri=s3_uri)
- filename = s3_uri.split("/")[-1] # Extract filename from the end of S3 URI
- file_path = create_named_temporary_file(delete=False, file_name=filename)
- LOG.info(f"Downloaded file to {file_path.name}")
- file_path.write(downloaded_bytes)
- return file_path.name
-
-
def get_file_name_and_suffix_from_headers(headers: CIMultiDictProxy[str] | dict[str, str]) -> tuple[str, str]:
file_stem = ""
file_suffix: str | None = ""
@@ -110,7 +100,7 @@ def _determine_download_filename(
return sanitize_filename(file_name)
-def validate_download_url(url: str) -> bool:
+def validate_download_url(url: str, organization_id: str | None = None) -> bool:
"""Validate if a URL is supported for downloading.
Security validation for URL downloads to prevent:
@@ -132,17 +122,14 @@ def validate_download_url(url: str) -> bool:
if scheme in ("http", "https"):
return True
- # Allow S3 URIs for Skyvern uploads bucket
- if scheme == "s3":
- if url.startswith(f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/o_"):
- return True
- return False
-
- # Allow Azure URIs for Skyvern uploads container
- if scheme == "azure":
- if url.startswith(f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{settings.ENV}/o_"):
+ if scheme in ("s3", "azure"):
+ try:
+ if organization_id is None:
+ return False
+ app.STORAGE.assert_managed_file_access(url, organization_id)
return True
- return False
+ except (PermissionError, RuntimeError):
+ return False
# Allow file:// URLs only in local environment
if scheme == "file":
@@ -172,6 +159,7 @@ async def download_file(
headers: dict[str, str] | None = None,
output_dir: str | None = None,
filename: str | None = None,
+ organization_id: str | None = None,
) -> str:
if not url or not url.strip():
raise ValueError("Download URL is empty — no file download was triggered by the browser")
@@ -185,32 +173,28 @@ async def download_file(
url = f"https://drive.google.com/uc?export=download&id={file_id}"
LOG.info("Converting Google Drive link to direct download", url=url)
- # Check if URL is a cloud storage URI (S3 or Azure)
+ # Check if URL is a cloud storage URI handled by the configured storage backend.
parsed = urlparse(url)
- if parsed.scheme == "s3":
- uploads_prefix = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/o_"
- if url.startswith(uploads_prefix):
- LOG.info("Downloading Skyvern file from S3", url=url)
- data = await app.STORAGE.download_uploaded_file(url)
- if data is None:
- raise Exception(f"Failed to download file from S3: {url}")
- filename = url.split("/")[-1]
- temp_file = create_named_temporary_file(delete=False, file_name=filename)
- LOG.info(f"Downloaded file to {temp_file.name}")
- temp_file.write(data)
- return temp_file.name
- elif parsed.scheme == "azure":
- uploads_prefix = f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{settings.ENV}/o_"
- if url.startswith(uploads_prefix):
- LOG.info("Downloading Skyvern file from Azure Blob Storage", url=url)
- data = await app.STORAGE.download_uploaded_file(url)
- if data is None:
- raise Exception(f"Failed to download file from Azure Blob Storage: {url}")
- filename = url.split("/")[-1]
- temp_file = create_named_temporary_file(delete=False, file_name=filename)
- LOG.info(f"Downloaded file to {temp_file.name}")
- temp_file.write(data)
- return temp_file.name
+ if parsed.scheme in ("s3", "azure"):
+ if organization_id is None:
+ raise PermissionError(f"No permission to access storage URI: {url}")
+
+ app.STORAGE.assert_managed_file_access(url, organization_id)
+
+ LOG.info(
+ "Downloading managed storage file",
+ url=url,
+ organization_id=organization_id,
+ storage_type=getattr(app.STORAGE, "storage_type", None),
+ )
+ data = await app.STORAGE.download_managed_file(url, organization_id)
+ if data is None:
+ raise Exception(f"Failed to download managed storage file: {url}")
+ filename = url.split("/")[-1]
+ temp_file = create_named_temporary_file(delete=False, file_name=filename)
+ LOG.info(f"Downloaded file to {temp_file.name}")
+ temp_file.write(data)
+ return temp_file.name
# Check if URL is a file:// URI
# we only support to download local files when the environment is local
@@ -259,6 +243,14 @@ async def download_file(
except DownloadFileMaxSizeExceeded as e:
LOG.exception(f"Failed to download file, max size exceeded: {e.max_size}")
raise
+ except PermissionError as e:
+ LOG.warning(
+ "Rejected storage URI download",
+ url=url,
+ organization_id=organization_id,
+ reason=str(e),
+ )
+ raise
except Exception:
LOG.exception("Failed to download file")
raise
diff --git a/skyvern/forge/sdk/artifact/storage/azure.py b/skyvern/forge/sdk/artifact/storage/azure.py
index 506825d97..79b832b4b 100644
--- a/skyvern/forge/sdk/artifact/storage/azure.py
+++ b/skyvern/forge/sdk/artifact/storage/azure.py
@@ -8,7 +8,7 @@ import structlog
from skyvern.config import settings
from skyvern.constants import BROWSER_DOWNLOADING_SUFFIX, DOWNLOAD_FILE_PREFIX
-from skyvern.forge.sdk.api.azure import StandardBlobTier
+from skyvern.forge.sdk.api.azure import AzureUri, StandardBlobTier
from skyvern.forge.sdk.api.files import (
calculate_sha256_for_file,
create_named_temporary_file,
@@ -546,8 +546,24 @@ class AzureStorage(BaseStorage):
except Exception:
return False
- async def download_uploaded_file(self, uri: str) -> bytes | None:
- """Download a user-uploaded file from Azure."""
+ def assert_managed_file_access(self, uri: str, organization_id: str) -> None:
+ try:
+ parsed_uri = AzureUri(uri)
+ except Exception as e:
+ raise PermissionError(f"No permission to access storage URI: {uri}") from e
+
+ allowed_prefixes = (
+ f"{settings.ENV}/{organization_id}/",
+ f"{DOWNLOAD_FILE_PREFIX}/{settings.ENV}/{organization_id}/",
+ )
+ if parsed_uri.container != settings.AZURE_STORAGE_CONTAINER_UPLOADS or not any(
+ parsed_uri.blob_path.startswith(prefix) for prefix in allowed_prefixes
+ ):
+ raise PermissionError(f"No permission to access storage URI: {uri}")
+
+ async def download_managed_file(self, uri: str, organization_id: str) -> bytes | None:
+ """Download a managed org-scoped file from Azure."""
+ self.assert_managed_file_access(uri, organization_id)
return await self.async_client.download_file(uri, log_exception=False)
async def file_exists(self, uri: str) -> bool:
diff --git a/skyvern/forge/sdk/artifact/storage/base.py b/skyvern/forge/sdk/artifact/storage/base.py
index 5feb2e182..66dcb241e 100644
--- a/skyvern/forge/sdk/artifact/storage/base.py
+++ b/skyvern/forge/sdk/artifact/storage/base.py
@@ -215,7 +215,11 @@ class BaseStorage(ABC):
pass
@abstractmethod
- async def download_uploaded_file(self, uri: str) -> bytes | None:
+ def assert_managed_file_access(self, uri: str, organization_id: str) -> None:
+ pass
+
+ @abstractmethod
+ async def download_managed_file(self, uri: str, organization_id: str) -> bytes | None:
pass
@abstractmethod
diff --git a/skyvern/forge/sdk/artifact/storage/local.py b/skyvern/forge/sdk/artifact/storage/local.py
index 1506821d5..e7ae20b02 100644
--- a/skyvern/forge/sdk/artifact/storage/local.py
+++ b/skyvern/forge/sdk/artifact/storage/local.py
@@ -8,6 +8,7 @@ import aiofiles
import structlog
from skyvern.config import settings
+from skyvern.constants import DOWNLOAD_FILE_PREFIX
from skyvern.forge.sdk.api.files import (
calculate_sha256_for_file,
get_download_dir,
@@ -479,8 +480,28 @@ class LocalStorage(BaseStorage):
)
return target_path.exists()
- async def download_uploaded_file(self, uri: str) -> bytes | None:
- """Download a user-uploaded file from local filesystem."""
+ def assert_managed_file_access(self, uri: str, organization_id: str) -> None:
+ if not uri.startswith("file://"):
+ raise PermissionError(f"No permission to access storage URI: {uri}")
+
+ try:
+ file_path = Path(parse_uri_to_path(uri)).resolve()
+ except Exception as e:
+ raise PermissionError(f"No permission to access storage URI: {uri}") from e
+
+ allowed_dirs = (
+ (Path(self.artifact_path) / settings.ENV / organization_id).resolve(),
+ (Path(self.artifact_path) / DOWNLOAD_FILE_PREFIX / settings.ENV / organization_id).resolve(),
+ )
+ if not any(
+ os.path.commonpath([str(file_path), str(allowed_dir)]) == str(allowed_dir) for allowed_dir in allowed_dirs
+ ):
+ raise PermissionError(f"No permission to access storage URI: {uri}")
+
+ async def download_managed_file(self, uri: str, organization_id: str) -> bytes | None:
+ """Download a managed org-scoped file from local filesystem."""
+ self.assert_managed_file_access(uri, organization_id)
+
try:
file_path = parse_uri_to_path(uri)
async with aiofiles.open(file_path, "rb") as f:
diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.py
index fcc4e9c18..2435bbb60 100644
--- a/skyvern/forge/sdk/artifact/storage/s3.py
+++ b/skyvern/forge/sdk/artifact/storage/s3.py
@@ -11,7 +11,7 @@ import zstandard as zstd
from skyvern.config import settings
from skyvern.constants import BROWSER_DOWNLOADING_SUFFIX, DOWNLOAD_FILE_PREFIX
-from skyvern.forge.sdk.api.aws import AsyncAWSClient, S3StorageClass
+from skyvern.forge.sdk.api.aws import AsyncAWSClient, S3StorageClass, S3Uri
from skyvern.forge.sdk.api.files import (
calculate_sha256_for_file,
create_named_temporary_file,
@@ -569,8 +569,24 @@ class S3Storage(BaseStorage):
except Exception:
return False
- async def download_uploaded_file(self, uri: str) -> bytes | None:
- """Download a user-uploaded file from S3."""
+ def assert_managed_file_access(self, uri: str, organization_id: str) -> None:
+ try:
+ parsed_uri = S3Uri(uri)
+ except Exception as e:
+ raise PermissionError(f"No permission to access storage URI: {uri}") from e
+
+ allowed_prefixes = (
+ f"{settings.ENV}/{organization_id}/",
+ f"{DOWNLOAD_FILE_PREFIX}/{settings.ENV}/{organization_id}/",
+ )
+ if parsed_uri.bucket != settings.AWS_S3_BUCKET_UPLOADS or not any(
+ parsed_uri.key.startswith(prefix) for prefix in allowed_prefixes
+ ):
+ raise PermissionError(f"No permission to access storage URI: {uri}")
+
+ async def download_managed_file(self, uri: str, organization_id: str) -> bytes | None:
+ """Download a managed org-scoped file from S3."""
+ self.assert_managed_file_access(uri, organization_id)
return await self.async_client.download_file(uri, log_exception=False)
async def file_exists(self, uri: str) -> bool:
diff --git a/skyvern/forge/sdk/artifact/storage/test_azure_storage.py b/skyvern/forge/sdk/artifact/storage/test_azure_storage.py
index 6187f49ac..742a0ec6d 100644
--- a/skyvern/forge/sdk/artifact/storage/test_azure_storage.py
+++ b/skyvern/forge/sdk/artifact/storage/test_azure_storage.py
@@ -142,27 +142,55 @@ class TestAzureStorageBrowserSessionFiles:
assert exists is False
- async def test_download_uploaded_file(self, azure_storage: AzureStorageForTests) -> None:
- """Test downloading an uploaded file."""
+ async def test_assert_managed_file_access_accepts_org_scoped_uploads(
+ self, azure_storage: AzureStorageForTests
+ ) -> None:
+ legacy_uri = (
+ f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{settings.ENV}/{TEST_ORGANIZATION_ID}/file.pdf"
+ )
+ downloads_uri = (
+ f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/"
+ f"downloads/{settings.ENV}/{TEST_ORGANIZATION_ID}/wr_123/file.pdf"
+ )
+
+ azure_storage.assert_managed_file_access(legacy_uri, TEST_ORGANIZATION_ID)
+ azure_storage.assert_managed_file_access(downloads_uri, TEST_ORGANIZATION_ID)
+
+ async def test_assert_managed_file_access_rejects_other_org(self, azure_storage: AzureStorageForTests) -> None:
+ uri = f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{settings.ENV}/o_other/file.pdf"
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ azure_storage.assert_managed_file_access(uri, TEST_ORGANIZATION_ID)
+
+ async def test_download_managed_file(self, azure_storage: AzureStorageForTests) -> None:
+ """Test downloading a managed file."""
test_data = b"uploaded file content"
azure_storage.async_client.download_file.return_value = test_data
- uri = f"azure://{TEST_CONTAINER}/uploads/file.pdf"
+ uri = f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{settings.ENV}/{TEST_ORGANIZATION_ID}/file.pdf"
- downloaded = await azure_storage.download_uploaded_file(uri)
+ downloaded = await azure_storage.download_managed_file(uri, TEST_ORGANIZATION_ID)
assert downloaded == test_data
azure_storage.async_client.download_file.assert_called_once_with(uri, log_exception=False)
- async def test_download_uploaded_file_returns_none(self, azure_storage: AzureStorageForTests) -> None:
- """Test downloading a non-existent file returns None."""
+ async def test_download_managed_file_returns_none(self, azure_storage: AzureStorageForTests) -> None:
+ """Test downloading a non-existent managed file returns None."""
azure_storage.async_client.download_file.return_value = None
- uri = f"azure://{TEST_CONTAINER}/nonexistent/file.txt"
+ uri = (
+ f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{settings.ENV}/{TEST_ORGANIZATION_ID}/"
+ "nonexistent/file.txt"
+ )
- downloaded = await azure_storage.download_uploaded_file(uri)
+ downloaded = await azure_storage.download_managed_file(uri, TEST_ORGANIZATION_ID)
assert downloaded is None
- def test_storage_type_property(self, azure_storage: AzureStorageForTests) -> None:
+ async def test_download_managed_file_rejects_other_org(self, azure_storage: AzureStorageForTests) -> None:
+ uri = f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{settings.ENV}/o_other/file.pdf"
+
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ await azure_storage.download_managed_file(uri, TEST_ORGANIZATION_ID)
+
+ async def test_storage_type_property(self, azure_storage: AzureStorageForTests) -> None:
"""Test storage_type returns 'azure'."""
assert azure_storage.storage_type == "azure"
diff --git a/skyvern/forge/sdk/artifact/storage/test_s3_storage.py b/skyvern/forge/sdk/artifact/storage/test_s3_storage.py
index 83d638e41..3c28db3e6 100644
--- a/skyvern/forge/sdk/artifact/storage/test_s3_storage.py
+++ b/skyvern/forge/sdk/artifact/storage/test_s3_storage.py
@@ -1,3 +1,4 @@
+import io
from datetime import datetime
from pathlib import Path
from typing import Generator
@@ -76,6 +77,7 @@ def boto3_test_client(moto_server: str) -> Generator[S3Client, None, None]:
endpoint_url=moto_server,
)
client.create_bucket(Bucket=TEST_BUCKET) # Ensure the bucket exists for the test
+ client.create_bucket(Bucket=settings.AWS_S3_BUCKET_UPLOADS)
yield client
@@ -377,32 +379,46 @@ class TestS3StorageBrowserSessionFiles:
exists = await s3_storage.file_exists(uri)
assert exists is False
- async def test_download_uploaded_file(
- self, s3_storage: S3Storage, boto3_test_client: S3Client, tmp_path: Path
- ) -> None:
- """Test downloading an uploaded file."""
- test_data = b"uploaded file content"
- test_file = tmp_path / "uploaded.pdf"
- test_file.write_bytes(test_data)
+ async def test_assert_managed_file_access_accepts_org_scoped_uploads(self, s3_storage: S3Storage) -> None:
+ legacy_uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/{TEST_ORGANIZATION_ID}/uploaded.pdf"
+ downloads_uri = (
+ f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/downloads/{settings.ENV}/{TEST_ORGANIZATION_ID}/wr_123/uploaded.pdf"
+ )
- uri = await s3_storage.sync_browser_session_file(
+ s3_storage.assert_managed_file_access(legacy_uri, TEST_ORGANIZATION_ID)
+ s3_storage.assert_managed_file_access(downloads_uri, TEST_ORGANIZATION_ID)
+
+ async def test_assert_managed_file_access_rejects_other_org(self, s3_storage: S3Storage) -> None:
+ uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/o_other/uploaded.pdf"
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ s3_storage.assert_managed_file_access(uri, TEST_ORGANIZATION_ID)
+
+ async def test_download_managed_file(self, s3_storage: S3Storage) -> None:
+ """Test downloading a managed file."""
+ test_data = b"uploaded file content"
+ saved = await s3_storage.save_legacy_file(
organization_id=TEST_ORGANIZATION_ID,
- browser_session_id=TEST_BROWSER_SESSION_ID,
- artifact_type="downloads",
- local_file_path=str(test_file),
- remote_path="uploaded.pdf",
+ filename="uploaded.pdf",
+ fileObj=io.BytesIO(test_data),
)
+ assert saved is not None
- downloaded = await s3_storage.download_uploaded_file(uri)
+ _, uri = saved
+ downloaded = await s3_storage.download_managed_file(uri, TEST_ORGANIZATION_ID)
assert downloaded == test_data
- async def test_download_uploaded_file_nonexistent(self, s3_storage: S3Storage) -> None:
- """Test downloading a non-existent file returns None."""
- uri = f"s3://{TEST_BUCKET}/nonexistent/path/file.txt"
- downloaded = await s3_storage.download_uploaded_file(uri)
+ async def test_download_managed_file_nonexistent(self, s3_storage: S3Storage) -> None:
+ """Test downloading a non-existent managed file returns None."""
+ uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/{TEST_ORGANIZATION_ID}/nonexistent/file.txt"
+ downloaded = await s3_storage.download_managed_file(uri, TEST_ORGANIZATION_ID)
assert downloaded is None
- def test_storage_type_property(self, s3_storage: S3Storage) -> None:
+ async def test_download_managed_file_rejects_other_org(self, s3_storage: S3Storage) -> None:
+ uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/o_other/uploaded.pdf"
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ await s3_storage.download_managed_file(uri, TEST_ORGANIZATION_ID)
+
+ async def test_storage_type_property(self, s3_storage: S3Storage) -> None:
"""Test storage_type returns 's3'."""
assert s3_storage.storage_type == "s3"
diff --git a/skyvern/forge/sdk/routes/sdk.py b/skyvern/forge/sdk/routes/sdk.py
index 8c3239884..060ee53f7 100644
--- a/skyvern/forge/sdk/routes/sdk.py
+++ b/skyvern/forge/sdk/routes/sdk.py
@@ -180,7 +180,7 @@ async def run_sdk_action(
timeout=action.timeout,
)
elif action.type == "ai_upload_file":
- if action.file_url and not validate_download_url(action.file_url):
+ if action.file_url and not validate_download_url(action.file_url, organization_id=organization_id):
raise HTTPException(status_code=400, detail="Unsupported file url")
result = await page_ai.ai_upload_file(
selector=action.selector,
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index f2f8e4bc1..267ee2dd1 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -56,9 +56,7 @@ from skyvern.forge.sdk.api import email
from skyvern.forge.sdk.api.aws import AsyncAWSClient
from skyvern.forge.sdk.api.files import (
calculate_sha256_for_file,
- create_named_temporary_file,
download_file,
- download_from_s3,
get_download_dir,
get_path_for_workflow_download_directory,
parse_uri_to_path,
@@ -2740,7 +2738,7 @@ class DownloadToS3Block(Block):
)
try:
- file_path = await download_file(self.url, max_size_mb=10)
+ file_path = await download_file(self.url, max_size_mb=10, organization_id=organization_id)
except Exception as e:
LOG.error("DownloadToS3Block: Failed to download file", url=self.url, error=str(e))
raise e
@@ -3263,6 +3261,7 @@ class SendEmailBlock(Block):
path.startswith("http://")
or path.startswith("https://")
or path.startswith("s3://")
+ or path.startswith("azure://")
or path.startswith("www.")
):
file_paths.append(path)
@@ -3271,13 +3270,6 @@ class SendEmailBlock(Block):
return file_paths
- async def _download_from_s3(self, s3_uri: str) -> str:
- client = self.get_async_aws_client()
- downloaded_bytes = await client.download_file(uri=s3_uri)
- file_path = create_named_temporary_file(delete=False)
- file_path.write(downloaded_bytes)
- return file_path.name
-
def get_real_email_recipients(self, workflow_run_context: WorkflowRunContext) -> list[str]:
recipients = []
for recipient in self.recipients:
@@ -3305,7 +3297,10 @@ class SendEmailBlock(Block):
return recipients
async def _build_email_message(
- self, workflow_run_context: WorkflowRunContext, workflow_run_id: str
+ self,
+ workflow_run_context: WorkflowRunContext,
+ workflow_run_id: str,
+ organization_id: str | None = None,
) -> EmailMessage:
msg = EmailMessage()
msg["Subject"] = (
@@ -3324,10 +3319,8 @@ class SendEmailBlock(Block):
file_names_by_hash: dict[str, list[str]] = defaultdict(list)
for filename in self._get_file_paths(workflow_run_context, workflow_run_id):
- if filename.startswith("s3://"):
- path = await download_from_s3(self.get_async_aws_client(), filename)
- elif filename.startswith("http://") or filename.startswith("https://"):
- path = await download_file(filename)
+ if filename.startswith(("s3://", "azure://", "http://", "https://")):
+ path = await download_file(filename, organization_id=organization_id)
else:
LOG.info("SendEmailBlock: Looking for file locally", filename=filename)
if not os.path.exists(filename):
@@ -3434,7 +3427,11 @@ class SendEmailBlock(Block):
smtp_host.starttls()
smtp_host.login(smtp_username_value, smtp_password_value)
LOG.info("SendEmailBlock: Logged in to SMTP server")
- message = await self._build_email_message(workflow_run_context, workflow_run_id)
+ message = await self._build_email_message(
+ workflow_run_context,
+ workflow_run_id,
+ organization_id=organization_id,
+ )
smtp_host.send_message(message)
LOG.info("SendEmailBlock: Email sent")
except Exception as e:
@@ -3876,11 +3873,8 @@ class FileParserBlock(Block):
)
try:
- # Download the file
- if self.file_url.startswith("s3://"):
- file_path = await download_from_s3(self.get_async_aws_client(), self.file_url)
- else:
- file_path = await download_file(self.file_url)
+ # Download the file.
+ file_path = await download_file(self.file_url, organization_id=organization_id)
# Auto-detect file type if not explicitly set (IMAGE/EXCEL/PDF/DOCX are explicit choices)
if self.file_type not in (FileType.IMAGE, FileType.EXCEL, FileType.PDF, FileType.DOCX):
@@ -4030,12 +4024,8 @@ class PDFParserBlock(Block):
organization_id=organization_id,
)
- # Download the file
- file_path = None
- if self.file_url.startswith("s3://"):
- file_path = await download_from_s3(self.get_async_aws_client(), self.file_url)
- else:
- file_path = await download_file(self.file_url)
+ # Download the file.
+ file_path = await download_file(self.file_url, organization_id=organization_id)
try:
extracted_text = extract_pdf_file(file_path, file_identifier=self.file_url)
@@ -4805,6 +4795,7 @@ class HttpRequestBlock(Block):
headers=self.headers,
output_dir=output_dir,
filename=self.download_filename,
+ organization_id=organization_id,
)
response_data = {
@@ -4944,11 +4935,11 @@ class HttpRequestBlock(Block):
else:
actual_file_path = file_path
- # Check if file_path is a URL or S3 URI
+ # Check if file_path is a URL or managed storage URI
is_url = (
file_path.startswith("http://") or file_path.startswith("https://") or file_path.startswith("www.")
)
- is_s3_uri = file_path.startswith("s3://")
+ is_managed_storage_uri = file_path.startswith("s3://") or file_path.startswith("azure://")
# Check if file is in allowed directories
is_allowed_local_file = False
@@ -4972,11 +4963,11 @@ class HttpRequestBlock(Block):
# Paths are on different drives (Windows) or incompatible
continue
- # If not URL, S3 URI, or allowed local file, reject
- if not (is_url or is_s3_uri or is_allowed_local_file):
+ # If not URL, managed storage URI, or allowed local file, reject
+ if not (is_url or is_managed_storage_uri or is_allowed_local_file):
return await self.build_block_result(
success=False,
- failure_reason=f"No permission to access local file: {file_path}. Only HTTP/HTTPS URLs, S3 URIs, or files in allowed directories are allowed.",
+ failure_reason=f"No permission to access local file: {file_path}. Only HTTP/HTTPS URLs, managed storage URIs, or files in allowed directories are allowed.",
output_parameter_value=None,
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
@@ -5010,12 +5001,9 @@ class HttpRequestBlock(Block):
field_name=field_name,
file_path=file_path,
is_url=is_url,
- is_s3_uri=is_s3_uri,
+ is_managed_storage_uri=is_managed_storage_uri,
)
- if is_s3_uri:
- local_file_path = await download_from_s3(self.get_async_aws_client(), file_path)
- else:
- local_file_path = await download_file(file_path)
+ local_file_path = await download_file(file_path, organization_id=organization_id)
downloaded_files[field_name] = local_file_path
LOG.info(
"HttpRequestBlock: File downloaded successfully",
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index acbd1ca38..acec05983 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -1609,7 +1609,7 @@ async def handle_upload_file_action(
locator = skyvern_element.locator
- file_path = await handler_utils.download_file(file_url, action.model_dump())
+ file_path = await handler_utils.download_file(file_url, action.model_dump(), task.organization_id)
is_file_input = await skyvern_element.is_file_input()
if not is_file_input:
@@ -2491,7 +2491,7 @@ async def chain_click(
file = pending_upload_files or []
if not file and action.file_url:
file_url = get_actual_value_of_parameter_if_secret_with_task(task, action.file_url)
- file = await handler_utils.download_file(file_url, action.model_dump())
+ file = await handler_utils.download_file(file_url, action.model_dump(), task.organization_id)
is_filechooser_trigger = False
diff --git a/skyvern/webeye/actions/handler_utils.py b/skyvern/webeye/actions/handler_utils.py
index 00c115de7..1a01490d1 100644
--- a/skyvern/webeye/actions/handler_utils.py
+++ b/skyvern/webeye/actions/handler_utils.py
@@ -11,9 +11,13 @@ from skyvern.forge.sdk.api.files import download_file as download_file_api
LOG = structlog.get_logger()
-async def download_file(file_url: str, action: dict[str, Any] | None = None) -> str | list[str]:
+async def download_file(
+ file_url: str,
+ action: dict[str, Any] | None = None,
+ organization_id: str | None = None,
+) -> str | list[str]:
try:
- return await download_file_api(file_url)
+ return await download_file_api(file_url, organization_id=organization_id)
except Exception:
LOG.exception(
"Failed to download file, continuing without it",
diff --git a/tests/unit/test_file_download_access_control.py b/tests/unit/test_file_download_access_control.py
new file mode 100644
index 000000000..c99944f6e
--- /dev/null
+++ b/tests/unit/test_file_download_access_control.py
@@ -0,0 +1,178 @@
+from __future__ import annotations
+
+import os
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from skyvern.config import settings
+from skyvern.constants import DOWNLOAD_FILE_PREFIX
+from skyvern.forge.sdk.api import files
+
+ATTACKER_ORG_ID = "o_attacker"
+VICTIM_ORG_ID = "o_victim"
+
+
+def _legacy_s3_uri(organization_id: str) -> str:
+ return f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/{organization_id}/secret.pdf"
+
+
+def _downloads_s3_uri(organization_id: str) -> str:
+ return (
+ f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/"
+ f"{DOWNLOAD_FILE_PREFIX}/{settings.ENV}/{organization_id}/wr_123/secret.pdf"
+ )
+
+
[email protected](autouse=True)
+def storage(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
+ def assert_managed_file_access(uri: str, organization_id: str) -> None:
+ if organization_id == ATTACKER_ORG_ID and (
+ uri == _legacy_s3_uri(ATTACKER_ORG_ID) or uri == _downloads_s3_uri(ATTACKER_ORG_ID)
+ ):
+ return
+ raise PermissionError(f"No permission to access storage URI: {uri}")
+
+ storage = SimpleNamespace(
+ storage_type="test",
+ assert_managed_file_access=MagicMock(side_effect=assert_managed_file_access),
+ download_managed_file=AsyncMock(return_value=b"tenant-secret-bytes"),
+ )
+ monkeypatch.setattr(files, "app", SimpleNamespace(STORAGE=storage))
+ return storage
+
+
+def test_validate_download_url_rejects_cross_org_s3_uri() -> None:
+ assert files.validate_download_url(_legacy_s3_uri(VICTIM_ORG_ID), organization_id=ATTACKER_ORG_ID) is False
+
+
+def test_validate_download_url_allows_same_org_downloads_prefix() -> None:
+ assert files.validate_download_url(_downloads_s3_uri(ATTACKER_ORG_ID), organization_id=ATTACKER_ORG_ID) is True
+
+
+async def test_download_file_rejects_cross_org_s3_uri(storage: SimpleNamespace) -> None:
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ await files.download_file(_legacy_s3_uri(VICTIM_ORG_ID), organization_id=ATTACKER_ORG_ID)
+
+ storage.assert_managed_file_access.assert_called_once_with(_legacy_s3_uri(VICTIM_ORG_ID), ATTACKER_ORG_ID)
+ storage.download_managed_file.assert_not_called()
+
+
+async def test_download_file_allows_same_org_legacy_upload(storage: SimpleNamespace) -> None:
+ path = await files.download_file(_legacy_s3_uri(ATTACKER_ORG_ID), organization_id=ATTACKER_ORG_ID)
+
+ storage.assert_managed_file_access.assert_called_once_with(_legacy_s3_uri(ATTACKER_ORG_ID), ATTACKER_ORG_ID)
+ storage.download_managed_file.assert_awaited_once_with(_legacy_s3_uri(ATTACKER_ORG_ID), ATTACKER_ORG_ID)
+ try:
+ with open(path, "rb") as f:
+ assert f.read() == b"tenant-secret-bytes"
+ finally:
+ os.unlink(path)
+
+
+async def test_download_file_allows_same_org_downloaded_artifact(storage: SimpleNamespace) -> None:
+ path = await files.download_file(_downloads_s3_uri(ATTACKER_ORG_ID), organization_id=ATTACKER_ORG_ID)
+
+ storage.assert_managed_file_access.assert_called_once_with(_downloads_s3_uri(ATTACKER_ORG_ID), ATTACKER_ORG_ID)
+ storage.download_managed_file.assert_awaited_once_with(_downloads_s3_uri(ATTACKER_ORG_ID), ATTACKER_ORG_ID)
+ try:
+ with open(path, "rb") as f:
+ assert f.read() == b"tenant-secret-bytes"
+ finally:
+ os.unlink(path)
+
+
+def test_validate_download_url_rejects_s3_uri_without_org_id() -> None:
+ assert files.validate_download_url(_legacy_s3_uri(ATTACKER_ORG_ID), organization_id=None) is False
+
+
+async def test_download_file_rejects_s3_uri_without_org_id(storage: SimpleNamespace) -> None:
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ await files.download_file(_legacy_s3_uri(ATTACKER_ORG_ID), organization_id=None)
+
+ storage.assert_managed_file_access.assert_not_called()
+ storage.download_managed_file.assert_not_called()
+
+
+def test_validate_download_url_allows_same_org_legacy_prefix() -> None:
+ assert files.validate_download_url(_legacy_s3_uri(ATTACKER_ORG_ID), organization_id=ATTACKER_ORG_ID) is True
+
+
+def test_validate_download_url_rejects_path_traversal() -> None:
+ uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/{ATTACKER_ORG_ID}/../{VICTIM_ORG_ID}/secret.pdf"
+ assert files.validate_download_url(uri, organization_id=ATTACKER_ORG_ID) is False
+
+
+def test_validate_download_url_rejects_different_bucket() -> None:
+ uri = f"s3://some-other-bucket/{settings.ENV}/{ATTACKER_ORG_ID}/file.csv"
+ assert files.validate_download_url(uri, organization_id=ATTACKER_ORG_ID) is False
+
+
+def test_validate_download_url_rejects_no_org_prefix() -> None:
+ uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/file.csv"
+ assert files.validate_download_url(uri, organization_id=ATTACKER_ORG_ID) is False
+
+
+def test_validate_download_url_rejects_wrong_env() -> None:
+ uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/production/{ATTACKER_ORG_ID}/file.csv"
+ assert files.validate_download_url(uri, organization_id=ATTACKER_ORG_ID) is False
+
+
+async def test_download_file_rejects_path_traversal(storage: SimpleNamespace) -> None:
+ uri = f"s3://{settings.AWS_S3_BUCKET_UPLOADS}/{settings.ENV}/{ATTACKER_ORG_ID}/../{VICTIM_ORG_ID}/secret.pdf"
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ await files.download_file(uri, organization_id=ATTACKER_ORG_ID)
+
+ storage.download_managed_file.assert_not_called()
+
+
+async def test_download_file_rejects_different_bucket(storage: SimpleNamespace) -> None:
+ uri = f"s3://some-other-bucket/{settings.ENV}/{ATTACKER_ORG_ID}/file.csv"
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ await files.download_file(uri, organization_id=ATTACKER_ORG_ID)
+
+ storage.download_managed_file.assert_not_called()
+
+
+def _legacy_azure_uri(organization_id: str) -> str:
+ return f"azure://{settings.AZURE_STORAGE_CONTAINER_UPLOADS}/{settings.ENV}/{organization_id}/secret.pdf"
+
+
+def test_validate_download_url_rejects_cross_org_azure_uri() -> None:
+ assert files.validate_download_url(_legacy_azure_uri(VICTIM_ORG_ID), organization_id=ATTACKER_ORG_ID) is False
+
+
+def test_validate_download_url_rejects_azure_uri_without_org_id() -> None:
+ assert files.validate_download_url(_legacy_azure_uri(ATTACKER_ORG_ID), organization_id=None) is False
+
+
+async def test_download_file_rejects_cross_org_azure_uri(storage: SimpleNamespace) -> None:
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ await files.download_file(_legacy_azure_uri(VICTIM_ORG_ID), organization_id=ATTACKER_ORG_ID)
+
+ storage.download_managed_file.assert_not_called()
+
+
+async def test_download_file_rejects_azure_uri_without_org_id(storage: SimpleNamespace) -> None:
+ with pytest.raises(PermissionError, match="No permission to access storage URI"):
+ await files.download_file(_legacy_azure_uri(ATTACKER_ORG_ID), organization_id=None)
+
+ storage.assert_managed_file_access.assert_not_called()
+ storage.download_managed_file.assert_not_called()
+
+
+async def test_download_file_reraises_permission_error() -> None:
+ """Verify PermissionError propagates to caller and is not silently caught."""
+ with pytest.raises(PermissionError, match="No permission") as exc_info:
+ await files.download_file(_legacy_s3_uri(VICTIM_ORG_ID), organization_id=ATTACKER_ORG_ID)
+ assert "No permission" in str(exc_info.value)