Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement sftp source (#73753)

Tom Owerse1d5e2016571
diff --git a/frontend/public/services/sftp.png b/frontend/public/services/sftp.png
deleted file mode 100644
index 36a8fdd691a3..000000000000
Binary files a/frontend/public/services/sftp.png and /dev/null differ
diff --git a/frontend/public/services/sftp.svg b/frontend/public/services/sftp.svg
new file mode 100644
index 000000000000..4ea28592033f
--- /dev/null
+++ b/frontend/public/services/sftp.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="none" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#EEEFF2"/><path fill="#fff" stroke="#8F90A6" stroke-width="2.5" stroke-linejoin="round" d="M17.5 14.75A2.25 2.25 0 0 1 19.75 12.5h15.19a2.25 2.25 0 0 1 1.59.66l9.06 9.06c.42.42.66 1 .66 1.59v25.44a2.25 2.25 0 0 1-2.25 2.25h-24.5a2.25 2.25 0 0 1-2.25-2.25V14.75Z"/><path stroke="#8F90A6" stroke-width="2.5" stroke-linejoin="round" d="M35.5 13v9a2 2 0 0 0 2 2h9"/><circle cx="45" cy="45" r="11" fill="#1D4AFF"/><path stroke="#fff" stroke-width="2.5" stroke-linecap="round" d="M42 43.5v-2.25a3 3 0 0 1 6 0v2.25"/><rect width="12" height="8.5" x="39" y="43.25" rx="2" fill="#fff"/></svg>
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index a4e02dad2ab4..a5edb6618802 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -28,6 +28,7 @@ vendor's API, see [COVERAGE_GAPS.md](COVERAGE_GAPS.md), refreshed by the
| **HTTP (vendor SDK)** | The vendor ships its own SDK that wraps HTTP. Where the SDK exposes a session/transport hook, we inject `make_tracked_session()` so the calls are still tracked. |
| **gRPC** | The vendor SDK uses gRPC over HTTP/2 (binary, not REST). Routed through the [tracked gRPC transport](common/grpc/) via client interceptors (see `common/grpc/`). |
| **DB protocol** | Native database wire protocol via a driver (e.g. PostgreSQL, MySQL, Snowflake). Not HTTP. |
+| **SSH (SFTP)** | SFTP over an SSH transport via `paramiko`. Not HTTP, so neither the HTTP nor the gRPC tracked transport applies. |
| **Webhook (S3-buffered)** | Vendor pushes events to a webhook endpoint; payloads are buffered to S3 by the `WebhookSourceManager` and consumed by the pipeline. |
When a source uses more than one transport (e.g. BigQuery REST + Storage gRPC, or Stripe pull-API + webhooks),
@@ -566,6 +567,7 @@ the row lists both.
| sentinelone | HTTP | requests | ✅ |
| sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |
| servicenow | HTTP | requests | ✅ |
+| sftp | SSH (SFTP) | paramiko | ➖ |
| shippo | HTTP | requests | ✅ |
| shipstation | HTTP | requests | ✅ |
| shopify | HTTP | requests | ✅ |
@@ -1315,7 +1317,6 @@ doesn't conflict with concurrent PRs.
- sevalla
- sevdesk
- sevenshifts
-- sftp
- sharepoint
- sharetribe
- shippo
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sftp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sftp.py
index 0d1ffd3b96dd..bf05a0e36a58 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sftp.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sftp.py
@@ -1,9 +1,33 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
+class SFTPAuthTypeConfig(config.Config):
+ selection: Literal["password", "ssh_key"] = "password"
+ password: str | None = None
+ private_key: str | None = None
+ passphrase: str | None = None
+
+
+class SFTPCombineFilesConfig(config.Config):
+ table_name: str
+ enabled: bool = config.value(converter=config.str_to_bool, default=False)
+
+
@config.config
class SFTPSourceConfig(config.Config):
- pass
+ host: str
+ user: str
+ auth_type: SFTPAuthTypeConfig
+ path: str
+ port: int = config.value(converter=int)
+ file_pattern: str | None = None
+ file_format: Literal["infer", "csv", "jsonl", "json"] = config.value(default="infer")
+ csv_delimiter: str | None = None
+ combine_files: SFTPCombineFilesConfig | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/settings.py
new file mode 100644
index 000000000000..788b327c21d0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/settings.py
@@ -0,0 +1,48 @@
+from typing import Literal
+
+FileFormat = Literal["csv", "jsonl", "json"]
+ConfiguredFileFormat = Literal["infer", "csv", "jsonl", "json"]
+
+DEFAULT_PORT = 22
+CONNECT_TIMEOUT_SECONDS = 30
+# Per-operation read timeout for directory and file transfers. A responsive server keeps data
+# flowing well within this, so it only trips on a stalled server holding an iterator thread.
+READ_TIMEOUT_SECONDS = 300
+
+# A whole-document JSON file has to be materialized to parse it, so cap how many decompressed bytes
+# we read before giving up and steering the user to JSON Lines (which streams). Also stops a small
+# gzip file from decompressing into unbounded memory.
+MAX_JSON_DOCUMENT_BYTES = 256 * 1024 * 1024
+
+# Paramiko builds one prefetch descriptor per 32 KiB block up to the requested size, so a server that
+# reports an enormous file size could balloon that list. Cap it: bytes past this are read on demand.
+MAX_PREFETCH_BYTES = 256 * 1024 * 1024
+
+# A remote tree is walked breadth-first with all three bounds enforced: an SFTP server can expose an
+# arbitrarily deep/wide tree, and discovery has to terminate without the user configuring limits.
+MAX_DIRECTORY_DEPTH = 5
+MAX_FILES = 1000
+# Depth and file count alone don't bound the walk: `MAX_FILES` counts only files matching the
+# pattern, so a pattern matching nothing (or a tree of nothing but folders) leaves the breadth of
+# each level unbounded. Capping how many folders are ever queued bounds both the listing round trips
+# and the queue itself.
+MAX_DIRECTORIES = 1000
+
+CHUNK_SIZE = 5000
+
+# Every row carries which file it came from, so a table built from many files stays traceable.
+FILE_PATH_COLUMN = "_file_name"
+FILE_MODIFIED_AT_COLUMN = "_file_modified_at"
+
+EXTENSION_FORMATS: dict[str, FileFormat] = {
+ ".csv": "csv",
+ ".tsv": "csv",
+ ".txt": "csv",
+ ".jsonl": "jsonl",
+ ".ndjson": "jsonl",
+ ".json": "json",
+}
+
+EXTENSION_DELIMITERS: dict[str, str] = {".tsv": "\t"}
+
+DEFAULT_DELIMITER = ","
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/sftp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/sftp.py
new file mode 100644
index 000000000000..e72f0c58f44a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/sftp.py
@@ -0,0 +1,620 @@
+import io
+import re
+import csv
+import gzip
+import json
+import stat
+import socket
+import posixpath
+import dataclasses
+from collections.abc import Generator, Iterable, Iterator
+from contextlib import contextmanager
+from datetime import UTC, datetime
+from io import StringIO
+from typing import IO, Any, Protocol, cast
+
+import re2
+import paramiko
+from structlog.types import FilteringBoundLogger
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.models.ssh_tunnel import from_private_key
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.settings import (
+ CHUNK_SIZE,
+ CONNECT_TIMEOUT_SECONDS,
+ DEFAULT_DELIMITER,
+ EXTENSION_DELIMITERS,
+ EXTENSION_FORMATS,
+ FILE_MODIFIED_AT_COLUMN,
+ FILE_PATH_COLUMN,
+ MAX_DIRECTORIES,
+ MAX_DIRECTORY_DEPTH,
+ MAX_FILES,
+ MAX_JSON_DOCUMENT_BYTES,
+ MAX_PREFETCH_BYTES,
+ READ_TIMEOUT_SECONDS,
+ ConfiguredFileFormat,
+ FileFormat,
+)
+
+# Error message prefixes. `get_non_retryable_errors` matches on these, so they have to stay stable
+# and stay out of the interpolated part of each message.
+AUTH_FAILED_ERROR = "SFTP authentication failed"
+CONNECTION_FAILED_ERROR = "Couldn't connect to the SFTP server"
+PRIVATE_KEY_ERROR = "The SSH private key could not be read"
+DIRECTORY_ERROR = "Couldn't read the remote directory"
+PATTERN_ERROR = "The file pattern isn't a valid regular expression"
+NO_FILES_ERROR = "No remote files are available for table"
+NO_MATCHING_FILES_ERROR = "No importable files were found"
+FORMAT_ERROR = "Can't work out the format of the remote file"
+DELIMITER_ERROR = "The CSV delimiter must be a single character"
+
+
+class SFTPCredentialsError(Exception):
+ """A permanent configuration problem: unreachable host, rejected credentials, missing directory."""
+
+
+class SFTPFileFormatError(Exception):
+ """A remote file couldn't be parsed with the configured (or inferred) format."""
+
+
+class RemoteAttributes(Protocol):
+ filename: str
+ st_mode: int | None
+ st_size: int | None
+ st_mtime: float | int | None
+
+
+class RemoteClient(Protocol):
+ """The slice of `paramiko.SFTPClient` this source uses."""
+
+ def listdir_attr(self, path: str) -> list[Any]: ...
+
+ def open(self, filename: str, mode: str = "r", bufsize: int = -1) -> Any: ...
+
+
[email protected](frozen=True)
+class RemoteFile:
+ path: str
+ relative_path: str
+ size: int
+ modified_at: datetime
+
+
[email protected](frozen=True)
+class ResolvedFormat:
+ file_format: FileFormat
+ delimiter: str
+ compressed: bool
+
+
+def normalize_remote_path(path: str | None) -> str:
+ stripped = (path or "").strip()
+ if not stripped:
+ return "."
+ normalized = posixpath.normpath(stripped)
+ return normalized.rstrip("/") or "/"
+
+
+def normalize_delimiter(delimiter: str | None) -> str | None:
+ """Accept a literal tab, an escaped `\\t`, or the word `tab` for tab-separated files."""
+ if delimiter is None:
+ return None
+ if delimiter in ("\\t", "tab", "\t"):
+ return "\t"
+ if delimiter == "":
+ return None
+ if len(delimiter) != 1:
+ raise SFTPCredentialsError(f"{DELIMITER_ERROR} (got {delimiter!r}). Use \\t for tab-separated files.")
+ return delimiter
+
+
+def load_private_key(private_key: str, passphrase: str | None = None) -> paramiko.PKey:
+ try:
+ return from_private_key(StringIO(private_key), passphrase or None)
+ except Exception as e:
+ raise SFTPCredentialsError(
+ f"{PRIVATE_KEY_ERROR}. Paste the full private key including the -----BEGIN and -----END lines, "
+ "and check the passphrase if the key is encrypted."
+ ) from e
+
+
+@frozen
+class SFTPAuth:
+ """How to authenticate as the configured user: a password, or an SSH key with optional passphrase."""
+
+ password: str | None = dataclasses.field(default=None, repr=False)
+ private_key: str | None = dataclasses.field(default=None, repr=False)
+ passphrase: str | None = dataclasses.field(default=None, repr=False)
+
+ def pkey(self) -> paramiko.PKey | None:
+ return load_private_key(self.private_key, self.passphrase) if self.private_key else None
+
+
+@contextmanager
+def sftp_connection(
+ host: str,
+ port: int,
+ user: str,
+ auth: SFTPAuth,
+ timeout: int = CONNECT_TIMEOUT_SECONDS,
+) -> Generator[paramiko.SFTPClient]:
+ pkey = auth.pkey()
+
+ try:
+ sock = socket.create_connection((host, port), timeout=timeout)
+ except OSError as e:
+ raise SFTPCredentialsError(
+ f"{CONNECTION_FAILED_ERROR} at {host}:{port}. Check the host and port, and that the server "
+ "accepts connections from the public internet."
+ ) from e
+
+ # The connect timeout must not linger as a read timeout — a large file transfer can idle
+ # longer than the handshake ever should.
+ sock.settimeout(None)
+ transport = paramiko.Transport(sock)
+ transport.banner_timeout = timeout
+
+ try:
+ try:
+ transport.connect(username=user, password=auth.password or None, pkey=pkey)
+ except paramiko.AuthenticationException as e:
+ raise SFTPCredentialsError(
+ f"{AUTH_FAILED_ERROR} for user '{user}'. Check the username and password or SSH key."
+ ) from e
+ except (paramiko.SSHException, OSError) as e:
+ raise SFTPCredentialsError(f"{CONNECTION_FAILED_ERROR} at {host}:{port}: {e}") from e
+
+ client = paramiko.SFTPClient.from_transport(transport)
+ if client is None:
+ raise SFTPCredentialsError(
+ f"{CONNECTION_FAILED_ERROR} at {host}:{port}: the server didn't open an SFTP session. "
+ "Check that the SFTP subsystem is enabled for this user."
+ )
+
+ # Bound directory and file reads so a server that connects and then stalls can't hold an
+ # iterator thread indefinitely. The handshake is already bounded by `banner_timeout`.
+ channel = client.get_channel()
+ if channel is not None:
+ channel.settimeout(READ_TIMEOUT_SECONDS)
+
+ try:
+ yield client
+ finally:
+ client.close()
+ finally:
+ transport.close()
+
+
+def _to_datetime(mtime: float | int | None) -> datetime:
+ return datetime.fromtimestamp(mtime or 0, tz=UTC)
+
+
+class CompiledPattern(Protocol):
+ def search(self, string: str) -> object | None: ...
+
+
+def _compile_pattern(pattern: str | None) -> CompiledPattern | None:
+ if not pattern:
+ return None
+ # re2 is linear-time, so a user-supplied pattern can't pin a worker CPU by backtracking on a
+ # long filename (matching runs during discovery and every sync, before the file-count limit).
+ try:
+ return cast(CompiledPattern, re2.compile(pattern))
+ except re2.error as e:
+ raise SFTPCredentialsError(f"{PATTERN_ERROR}: {e}") from e
+
+
+def list_remote_files(
+ client: RemoteClient,
+ root: str,
+ pattern: str | None = None,
+ max_depth: int = MAX_DIRECTORY_DEPTH,
+ max_files: int = MAX_FILES,
+ max_directories: int = MAX_DIRECTORIES,
+ logger: FilteringBoundLogger | None = None,
+) -> list[RemoteFile]:
+ """List regular files under `root`, breadth-first, filtered by `pattern` on the relative path."""
+ compiled = _compile_pattern(pattern)
+ root = normalize_remote_path(root)
+
+ files: list[RemoteFile] = []
+ queue: list[tuple[str, int]] = [(root, 0)]
+ queued_directories = 1
+ skipped_directories = False
+
+ while queue:
+ directory, depth = queue.pop(0)
+ try:
+ entries = cast(list[RemoteAttributes], client.listdir_attr(directory))
+ except OSError as e:
+ if directory == root:
+ raise SFTPCredentialsError(
+ f"{DIRECTORY_ERROR} '{directory}'. Check that it exists and that the user can read it."
+ ) from e
+ if logger is not None:
+ logger.warning("Skipping unreadable SFTP directory", directory=directory, error=str(e))
+ continue
+
+ for entry in sorted(entries, key=lambda e: e.filename):
+ if entry.filename in (".", ".."):
+ continue
+ full_path = posixpath.join(directory, entry.filename)
+ mode = entry.st_mode or 0
+ if stat.S_ISDIR(mode):
+ if depth < max_depth:
+ if queued_directories >= max_directories:
+ skipped_directories = True
+ continue
+ queue.append((full_path, depth + 1))
+ queued_directories += 1
+ continue
+ # Anything that isn't a plain file (symlinks, sockets, devices) is skipped: following
+ # links risks cycles, and only regular files can be parsed.
+ if not stat.S_ISREG(mode):
+ continue
+
+ relative_path = posixpath.relpath(full_path, root)
+ if compiled is not None and not compiled.search(relative_path):
+ continue
+
+ files.append(
+ RemoteFile(
+ path=full_path,
+ relative_path=relative_path,
+ size=entry.st_size or 0,
+ modified_at=_to_datetime(entry.st_mtime),
+ )
+ )
+
+ if len(files) >= max_files:
+ if logger is not None:
+ logger.warning(
+ "Reached the SFTP file limit; later files are ignored",
+ root=root,
+ max_files=max_files,
+ )
+ return sorted(files, key=lambda f: f.relative_path)
+
+ if skipped_directories and logger is not None:
+ logger.warning(
+ "Reached the SFTP folder limit; later folders are ignored",
+ root=root,
+ max_directories=max_directories,
+ )
+
+ return sorted(files, key=lambda f: f.relative_path)
+
+
+def sanitize_table_name(name: str) -> str:
+ sanitized = re.sub(r"[^0-9a-zA-Z]+", "_", name).strip("_").lower()
+ return sanitized or "sftp_data"
+
+
+def table_name_for_file(relative_path: str) -> str:
+ without_compression = re.sub(r"\.gz$", "", relative_path, flags=re.IGNORECASE)
+ stem = posixpath.splitext(without_compression)[0]
+ return sanitize_table_name(stem)
+
+
+def group_files_by_table(
+ files: Iterable[RemoteFile], combined_table_name: str | None = None
+) -> dict[str, list[RemoteFile]]:
+ """Map table name -> the files feeding it.
+
+ One table per file by default; a single combined table when the user opted into that. Names are
+ derived from the (sorted) relative paths, so the same remote tree always produces the same tables.
+ """
+ ordered = sorted(files, key=lambda f: f.relative_path)
+
+ if combined_table_name:
+ return {sanitize_table_name(combined_table_name): ordered}
+
+ grouped: dict[str, list[RemoteFile]] = {}
+ for file in ordered:
+ base = table_name_for_file(file.relative_path)
+ name = base
+ suffix = 2
+ while name in grouped:
+ name = f"{base}_{suffix}"
+ suffix += 1
+ grouped[name] = [file]
+ return grouped
+
+
+def is_format_inferable(relative_path: str) -> bool:
+ lowered = relative_path.lower()
+ if lowered.endswith(".gz"):
+ lowered = lowered[: -len(".gz")]
+ return posixpath.splitext(lowered)[1] in EXTENSION_FORMATS
+
+
+def parseable_files(
+ files: Iterable[RemoteFile], configured_format: ConfiguredFileFormat | str | None = "infer"
+) -> list[RemoteFile]:
+ """Drop files whose format can't be worked out, so discovery never offers a table that can't sync.
+
+ An explicit file format applies to every matched file, so nothing is dropped then. Both discovery
+ and the sync filter identically — otherwise the same remote tree would produce different table names.
+ """
+ if configured_format and configured_format != "infer":
+ return list(files)
+ return [file for file in files if is_format_inferable(file.relative_path)]
+
+
+def resolve_file_format(
+ relative_path: str,
+ configured_format: ConfiguredFileFormat | str | None = "infer",
+ delimiter: str | None = None,
+) -> ResolvedFormat:
+ lowered = relative_path.lower()
+ compressed = lowered.endswith(".gz")
+ if compressed:
+ lowered = lowered[: -len(".gz")]
+ extension = posixpath.splitext(lowered)[1]
+
+ if configured_format and configured_format != "infer":
+ file_format = cast(FileFormat, configured_format)
+ else:
+ inferred = EXTENSION_FORMATS.get(extension)
+ if inferred is None:
+ raise SFTPFileFormatError(
+ f"{FORMAT_ERROR} '{relative_path}'. Set the file format explicitly, or restrict the file "
+ "pattern to .csv, .json, or .jsonl files."
+ )
+ file_format = inferred
+
+ resolved_delimiter = normalize_delimiter(delimiter) or EXTENSION_DELIMITERS.get(extension, DEFAULT_DELIMITER)
+ return ResolvedFormat(file_format=file_format, delimiter=resolved_delimiter, compressed=compressed)
+
+
+def normalize_column_name(header: str) -> str:
+ """Headers like 'Order Total (USD)' become stable snake_case columns."""
+ normalized = re.sub(r"[^0-9a-zA-Z]+", "_", header).strip("_").lower()
+ return normalized or "column"
+
+
+def _dedupe_headers(headers: list[str]) -> list[str]:
+ seen: dict[str, int] = {}
+ result = []
+ for header in headers:
+ name = normalize_column_name(header)
+ if name in seen:
+ seen[name] += 1
+ name = f"{name}_{seen[name]}"
+ else:
+ seen[name] = 1
+ result.append(name)
+ return result
+
+
+def _decompressed_stream(stream: IO[bytes], compressed: bool) -> IO[bytes]:
+ return cast(IO[bytes], gzip.GzipFile(fileobj=stream)) if compressed else stream
+
+
+def _text_stream(binary: IO[bytes]) -> IO[str]:
+ return io.TextIOWrapper(binary, encoding="utf-8", errors="replace", newline="")
+
+
+def _iter_csv_rows(
+ text: IO[str],
+ delimiter: str,
+ relative_path: str,
+ chunk_size: int,
+ logger: FilteringBoundLogger | None,
+) -> Iterator[list[dict[str, Any]]]:
+ reader = csv.reader(text, delimiter=delimiter)
+ headers: list[str] | None = None
+ chunk: list[dict[str, Any]] = []
+
+ for line_number, row in enumerate(reader, start=1):
+ if headers is None:
+ headers = _dedupe_headers(row)
+ continue
+ if not any(cell.strip() for cell in row):
+ continue
+ if len(row) > len(headers):
+ # More values than headers means the file is malformed or the delimiter is wrong.
+ # Dropping the row keeps the extra values from silently landing in the wrong columns.
+ if logger is not None:
+ logger.warning(
+ "Skipping SFTP CSV row with more values than headers",
+ file=relative_path,
+ line=line_number,
+ expected=len(headers),
+ got=len(row),
+ )
+ continue
+ values: list[str | None] = [*row, *([None] * (len(headers) - len(row)))]
+ chunk.append(dict(zip(headers, values)))
+ if len(chunk) >= chunk_size:
+ yield chunk
+ chunk = []
+
+ if chunk:
+ yield chunk
+
+
+def _as_rows(value: Any) -> list[dict[str, Any]]:
+ if isinstance(value, dict):
+ return [value]
+ if isinstance(value, list):
+ return [item if isinstance(item, dict) else {"value": item} for item in value]
+ return [{"value": value}]
+
+
+def _iter_jsonl_rows(text: IO[str], relative_path: str, chunk_size: int) -> Iterator[list[dict[str, Any]]]:
+ chunk: list[dict[str, Any]] = []
+ for line_number, line in enumerate(text, start=1):
+ if not line.strip():
+ continue
+ try:
+ parsed = json.loads(line)
+ except json.JSONDecodeError as e:
+ raise SFTPFileFormatError(
+ f"Line {line_number} of '{relative_path}' isn't valid JSON: {e}. If the file holds one "
+ "JSON document rather than one object per line, set the file format to JSON."
+ ) from e
+ chunk.extend(_as_rows(parsed))
+ if len(chunk) >= chunk_size:
+ yield chunk
+ chunk = []
+ if chunk:
+ yield chunk
+
+
+def _iter_json_rows(binary: IO[bytes], relative_path: str, chunk_size: int) -> Iterator[list[dict[str, Any]]]:
+ # A whole-document JSON file can't be chunked, so it has to fit in memory. Read one decompressed
+ # byte past the limit to detect an oversized (or gzip-bomb) document before materializing it, and
+ # point the user at JSON Lines, which streams. The byte cap is what bounds memory here, so it runs
+ # on the decompressed bytes rather than a decoded-character count.
+ raw = binary.read(MAX_JSON_DOCUMENT_BYTES + 1)
+ if len(raw) > MAX_JSON_DOCUMENT_BYTES:
+ raise SFTPFileFormatError(
+ f"'{relative_path}' is larger than the {MAX_JSON_DOCUMENT_BYTES // (1024 * 1024)} MB limit for a "
+ "single JSON document. Convert it to JSON Lines (one object per line) so it can stream in."
+ )
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError as e:
+ raise SFTPFileFormatError(
+ f"'{relative_path}' isn't valid JSON: {e}. If the file holds one JSON object per line, "
+ "set the file format to JSON Lines."
+ ) from e
+
+ rows = _as_rows(parsed)
+ for start in range(0, len(rows), chunk_size):
+ yield rows[start : start + chunk_size]
+
+
+def iter_file_rows(
+ stream: IO[bytes],
+ resolved: ResolvedFormat,
+ relative_path: str,
+ chunk_size: int = CHUNK_SIZE,
+ logger: FilteringBoundLogger | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ binary = _decompressed_stream(stream, resolved.compressed)
+ if resolved.file_format == "csv":
+ yield from _iter_csv_rows(_text_stream(binary), resolved.delimiter, relative_path, chunk_size, logger)
+ elif resolved.file_format == "jsonl":
+ yield from _iter_jsonl_rows(_text_stream(binary), relative_path, chunk_size)
+ else:
+ yield from _iter_json_rows(binary, relative_path, chunk_size)
+
+
+def iter_table_rows(
+ client: RemoteClient,
+ files: Iterable[RemoteFile],
+ configured_format: ConfiguredFileFormat | str | None = "infer",
+ delimiter: str | None = None,
+ chunk_size: int = CHUNK_SIZE,
+ logger: FilteringBoundLogger | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ for file in files:
+ resolved = resolve_file_format(file.relative_path, configured_format, delimiter)
+ with client.open(file.path, "rb") as handle:
+ prefetch = getattr(handle, "prefetch", None)
+ if callable(prefetch) and file.size:
+ # Cap what we ask paramiko to prefetch so a server that reports a huge size can't
+ # blow up the prefetch descriptor list; bytes past the cap are read on demand.
+ prefetch(min(file.size, MAX_PREFETCH_BYTES))
+ for chunk in iter_file_rows(handle, resolved, file.relative_path, chunk_size, logger):
+ yield [
+ {
+ **row,
+ FILE_PATH_COLUMN: file.relative_path,
+ FILE_MODIFIED_AT_COLUMN: file.modified_at,
+ }
+ for row in chunk
+ ]
+
+
+def get_rows(
+ host: str,
+ port: int,
+ user: str,
+ schema_name: str,
+ auth: SFTPAuth,
+ path: str = "/",
+ file_pattern: str | None = None,
+ configured_format: ConfiguredFileFormat | str | None = "infer",
+ delimiter: str | None = None,
+ combined_table_name: str | None = None,
+ logger: FilteringBoundLogger | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ with sftp_connection(host=host, port=port, user=user, auth=auth) as client:
+ files = parseable_files(list_remote_files(client, path, file_pattern, logger=logger), configured_format)
+ grouped = group_files_by_table(files, combined_table_name)
+ target = grouped.get(schema_name)
+ if not target:
+ raise SFTPCredentialsError(
+ f"{NO_FILES_ERROR} '{schema_name}'. The file it was discovered from may have been renamed, "
+ "moved, or removed on the SFTP server."
+ )
+ yield from iter_table_rows(client, target, configured_format, delimiter, logger=logger)
+
+
+def validate_credentials(
+ host: str,
+ port: int,
+ user: str,
+ auth: SFTPAuth,
+ path: str = "/",
+ file_pattern: str | None = None,
+ configured_format: ConfiguredFileFormat | str | None = "infer",
+ delimiter: str | None = None,
+) -> bool:
+ """Connect, then confirm the folder holds at least one importable file.
+
+ Raises `SFTPCredentialsError` for anything the user has to fix. The file check mirrors discovery:
+ a folder with nothing importable would create a source with no tables, which is a dead end.
+ """
+ _compile_pattern(file_pattern)
+ # Catch a bad delimiter here rather than on every sync — it's a permanent misconfiguration.
+ normalize_delimiter(delimiter)
+ with sftp_connection(host=host, port=port, user=user, auth=auth) as client:
+ files = parseable_files(list_remote_files(client, path, file_pattern), configured_format)
+
+ if not files:
+ raise SFTPCredentialsError(
+ f"{NO_MATCHING_FILES_ERROR} in '{normalize_remote_path(path)}'. PostHog connected to the server "
+ "but found nothing to import there. Check the folder, the file pattern, and the file format."
+ )
+
+ return True
+
+
+def sftp_source(
+ host: str,
+ port: int,
+ user: str,
+ schema_name: str,
+ auth: SFTPAuth,
+ path: str = "/",
+ file_pattern: str | None = None,
+ configured_format: ConfiguredFileFormat | str | None = "infer",
+ delimiter: str | None = None,
+ combined_table_name: str | None = None,
+ logger: FilteringBoundLogger | None = None,
+) -> SourceResponse:
+ return SourceResponse(
+ name=schema_name,
+ items=lambda: get_rows(
+ host=host,
+ port=port,
+ user=user,
+ schema_name=schema_name,
+ auth=auth,
+ path=path,
+ file_pattern=file_pattern,
+ configured_format=configured_format,
+ delimiter=delimiter,
+ combined_table_name=combined_table_name,
+ logger=logger,
+ ),
+ # Files carry no stable row identity, so tables are replaced wholesale on every sync.
+ primary_keys=None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/source.py
index 76af00d2c951..cc6684621382 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/source.py
@@ -1,30 +1,346 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
+ SourceFieldSwitchGroupConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sftp import SFTPSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp import (
+ AUTH_FAILED_ERROR,
+ CONNECTION_FAILED_ERROR,
+ DELIMITER_ERROR,
+ DIRECTORY_ERROR,
+ FORMAT_ERROR,
+ NO_FILES_ERROR,
+ PATTERN_ERROR,
+ PRIVATE_KEY_ERROR,
+ SFTPAuth,
+ SFTPCredentialsError,
+ group_files_by_table,
+ list_remote_files,
+ parseable_files,
+ sftp_connection,
+ sftp_source,
+ validate_credentials as validate_sftp_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SFTPSource(SimpleSource[SFTPSourceConfig]):
+class SFTPSource(SimpleSource[SFTPSourceConfig], ValidateDatabaseHostMixin):
+ api_docs_url = "https://datatracker.ietf.org/doc/html/draft-ietf-secsh-filexfer-02"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SFTP
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The port picks which service on the host receives the stored password or key, so editing
+ # only the port retargets the credential just as a host change would.
+ return ["port"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ AUTH_FAILED_ERROR: (
+ "The SFTP server rejected these credentials. Check the username, and the password or "
+ "SSH private key, then reconnect the source."
+ ),
+ PRIVATE_KEY_ERROR: (
+ "The SSH private key couldn't be read. Paste the full private key including the "
+ "-----BEGIN and -----END lines, and check the passphrase if the key is encrypted."
+ ),
+ CONNECTION_FAILED_ERROR: (
+ "PostHog couldn't reach the SFTP server. Check the host and port, and that the server "
+ "allows connections from the public internet."
+ ),
+ DIRECTORY_ERROR: (
+ "PostHog couldn't read the remote folder. Check that the path exists and that this user "
+ "has permission to list it."
+ ),
+ PATTERN_ERROR: "The file pattern isn't a valid regular expression. Fix the pattern and try again.",
+ DELIMITER_ERROR: (
+ "The CSV delimiter must be a single character (use \\t for tab-separated files). "
+ "Fix the delimiter and try again."
+ ),
+ FORMAT_ERROR: (
+ "PostHog couldn't work out the format of a remote file. Set the file format explicitly, "
+ "or restrict the file pattern to .csv, .json, or .jsonl files."
+ ),
+ NO_FILES_ERROR: (
+ "The file behind this table is no longer on the SFTP server. Refresh the source's tables, "
+ "or restore the file."
+ ),
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SFTP,
category=DataWarehouseSourceCategory.FILE_STORAGE,
label="SFTP",
- iconPath="/static/services/sftp.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ caption=(
+ "Import CSV and JSON files from an SFTP server. PostHog lists the files in the folder you "
+ "point it at, including subfolders, and creates one table per file, or one combined table "
+ "if you prefer. Every sync reads the files in full, so each table matches what's on the "
+ "server right now."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/sftp",
+ iconPath="/static/services/sftp.svg",
+ keywords=["ssh file transfer", "ssh", "files"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Host",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="sftp.example.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="port",
+ label="Port",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=True,
+ placeholder="22",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="user",
+ label="Username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="posthog",
+ secret=False,
+ ),
+ SourceFieldSelectConfig(
+ name="auth_type",
+ label="Authentication type",
+ required=True,
+ defaultValue="password",
+ options=[
+ SourceFieldSelectConfigOption(
+ label="Password",
+ value="password",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="password",
+ label="Password",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ SourceFieldSelectConfigOption(
+ label="SSH private key",
+ value="ssh_key",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="private_key",
+ label="Private key",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=False,
+ placeholder="-----BEGIN OPENSSH PRIVATE KEY-----",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="passphrase",
+ label="Passphrase (optional)",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="path",
+ label="Folder",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="/incoming",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="file_pattern",
+ label="File pattern (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="\\.csv$",
+ caption=(
+ "A regular expression matched against each file's path inside the folder. Leave "
+ "it empty to import every file."
+ ),
+ secret=False,
+ ),
+ SourceFieldSelectConfig(
+ name="file_format",
+ label="File format",
+ required=True,
+ defaultValue="infer",
+ options=[
+ SourceFieldSelectConfigOption(label="Detect from file extension", value="infer"),
+ SourceFieldSelectConfigOption(label="CSV", value="csv"),
+ SourceFieldSelectConfigOption(label="JSON Lines", value="jsonl"),
+ SourceFieldSelectConfigOption(label="JSON", value="json"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="csv_delimiter",
+ label="CSV delimiter (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder=",",
+ caption="Use \\t for tab-separated files. Defaults to a comma.",
+ secret=False,
+ ),
+ SourceFieldSwitchGroupConfig(
+ name="combine_files",
+ label="Combine every file into one table?",
+ caption=(
+ "Turn this on when the folder holds files that share the same columns, such as a "
+ "daily export. All matching files land in one table instead of one table per file."
+ ),
+ default=False,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="table_name",
+ label="Table name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="orders",
+ secret=False,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ )
+
+ def _auth(self, config: SFTPSourceConfig) -> SFTPAuth:
+ """Keep the unselected authentication type's stored secrets out of the connection."""
+ auth = config.auth_type
+ if auth.selection == "ssh_key":
+ return SFTPAuth(private_key=auth.private_key, passphrase=auth.passphrase)
+ return SFTPAuth(password=auth.password)
+
+ def _combined_table_name(self, config: SFTPSourceConfig) -> str | None:
+ combine = config.combine_files
+ if combine is not None and combine.enabled:
+ return combine.table_name
+ return None
+
+ def _ensure_host_allowed(self, config: SFTPSourceConfig, team_id: int) -> None:
+ """Re-check the host every time we're about to send the stored credential to it."""
+ is_host_valid, host_error = self.is_database_host_valid(config.host, team_id)
+ if not is_host_valid:
+ raise SFTPCredentialsError(f"{CONNECTION_FAILED_ERROR} at {config.host}: {host_error}")
+
+ def validate_credentials(
+ self,
+ config: SFTPSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ is_host_valid, host_error = self.is_database_host_valid(config.host, team_id)
+ if not is_host_valid:
+ return False, host_error
+
+ if not 0 < config.port < 65536:
+ return False, "The port must be between 1 and 65535. SFTP servers usually listen on port 22."
+
+ auth = self._auth(config)
+ if not auth.password and not auth.private_key:
+ return False, "Enter either a password or an SSH private key for this user."
+
+ try:
+ validate_sftp_credentials(
+ host=config.host,
+ port=config.port,
+ user=config.user,
+ auth=auth,
+ path=config.path,
+ file_pattern=config.file_pattern,
+ configured_format=config.file_format,
+ delimiter=config.csv_delimiter,
+ )
+ except SFTPCredentialsError as e:
+ return False, str(e)
+
+ return True, None
+
+ def get_schemas(
+ self,
+ config: SFTPSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ self._ensure_host_allowed(config, team_id)
+
+ with sftp_connection(
+ host=config.host,
+ port=config.port,
+ user=config.user,
+ auth=self._auth(config),
+ ) as client:
+ files = parseable_files(list_remote_files(client, config.path, config.file_pattern), config.file_format)
+
+ grouped = group_files_by_table(files, self._combined_table_name(config))
+
+ schemas = [SourceSchema(name=name, supports_incremental=False, supports_append=False) for name in grouped]
+
+ if names is not None:
+ requested = set(names)
+ schemas = [schema for schema in schemas if schema.name in requested]
+
+ return schemas
+
+ def source_for_pipeline(self, config: SFTPSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ self._ensure_host_allowed(config, inputs.team_id)
+
+ return sftp_source(
+ host=config.host,
+ port=config.port,
+ user=config.user,
+ schema_name=inputs.schema_name,
+ auth=self._auth(config),
+ path=config.path,
+ file_pattern=config.file_pattern,
+ configured_format=config.file_format,
+ delimiter=config.csv_delimiter,
+ combined_table_name=self._combined_table_name(config),
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp.py
new file mode 100644
index 000000000000..f595c7a31819
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp.py
@@ -0,0 +1,722 @@
+import io
+import gzip
+import stat
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import paramiko
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import ed25519
+from paramiko.file import BufferedFile
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.settings import (
+ FILE_MODIFIED_AT_COLUMN,
+ FILE_PATH_COLUMN,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp import (
+ AUTH_FAILED_ERROR,
+ CONNECTION_FAILED_ERROR,
+ DELIMITER_ERROR,
+ DIRECTORY_ERROR,
+ FORMAT_ERROR,
+ NO_FILES_ERROR,
+ NO_MATCHING_FILES_ERROR,
+ PATTERN_ERROR,
+ PRIVATE_KEY_ERROR,
+ RemoteFile,
+ ResolvedFormat,
+ SFTPAuth,
+ SFTPCredentialsError,
+ SFTPFileFormatError,
+ get_rows,
+ group_files_by_table,
+ iter_file_rows,
+ iter_table_rows,
+ list_remote_files,
+ load_private_key,
+ normalize_delimiter,
+ normalize_remote_path,
+ resolve_file_format,
+ sftp_connection,
+ sftp_source,
+ table_name_for_file,
+ validate_credentials,
+)
+
+DIRECTORY_MODE = stat.S_IFDIR | 0o755
+FILE_MODE = stat.S_IFREG | 0o644
+SYMLINK_MODE = stat.S_IFLNK | 0o777
+
+
+class FakeAttributes:
+ def __init__(self, filename: str, st_mode: int = FILE_MODE, st_size: int = 16, st_mtime: int = 1_700_000_000):
+ self.filename = filename
+ self.st_mode = st_mode
+ self.st_size = st_size
+ self.st_mtime = st_mtime
+
+
+class BufferedRemoteHandle(BufferedFile):
+ """Stands in for `paramiko.SFTPFile`, which is a `BufferedFile` rather than a `BytesIO`."""
+
+ def __init__(self, data: bytes) -> None:
+ super().__init__()
+ self._set_mode("rb") # type: ignore[attr-defined]
+ self._source = io.BytesIO(data)
+
+ def _read(self, size: int) -> bytes:
+ return self._source.read(size)
+
+ def prefetch(self, file_size: int | None = None) -> None:
+ return None
+
+
+class FakeRemoteHandle(io.BytesIO):
+ def __init__(self, data: bytes) -> None:
+ super().__init__(data)
+ self.prefetched: int | None = None
+
+ def prefetch(self, file_size: int | None = None) -> None:
+ self.prefetched = file_size
+
+
+class FakeClient:
+ def __init__(
+ self,
+ tree: dict[str, list[FakeAttributes]],
+ contents: dict[str, bytes] | None = None,
+ unreadable: set[str] | None = None,
+ handle_factory: Callable[[bytes], Any] = FakeRemoteHandle,
+ ) -> None:
+ self.tree = tree
+ self.contents = contents or {}
+ self.unreadable = unreadable or set()
+ self.handle_factory = handle_factory
+ self.handles: list[Any] = []
+ self.closed = False
+
+ def listdir_attr(self, path: str) -> list[Any]:
+ if path in self.unreadable:
+ raise OSError(f"permission denied: {path}")
+ if path not in self.tree:
+ raise OSError(f"no such directory: {path}")
+ return list(self.tree[path])
+
+ def open(self, filename: str, mode: str = "r", bufsize: int = -1) -> Any:
+ handle = self.handle_factory(self.contents[filename])
+ self.handles.append(handle)
+ return handle
+
+ def close(self) -> None:
+ self.closed = True
+
+
+def make_file(relative_path: str, modified_at: datetime | None = None) -> RemoteFile:
+ return RemoteFile(
+ path=f"/data/{relative_path}",
+ relative_path=relative_path,
+ size=10,
+ modified_at=modified_at or datetime(2024, 1, 1, tzinfo=UTC),
+ )
+
+
+def csv_stream(text: str) -> io.BytesIO:
+ return io.BytesIO(text.encode("utf-8"))
+
+
+class TestPathAndDelimiterNormalization:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("/data", "/data"),
+ ("/data/", "/data"),
+ ("/data//sub/", "/data/sub"),
+ ("/", "/"),
+ ("", "."),
+ (" ", "."),
+ (None, "."),
+ ],
+ )
+ def test_normalize_remote_path(self, raw: str | None, expected: str) -> None:
+ assert normalize_remote_path(raw) == expected
+
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ (None, None),
+ ("", None),
+ (",", ","),
+ (";", ";"),
+ ("\t", "\t"),
+ ("\\t", "\t"),
+ ("tab", "\t"),
+ ],
+ )
+ def test_normalize_delimiter(self, raw: str | None, expected: str | None) -> None:
+ assert normalize_delimiter(raw) == expected
+
+ def test_normalize_delimiter_rejects_multiple_characters(self) -> None:
+ with pytest.raises(SFTPCredentialsError, match="single character"):
+ normalize_delimiter("||")
+
+
+class TestListRemoteFiles:
+ def _tree_client(self) -> FakeClient:
+ return FakeClient(
+ {
+ "/data": [
+ FakeAttributes("top.csv"),
+ FakeAttributes("sub", st_mode=DIRECTORY_MODE),
+ FakeAttributes("notes.txt"),
+ FakeAttributes("link.csv", st_mode=SYMLINK_MODE),
+ ],
+ "/data/sub": [
+ FakeAttributes("nested.json"),
+ FakeAttributes("deeper", st_mode=DIRECTORY_MODE),
+ ],
+ "/data/sub/deeper": [FakeAttributes("deep.csv")],
+ }
+ )
+
+ def test_walks_subdirectories_and_returns_sorted_relative_paths(self) -> None:
+ files = list_remote_files(self._tree_client(), "/data/")
+
+ assert [file.relative_path for file in files] == [
+ "notes.txt",
+ "sub/deeper/deep.csv",
+ "sub/nested.json",
+ "top.csv",
+ ]
+ assert files[-1].path == "/data/top.csv"
+ assert files[-1].modified_at == datetime.fromtimestamp(1_700_000_000, tz=UTC)
+
+ def test_skips_entries_that_are_not_regular_files(self) -> None:
+ files = list_remote_files(self._tree_client(), "/data")
+
+ assert "link.csv" not in [file.relative_path for file in files]
+
+ @pytest.mark.parametrize(
+ ("pattern", "expected"),
+ [
+ (r"\.csv$", ["sub/deeper/deep.csv", "top.csv"]),
+ (r"^sub/", ["sub/deeper/deep.csv", "sub/nested.json"]),
+ (r"nested", ["sub/nested.json"]),
+ (None, ["notes.txt", "sub/deeper/deep.csv", "sub/nested.json", "top.csv"]),
+ ],
+ )
+ def test_filters_by_pattern(self, pattern: str | None, expected: list[str]) -> None:
+ files = list_remote_files(self._tree_client(), "/data", pattern)
+
+ assert [file.relative_path for file in files] == expected
+
+ def test_rejects_invalid_pattern(self) -> None:
+ with pytest.raises(SFTPCredentialsError, match=PATTERN_ERROR):
+ list_remote_files(self._tree_client(), "/data", "([unclosed")
+
+ def test_stops_at_max_depth(self) -> None:
+ files = list_remote_files(self._tree_client(), "/data", max_depth=1)
+
+ assert [file.relative_path for file in files] == ["notes.txt", "sub/nested.json", "top.csv"]
+
+ def test_stops_at_max_files_and_warns(self) -> None:
+ logger = MagicMock()
+
+ files = list_remote_files(self._tree_client(), "/data", max_files=2, logger=logger)
+
+ assert len(files) == 2
+ assert logger.warning.called
+
+ def test_stops_at_max_directories_and_warns(self) -> None:
+ # `max_files` counts matching files only, so a pattern matching nothing has to be bounded by
+ # the folder budget instead — otherwise a wide tree walks until the worker gives up.
+ listings = 0
+
+ class WideTree:
+ def listdir_attr(self, path: str) -> list[Any]:
+ nonlocal listings
+ listings += 1
+ return [FakeAttributes(f"d{index}", st_mode=DIRECTORY_MODE) for index in range(10)]
+
+ def open(self, filename: str, mode: str = "r", bufsize: int = -1) -> Any:
+ raise NotImplementedError
+
+ logger = MagicMock()
+
+ files = list_remote_files(WideTree(), "/data", pattern=r"\.csv$", max_directories=25, logger=logger)
+
+ assert files == []
+ assert listings == 25
+ assert logger.warning.called
+
+ def test_unreadable_root_is_a_credentials_error(self) -> None:
+ client = FakeClient({"/data": []}, unreadable={"/data"})
+
+ with pytest.raises(SFTPCredentialsError, match=DIRECTORY_ERROR):
+ list_remote_files(client, "/data")
+
+ def test_unreadable_subdirectory_is_skipped(self) -> None:
+ client = FakeClient(
+ {
+ "/data": [FakeAttributes("top.csv"), FakeAttributes("locked", st_mode=DIRECTORY_MODE)],
+ "/data/locked": [FakeAttributes("secret.csv")],
+ },
+ unreadable={"/data/locked"},
+ )
+ logger = MagicMock()
+
+ files = list_remote_files(client, "/data", logger=logger)
+
+ assert [file.relative_path for file in files] == ["top.csv"]
+ assert logger.warning.called
+
+
+class TestTableGrouping:
+ @pytest.mark.parametrize(
+ ("relative_path", "expected"),
+ [
+ ("orders.csv", "orders"),
+ ("Orders 2024.csv", "orders_2024"),
+ ("sub/dir/orders.json", "sub_dir_orders"),
+ ("orders.csv.gz", "orders"),
+ ("orders.CSV.GZ", "orders"),
+ ("---.csv", "sftp_data"),
+ ],
+ )
+ def test_table_name_for_file(self, relative_path: str, expected: str) -> None:
+ assert table_name_for_file(relative_path) == expected
+
+ def test_one_table_per_file(self) -> None:
+ grouped = group_files_by_table([make_file("b.csv"), make_file("a.csv")])
+
+ assert list(grouped) == ["a", "b"]
+ assert [file.relative_path for file in grouped["a"]] == ["a.csv"]
+
+ def test_colliding_names_are_deduplicated_deterministically(self) -> None:
+ files = [make_file("2024/orders.csv"), make_file("orders.csv"), make_file("orders.json")]
+
+ first = group_files_by_table(files)
+ second = group_files_by_table(list(reversed(files)))
+
+ assert list(first) == ["2024_orders", "orders", "orders_2"]
+ assert first == second
+
+ def test_combined_mode_puts_every_file_in_one_sanitized_table(self) -> None:
+ grouped = group_files_by_table([make_file("a.csv"), make_file("b.csv")], combined_table_name="Daily Orders")
+
+ assert list(grouped) == ["daily_orders"]
+ assert [file.relative_path for file in grouped["daily_orders"]] == ["a.csv", "b.csv"]
+
+
+class TestResolveFileFormat:
+ @pytest.mark.parametrize(
+ ("relative_path", "expected"),
+ [
+ ("orders.csv", ResolvedFormat("csv", ",", False)),
+ ("orders.CSV", ResolvedFormat("csv", ",", False)),
+ ("orders.tsv", ResolvedFormat("csv", "\t", False)),
+ ("orders.txt", ResolvedFormat("csv", ",", False)),
+ ("orders.jsonl", ResolvedFormat("jsonl", ",", False)),
+ ("orders.ndjson", ResolvedFormat("jsonl", ",", False)),
+ ("orders.json", ResolvedFormat("json", ",", False)),
+ ("orders.csv.gz", ResolvedFormat("csv", ",", True)),
+ ("orders.jsonl.gz", ResolvedFormat("jsonl", ",", True)),
+ ],
+ )
+ def test_infers_from_extension(self, relative_path: str, expected: ResolvedFormat) -> None:
+ assert resolve_file_format(relative_path, "infer") == expected
+
+ def test_explicit_format_wins_over_extension(self) -> None:
+ assert resolve_file_format("orders.txt", "jsonl") == ResolvedFormat("jsonl", ",", False)
+
+ def test_explicit_delimiter_wins_over_extension_default(self) -> None:
+ assert resolve_file_format("orders.tsv", "infer", ";") == ResolvedFormat("csv", ";", False)
+
+ def test_unknown_extension_without_explicit_format_raises(self) -> None:
+ with pytest.raises(SFTPFileFormatError, match=FORMAT_ERROR):
+ resolve_file_format("orders.parquet", "infer")
+
+
+class TestIterFileRows:
+ def test_csv_headers_are_normalized_and_deduplicated(self) -> None:
+ stream = csv_stream("Order Total (USD),name,Name\n1,a,b\n")
+
+ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))
+
+ assert chunks == [[{"order_total_usd": "1", "name": "a", "name_2": "b"}]]
+
+ def test_csv_quoting_and_blank_lines(self) -> None:
+ stream = csv_stream('a,b\n"x,y",2\n\n"multi\nline",3\n')
+
+ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))
+
+ assert chunks == [[{"a": "x,y", "b": "2"}, {"a": "multi\nline", "b": "3"}]]
+
+ def test_csv_short_rows_are_padded(self) -> None:
+ stream = csv_stream("a,b,c\n1,2\n")
+
+ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv"))
+
+ assert chunks == [[{"a": "1", "b": "2", "c": None}]]
+
+ def test_csv_rows_with_extra_values_are_skipped_and_logged(self) -> None:
+ stream = csv_stream("a,b\n1,2\n1,2,3\n")
+ logger = MagicMock()
+
+ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv", logger=logger))
+
+ assert chunks == [[{"a": "1", "b": "2"}]]
+ assert logger.warning.called
+
+ def test_csv_uses_the_configured_delimiter(self) -> None:
+ stream = csv_stream("a\tb\n1\t2\n")
+
+ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", "\t", False), "orders.tsv"))
+
+ assert chunks == [[{"a": "1", "b": "2"}]]
+
+ def test_gzipped_csv_is_decompressed(self) -> None:
+ stream = io.BytesIO(gzip.compress(b"a,b\n1,2\n"))
+
+ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", True), "orders.csv.gz"))
+
+ assert chunks == [[{"a": "1", "b": "2"}]]
+
+ def test_rows_are_chunked(self) -> None:
+ stream = csv_stream("a\n1\n2\n3\n4\n5\n")
+
+ chunks = list(iter_file_rows(stream, ResolvedFormat("csv", ",", False), "orders.csv", chunk_size=2))
+
+ assert [len(chunk) for chunk in chunks] == [2, 2, 1]
+
+ @pytest.mark.parametrize(
+ ("payload", "file_format", "expected"),
+ [
+ (b'{"id": 1}\n{"id": 2}\n', "jsonl", [{"id": 1}, {"id": 2}]),
+ (b'\n{"id": 1}\n\n', "jsonl", [{"id": 1}]),
+ (b'[{"id": 1}, {"id": 2}]\n', "jsonl", [{"id": 1}, {"id": 2}]),
+ (b'[{"id": 1}, {"id": 2}]', "json", [{"id": 1}, {"id": 2}]),
+ (b'{"id": 1}', "json", [{"id": 1}]),
+ (b'["a", "b"]', "json", [{"value": "a"}, {"value": "b"}]),
+ ],
+ )
+ def test_json_shapes(self, payload: bytes, file_format: str, expected: list[dict[str, Any]]) -> None:
+ resolved = ResolvedFormat(cast(Any, file_format), ",", False)
+
+ chunks = list(iter_file_rows(io.BytesIO(payload), resolved, "orders.json"))
+
+ assert [row for chunk in chunks for row in chunk] == expected
+
+ def test_malformed_jsonl_line_reports_its_line_number(self) -> None:
+ stream = io.BytesIO(b'{"id": 1}\nnot json\n')
+
+ with pytest.raises(SFTPFileFormatError, match="Line 2"):
+ list(iter_file_rows(stream, ResolvedFormat("jsonl", ",", False), "orders.jsonl"))
+
+ def test_malformed_json_document_points_at_json_lines(self) -> None:
+ stream = io.BytesIO(b'{"id": 1}\n{"id": 2}\n')
+
+ with pytest.raises(SFTPFileFormatError, match="JSON Lines"):
+ list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json"))
+
+ def test_json_chunking(self) -> None:
+ stream = io.BytesIO(b"[1, 2, 3]")
+
+ chunks = list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json", chunk_size=2))
+
+ assert [len(chunk) for chunk in chunks] == [2, 1]
+
+ def test_oversized_json_document_is_rejected_before_it_is_parsed(self) -> None:
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp"
+ stream = io.BytesIO(b"[" + b"0," * 100 + b"0]")
+
+ with patch(f"{module}.MAX_JSON_DOCUMENT_BYTES", 8):
+ with pytest.raises(SFTPFileFormatError, match="single JSON document"):
+ list(iter_file_rows(stream, ResolvedFormat("json", ",", False), "orders.json"))
+
+
+class TestIterTableRows:
+ def test_adds_file_metadata_to_every_row_across_files(self) -> None:
+ modified_at = datetime(2024, 3, 1, 12, tzinfo=UTC)
+ files = [make_file("a.csv", modified_at), make_file("b.jsonl", modified_at)]
+ client = FakeClient(
+ {},
+ contents={"/data/a.csv": b"id\n1\n", "/data/b.jsonl": b'{"id": 2}\n'},
+ )
+
+ rows = [row for chunk in iter_table_rows(client, files) for row in chunk]
+
+ assert rows == [
+ {"id": "1", FILE_PATH_COLUMN: "a.csv", FILE_MODIFIED_AT_COLUMN: modified_at},
+ {"id": 2, FILE_PATH_COLUMN: "b.jsonl", FILE_MODIFIED_AT_COLUMN: modified_at},
+ ]
+
+ def test_prefetches_each_file(self) -> None:
+ client = FakeClient({}, contents={"/data/a.csv": b"id\n1\n"})
+
+ list(iter_table_rows(client, [make_file("a.csv")]))
+
+ assert [handle.prefetched for handle in client.handles] == [10]
+
+ def test_reads_a_paramiko_style_buffered_file(self) -> None:
+ # paramiko hands back a `BufferedFile`, not a `BytesIO`, and parsing wraps it in a
+ # `TextIOWrapper` — which only works while that class keeps its file-object surface.
+ client = FakeClient({}, contents={"/data/a.csv": b"id\n1\n"}, handle_factory=BufferedRemoteHandle)
+
+ rows = [row for chunk in iter_table_rows(client, [make_file("a.csv")]) for row in chunk]
+
+ assert [row["id"] for row in rows] == ["1"]
+
+ def test_unparseable_file_format_propagates(self) -> None:
+ client = FakeClient({}, contents={"/data/a.parquet": b"junk"})
+
+ with pytest.raises(SFTPFileFormatError):
+ list(iter_table_rows(client, [make_file("a.parquet")]))
+
+
+class TestSFTPConnection:
+ def test_unreachable_host_is_a_credentials_error(self) -> None:
+ with patch("socket.create_connection", side_effect=OSError("connection refused")):
+ with pytest.raises(SFTPCredentialsError, match=CONNECTION_FAILED_ERROR):
+ with sftp_connection(
+ host="sftp.example.com", port=22, user="posthog", auth=SFTPAuth(password="hunter2")
+ ):
+ pass
+
+ def test_rejected_credentials_are_a_credentials_error(self) -> None:
+ transport = MagicMock()
+ transport.connect.side_effect = paramiko.AuthenticationException("nope")
+
+ with (
+ patch("socket.create_connection", return_value=MagicMock()),
+ patch("paramiko.Transport", return_value=transport),
+ ):
+ with pytest.raises(SFTPCredentialsError, match=AUTH_FAILED_ERROR):
+ with sftp_connection(host="sftp.example.com", port=22, user="posthog", auth=SFTPAuth(password="wrong")):
+ pass
+
+ transport.close.assert_called_once()
+
+ def test_ssh_error_during_handshake_is_a_credentials_error(self) -> None:
+ transport = MagicMock()
+ transport.connect.side_effect = paramiko.SSHException("no matching kex")
+
+ with (
+ patch("socket.create_connection", return_value=MagicMock()),
+ patch("paramiko.Transport", return_value=transport),
+ ):
+ with pytest.raises(SFTPCredentialsError, match=CONNECTION_FAILED_ERROR):
+ with sftp_connection(
+ host="sftp.example.com", port=22, user="posthog", auth=SFTPAuth(password="hunter2")
+ ):
+ pass
+
+ def test_missing_sftp_subsystem_is_a_credentials_error(self) -> None:
+ with (
+ patch("socket.create_connection", return_value=MagicMock()),
+ patch("paramiko.Transport", return_value=MagicMock()),
+ patch("paramiko.SFTPClient.from_transport", return_value=None),
+ ):
+ with pytest.raises(SFTPCredentialsError, match="SFTP subsystem"):
+ with sftp_connection(
+ host="sftp.example.com", port=22, user="posthog", auth=SFTPAuth(password="hunter2")
+ ):
+ pass
+
+ def test_closes_the_client_and_transport_on_success(self) -> None:
+ transport = MagicMock()
+ client = MagicMock()
+
+ with (
+ patch("socket.create_connection", return_value=MagicMock()),
+ patch("paramiko.Transport", return_value=transport),
+ patch("paramiko.SFTPClient.from_transport", return_value=client),
+ ):
+ with sftp_connection(
+ host="sftp.example.com", port=22, user="posthog", auth=SFTPAuth(password="hunter2")
+ ) as opened:
+ assert opened is client
+
+ client.close.assert_called_once()
+ transport.close.assert_called_once()
+
+ def test_connects_with_a_parsed_private_key(self) -> None:
+ transport = MagicMock()
+
+ with (
+ patch("socket.create_connection", return_value=MagicMock()),
+ patch("paramiko.Transport", return_value=transport),
+ patch("paramiko.SFTPClient.from_transport", return_value=MagicMock()),
+ ):
+ with sftp_connection(
+ host="sftp.example.com", port=22, user="posthog", auth=SFTPAuth(private_key=_generate_private_key())
+ ):
+ pass
+
+ assert transport.connect.call_args.kwargs["pkey"] is not None
+ assert transport.connect.call_args.kwargs["password"] is None
+
+
+def _generate_private_key() -> str:
+ key = ed25519.Ed25519PrivateKey.generate()
+ return key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.OpenSSH,
+ encryption_algorithm=serialization.NoEncryption(),
+ ).decode("utf-8")
+
+
+class TestLoadPrivateKey:
+ def test_parses_an_openssh_key(self) -> None:
+ assert isinstance(load_private_key(_generate_private_key()), paramiko.PKey)
+
+ @pytest.mark.parametrize("private_key", ["not-a-key", "", "-----BEGIN OPENSSH PRIVATE KEY-----\ntruncated\n"])
+ def test_unreadable_key_is_a_credentials_error(self, private_key: str) -> None:
+ with pytest.raises(SFTPCredentialsError, match=PRIVATE_KEY_ERROR):
+ load_private_key(private_key)
+
+
+@contextmanager
+def _patched_connection(client: FakeClient) -> Iterator[FakeClient]:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp.sftp_connection"
+ ) as connection:
+ connection.return_value.__enter__.return_value = client
+ yield client
+
+
+class TestGetRows:
+ def _client(self) -> FakeClient:
+ return FakeClient(
+ {"/data": [FakeAttributes("orders.csv", st_size=10), FakeAttributes("refunds.csv", st_size=10)]},
+ contents={"/data/orders.csv": b"id\n1\n", "/data/refunds.csv": b"id\n2\n"},
+ )
+
+ def test_yields_only_the_requested_table(self) -> None:
+ with _patched_connection(self._client()):
+ rows = [
+ row
+ for chunk in get_rows(
+ host="h", port=22, user="u", schema_name="orders", auth=SFTPAuth(password="p"), path="/data"
+ )
+ for row in chunk
+ ]
+
+ assert [row["id"] for row in rows] == ["1"]
+ assert {row[FILE_PATH_COLUMN] for row in rows} == {"orders.csv"}
+
+ def test_combined_table_reads_every_file(self) -> None:
+ with _patched_connection(self._client()):
+ rows = [
+ row
+ for chunk in get_rows(
+ host="h",
+ port=22,
+ user="u",
+ schema_name="all_orders",
+ auth=SFTPAuth(password="p"),
+ path="/data",
+ combined_table_name="all_orders",
+ )
+ for row in chunk
+ ]
+
+ assert [row["id"] for row in rows] == ["1", "2"]
+
+ def test_missing_table_is_a_credentials_error(self) -> None:
+ with _patched_connection(self._client()):
+ with pytest.raises(SFTPCredentialsError, match=NO_FILES_ERROR):
+ list(
+ get_rows(host="h", port=22, user="u", schema_name="gone", auth=SFTPAuth(password="p"), path="/data")
+ )
+
+
+class TestValidateCredentials:
+ def test_returns_true_when_the_directory_holds_importable_files(self) -> None:
+ client = FakeClient({"/data": [FakeAttributes("orders.csv")]})
+
+ with _patched_connection(client):
+ assert validate_credentials(host="h", port=22, user="u", auth=SFTPAuth(password="p"), path="/data") is True
+
+ @pytest.mark.parametrize(
+ ("entries", "file_pattern"),
+ [
+ ([], None),
+ ([FakeAttributes("readme.md")], None),
+ ([FakeAttributes("orders.csv")], r"\.json$"),
+ ],
+ )
+ def test_rejects_a_folder_with_nothing_to_import(
+ self, entries: list[FakeAttributes], file_pattern: str | None
+ ) -> None:
+ client = FakeClient({"/data": entries})
+
+ with _patched_connection(client):
+ with pytest.raises(SFTPCredentialsError, match=NO_MATCHING_FILES_ERROR):
+ validate_credentials(
+ host="h", port=22, user="u", auth=SFTPAuth(password="p"), path="/data", file_pattern=file_pattern
+ )
+
+ def test_an_explicit_format_accepts_files_without_a_known_extension(self) -> None:
+ client = FakeClient({"/data": [FakeAttributes("export")]})
+
+ with _patched_connection(client):
+ assert (
+ validate_credentials(
+ host="h", port=22, user="u", auth=SFTPAuth(password="p"), path="/data", configured_format="csv"
+ )
+ is True
+ )
+
+ def test_rejects_an_invalid_pattern_before_connecting(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp.sftp_connection"
+ ) as connection:
+ with pytest.raises(SFTPCredentialsError, match=PATTERN_ERROR):
+ validate_credentials(
+ host="h", port=22, user="u", auth=SFTPAuth(password="p"), path="/data", file_pattern="(["
+ )
+
+ connection.assert_not_called()
+
+ def test_rejects_an_invalid_delimiter_before_connecting(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp.sftp_connection"
+ ) as connection:
+ with pytest.raises(SFTPCredentialsError, match=DELIMITER_ERROR):
+ validate_credentials(
+ host="h", port=22, user="u", auth=SFTPAuth(password="p"), path="/data", delimiter="||"
+ )
+
+ connection.assert_not_called()
+
+ def test_surfaces_an_unreadable_directory(self) -> None:
+ client = FakeClient({"/data": []}, unreadable={"/data"})
+
+ with _patched_connection(client):
+ with pytest.raises(SFTPCredentialsError, match=DIRECTORY_ERROR):
+ validate_credentials(host="h", port=22, user="u", auth=SFTPAuth(password="p"), path="/data")
+
+
+class TestSFTPSource:
+ def test_response_shape_and_lazy_items(self) -> None:
+ client = FakeClient(
+ {"/data": [FakeAttributes("orders.csv")]},
+ contents={"/data/orders.csv": b"id\n1\n"},
+ )
+
+ response = sftp_source(
+ host="h", port=22, user="u", schema_name="orders", auth=SFTPAuth(password="p"), path="/data"
+ )
+
+ assert response.name == "orders"
+ assert response.primary_keys is None
+
+ with _patched_connection(client):
+ rows = [row for chunk in cast(Any, response.items()) for row in chunk]
+
+ assert [row["id"] for row in rows] == ["1"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp_source.py
new file mode 100644
index 000000000000..d4b3d913359e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sftp/tests/test_sftp_source.py
@@ -0,0 +1,383 @@
+import io
+import stat
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSwitchGroupConfig,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sftp import (
+ SFTPAuthTypeConfig,
+ SFTPCombineFilesConfig,
+ SFTPSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.settings import FILE_PATH_COLUMN
+from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp import (
+ AUTH_FAILED_ERROR,
+ DELIMITER_ERROR,
+ DIRECTORY_ERROR,
+ SFTPAuth,
+ SFTPCredentialsError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sftp.source import SFTPSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+DIRECTORY_MODE = stat.S_IFDIR | 0o755
+FILE_MODE = stat.S_IFREG | 0o644
+
+CONNECTION_TARGET = "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.source.sftp_connection"
+TRANSPORT_CONNECTION_TARGET = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.sftp.sftp_connection"
+)
+
+
+class FakeAttributes:
+ def __init__(self, filename: str, st_mode: int = FILE_MODE) -> None:
+ self.filename = filename
+ self.st_mode = st_mode
+ self.st_size = 8
+ self.st_mtime = 1_700_000_000
+
+
+class FakeHandle(io.BytesIO):
+ def prefetch(self, file_size: int | None = None) -> None:
+ return None
+
+
+class FakeClient:
+ def __init__(
+ self,
+ tree: dict[str, list[FakeAttributes]],
+ contents: dict[str, bytes] | None = None,
+ unreadable: set[str] | None = None,
+ ) -> None:
+ self.tree = tree
+ self.contents = contents or {}
+ self.unreadable = unreadable or set()
+
+ def listdir_attr(self, path: str) -> list[Any]:
+ if path in self.unreadable:
+ raise OSError(f"permission denied: {path}")
+ if path not in self.tree:
+ raise OSError(f"no such directory: {path}")
+ return list(self.tree[path])
+
+ def open(self, filename: str, mode: str = "r", bufsize: int = -1) -> FakeHandle:
+ return FakeHandle(self.contents[filename])
+
+
+def make_config(
+ auth: SFTPAuthTypeConfig | None = None,
+ path: str = "/data",
+ port: int = 22,
+ file_pattern: str | None = None,
+ file_format: str = "infer",
+ csv_delimiter: str | None = None,
+ combine_files: SFTPCombineFilesConfig | None = None,
+) -> SFTPSourceConfig:
+ return SFTPSourceConfig(
+ host="sftp.example.com",
+ user="posthog",
+ auth_type=auth or SFTPAuthTypeConfig(selection="password", password="hunter2"),
+ path=path,
+ port=port,
+ file_pattern=file_pattern,
+ file_format=cast(Any, file_format),
+ csv_delimiter=csv_delimiter,
+ combine_files=combine_files,
+ )
+
+
+def make_inputs(schema_name: str = "orders") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+def patched_connection(client: FakeClient, target: str = CONNECTION_TARGET) -> Any:
+ connection = patch(target)
+ started = connection.start()
+ started.return_value.__enter__.return_value = client
+ return connection
+
+
+class TestSFTPSourceConfig:
+ def setup_method(self) -> None:
+ self.source = SFTPSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SFTP
+
+ def test_is_released_as_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.category == DataWarehouseSourceCategory.FILE_STORAGE
+
+ def test_field_names(self) -> None:
+ names = [field.name for field in self.source.get_source_config.fields]
+
+ assert names == [
+ "host",
+ "port",
+ "user",
+ "auth_type",
+ "path",
+ "file_pattern",
+ "file_format",
+ "csv_delimiter",
+ "combine_files",
+ ]
+
+ def test_credentials_are_marked_secret(self) -> None:
+ auth_field = next(
+ field for field in self.source.get_source_config.fields if isinstance(field, SourceFieldSelectConfig)
+ )
+ option_fields = [field for option in auth_field.options for field in option.fields or []]
+
+ assert {field.name for field in option_fields} == {"password", "private_key", "passphrase"}
+ for field in option_fields:
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.secret is True
+ assert field.type in (SourceFieldInputConfigType.PASSWORD, SourceFieldInputConfigType.TEXTAREA)
+
+ def test_combine_files_group_asks_for_a_table_name(self) -> None:
+ group = next(
+ field for field in self.source.get_source_config.fields if isinstance(field, SourceFieldSwitchGroupConfig)
+ )
+
+ assert group.default is False
+ assert [field.name for field in group.fields or []] == ["table_name"]
+
+ def test_port_change_requires_credential_reentry(self) -> None:
+ assert self.source.connection_host_fields == ["port"]
+
+ def test_non_retryable_errors_cover_connection_and_auth_failures(self) -> None:
+ errors = self.source.get_non_retryable_errors()
+
+ assert AUTH_FAILED_ERROR in errors
+ assert all(message for message in errors.values())
+
+
+class TestValidateCredentials:
+ def setup_method(self) -> None:
+ self.source = SFTPSource()
+
+ @pytest.mark.parametrize(
+ ("config", "expected_error"),
+ [
+ (make_config(port=0), "port must be between"),
+ (make_config(port=70000), "port must be between"),
+ (make_config(auth=SFTPAuthTypeConfig(selection="password")), "password or an SSH private key"),
+ (make_config(auth=SFTPAuthTypeConfig(selection="ssh_key")), "password or an SSH private key"),
+ ],
+ )
+ def test_rejects_incomplete_config_without_connecting(self, config: SFTPSourceConfig, expected_error: str) -> None:
+ with patch(CONNECTION_TARGET) as connection:
+ is_valid, error = self.source.validate_credentials(config, team_id=1)
+
+ assert is_valid is False
+ assert error is not None and expected_error in error
+ connection.assert_not_called()
+
+ def test_rejects_an_invalid_delimiter_without_connecting(self) -> None:
+ with patch(CONNECTION_TARGET) as connection:
+ is_valid, error = self.source.validate_credentials(make_config(csv_delimiter="||"), team_id=1)
+
+ assert is_valid is False
+ assert error is not None and DELIMITER_ERROR in error
+ connection.assert_not_called()
+
+ def test_rejects_an_unsafe_host(self) -> None:
+ with patch.object(SFTPSource, "is_database_host_valid", return_value=(False, "nope")):
+ is_valid, error = self.source.validate_credentials(make_config(), team_id=1)
+
+ assert (is_valid, error) == (False, "nope")
+
+ def test_accepts_a_readable_directory(self) -> None:
+ connection = patched_connection(
+ FakeClient({"/data": [FakeAttributes("orders.csv")]}), TRANSPORT_CONNECTION_TARGET
+ )
+ try:
+ assert self.source.validate_credentials(make_config(), team_id=1) == (True, None)
+ finally:
+ connection.stop()
+
+ def test_surfaces_a_connection_failure_as_a_message(self) -> None:
+ with patch(TRANSPORT_CONNECTION_TARGET, side_effect=SFTPCredentialsError(f"{DIRECTORY_ERROR} '/data'")):
+ is_valid, error = self.source.validate_credentials(make_config(), team_id=1)
+
+ assert is_valid is False
+ assert error is not None and DIRECTORY_ERROR in error
+
+
+class TestGetSchemas:
+ def setup_method(self) -> None:
+ self.source = SFTPSource()
+ self.client = FakeClient(
+ {
+ "/data": [
+ FakeAttributes("orders.csv"),
+ FakeAttributes("2024", st_mode=DIRECTORY_MODE),
+ FakeAttributes("notes.md"),
+ ],
+ "/data/2024": [FakeAttributes("orders.csv")],
+ }
+ )
+
+ def test_one_full_refresh_table_per_file_with_a_recognized_format(self) -> None:
+ connection = patched_connection(self.client)
+ try:
+ schemas = self.source.get_schemas(make_config(), team_id=1)
+ finally:
+ connection.stop()
+
+ # notes.md has no format we can parse, so discovery doesn't offer it as a table.
+ assert [schema.name for schema in schemas] == ["2024_orders", "orders"]
+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)
+ assert all(schema.incremental_fields == [] for schema in schemas)
+
+ def test_an_explicit_format_offers_every_matched_file(self) -> None:
+ connection = patched_connection(self.client)
+ try:
+ schemas = self.source.get_schemas(make_config(file_format="csv"), team_id=1)
+ finally:
+ connection.stop()
+
+ assert [schema.name for schema in schemas] == ["2024_orders", "notes", "orders"]
+
+ def test_pattern_narrows_the_tables(self) -> None:
+ connection = patched_connection(self.client)
+ try:
+ schemas = self.source.get_schemas(make_config(file_pattern=r"\.csv$"), team_id=1)
+ finally:
+ connection.stop()
+
+ assert [schema.name for schema in schemas] == ["2024_orders", "orders"]
+
+ def test_combine_files_produces_a_single_table(self) -> None:
+ connection = patched_connection(self.client)
+ try:
+ schemas = self.source.get_schemas(
+ make_config(combine_files=SFTPCombineFilesConfig(table_name="All orders", enabled=True)),
+ team_id=1,
+ )
+ finally:
+ connection.stop()
+
+ assert [schema.name for schema in schemas] == ["all_orders"]
+
+ def test_disabled_combine_files_keeps_one_table_per_file(self) -> None:
+ connection = patched_connection(self.client)
+ try:
+ schemas = self.source.get_schemas(
+ make_config(combine_files=SFTPCombineFilesConfig(table_name="All orders", enabled=False)),
+ team_id=1,
+ )
+ finally:
+ connection.stop()
+
+ assert [schema.name for schema in schemas] == ["2024_orders", "orders"]
+
+ def test_filters_by_requested_names(self) -> None:
+ connection = patched_connection(self.client)
+ try:
+ schemas = self.source.get_schemas(make_config(), team_id=1, names=["orders"])
+ finally:
+ connection.stop()
+
+ assert [schema.name for schema in schemas] == ["orders"]
+
+ def test_lists_no_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is False
+ assert self.source.get_documented_tables() == []
+
+
+class TestSourceForPipeline:
+ def setup_method(self) -> None:
+ self.source = SFTPSource()
+
+ def test_passes_the_configured_format_and_credentials_through(self) -> None:
+ config = make_config(
+ auth=SFTPAuthTypeConfig(selection="ssh_key", private_key="key", passphrase="phrase"),
+ file_format="csv",
+ csv_delimiter="\\t",
+ file_pattern=r"\.tsv$",
+ combine_files=SFTPCombineFilesConfig(table_name="orders", enabled=True),
+ )
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.source.sftp_source"
+ ) as source_fn:
+ self.source.source_for_pipeline(config, make_inputs("orders"))
+
+ kwargs = source_fn.call_args.kwargs
+ assert kwargs["auth"] == SFTPAuth(private_key="key", passphrase="phrase")
+ assert kwargs["configured_format"] == "csv"
+ assert kwargs["delimiter"] == "\\t"
+ assert kwargs["file_pattern"] == r"\.tsv$"
+ assert kwargs["combined_table_name"] == "orders"
+ assert kwargs["schema_name"] == "orders"
+
+ def test_reads_the_rows_of_the_requested_table(self) -> None:
+ client = FakeClient(
+ {"/data": [FakeAttributes("orders.csv"), FakeAttributes("refunds.csv")]},
+ contents={"/data/orders.csv": b"id,total\n1,10\n", "/data/refunds.csv": b"id,total\n2,20\n"},
+ )
+
+ response = self.source.source_for_pipeline(make_config(), make_inputs("refunds"))
+
+ connection = patched_connection(client, TRANSPORT_CONNECTION_TARGET)
+ try:
+ rows = [row for chunk in cast(Any, response.items()) for row in chunk]
+ finally:
+ connection.stop()
+
+ assert response.name == "refunds"
+ assert [(row["id"], row["total"], row[FILE_PATH_COLUMN]) for row in rows] == [("2", "20", "refunds.csv")]
+
+
+class TestHostRechecks:
+ """A stored credential must not be sent to a host that stopped being reachable-safe after create."""
+
+ def setup_method(self) -> None:
+ self.source = SFTPSource()
+
+ @pytest.mark.parametrize("method", ["get_schemas", "source_for_pipeline"])
+ def test_rejects_an_unsafe_host_before_connecting(self, method: str) -> None:
+ with patch.object(SFTPSource, "is_database_host_valid", return_value=(False, "internal IP")):
+ with (
+ patch(CONNECTION_TARGET) as connection,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.sftp.source.sftp_source"
+ ) as source_fn,
+ ):
+ with pytest.raises(SFTPCredentialsError, match="internal IP"):
+ if method == "get_schemas":
+ self.source.get_schemas(make_config(), team_id=1)
+ else:
+ self.source.source_for_pipeline(make_config(), make_inputs())
+
+ connection.assert_not_called()
+ source_fn.assert_not_called()