Skip to content

Automate browser based workflows with AI

Read files from an SFTP server as a File Download source (SKY-18299) (#9071)

Aaron Perez6329a8129fd8
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 0428d338e..5d17685f0 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -15285,6 +15285,17 @@
"download_target": {
"$ref": "#/components/schemas/FileDownloadTarget",
"default": "website"
+ },
+ "sftp_source_path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Source Path"
}
},
"type": "object",
@@ -15548,6 +15559,17 @@
],
"title": "Sftp Host Key"
},
+ "sftp_source_path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Source Path"
+ },
"path": {
"anyOf": [
{
diff --git a/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.test.ts b/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.test.ts
index 6e055ec01..5d7bbe373 100644
--- a/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/browserBlockUrl.test.ts
@@ -14,6 +14,7 @@ import {
navigationNodeDefaultData,
type NavigationNodeData,
} from "./nodes/NavigationNode/types";
+import { fileDownloadNodeDefaultData } from "./nodes/FileDownloadNode/types";
import { urlNodeDefaultData } from "./nodes/URLNode/types";
import { isMissingRequiredStartUrl } from "./workflowEditorUtils";
@@ -58,6 +59,27 @@ describe("isMissingRequiredStartUrl", () => {
expect(isMissingRequiredStartUrl(withUrl, edges, "first")).toBe(false);
});
+ test("an SFTP source needs no start URL and does not provide browser state", () => {
+ const sftpSource = {
+ id: "sftp-source",
+ type: "fileDownload",
+ position: { x: 0, y: 0 },
+ data: {
+ ...fileDownloadNodeDefaultData,
+ label: "sftp-source",
+ sftpSourcePath: "/reports/report.csv",
+ },
+ } as AppNode;
+ const nodes = [start, sftpSource, navigation("after-sftp")];
+ const edges = [
+ edge("start", "sftp-source"),
+ edge("sftp-source", "after-sftp"),
+ ];
+
+ expect(isMissingRequiredStartUrl(nodes, edges, "sftp-source")).toBe(false);
+ expect(isMissingRequiredStartUrl(nodes, edges, "after-sftp")).toBe(true);
+ });
+
test("a 2.0 block derives its own URL and does not open a page for later blocks", () => {
const nodes = [
start,
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/types.ts
index 33439a9b6..541b602b5 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/types.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/FileDownloadNode/types.ts
@@ -37,6 +37,7 @@ export type FileDownloadNodeData = NodeBaseData & {
sftpPrivateKeyPassphrase: string | null;
sftpRemotePath: string | null;
sftpHostKey: string | null;
+ sftpSourcePath: string | null;
continueOnEmpty: boolean;
};
@@ -81,6 +82,7 @@ export const fileDownloadNodeDefaultData: FileDownloadNodeData = {
sftpPrivateKeyPassphrase: null,
sftpRemotePath: null,
sftpHostKey: null,
+ sftpSourcePath: null,
continueOnEmpty: false,
ignoreWorkflowSystemPrompt: false,
} as const;
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts
index 142425ff8..8b2c6a030 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.test.ts
@@ -548,3 +548,76 @@ describe("block model override on save", () => {
});
});
});
+
+describe("FileDownloadBlock SFTP source round trip", () => {
+ test("preserves source path and shared credentials for website downloads", () => {
+ const sourceBlock = {
+ block_type: "file_download",
+ label: "read_report",
+ continue_on_failure: false,
+ next_loop_on_failure: false,
+ url: null,
+ title: "Read report",
+ navigation_goal: "Read the report",
+ error_code_mapping: null,
+ parameters: [],
+ download_target: "website",
+ path: "{{ workflow_run_id }}",
+ prompt: null,
+ sftp_source_path: "/reports/report.csv",
+ sftp_host: "sftp.example.test",
+ sftp_port: 2222,
+ sftp_username: "source_user",
+ sftp_password: "source_password",
+ sftp_private_key: "source_private_key",
+ sftp_private_key_passphrase: "source_passphrase",
+ sftp_host_key: "ssh-ed25519 AAAA",
+ } as unknown as WorkflowBlock;
+
+ const { nodes, edges } = getElements([sourceBlock], SETTINGS, true);
+ const fileDownloadNode = nodes.find((node) => node.type === "fileDownload");
+ expect(fileDownloadNode?.data).toMatchObject({
+ sftpSourcePath: "/reports/report.csv",
+ sftpHost: "sftp.example.test",
+ sftpPort: "2222",
+ sftpUsername: "source_user",
+ sftpPassword: "source_password",
+ sftpPrivateKey: "source_private_key",
+ sftpPrivateKeyPassphrase: "source_passphrase",
+ sftpHostKey: "ssh-ed25519 AAAA",
+ });
+
+ const savedFromNodes = getWorkflowBlocks(nodes, edges)[0];
+ expect(savedFromNodes).toMatchObject({
+ block_type: "file_download",
+ sftp_source_path: "/reports/report.csv",
+ sftp_host: "sftp.example.test",
+ sftp_port: 2222,
+ sftp_username: "source_user",
+ sftp_password: "source_password",
+ sftp_private_key: "source_private_key",
+ sftp_private_key_passphrase: "source_passphrase",
+ sftp_host_key: "ssh-ed25519 AAAA",
+ });
+ expect(savedFromNodes).not.toHaveProperty("sftp_remote_path");
+
+ const exportedBlock = convert({
+ workflow_definition: {
+ version: 1,
+ parameters: [],
+ blocks: [sourceBlock],
+ },
+ } as unknown as WorkflowApiResponse).workflow_definition.blocks[0];
+ expect(exportedBlock).toMatchObject({
+ sftp_source_path: "/reports/report.csv",
+ sftp_host: "sftp.example.test",
+ sftp_port: 2222,
+ sftp_username: "source_user",
+ sftp_password: "source_password",
+ sftp_private_key: "source_private_key",
+ sftp_private_key_passphrase: "source_passphrase",
+ sftp_host_key: "ssh-ed25519 AAAA",
+ });
+ expect(exportedBlock).not.toHaveProperty("sftp_remote_path");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
index 7aa0c367b..367380ad2 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
@@ -1102,6 +1102,7 @@ function convertToNode(
sftpPrivateKeyPassphrase: block.sftp_private_key_passphrase ?? "",
sftpRemotePath: block.sftp_remote_path ?? "",
sftpHostKey: block.sftp_host_key ?? "",
+ sftpSourcePath: block.sftp_source_path ?? "",
continueOnEmpty: block.continue_on_empty ?? false,
},
};
@@ -3602,22 +3603,26 @@ function getWorkflowBlock(
...(node.data.downloadTarget === "google_drive" && {
google_drive_folder_id: node.data.googleDriveFolderId ?? "",
}),
- ...(node.data.downloadTarget === "sftp" && {
- sftp_host: node.data.sftpHost ?? "",
- sftp_port:
- node.data.sftpPort &&
- Number.isFinite(Number(node.data.sftpPort))
- ? Number(node.data.sftpPort)
- : null,
- sftp_username: node.data.sftpUsername ?? "",
- sftp_password: node.data.sftpPassword ?? "",
- sftp_private_key: node.data.sftpPrivateKey ?? "",
- sftp_private_key_passphrase:
- node.data.sftpPrivateKeyPassphrase ?? "",
- sftp_remote_path: node.data.sftpRemotePath ?? "",
- sftp_host_key: node.data.sftpHostKey ?? "",
- }),
}),
+ ...((node.data.downloadTarget === "sftp" ||
+ node.data.sftpSourcePath) && {
+ sftp_host: node.data.sftpHost ?? "",
+ sftp_port:
+ node.data.sftpPort && Number.isFinite(Number(node.data.sftpPort))
+ ? Number(node.data.sftpPort)
+ : null,
+ sftp_username: node.data.sftpUsername ?? "",
+ sftp_password: node.data.sftpPassword ?? "",
+ sftp_private_key: node.data.sftpPrivateKey ?? "",
+ sftp_private_key_passphrase: node.data.sftpPrivateKeyPassphrase ?? "",
+ sftp_host_key: node.data.sftpHostKey ?? "",
+ ...(node.data.downloadTarget === "sftp" && {
+ sftp_remote_path: node.data.sftpRemotePath ?? "",
+ }),
+ ...(node.data.sftpSourcePath && {
+ sftp_source_path: node.data.sftpSourcePath,
+ }),
+ }),
};
}
case "sendEmail": {
@@ -4710,6 +4715,8 @@ function leavesBrowserState(node: AppNode, nodes: Array<AppNode>): boolean {
case "url":
return true;
case "fileDownload":
+ // An SFTP source bypasses super().execute entirely, so it leaves no page.
+ if (node.data.sftpSourcePath) return false;
// A Drive source download is fetched through the Drive API and skips
// super().execute entirely, so it leaves no page for a later block to
// start from. A maybe counts as the Drive path, which keeps the warning.
@@ -5208,18 +5215,23 @@ function convertBlocksToBlockYAML(
...(block.download_target === "google_drive" && {
google_drive_folder_id: block.google_drive_folder_id ?? "",
}),
- ...(block.download_target === "sftp" && {
- sftp_host: block.sftp_host ?? "",
- sftp_port: block.sftp_port ?? null,
- sftp_username: block.sftp_username ?? "",
- sftp_password: block.sftp_password ?? "",
- sftp_private_key: block.sftp_private_key ?? "",
- sftp_private_key_passphrase:
- block.sftp_private_key_passphrase ?? "",
- sftp_remote_path: block.sftp_remote_path ?? "",
- sftp_host_key: block.sftp_host_key ?? "",
- }),
}),
+ ...((block.download_target === "sftp" || block.sftp_source_path) && {
+ sftp_host: block.sftp_host ?? "",
+ sftp_port: block.sftp_port ?? null,
+ sftp_username: block.sftp_username ?? "",
+ sftp_password: block.sftp_password ?? "",
+ sftp_private_key: block.sftp_private_key ?? "",
+ sftp_private_key_passphrase:
+ block.sftp_private_key_passphrase ?? "",
+ sftp_host_key: block.sftp_host_key ?? "",
+ ...(block.download_target === "sftp" && {
+ sftp_remote_path: block.sftp_remote_path ?? "",
+ }),
+ ...(block.sftp_source_path && {
+ sftp_source_path: block.sftp_source_path,
+ }),
+ }),
};
return blockYaml;
}
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
index e63258fc1..f8390206d 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
@@ -659,6 +659,7 @@ export type FileDownloadBlock = WorkflowBlockBase & {
sftp_private_key_passphrase: string | null;
sftp_remote_path: string | null;
sftp_host_key: string | null;
+ sftp_source_path: string | null;
continue_on_empty: boolean;
};
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
index 32fdbc040..c65704a08 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
@@ -369,6 +369,7 @@ export type FileDownloadBlockYAML = BlockYAMLBase & {
sftp_private_key_passphrase?: string | null;
sftp_remote_path?: string | null;
sftp_host_key?: string | null;
+ sftp_source_path?: string | null;
continue_on_empty?: boolean;
url: string | null;
title?: string;
diff --git a/skyvern/core/script_generations/generate_script.py b/skyvern/core/script_generations/generate_script.py
index 59859254c..afc122c79 100644
--- a/skyvern/core/script_generations/generate_script.py
+++ b/skyvern/core/script_generations/generate_script.py
@@ -1768,6 +1768,20 @@ def _build_download_statement(
],
}
destination_fields = destination_fields_by_target.get(download_target)
+ source_fields = (
+ [
+ "sftp_source_path",
+ "sftp_host",
+ "sftp_port",
+ "sftp_username",
+ "sftp_password",
+ "sftp_private_key",
+ "sftp_private_key_passphrase",
+ "sftp_host_key",
+ ]
+ if block.get("sftp_source_path")
+ else []
+ )
if destination_fields is not None and block.get("prompt") is not None:
args[0] = args[0].with_changes(keyword=cst.Name("navigation_goal"))
@@ -1794,6 +1808,20 @@ def _build_download_statement(
),
)
)
+ for key in source_fields:
+ if destination_fields is not None and key in destination_fields:
+ continue
+ if block.get(key) is not None:
+ args.append(
+ cst.Arg(
+ keyword=cst.Name(key),
+ value=_value(block.get(key, "")),
+ whitespace_after_arg=cst.ParenthesizedWhitespace(
+ indent=True,
+ last_line=cst.SimpleWhitespace(INDENT),
+ ),
+ )
+ )
_mark_last_arg_as_comma(args)
call = cst.Call(
func=cst.Attribute(value=cst.Name("skyvern"), attr=cst.Name("download")),
diff --git a/skyvern/forge/sdk/services/file_download_utils.py b/skyvern/forge/sdk/services/file_download_utils.py
new file mode 100644
index 000000000..8a8ddd41e
--- /dev/null
+++ b/skyvern/forge/sdk/services/file_download_utils.py
@@ -0,0 +1,21 @@
+import os
+from pathlib import Path
+
+
+def publish_unique_download(temporary_path: Path, destination_dir: Path, filename: str) -> Path:
+ """Atomically publish a download without replacing an earlier run artifact."""
+ requested_path = destination_dir / filename
+ collision_index = 0
+ while True:
+ destination_path = (
+ requested_path
+ if collision_index == 0
+ else requested_path.with_name(f"{requested_path.stem} ({collision_index}){requested_path.suffix}")
+ )
+ try:
+ os.link(temporary_path, destination_path)
+ except FileExistsError:
+ collision_index += 1
+ continue
+ temporary_path.unlink()
+ return destination_path
diff --git a/skyvern/forge/sdk/services/google_drive_service.py b/skyvern/forge/sdk/services/google_drive_service.py
index 03592033a..f4462f13b 100644
--- a/skyvern/forge/sdk/services/google_drive_service.py
+++ b/skyvern/forge/sdk/services/google_drive_service.py
@@ -20,6 +20,7 @@ import httpx
from skyvern.config import settings
from skyvern.exceptions import DownloadFileMaxSizeExceeded
+from skyvern.forge.sdk.services.file_download_utils import publish_unique_download
DRIVE_UPLOAD_API_BASE = "https://www.googleapis.com/upload/drive/v3"
DRIVE_API_BASE = "https://www.googleapis.com/drive/v3"
@@ -634,28 +635,6 @@ def _downloadable_file_from_payload(payload: Mapping[str, Any], file_id: str) ->
)
-def _publish_unique_download(
- temporary_path: Path,
- destination_dir: Path,
- filename: str,
-) -> Path:
- requested_path = destination_dir / filename
- collision_index = 0
- while True:
- destination_path = (
- requested_path
- if collision_index == 0
- else requested_path.with_name(f"{requested_path.stem} ({collision_index}){requested_path.suffix}")
- )
- try:
- os.link(temporary_path, destination_path)
- except FileExistsError:
- collision_index += 1
- continue
- temporary_path.unlink()
- return destination_path
-
-
async def _get_download_metadata_with_retry(
client: httpx.AsyncClient,
url: str,
@@ -788,7 +767,7 @@ async def download_file(
break
else:
raise AssertionError("Drive download media retry loop exited without a response")
- destination_path = _publish_unique_download(temporary_path, destination_dir, metadata.name)
+ destination_path = publish_unique_download(temporary_path, destination_dir, metadata.name)
return str(destination_path)
except BaseException:
temporary_path.unlink(missing_ok=True)
diff --git a/skyvern/forge/sdk/services/sftp_service.py b/skyvern/forge/sdk/services/sftp_service.py
index 06c0d0fde..b60b3323a 100644
--- a/skyvern/forge/sdk/services/sftp_service.py
+++ b/skyvern/forge/sdk/services/sftp_service.py
@@ -1,44 +1,70 @@
import asyncio
import posixpath
+import tempfile
+from enum import StrEnum
from pathlib import Path
from typing import Any
+import aiofiles
import asyncssh
import structlog
from skyvern.config import settings
+from skyvern.constants import BROWSER_DOWNLOAD_TIMEOUT
+from skyvern.exceptions import BlockedHost, UnresolvableHost
+from skyvern.forge.sdk.services.file_download_utils import publish_unique_download
from skyvern.utils.url_validators import resolve_fetch_host_ips
LOG = structlog.get_logger()
+class SFTPDownloadErrorCategory(StrEnum):
+ AUTHENTICATION_FAILED = "authentication_failed"
+ HOST_KEY_MISSING = "host_key_missing"
+ HOST_KEY_MISMATCH = "host_key_mismatch"
+ PATH_NOT_FOUND = "path_not_found"
+ FILE_TOO_LARGE = "file_too_large"
+ HOST_BLOCKED = "host_blocked"
+ HOST_UNREACHABLE = "host_unreachable"
+ TRANSFER_FAILED = "transfer_failed"
+ REGISTRATION_FAILED = "registration_failed"
+ CONFIGURATION = "configuration"
+
+
+class SFTPDownloadError(Exception):
+ def __init__(self, category: SFTPDownloadErrorCategory, bytes_transferred: int = 0):
+ self.category = category
+ self.bytes_transferred = bytes_transferred
+ super().__init__(f"SFTP download failed ({category.value})")
+
+
def build_remote_target(remote_path: str | None, filename: str) -> str:
if remote_path:
return posixpath.join(remote_path, filename)
return filename
-async def upload_file(
+async def _connection_kwargs(
*,
- file_path: str,
host: str,
port: int,
username: str,
- remote_path: str | None = None,
- password: str | None = None,
- private_key: str | None = None,
- private_key_passphrase: str | None = None,
- host_key: str | None = None,
- connect_timeout: int = 30,
-) -> str:
+ password: str | None,
+ private_key: str | None,
+ private_key_passphrase: str | None,
+ host_key: str | None,
+ require_host_key: bool,
+ connect_timeout: int,
+) -> dict[str, Any]:
+ if require_host_key and (not host_key or not host_key.strip()):
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.HOST_KEY_MISSING)
+
connect_host = host
host_key_alias: str | None = None
if not settings.ALLOW_SFTP_INTERNAL_HOSTS:
resolved_ips = await asyncio.to_thread(resolve_fetch_host_ips, host)
connect_host = resolved_ips[0]
- # Connect directly to the validated address to prevent a second DNS
- # lookup from rebinding the hostname to an internal target. Keep the
- # configured hostname as the identity used for host-key validation.
+ # Keep the configured hostname as the identity used for host-key validation.
host_key_alias = host
connect_kwargs: dict[str, Any] = {
@@ -46,8 +72,7 @@ async def upload_file(
"port": port,
"username": username,
"connect_timeout": connect_timeout,
- # Authenticate only with the credentials configured on the block, never the
- # worker's ambient SSH identity (ssh config, agent, default keys, or GSSAPI).
+ # Use only block credentials, never the worker's ambient SSH identity.
"config": None,
"agent_path": None,
"gss_host": None,
@@ -61,9 +86,8 @@ async def upload_file(
known_hosts: bytes | None = f"{entry} {host_key}\n".encode()
else:
known_hosts = None
- # The host can be a value the workflow bound to a secret parameter, and `host` is
- # not redacted by log_redaction. The run context already identifies the block.
- LOG.warning("SFTP host key verification disabled; no host_key provided", port=port)
+ if not require_host_key:
+ LOG.warning("SFTP host key verification disabled; no host_key provided", port=port)
connect_kwargs["known_hosts"] = known_hosts
if private_key:
@@ -73,11 +97,135 @@ async def upload_file(
if password:
connect_kwargs["password"] = password
- async with asyncssh.connect(**connect_kwargs) as conn:
- async with conn.start_sftp_client() as sftp:
- filename = Path(file_path).name
- if remote_path:
- await sftp.makedirs(remote_path, exist_ok=True)
- remote_target = build_remote_target(remote_path, filename)
- await sftp.put(file_path, remote_target)
- return remote_target
+ return connect_kwargs
+
+
+async def upload_file(
+ *,
+ file_path: str,
+ host: str,
+ port: int,
+ username: str,
+ remote_path: str | None = None,
+ password: str | None = None,
+ private_key: str | None = None,
+ private_key_passphrase: str | None = None,
+ host_key: str | None = None,
+ connect_timeout: int = 30,
+) -> str:
+ connect_kwargs = await _connection_kwargs(
+ host=host,
+ port=port,
+ username=username,
+ password=password,
+ private_key=private_key,
+ private_key_passphrase=private_key_passphrase,
+ host_key=host_key,
+ require_host_key=False,
+ connect_timeout=connect_timeout,
+ )
+
+ async with asyncssh.connect(**connect_kwargs) as conn, conn.start_sftp_client() as sftp:
+ filename = Path(file_path).name
+ if remote_path:
+ await sftp.makedirs(remote_path, exist_ok=True)
+ remote_target = build_remote_target(remote_path, filename)
+ await sftp.put(file_path, remote_target)
+ return remote_target
+
+
+async def download_file(
+ *,
+ output_dir: str,
+ remote_path: str,
+ host: str,
+ port: int,
+ username: str,
+ password: str | None = None,
+ private_key: str | None = None,
+ private_key_passphrase: str | None = None,
+ host_key: str | None = None,
+ connect_timeout: int = 30,
+) -> str:
+ if not remote_path.strip() or not host.strip() or not username.strip() or not (password or private_key):
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.CONFIGURATION)
+
+ filename = Path(remote_path).name
+ if filename in {"", ".", ".."}:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.PATH_NOT_FOUND)
+
+ output_dir_path = Path(output_dir)
+ output_dir_path.mkdir(parents=True, exist_ok=True)
+ temporary_path: Path | None = None
+ byte_count = 0
+ max_size = settings.MAX_HTTP_DOWNLOAD_FILE_SIZE
+ deadline = asyncio.timeout(BROWSER_DOWNLOAD_TIMEOUT)
+
+ try:
+ with tempfile.NamedTemporaryFile(dir=output_dir_path, prefix=".sftp-", delete=False) as local_file:
+ temporary_path = Path(local_file.name)
+
+ async with deadline:
+ connect_kwargs = await _connection_kwargs(
+ host=host,
+ port=port,
+ username=username,
+ password=password,
+ private_key=private_key,
+ private_key_passphrase=private_key_passphrase,
+ host_key=host_key,
+ require_host_key=True,
+ connect_timeout=connect_timeout,
+ )
+ async with asyncssh.connect(**connect_kwargs) as conn, conn.start_sftp_client() as sftp:
+ attributes = await sftp.stat(remote_path)
+ if attributes.size is not None and attributes.size > max_size:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.FILE_TOO_LARGE)
+
+ async with (
+ sftp.open(remote_path, "rb") as remote_file,
+ aiofiles.open(temporary_path, "wb") as local_file,
+ ):
+ try:
+ while chunk := await remote_file.read(64 * 1024):
+ byte_count += len(chunk)
+ if byte_count > max_size:
+ raise SFTPDownloadError(
+ SFTPDownloadErrorCategory.FILE_TOO_LARGE,
+ bytes_transferred=byte_count,
+ )
+ await local_file.write(chunk)
+ except OSError as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.TRANSFER_FAILED, byte_count) from exc
+
+ try:
+ published_path = publish_unique_download(temporary_path, output_dir_path, filename)
+ except OSError as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.TRANSFER_FAILED, byte_count) from exc
+ return str(published_path)
+ except SFTPDownloadError:
+ raise
+ except UnresolvableHost as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.HOST_UNREACHABLE, byte_count) from exc
+ except BlockedHost as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.HOST_BLOCKED, byte_count) from exc
+ except asyncssh.PermissionDenied as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.AUTHENTICATION_FAILED, byte_count) from exc
+ except asyncssh.HostKeyNotVerifiable as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.HOST_KEY_MISMATCH, byte_count) from exc
+ except asyncssh.SFTPNoSuchFile as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.PATH_NOT_FOUND, byte_count) from exc
+ except asyncssh.SFTPError as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.TRANSFER_FAILED, byte_count) from exc
+ except TimeoutError as exc:
+ category = (
+ SFTPDownloadErrorCategory.TRANSFER_FAILED
+ if deadline.expired()
+ else SFTPDownloadErrorCategory.HOST_UNREACHABLE
+ )
+ raise SFTPDownloadError(category, byte_count) from exc
+ except (OSError, asyncssh.Error) as exc:
+ raise SFTPDownloadError(SFTPDownloadErrorCategory.HOST_UNREACHABLE, byte_count) from exc
+ finally:
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 70473aaaf..08aaf1219 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -16287,6 +16287,9 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
# Parameter 1 of Literal[...] cannot be of type "Any"
block_type: Literal[BlockType.FILE_DOWNLOAD] = BlockType.FILE_DOWNLOAD # type: ignore
download_target: FileDownloadTarget = FileDownloadTarget.WEBSITE
+ sftp_source_path: str | None = None
+
+ TEMPLATABLE_FIELDS: ClassVar[frozenset[str]] = frozenset({"sftp_source_path"})
def get_all_parameters(self, workflow_run_id: str) -> list[PARAMETER_TYPE]:
parameters = super().get_all_parameters(workflow_run_id)
@@ -16296,9 +16299,13 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
if destination_param.key not in existing_keys:
parameters.append(destination_param)
existing_keys.add(destination_param.key)
+ if self.sftp_source_path and workflow_run_context.has_parameter(self.sftp_source_path):
+ source_param = workflow_run_context.get_parameter(self.sftp_source_path)
+ if source_param.key not in existing_keys:
+ parameters.append(source_param)
return parameters
- async def _register_authenticated_google_drive_download(
+ async def _register_authenticated_download(
self,
*,
organization_id: str,
@@ -16314,9 +16321,9 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
organization_id=organization_id,
run_id=run_download_id,
)
- except asyncio.TimeoutError:
+ except TimeoutError:
LOG.warning(
- "Timeout saving authenticated Google Drive download; workflow finalization will retry",
+ "Timeout saving direct file download; workflow finalization will retry",
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
)
@@ -16324,17 +16331,16 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
except DownloadSaveIncompleteError as exc:
skipped_files = set(exc.skipped_files)
LOG.warning(
- "Storage partially saved authenticated Google Drive download; workflow finalization will retry",
+ "Storage partially saved direct file download; workflow finalization will retry",
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
skipped_file_count=len(skipped_files),
)
- except Exception:
+ except Exception: # noqa: BLE001 -- workflow finalization retries registration failures.
LOG.warning(
- "Failed to save authenticated Google Drive download; workflow finalization will retry",
+ "Failed to save direct file download; workflow finalization will retry",
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
- exc_info=True,
)
return None
@@ -16344,23 +16350,38 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
organization_id=organization_id,
run_id=run_download_id,
)
- except asyncio.TimeoutError:
+ except TimeoutError:
LOG.warning(
- "Timeout reading back authenticated Google Drive download",
+ "Timeout reading back direct file download",
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
)
return None
- except Exception:
+ except Exception: # noqa: BLE001 -- workflow finalization retries registration failures.
LOG.warning(
- "Failed to read back authenticated Google Drive download",
+ "Failed to read back direct file download",
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
- exc_info=True,
)
return None
return None if filename in skipped_files else downloaded_files
+ @staticmethod
+ def _matching_authenticated_download(
+ file_path: str,
+ downloaded_files: list[FileInfo] | None,
+ ) -> list[FileInfo] | None:
+ if downloaded_files is None:
+ return None
+ filename = Path(file_path).name
+ checksum = calculate_sha256_for_file(file_path)
+ filename_matches = [file_info for file_info in downloaded_files if file_info.filename == filename]
+ checksum_matches = [file_info for file_info in filename_matches if file_info.checksum == checksum]
+ if checksum_matches:
+ return checksum_matches
+ checksumless_matches = [file_info for file_info in filename_matches if file_info.checksum is None]
+ return checksumless_matches if len(checksumless_matches) == 1 else []
+
async def _download_authenticated_google_drive_source(
self,
*,
@@ -16424,24 +16445,14 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
)
return None
- downloaded_files = await self._register_authenticated_google_drive_download(
+ downloaded_files = await self._register_authenticated_download(
organization_id=org_id,
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
run_download_id=run_download_id,
filename=Path(file_path).name,
)
- filename = Path(file_path).name
- matching_files: list[FileInfo] | None = None
- if downloaded_files is not None:
- checksum = calculate_sha256_for_file(file_path)
- filename_matches = [file_info for file_info in downloaded_files if file_info.filename == filename]
- checksum_matches = [file_info for file_info in filename_matches if file_info.checksum == checksum]
- if checksum_matches:
- matching_files = checksum_matches
- else:
- checksumless_matches = [file_info for file_info in filename_matches if file_info.checksum is None]
- matching_files = checksumless_matches if len(checksumless_matches) == 1 else []
+ matching_files = self._matching_authenticated_download(file_path, downloaded_files)
if matching_files == []:
raise RuntimeError(DOWNLOAD_BINDING_FAILURE_REASON)
return (
@@ -16450,6 +16461,131 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
google_credentials.token,
)
+ async def _download_authenticated_sftp_source(
+ self,
+ *,
+ workflow_run_context: WorkflowRunContext,
+ organization_id: str | None,
+ workflow_run_id: str,
+ run_download_id: str,
+ workflow_run_block_id: str,
+ download_files_path: str,
+ ) -> tuple[str, list[FileInfo], None]:
+ category = sftp_service.SFTPDownloadErrorCategory.CONFIGURATION
+ byte_count = 0
+ succeeded = False
+ started_at = monotonic()
+ org_id = organization_id or workflow_run_context.organization_id
+ try:
+ if not org_id:
+ raise sftp_service.SFTPDownloadError(sftp_service.SFTPDownloadErrorCategory.CONFIGURATION)
+
+ def render(field: str, value: str | None) -> str | None:
+ if not value:
+ return value
+ return self.render_templatable_field(field, value, workflow_run_context)
+
+ host = _resolve_block_secret_reference(workflow_run_context, render("sftp_host", self.sftp_host))
+ remote_path = _resolve_block_secret_reference(
+ workflow_run_context,
+ render("sftp_source_path", self.sftp_source_path),
+ )
+ username = _resolve_block_secret_reference(
+ workflow_run_context,
+ render("sftp_username", self.sftp_username),
+ )
+ host_key = _resolve_block_secret_reference(
+ workflow_run_context,
+ render("sftp_host_key", self.sftp_host_key),
+ )
+ password = await _resolve_sensitive_block_secret(
+ workflow_run_context,
+ render("sftp_password", self.sftp_password),
+ "sftp_password",
+ )
+ private_key = await _resolve_sensitive_block_secret(
+ workflow_run_context,
+ render("sftp_private_key", self.sftp_private_key),
+ "sftp_private_key",
+ )
+ passphrase = await _resolve_sensitive_block_secret(
+ workflow_run_context,
+ render("sftp_private_key_passphrase", self.sftp_private_key_passphrase),
+ "sftp_private_key_passphrase",
+ )
+ if (
+ not host
+ or not host.strip()
+ or not remote_path
+ or not remote_path.strip()
+ or not username
+ or not username.strip()
+ or not (password or private_key)
+ ):
+ raise sftp_service.SFTPDownloadError(sftp_service.SFTPDownloadErrorCategory.CONFIGURATION)
+
+ category = sftp_service.SFTPDownloadErrorCategory.TRANSFER_FAILED
+ file_path = await sftp_service.download_file(
+ output_dir=download_files_path,
+ remote_path=remote_path,
+ host=host,
+ port=22 if self.sftp_port is None else self.sftp_port,
+ username=username,
+ password=password,
+ private_key=private_key,
+ private_key_passphrase=passphrase,
+ host_key=host_key,
+ )
+ byte_count = os.path.getsize(file_path)
+ registered_files = await self._register_authenticated_download(
+ organization_id=org_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ run_download_id=run_download_id,
+ filename=Path(file_path).name,
+ )
+ matching_files = self._matching_authenticated_download(file_path, registered_files)
+ if not matching_files:
+ raise sftp_service.SFTPDownloadError(
+ sftp_service.SFTPDownloadErrorCategory.REGISTRATION_FAILED,
+ bytes_transferred=byte_count,
+ )
+ LOG.info(
+ "FileDownloadBlock SFTP source completed",
+ organization_id=org_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ outcome="success",
+ error_category=None,
+ byte_count=byte_count,
+ duration_ms=int((monotonic() - started_at) * 1000),
+ )
+ succeeded = True
+ return file_path, matching_files, None
+ except sftp_service.SFTPDownloadError as exc:
+ category = exc.category
+ byte_count = exc.bytes_transferred or byte_count
+ raise
+ except Exception as exc:
+ raise sftp_service.SFTPDownloadError(category, byte_count) from exc
+ finally:
+ if not succeeded:
+ with contained_effect(
+ "SFTP source failure log",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ ):
+ LOG.warning(
+ "FileDownloadBlock SFTP source failed",
+ organization_id=org_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ outcome="failure",
+ error_category=category.value,
+ byte_count=byte_count,
+ duration_ms=int((monotonic() - started_at) * 1000),
+ )
+
async def execute(
self,
workflow_run_id: str,
@@ -16461,11 +16597,21 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
download_files_path = ""
run_download_id = workflow_run_id
direct_google_access_token: str | None = None
+ attempt_started_at: datetime | None = None
baseline_unknown = False
pre_names: set[str] = set()
pre_hashes: dict[str, str] = {}
pre_mtimes: dict[str, int] = {}
colliding_normalized_names: set[str] = set()
+ if self.sftp_source_path and self.download_target == FileDownloadTarget.WEBSITE:
+ early_context = self.get_workflow_run_context(workflow_run_id)
+ context = skyvern_context.current()
+ run_download_id = resolve_run_download_id(context, fallback_run_id=workflow_run_id) or workflow_run_id
+ download_files_path = str(get_path_for_workflow_download_directory(run_download_id).absolute())
+ attempt_started_at = await get_download_retry_started_at(
+ organization_id or early_context.organization_id,
+ run_download_id,
+ )
if self.download_target != FileDownloadTarget.WEBSITE:
# Fail fast on a misconfigured destination before running the (expensive) browser
# download, so a missing required field does not waste a download that cannot be delivered.
@@ -16538,8 +16684,29 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
organization_id=organization_id,
)
- direct_download: tuple[str, list[FileInfo] | None, str] | None = None
- if self.download_target != FileDownloadTarget.WEBSITE:
+ direct_download: tuple[str, list[FileInfo] | None, str | None] | None = None
+ if self.sftp_source_path:
+ workflow_run_context = self.get_workflow_run_context(workflow_run_id)
+ try:
+ direct_download = await self._download_authenticated_sftp_source(
+ workflow_run_context=workflow_run_context,
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ run_download_id=run_download_id,
+ workflow_run_block_id=workflow_run_block_id,
+ download_files_path=download_files_path,
+ )
+ except sftp_service.SFTPDownloadError as exc:
+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, None)
+ return await self.build_block_result(
+ success=False,
+ failure_reason=f"Failed to download file from SFTP: {exc.category.value}",
+ output_parameter_value=None,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ elif self.download_target != FileDownloadTarget.WEBSITE:
workflow_run_context = self.get_workflow_run_context(workflow_run_id)
try:
direct_download = await self._download_authenticated_google_drive_source(
@@ -16599,6 +16766,9 @@ class FileDownloadBlock(BaseTaskBlock, FileDestinationBlock):
organization_id=organization_id,
)
+ if self.download_target == FileDownloadTarget.WEBSITE:
+ return result
+
storage_type = FileStorageType(self.download_target.value)
workflow_run_context = self.get_workflow_run_context(workflow_run_id)
try:
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index beb31eee8..2ef082e40 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -918,6 +918,7 @@ def block_yaml_to_block(
sftp_private_key_passphrase=block_yaml.sftp_private_key_passphrase,
sftp_remote_path=block_yaml.sftp_remote_path,
sftp_host_key=block_yaml.sftp_host_key,
+ sftp_source_path=block_yaml.sftp_source_path,
path=block_yaml.path,
prompt=block_yaml.prompt,
continue_on_empty=block_yaml.continue_on_empty,
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index ee2d89024..48ffd0ae2 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -1490,6 +1490,7 @@ class FileDownloadBlockYAML(BlockYAML):
sftp_private_key_passphrase: str | None = None
sftp_remote_path: str | None = None
sftp_host_key: str | None = None
+ sftp_source_path: str | None = None
path: str | None = None
prompt: str | None = None
continue_on_empty: bool = False
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index 97b7e81dc..24794c817 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -2555,6 +2555,7 @@ async def download(
sftp_private_key_passphrase: str | None = None,
sftp_remote_path: str | None = None,
sftp_host_key: str | None = None,
+ sftp_source_path: str | None = None,
path: str | None = None,
continue_on_empty: bool | None = None,
) -> None:
@@ -2595,6 +2596,8 @@ async def download(
sftp_remote_path = _render_template_with_label(sftp_remote_path, cache_key)
if sftp_host_key:
sftp_host_key = _render_template_with_label(sftp_host_key, cache_key)
+ if sftp_source_path:
+ sftp_source_path = _render_template_with_label(sftp_source_path, cache_key)
if destination_prompt:
destination_prompt = _render_template_with_label(destination_prompt, cache_key)
if path:
@@ -2621,11 +2624,12 @@ async def download(
"sftp_private_key_passphrase": sftp_private_key_passphrase,
"sftp_remote_path": sftp_remote_path,
"sftp_host_key": sftp_host_key,
+ "sftp_source_path": sftp_source_path,
"prompt": destination_prompt,
"path": path,
"continue_on_empty": continue_on_empty if continue_on_empty is not None else False,
}
- cached_fn = script_run_context_manager.get_cached_fn(cache_key)
+ cached_fn = None if sftp_source_path else script_run_context_manager.get_cached_fn(cache_key)
context: skyvern_context.SkyvernContext | None
if cache_key and cached_fn:
_refuse_statement_after_browser_connection_loss()
diff --git a/tests/unit/test_file_download_targets.py b/tests/unit/test_file_download_targets.py
index c23359a47..57eaca123 100644
--- a/tests/unit/test_file_download_targets.py
+++ b/tests/unit/test_file_download_targets.py
@@ -16,13 +16,14 @@ from skyvern.config import settings
from skyvern.exceptions import AzureConfigurationError, BlockedHost, DownloadSaveIncompleteError, UnresolvableHost
from skyvern.forge.sdk.api.llm.api_handler_factory import LLMAPIHandlerFactory
from skyvern.forge.sdk.schemas.files import FileInfo
-from skyvern.forge.sdk.services import google_drive_service, google_oauth_service
+from skyvern.forge.sdk.services import google_drive_service, google_oauth_service, sftp_service
from skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, FileDownloadBlock
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
from skyvern.forge.sdk.workflow.workflow_definition_converter import block_yaml_to_block
from skyvern.schemas.workflows import (
BlockResult,
BlockStatus,
+ BlockType,
FileDownloadBlockYAML,
FileDownloadTarget,
FileStorageType,
@@ -112,6 +113,11 @@ async def _execute_file_download(
block.sftp_password,
block.sftp_private_key,
block.sftp_private_key_passphrase,
+ block.sftp_host,
+ block.sftp_username,
+ block.sftp_host_key,
+ block.sftp_source_path,
+ block.sftp_remote_path,
block.google_credential_id,
)
if value
@@ -423,6 +429,124 @@ async def test_google_drive_api_file_not_downloadable_does_not_fall_back_to_brow
execution.record_output.assert_awaited_once()
+async def test_sftp_source_downloads_without_browser_and_binds_registered_file(tmp_path: Path) -> None:
+ payload = b"id,value\n1,ok\n"
+ download_dir = tmp_path / "downloads"
+ block = _file_download_block(
+ FileDownloadTarget.WEBSITE,
+ sftp_host="host-ref",
+ sftp_port=2222,
+ sftp_username="username-ref",
+ sftp_password="password-ref",
+ sftp_source_path="path-ref",
+ sftp_host_key="host-key-ref",
+ )
+ downloaded_file = FileInfo(
+ url="https://app.example.test/artifacts/private",
+ checksum=hashlib.sha256(payload).hexdigest(),
+ filename="report.csv",
+ file_size=len(payload),
+ artifact_id="artifact-private",
+ )
+
+ async def download_source(**kwargs: object) -> str:
+ assert kwargs["host"] == "resolved-host"
+ assert kwargs["remote_path"] == "/reports/report.csv"
+ assert kwargs["username"] == "resolved-user"
+ assert kwargs["password"] == "resolved-password"
+ assert kwargs["host_key"] == "resolved-host-key"
+ path = Path(str(kwargs["output_dir"])) / "report.csv"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(payload)
+ return str(path)
+
+ with patch(
+ "skyvern.forge.sdk.workflow.models.block.sftp_service.download_file",
+ new_callable=AsyncMock,
+ side_effect=download_source,
+ ) as sftp_download:
+ execution = await _execute_file_download(
+ block,
+ _browser_result(block),
+ download_dir,
+ secret_values={
+ "host-ref": "resolved-host",
+ "path-ref": "/reports/report.csv",
+ "username-ref": "resolved-user",
+ "password-ref": "resolved-password",
+ "host-key-ref": "resolved-host-key",
+ },
+ downloaded_file_infos=[downloaded_file],
+ )
+
+ assert execution.result.success is True
+ assert execution.result.output_parameter_value["file_name"] == "report.csv"
+ assert execution.result.output_parameter_value["downloaded_files"][0]["filename"] == "report.csv"
+ execution.browser_execute.assert_not_awaited()
+ execution.storage_save.assert_awaited_once_with(organization_id="organization-id", run_id="workflow-run-id")
+ execution.upload.assert_not_awaited()
+ sftp_download.assert_awaited_once()
+
+
+def test_file_download_sftp_source_is_optional_and_round_trips_yaml() -> None:
+ base = {
+ "block_type": BlockType.FILE_DOWNLOAD,
+ "label": "download",
+ "navigation_goal": "Download the requested file.",
+ }
+ legacy_yaml = FileDownloadBlockYAML(**base)
+ legacy_block = block_yaml_to_block(legacy_yaml, {"download_output": _output_parameter()}, workflow_id="workflow-id")
+ assert legacy_yaml.sftp_source_path is None
+ assert legacy_block.sftp_source_path is None
+
+ source_yaml = FileDownloadBlockYAML(**base, sftp_source_path="/reports/report.csv")
+ source_block = block_yaml_to_block(source_yaml, {"download_output": _output_parameter()}, workflow_id="workflow-id")
+ assert source_block.sftp_source_path == "/reports/report.csv"
+
+
+async def test_sftp_source_failure_does_not_fall_back_to_browser(tmp_path: Path) -> None:
+ block = _file_download_block(
+ FileDownloadTarget.WEBSITE,
+ sftp_host="sftp.example.test",
+ sftp_username="user",
+ sftp_password="password",
+ sftp_source_path="/reports/report.csv",
+ )
+ error = sftp_service.SFTPDownloadError(sftp_service.SFTPDownloadErrorCategory.HOST_KEY_MISMATCH)
+
+ with patch(
+ "skyvern.forge.sdk.workflow.models.block.sftp_service.download_file",
+ new_callable=AsyncMock,
+ side_effect=error,
+ ):
+ execution = await _execute_file_download(block, _browser_result(block), tmp_path / "downloads")
+
+ assert execution.result.success is False
+ assert execution.result.failure_reason == "Failed to download file from SFTP: host_key_mismatch"
+ execution.browser_execute.assert_not_awaited()
+ execution.record_output.assert_awaited_once()
+
+
+async def test_sftp_source_template_failure_is_configuration_error(tmp_path: Path) -> None:
+ block = _file_download_block(
+ FileDownloadTarget.WEBSITE,
+ sftp_host="sftp.example.test",
+ sftp_username="user",
+ sftp_password="password",
+ sftp_source_path="/reports/report.csv",
+ )
+
+ with patch.object(FileDownloadBlock, "render_templatable_field", side_effect=ValueError("invalid template")):
+ execution = await _execute_file_download(block, _browser_result(block), tmp_path / "downloads")
+
+ assert execution.result.success is False
+ assert execution.result.failure_reason == "Failed to download file from SFTP: configuration"
+ execution.browser_execute.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_sftp_target_dispatches_each_download_and_preserves_browser_result(tmp_path: Path) -> None:
download_dir = tmp_path / "downloads"
diff --git a/tests/unit/test_script_service_block_outcome.py b/tests/unit/test_script_service_block_outcome.py
index 38225adc7..450be8107 100644
--- a/tests/unit/test_script_service_block_outcome.py
+++ b/tests/unit/test_script_service_block_outcome.py
@@ -472,6 +472,45 @@ async def test_uncached_download_failure_after_browser_loss_raises_the_typed_ref
await script_service.download(prompt="Download the invoice", label="invoice")
+async def test_sftp_source_download_bypasses_cached_browser_download(
+ cached_run: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ cached_lookup = MagicMock(side_effect=AssertionError("SFTP sources must bypass cached browser downloads"))
+ monkeypatch.setattr(script_service.script_run_context_manager, "get_cached_fn", cached_lookup)
+ executed_blocks: list[FileDownloadBlock] = []
+
+ async def execute_source(block: FileDownloadBlock, **_: object) -> BlockResult:
+ executed_blocks.append(block)
+ return BlockResult(
+ success=True,
+ output_parameter=make_block_output_parameter("download_output"),
+ status=BlockStatus.completed,
+ )
+
+ monkeypatch.setattr(FileDownloadBlock, "execute_safe", execute_source)
+
+ await script_service.download(
+ prompt="Read the report",
+ label="sftp_source",
+ sftp_source_path="/reports/report.csv",
+ sftp_host="sftp.example.test",
+ sftp_port=2222,
+ sftp_username="source_user",
+ sftp_password="source_password",
+ sftp_host_key="ssh-ed25519 AAAA",
+ )
+
+ cached_lookup.assert_not_called()
+ assert len(executed_blocks) == 1
+ assert executed_blocks[0].sftp_source_path == "/reports/report.csv"
+ assert executed_blocks[0].sftp_host == "sftp.example.test"
+ assert executed_blocks[0].sftp_port == 2222
+ assert executed_blocks[0].sftp_username == "source_user"
+ assert executed_blocks[0].sftp_password == "source_password"
+ assert executed_blocks[0].sftp_host_key == "ssh-ed25519 AAAA"
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("complete_if_empty", "expected_status", "expected_reason"),
diff --git a/tests/unit/test_sftp_upload.py b/tests/unit/test_sftp_upload.py
index 482f396cd..8fa3b1388 100644
--- a/tests/unit/test_sftp_upload.py
+++ b/tests/unit/test_sftp_upload.py
@@ -1,10 +1,15 @@
+import asyncio
+from contextlib import asynccontextmanager
+from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
+import asyncssh
import libcst as cst
import pytest
from skyvern.core.script_generations.generate_script import _build_download_statement, _build_file_upload_statement
-from skyvern.exceptions import BlockedHost
+from skyvern.exceptions import BlockedHost, UnresolvableHost
from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.sdk.services import sftp_service
from skyvern.schemas.workflows import FileStorageType, FileUploadDestination
@@ -47,6 +52,263 @@ def _sftp_destination(**overrides) -> FileUploadDestination:
return FileUploadDestination(**fields)
+@asynccontextmanager
+async def _sftp_test_server(root: Path, password: str = "pw"):
+ class Server(asyncssh.SSHServer):
+ def begin_auth(self, username: str) -> bool:
+ return True
+
+ def password_auth_supported(self) -> bool:
+ return True
+
+ def validate_password(self, username: str, supplied_password: str) -> bool:
+ return supplied_password == password
+
+ server_key = asyncssh.generate_private_key("ssh-ed25519")
+ server = await asyncssh.create_server(
+ Server,
+ "127.0.0.1",
+ 0,
+ server_host_keys=[server_key],
+ sftp_factory=lambda channel: asyncssh.SFTPServer(channel, chroot=str(root)),
+ )
+ try:
+ yield server, server_key
+ finally:
+ server.close()
+ await server.wait_closed()
+
+
+def _sftp_public_key(key) -> str:
+ return key.export_public_key().decode().strip()
+
+
+async def _download_from_server(server, host_key: str | None, **overrides) -> str:
+ args = {
+ "host": "sftp.test",
+ "port": server.get_port(),
+ "username": "user",
+ "password": "pw",
+ "remote_path": "/report.csv",
+ "output_dir": ".",
+ "host_key": host_key,
+ }
+ args.update(overrides)
+ with patch.object(sftp_service, "resolve_fetch_host_ips", return_value=("127.0.0.1",)):
+ return await sftp_service.download_file(**args)
+
+
+async def test_sftp_service_download_file_reads_and_pins_host_key(tmp_path, monkeypatch):
+ remote_root = tmp_path / "remote"
+ remote_root.mkdir()
+ (remote_root / "report.csv").write_bytes(b"id,value\n1,ok\n")
+ output_dir = tmp_path / "downloads"
+ monkeypatch.setattr(sftp_service.settings, "ALLOW_SFTP_INTERNAL_HOSTS", False)
+
+ async with _sftp_test_server(remote_root) as (server, server_key):
+ path = await _download_from_server(
+ server,
+ _sftp_public_key(server_key),
+ output_dir=str(output_dir),
+ )
+
+ assert Path(path).read_bytes() == b"id,value\n1,ok\n"
+ assert Path(path).name == "report.csv"
+
+
+async def test_sftp_service_download_file_preserves_same_basename_reads(tmp_path, monkeypatch):
+ remote_root = tmp_path / "remote"
+ remote_root.mkdir()
+ remote_file = remote_root / "report.csv"
+ remote_file.write_bytes(b"first report")
+ output_dir = tmp_path / "downloads"
+ monkeypatch.setattr(sftp_service.settings, "ALLOW_SFTP_INTERNAL_HOSTS", False)
+
+ async with _sftp_test_server(remote_root) as (server, server_key):
+ first_path = await _download_from_server(
+ server,
+ _sftp_public_key(server_key),
+ output_dir=str(output_dir),
+ )
+ remote_file.write_bytes(b"second report")
+ second_path = await _download_from_server(
+ server,
+ _sftp_public_key(server_key),
+ output_dir=str(output_dir),
+ )
+
+ assert first_path != second_path
+ assert Path(first_path).name == "report.csv"
+ assert Path(second_path).name == "report (1).csv"
+ assert Path(first_path).read_bytes() == b"first report"
+ assert Path(second_path).read_bytes() == b"second report"
+
+
+async def test_sftp_service_download_file_enforces_overall_timeout(tmp_path, monkeypatch):
+ monkeypatch.setattr(sftp_service, "BROWSER_DOWNLOAD_TIMEOUT", 0.05)
+ monkeypatch.setattr(sftp_service.settings, "ALLOW_SFTP_INTERNAL_HOSTS", True)
+
+ async def slow_read(_size: int) -> bytes:
+ await asyncio.sleep(1)
+ return b"report"
+
+ remote_file = MagicMock()
+ remote_file.read = AsyncMock(side_effect=slow_read)
+ sftp = MagicMock()
+ sftp.stat = AsyncMock(return_value=SimpleNamespace(size=6))
+ sftp.open = MagicMock(return_value=_acm(remote_file))
+ conn = MagicMock()
+ conn.start_sftp_client = MagicMock(return_value=_acm(sftp))
+
+ with (
+ patch.object(sftp_service.asyncssh, "connect", return_value=_acm(conn)),
+ pytest.raises(sftp_service.SFTPDownloadError) as error,
+ ):
+ await sftp_service.download_file(
+ output_dir=str(tmp_path / "downloads"),
+ remote_path="/report.csv",
+ host="sftp.test",
+ port=22,
+ username="user",
+ password="pw",
+ host_key="ssh-ed25519 AAAA",
+ )
+
+ assert error.value.category == sftp_service.SFTPDownloadErrorCategory.TRANSFER_FAILED
+ assert not list((tmp_path / "downloads").glob("report*"))
+ assert not list((tmp_path / "downloads").glob(".sftp-*"))
+
+
+async def test_sftp_service_download_file_requires_a_pinned_host_key(tmp_path):
+ async with _sftp_test_server(tmp_path) as (server, _server_key):
+ with pytest.raises(sftp_service.SFTPDownloadError) as error:
+ await _download_from_server(server, None, output_dir=str(tmp_path / "downloads"))
+
+ assert error.value.category == sftp_service.SFTPDownloadErrorCategory.HOST_KEY_MISSING
+
+
+async def test_sftp_service_download_file_rejects_mismatched_host_key(tmp_path):
+ async with _sftp_test_server(tmp_path) as (server, _server_key):
+ mismatched_key = asyncssh.generate_private_key("ssh-ed25519")
+ with pytest.raises(sftp_service.SFTPDownloadError) as error:
+ await _download_from_server(
+ server,
+ _sftp_public_key(mismatched_key),
+ output_dir=str(tmp_path / "downloads"),
+ )
+
+ assert error.value.category == sftp_service.SFTPDownloadErrorCategory.HOST_KEY_MISMATCH
+
+
+async def test_sftp_service_download_file_classifies_authentication_failure(tmp_path):
+ async with _sftp_test_server(tmp_path) as (server, server_key):
+ with pytest.raises(sftp_service.SFTPDownloadError) as error:
+ await _download_from_server(
+ server,
+ _sftp_public_key(server_key),
+ password="wrong",
+ output_dir=str(tmp_path / "downloads"),
+ )
+
+ assert error.value.category == sftp_service.SFTPDownloadErrorCategory.AUTHENTICATION_FAILED
+
+
+async def test_sftp_service_download_file_classifies_missing_remote_path(tmp_path):
+ async with _sftp_test_server(tmp_path) as (server, server_key):
+ with pytest.raises(sftp_service.SFTPDownloadError) as error:
+ await _download_from_server(
+ server,
+ _sftp_public_key(server_key),
+ output_dir=str(tmp_path / "downloads"),
+ )
+
+ assert error.value.category == sftp_service.SFTPDownloadErrorCategory.PATH_NOT_FOUND
+
+
+async def test_sftp_service_download_file_enforces_existing_size_cap(tmp_path, monkeypatch):
+ (tmp_path / "report.csv").write_bytes(b"larger than cap")
+ monkeypatch.setattr(sftp_service.settings, "MAX_HTTP_DOWNLOAD_FILE_SIZE", 3)
+
+ async with _sftp_test_server(tmp_path) as (server, server_key):
+ with pytest.raises(sftp_service.SFTPDownloadError) as error:
+ await _download_from_server(
+ server,
+ _sftp_public_key(server_key),
+ output_dir=str(tmp_path / "downloads"),
+ )
+
+ assert error.value.category == sftp_service.SFTPDownloadErrorCategory.FILE_TOO_LARGE
+ assert not (tmp_path / "downloads" / "report.csv").exists()
+
+
+async def test_sftp_service_download_file_classifies_blocked_host(tmp_path):
+ with (
+ patch.object(sftp_service, "resolve_fetch_host_ips", side_effect=BlockedHost(host="127.0.0.1")),
+ pytest.raises(sftp_service.SFTPDownloadError) as error,
+ ):
+ await sftp_service.download_file(
+ host="sftp.test",
+ port=22,
+ username="user",
+ password="pw",
+ remote_path="/report.csv",
+ output_dir=str(tmp_path / "downloads"),
+ host_key="ssh-ed25519 AAAA",
+ )
+
+ assert error.value.category == sftp_service.SFTPDownloadErrorCategory.HOST_BLOCKED
+
+
+async def test_sftp_service_download_file_classifies_unresolvable_host(tmp_path):
+ with (
+ patch.object(sftp_service, "resolve_fetch_host_ips", side_effect=UnresolvableHost(host="sftp.test")),
+ pytest.raises(sftp_service.SFTPDownloadError) as error,
+ ):
+ await sftp_service.download_file(
+ host="sftp.test",
+ port=22,
+ username="user",
+ password="pw",
+ remote_path="/report.csv",
+ output_dir=str(tmp_path / "downloads"),
+ host_key="ssh-ed25519 AAAA",
+ )
+
+ assert error.value.category == sftp_service.SFTPDownloadErrorCategory.HOST_UNREACHABLE
+
+
+async def test_sftp_service_upload_still_allows_missing_host_key(tmp_path, monkeypatch):
+ remote_root = tmp_path / "remote"
+ remote_root.mkdir()
+ file_path = _write_file(tmp_path)
+ monkeypatch.setattr(sftp_service.settings, "ALLOW_SFTP_INTERNAL_HOSTS", False)
+
+ async with _sftp_test_server(remote_root) as (server, _server_key):
+ with patch.object(sftp_service, "resolve_fetch_host_ips", return_value=("127.0.0.1",)):
+ result = await sftp_service.upload_file(
+ file_path=file_path,
+ host="sftp.test",
+ port=server.get_port(),
+ username="user",
+ password="pw",
+ remote_path="/incoming",
+ )
+
+ assert result == "/incoming/f.csv"
+ assert (remote_root / "incoming" / "f.csv").read_text() == "data"
+
+
@pytest.mark.asyncio
async def test_sftp_service_upload_file_uses_password_auth_and_remote_path(tmp_path):
file_path = _write_file(tmp_path)
@@ -365,6 +627,37 @@ def test_generated_website_download_with_stale_prompt_keeps_required_navigation_
assert "continue_on_empty=" not in compact
+def test_generated_website_sftp_source_emits_source_and_shared_credentials():
+ block = {
+ "block_type": "file_download",
+ "label": "download",
+ "navigation_goal": "Download the file",
+ "download_target": "website",
+ "sftp_source_path": "/reports/report.csv",
+ "sftp_host": "sftp.example.test",
+ "sftp_port": 2222,
+ "sftp_username": "user",
+ "sftp_password": "password",
+ "sftp_private_key": "private-key",
+ "sftp_private_key_passphrase": "passphrase",
+ "sftp_host_key": "ssh-ed25519 AAAA",
+ "sftp_remote_path": "/stale-destination",
+ }
+
+ compact = cst.Module(body=[_build_download_statement("download", block)]).code.replace(" ", "").replace("\n", "")
+
+ assert "download_target=" not in compact
+ assert "sftp_source_path='/reports/report.csv'" in compact
+ assert "sftp_host='sftp.example.test'" in compact
+ assert "sftp_port=2222" in compact
+ assert "sftp_username='user'" in compact
+ assert "sftp_password='password'" in compact
+ assert "sftp_private_key='private-key'" in compact
+ assert "sftp_private_key_passphrase='passphrase'" in compact
+ assert "sftp_host_key='ssh-ed25519AAAA'" in compact
+ assert "sftp_remote_path=" not in compact
+
+
def test_generated_external_download_omits_other_targets_stale_secrets():
block = {
"block_type": "file_download",