: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement n8n import source (#67821)
Tom Owers99dbd17f49c9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 710833b6a859..9242b05b404d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -216,6 +216,7 @@ the row lists both.| mssql | DB protocol | pyodbc / pymssql | ➖ || mux | HTTP | requests | ✅ || mysql | DB protocol | pymysql | ➖ |+| n8n | HTTP | requests | ✅ || new_york_times | HTTP | requests | ✅ || news_api | HTTP | requests | ✅ || newsdata | HTTP | requests | ✅ |@@ -531,7 +532,6 @@ doesn't conflict with concurrent PRs.- missive- mode- my_hours-- n8n- nasa- navan- nebius_aidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 7d19518ed1e1..d2158c8dd7a9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2102,7 +2102,8 @@ class MySQLSourceConfig(config.Config):@config.configclass N8nSourceConfig(config.Config):- pass+ host: str+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/canonical_descriptions.pynew file mode 100644index 000000000000..7fea87344992--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/canonical_descriptions.py@@ -0,0 +1,94 @@+"""Canonical, documentation-sourced descriptions for n8n endpoints and columns.++Sourced from the official n8n public API reference (https://docs.n8n.io/api/api-reference/).+Keyed by the endpoint names in `settings.py` `N8N_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced n8n table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "workflows": {+ "description": "Automation workflows defined in the n8n instance.",+ "docs_url": "https://docs.n8n.io/api/api-reference/",+ "columns": {+ "id": "Unique identifier for the workflow.",+ "name": "Human-readable name of the workflow.",+ "active": "Whether the workflow is currently active (its triggers are enabled).",+ "isArchived": "Whether the workflow has been archived.",+ "nodes": "The nodes that make up the workflow.",+ "connections": "How the workflow's nodes are wired together.",+ "settings": "Workflow-level settings (error workflow, timezone, execution order, etc.).",+ "staticData": "Persisted static data used by the workflow's nodes across executions.",+ "tags": "Tags assigned to the workflow.",+ "triggerCount": "Number of active trigger nodes in the workflow.",+ "versionId": "Identifier of the current workflow version, used for optimistic locking.",+ "meta": "Workflow metadata such as onboarding and template information.",+ "createdAt": "Time at which the workflow was created.",+ "updatedAt": "Time at which the workflow was last updated.",+ },+ },+ "executions": {+ "description": "Individual runs of workflows, one row per execution.",+ "docs_url": "https://docs.n8n.io/api/api-reference/",+ "columns": {+ "id": "Unique identifier for the execution.",+ "finished": "Whether the execution finished running.",+ "mode": "How the execution was triggered (e.g. manual, trigger, webhook, retry).",+ "retryOf": "The id of the execution this run is a retry of, if any.",+ "retrySuccessId": "The id of the successful execution produced when retrying this one.",+ "status": "Execution status (e.g. success, error, running, waiting, canceled).",+ "startedAt": "Time at which the execution started.",+ "stoppedAt": "Time at which the execution stopped. Null while still running.",+ "waitTill": "Time until which a waiting execution is paused, if applicable.",+ "workflowId": "The id of the workflow this execution belongs to.",+ "customData": "Custom key-value data attached to the execution.",+ },+ },+ "tags": {+ "description": "Tags used to organize and group workflows.",+ "docs_url": "https://docs.n8n.io/api/api-reference/",+ "columns": {+ "id": "Unique identifier for the tag.",+ "name": "The tag's name.",+ "createdAt": "Time at which the tag was created.",+ "updatedAt": "Time at which the tag was last updated.",+ },+ },+ "users": {+ "description": "Users of the n8n instance.",+ "docs_url": "https://docs.n8n.io/api/api-reference/",+ "columns": {+ "id": "Unique identifier for the user.",+ "email": "The user's email address.",+ "firstName": "The user's first name.",+ "lastName": "The user's last name.",+ "isPending": "Whether the user's invitation is still pending acceptance.",+ "role": "The user's global role on the instance (e.g. owner, admin, member).",+ "createdAt": "Time at which the user was created.",+ "updatedAt": "Time at which the user was last updated.",+ },+ },+ "variables": {+ "description": "Instance-level environment variables usable across workflows.",+ "docs_url": "https://docs.n8n.io/api/api-reference/",+ "columns": {+ "id": "Unique identifier for the variable.",+ "key": "The variable's key.",+ "value": "The variable's value.",+ "type": "The variable's type.",+ "project": "The project the variable belongs to, if scoped to one.",+ },+ },+ "projects": {+ "description": "Projects that group workflows, credentials, and variables.",+ "docs_url": "https://docs.n8n.io/api/api-reference/",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "The project's name.",+ "type": "The project's type (e.g. personal or team).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.pynew file mode 100644index 000000000000..43d655f8b505--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/n8n.py@@ -0,0 +1,202 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.cloud_utils import is_cloud++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.settings import (+ N8N_API_PATH,+ N8N_ENDPOINTS,+ PAGE_SIZE,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5+++class N8nRetryableError(Exception):+ pass+++class N8nResumeConfig:+ # The `nextCursor` token to fetch the next page. None means "start from the+ # first page" — used both on a fresh sync and when the bookmark predates any page.+ next_cursor: Optional[str] = None+++def normalize_host(host: str) -> str:+ """Normalize the instance URL and reject anything that isn't plain http(s).++ Accepts either a bare host (`myinstance.app.n8n.cloud`) or a full URL, with or+ without the `/api/v1` suffix, and returns the instance origin (no trailing slash).+ """+ host = host.strip()+ if not host:+ raise ValueError("n8n host is required")+ if "://" not in host:+ host = f"https://{host}"+ host = host.rstrip("/")+ # Tolerate a pasted API base URL by trimming a trailing /api/v1.+ if host.endswith(N8N_API_PATH):+ host = host[: -len(N8N_API_PATH)]+ parsed = urlparse(host)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise ValueError(f"Invalid n8n host: {host}")+ # The API key rides in the X-N8N-API-KEY header on every request, so plaintext http+ # would leak it to any network observer. On PostHog Cloud the request egresses over the+ # public internet, so require https. Self-hosted operators control their own network path+ # (e.g. an internal n8n reachable only over http), so http stays allowed there — mirroring+ # how host IP safety is only enforced on cloud.+ if parsed.scheme == "http" and is_cloud():+ raise ValueError("n8n instance URL must use https")+ # SSRF guard: urlparse treats a backslash as userinfo and an "@" as a userinfo+ # separator, but urllib3/requests treat the backslash as an authority separator, so+ # `http://127.0.0.1\@example.com` validates as example.com yet connects to 127.0.0.1.+ # A legitimate instance URL has no userinfo, so reject either construct outright.+ if "\\" in host or "%5c" in host.lower() or "@" in parsed.netloc:+ raise ValueError(f"Invalid n8n host: {host}")+ return host+++def hostname_of(host: str) -> str:+ return urlparse(normalize_host(host)).hostname or ""+++def _base_url(host: str) -> str:+ return f"{normalize_host(host)}{N8N_API_PATH}"+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"X-N8N-API-KEY": api_key, "Accept": "application/json"}+++def _get_session(api_key: str) -> requests.Session:+ # `host` is user-supplied, so pin redirects off so validation and the outbound+ # request stay on the same target (SSRF defense-in-depth). Redact the key from logs.+ return make_tracked_session(redact_values=(api_key,), allow_redirects=False)+++def _build_url(base_url: str, params: dict[str, Any]) -> str:+ if not params:+ return base_url+ return f"{base_url}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type(+ (+ N8nRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise N8nRetryableError(f"n8n API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"n8n API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ body = response.json()+ return body if isinstance(body, dict) else {"data": body}+++def validate_credentials(host: str, api_key: str) -> bool:+ """Confirm the instance is reachable and the key is accepted.++ Probes /workflows with limit=1 — the most broadly-available scope on an API key.+ """+ try:+ url = _build_url(f"{_base_url(host)}/workflows", {"limit": 1})+ response = _get_session(api_key).get(url, headers=_get_headers(api_key), timeout=15)+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ host: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[N8nResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = N8N_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ session = _get_session(api_key)++ base_params: dict[str, Any] = {"limit": PAGE_SIZE, **config.extra_params}+ endpoint_url = f"{_base_url(host)}{config.path}"++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor: Optional[str] = resume_config.next_cursor if resume_config is not None else None+ if cursor:+ logger.debug(f"n8n: resuming {endpoint} from cursor")++ while True:+ params = dict(base_params)+ if cursor:+ params["cursor"] = cursor++ data = _fetch_page(session, _build_url(endpoint_url, params), headers, logger)++ # `data` is the required envelope field; fail fast if a 200 response ever omits it.+ items = data["data"]+ next_cursor = data.get("nextCursor")++ if items:+ yield items++ if not next_cursor:+ break++ cursor = next_cursor+ # Save state AFTER yielding so a crash re-yields the in-flight page rather+ # than skipping it — merge dedupes on the primary key.+ resumable_source_manager.save_state(N8nResumeConfig(next_cursor=cursor))+++def n8n_source(+ host: str,+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[N8nResumeConfig],+) -> SourceResponse:+ config = N8N_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=list(config.primary_keys),+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.pynew file mode 100644index 000000000000..296c81d2daa1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/settings.py@@ -0,0 +1,63 @@+from dataclasses import dataclass, field+from typing import Optional++# n8n's public REST API is served per-instance under this base path.+N8N_API_PATH = "/api/v1"++# Cursor pagination page size. The API defaults to 100 and caps at 250; we+# request the max to minimize round trips on large instances.+PAGE_SIZE = 250+++@dataclass+class N8nEndpointConfig:+ name: str+ path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable datetime field used for datetime partitioning. n8n objects that+ # carry no timestamp (variables, projects) leave this None and go unpartitioned.+ partition_key: Optional[str] = None+ # Extra query params sent on every list request for this endpoint.+ extra_params: dict[str, str] = field(default_factory=dict)+++N8N_ENDPOINTS: dict[str, N8nEndpointConfig] = {+ # Workflows carry createdAt/updatedAt. `excludePinnedData` keeps the+ # dev-time pinned sample payloads out of each row.+ "workflows": N8nEndpointConfig(+ name="workflows",+ path="/workflows",+ partition_key="createdAt",+ extra_params={"excludePinnedData": "true"},+ ),+ # Executions have no createdAt/updatedAt; startedAt is the stable creation+ # timestamp. The heavy per-run `data` blob is omitted (includeData defaults+ # to false) to keep rows small.+ "executions": N8nEndpointConfig(+ name="executions",+ path="/executions",+ partition_key="startedAt",+ ),+ "tags": N8nEndpointConfig(+ name="tags",+ path="/tags",+ partition_key="createdAt",+ ),+ "users": N8nEndpointConfig(+ name="users",+ path="/users",+ partition_key="createdAt",+ ),+ # Variables and projects expose no timestamp field, so they are full refresh+ # only with no datetime partitioning.+ "variables": N8nEndpointConfig(+ name="variables",+ path="/variables",+ ),+ "projects": N8nEndpointConfig(+ name="projects",+ path="/projects",+ ),+}++ENDPOINTS = tuple(N8N_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/source.pyindex 09e57cf2b34a..43229bb5198d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/source.py@@ -1,30 +1,163 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import N8nSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.n8n import (+ N8nResumeConfig,+ hostname_of,+ n8n_source,+ validate_credentials as validate_n8n_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.settings import ENDPOINTS, N8N_ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class N8nSource(SimpleSource[N8nSourceConfig]):+class N8nSource(ResumableSource[N8nSourceConfig, N8nResumeConfig], ValidateDatabaseHostMixin):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.N8N+ @property+ def connection_host_fields(self) -> list[str]:+ # `host` determines where the stored API key is sent, so retargeting it+ # must re-require the key.+ return ["host"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.N8N,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="n8n",+ caption="""Connect your n8n instance to pull your workflow automation data into the PostHog Data warehouse.++Works with n8n Cloud and self-hosted instances. Enter your instance URL (e.g. `https://myorg.app.n8n.cloud`) and an API key created under **Settings > n8n API**.++Some tables (users, projects, variables) require an owner/admin key or an Enterprise plan; deselect them if your key can't access them.""",iconPath="/static/services/n8n.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/n8n",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="Instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://myorg.app.n8n.cloud",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="n8n_api_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your n8n API key is invalid or has been revoked. Create a new key under Settings > n8n API, then reconnect.",+ "403 Client Error: Forbidden for url": "Your n8n API key does not have access to this resource. Some tables require an owner/admin key or an Enterprise plan — deselect them or use a key with the required access.",+ }++ def get_schemas(+ self,+ config: N8nSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # n8n's public API exposes no server-side timestamp filter, so every table+ # is full refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=list(N8N_ENDPOINTS[endpoint].primary_keys),+ )+ for endpoint in ENDPOINTS+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self, config: N8nSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), team_id)+ except ValueError:+ return False, "Invalid n8n instance URL"+ if not host_valid:+ return False, host_error++ if validate_n8n_credentials(config.host, config.api_key):+ return True, None++ return False, "Invalid n8n credentials. Check the instance URL and API key."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[N8nResumeConfig]:+ return ResumableSourceManager[N8nResumeConfig](inputs, N8nResumeConfig)++ def source_for_pipeline(+ self,+ config: N8nSourceConfig,+ resumable_source_manager: ResumableSourceManager[N8nResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.host), inputs.team_id)+ except ValueError:+ raise ValueError("Invalid n8n instance URL")+ if not host_valid:+ raise ValueError(host_error or "Invalid n8n host")++ return n8n_source(+ host=config.host,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n.pynew file mode 100644index 000000000000..d6f32a1ee3a6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n.py@@ -0,0 +1,230 @@+from typing import Any++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.n8n import (+ N8nResumeConfig,+ N8nRetryableError,+ _build_url,+ _fetch_page,+ get_rows,+ hostname_of,+ n8n_source,+ normalize_host,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.settings import ENDPOINTS, N8N_ENDPOINTS++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.n8n.n8n"++# `_fetch_page` is wrapped by tenacity's @retry; call the underlying function directly so a+# retryable status raises immediately instead of sleeping through the backoff schedule.+_fetch_undecorated = _fetch_page.__wrapped__ # type: ignore[attr-defined]+++def _make_manager(resume_state: N8nResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: Any, status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = status_code < 400+ return resp+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("https://myorg.app.n8n.cloud", "https://myorg.app.n8n.cloud"),+ ("myorg.app.n8n.cloud", "https://myorg.app.n8n.cloud"),+ ("https://n8n.example.com/", "https://n8n.example.com"),+ ("http://n8n.internal:5678", "http://n8n.internal:5678"),+ # A pasted API base URL is tolerated by trimming the /api/v1 suffix.+ ("https://myorg.app.n8n.cloud/api/v1", "https://myorg.app.n8n.cloud"),+ ("https://myorg.app.n8n.cloud/api/v1/", "https://myorg.app.n8n.cloud"),+ ],+ )+ def test_valid_hosts(self, value, expected):+ assert normalize_host(value) == expected++ @pytest.mark.parametrize(+ "value",+ [+ "",+ " ",+ "ftp://example.com",+ "https://",+ # SSRF: urlparse reads the host as example.com but urllib3 connects to+ # 127.0.0.1 (backslash / userinfo confusion), so these must be rejected.+ r"http://127.0.0.1\@example.com",+ r"http://127.0.0.1%[email protected]",+ "https://[email protected]",+ ],+ )+ def test_invalid_hosts_raise(self, value):+ with pytest.raises(ValueError):+ normalize_host(value)++ @pytest.mark.parametrize(+ "cloud, host, expect_raise",+ [+ # On cloud the API key would egress over the public internet, so plaintext+ # http is rejected while https is fine.+ (True, "http://n8n.example.com", True),+ (True, "https://n8n.example.com", False),+ # Self-hosted operators control their network path, so http stays allowed.+ (False, "http://n8n.internal:5678", False),+ ],+ )+ def test_http_requires_https_only_on_cloud(self, cloud, host, expect_raise):+ with mock.patch(f"{_MODULE}.is_cloud", return_value=cloud):+ if expect_raise:+ with pytest.raises(ValueError):+ normalize_host(host)+ else:+ assert normalize_host(host) == host++ def test_hostname_of(self):+ assert hostname_of("https://myorg.app.n8n.cloud/api/v1") == "myorg.app.n8n.cloud"+++class TestBuildUrl:+ def test_no_params_returns_base(self):+ assert _build_url("https://x/api/v1/workflows", {}) == "https://x/api/v1/workflows"++ def test_params_are_urlencoded(self):+ url = _build_url("https://x/api/v1/workflows", {"limit": 250, "cursor": "a b/c"})+ assert url == "https://x/api/v1/workflows?limit=250&cursor=a+b%2Fc"+++class TestFetchPage:+ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])+ def test_retryable_statuses_raise_retryable_error(self, status_code):+ session = mock.MagicMock()+ session.get.return_value = _response({}, status_code=status_code)+ with pytest.raises(N8nRetryableError):+ _fetch_undecorated(session, "https://x", {}, mock.MagicMock())++ @pytest.mark.parametrize("status_code", [400, 401, 403, 404])+ def test_client_errors_raise_for_status(self, status_code):+ session = mock.MagicMock()+ resp = _response({}, status_code=status_code)+ resp.raise_for_status.side_effect = requests.HTTPError(f"{status_code} Client Error", response=resp)+ session.get.return_value = resp+ with pytest.raises(requests.HTTPError):+ _fetch_undecorated(session, "https://x", {}, mock.MagicMock())++ def test_non_dict_body_is_wrapped_in_data(self):+ session = mock.MagicMock()+ session.get.return_value = _response([{"id": "1"}])+ body = _fetch_undecorated(session, "https://x", {}, mock.MagicMock())+ assert body == {"data": [{"id": "1"}]}+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_credentials(self, mock_session):+ mock_session.return_value.get.return_value = _response({"data": [], "nextCursor": None})++ assert validate_credentials("https://myorg.app.n8n.cloud", "key") is True+ url = mock_session.return_value.get.call_args.args[0]+ headers = mock_session.return_value.get.call_args.kwargs["headers"]+ assert url == "https://myorg.app.n8n.cloud/api/v1/workflows?limit=1"+ assert headers["X-N8N-API-KEY"] == "key"++ @pytest.mark.parametrize("status_code", [401, 403, 500])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_non_200_fails_validation(self, mock_session, status_code):+ mock_session.return_value.get.return_value = _response({}, status_code=status_code)+ assert validate_credentials("https://myorg.app.n8n.cloud", "bad") is False++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_network_error_fails_validation(self, mock_session):+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")+ assert validate_credentials("https://myorg.app.n8n.cloud", "key") is False+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_single_page_yields_and_stops(self, mock_session):+ mock_session.return_value.get.return_value = _response({"data": [{"id": "1"}, {"id": "2"}], "nextCursor": None})++ manager = _make_manager()+ batches = list(get_rows("https://n.example.com", "key", "workflows", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["1", "2"]+ # A single page never advances the cursor, so no resume state is persisted.+ manager.save_state.assert_not_called()+ url = mock_session.return_value.get.call_args.args[0]+ assert url.startswith("https://n.example.com/api/v1/workflows?")+ assert "limit=250" in url+ assert "excludePinnedData=true" in url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_and_saves_cursor_after_each_page(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({"data": [{"id": "1"}], "nextCursor": "CURSOR_A"}),+ _response({"data": [{"id": "2"}], "nextCursor": "CURSOR_B"}),+ _response({"data": [{"id": "3"}], "nextCursor": None}),+ ]++ manager = _make_manager()+ batches = list(get_rows("https://n.example.com", "key", "tags", mock.MagicMock(), manager))++ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]+ # State saved once per page that has a following page (not for the last page).+ saved = [call.args[0].next_cursor for call in manager.save_state.call_args_list]+ assert saved == ["CURSOR_A", "CURSOR_B"]+ # The second request carries the cursor from the first page.+ second_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert "cursor=CURSOR_A" in second_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_cursor(self, mock_session):+ mock_session.return_value.get.return_value = _response({"data": [{"id": "9"}], "nextCursor": None})++ manager = _make_manager(N8nResumeConfig(next_cursor="SAVED"))+ list(get_rows("https://n.example.com", "key", "workflows", mock.MagicMock(), manager))++ first_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "cursor=SAVED" in first_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_page_still_terminates(self, mock_session):+ mock_session.return_value.get.return_value = _response({"data": [], "nextCursor": None})++ manager = _make_manager()+ batches = list(get_rows("https://n.example.com", "key", "projects", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()+++class TestN8nSource:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_response_primary_key_and_partitioning(self, endpoint):+ config = N8N_ENDPOINTS[endpoint]+ response = n8n_source("https://n.example.com", "key", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_executions_partition_on_started_at(self):+ # Executions have no createdAt/updatedAt; startedAt is the stable creation field.+ response = n8n_source("https://n.example.com", "key", "executions", mock.MagicMock(), _make_manager())+ assert response.partition_keys == ["startedAt"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n_source.pynew file mode 100644index 000000000000..1eaf6bffc993--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/n8n/tests/test_n8n_source.py@@ -0,0 +1,166 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import N8nSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.n8n import N8nResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.n8n.source import N8nSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestN8nSource:+ def setup_method(self):+ self.source = N8nSource()+ self.team_id = 123+ self.config = N8nSourceConfig(host="https://myorg.app.n8n.cloud", api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.N8N++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "N8n"+ assert config.label == "n8n"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/n8n.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/n8n"++ field_names = [f.name for f in config.fields]+ assert field_names == ["host", "api_key"]++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ def test_connection_host_fields_cover_host(self):+ # The instance URL decides where the stored API key gets sent.+ assert self.source.connection_host_fields == ["host"]++ def test_lists_tables_without_credentials(self):+ # get_schemas is a static endpoint catalog, so the public docs can render tables.+ assert self.source.lists_tables_without_credentials is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://myorg.app.n8n.cloud/api/v1/workflows",+ "403 Client Error: Forbidden for url: https://myorg.app.n8n.cloud/api/v1/users",+ ],+ )+ def test_non_retryable_errors_match_known_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "error",+ [+ "500 Server Error for url: https://myorg.app.n8n.cloud/api/v1/workflows",+ "429 Client Error: Too Many Requests",+ ],+ )+ def test_non_retryable_errors_does_not_match_transient_failures(self, error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in error for key in non_retryable_errors)++ def test_get_schemas_are_all_full_refresh(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # n8n exposes no server-side timestamp filter, so nothing is incremental.+ assert all(not schema.supports_incremental for schema in schemas.values())+ assert all(not schema.supports_append for schema in schemas.values())+ assert all(schema.incremental_fields == [] for schema in schemas.values())+ # Primary keys are surfaced so the public docs' Supported tables section renders them.+ assert all(schema.detected_primary_keys == ["id"] for schema in schemas.values())++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["workflows"])+ assert len(schemas) == 1+ assert schemas[0].name == "workflows"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.n8n.source.validate_n8n_credentials")+ @mock.patch.object(N8nSource, "is_database_host_valid")+ def test_validate_credentials_happy_path(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = True++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert error_message is None+ mock_host_valid.assert_called_once_with("myorg.app.n8n.cloud", self.team_id)+ mock_validate.assert_called_once_with("https://myorg.app.n8n.cloud", "key")++ @mock.patch.object(N8nSource, "is_database_host_valid")+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message == "Host is not allowed"++ def test_validate_credentials_rejects_invalid_url(self):+ config = N8nSourceConfig(host="ftp://nope", api_key="key")++ is_valid, error_message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is False+ assert error_message == "Invalid n8n instance URL"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.n8n.source.validate_n8n_credentials")+ @mock.patch.object(N8nSource, "is_database_host_valid")+ def test_validate_credentials_bad_key(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = False++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert "Invalid n8n credentials" in (error_message or "")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is N8nResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.n8n.source.n8n_source")+ @mock.patch.object(N8nSource, "is_database_host_valid")+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_n8n_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.schema_name = "workflows"+ inputs.team_id = self.team_id+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_n8n_source.assert_called_once()+ kwargs = mock_n8n_source.call_args.kwargs+ assert kwargs["host"] == "https://myorg.app.n8n.cloud"+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "workflows"+ assert kwargs["resumable_source_manager"] is manager++ @mock.patch.object(N8nSource, "is_database_host_valid")+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")+ inputs = mock.MagicMock()+ inputs.schema_name = "workflows"+ inputs.team_id = self.team_id++ with pytest.raises(ValueError, match="Host is not allowed"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)