: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): add Lightdash source (#73197)
Tom Owers364e58de3ee4
diff --git a/frontend/public/services/lightdash.png b/frontend/public/services/lightdash.pngindex 7418dcafc6ed..a2c244aa128c 100644Binary files a/frontend/public/services/lightdash.png and b/frontend/public/services/lightdash.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0cb7284a7183..43676e300d16 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -331,6 +331,7 @@ the row lists both.| lemlist | HTTP | requests | ✅ || lemon_squeezy | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || less_annoying_crm | HTTP | requests | ✅ |+| lightdash | HTTP | requests + `rest_source.RESTClient` | ✅ || lightfield | HTTP | requests + `rest_source.RESTClient` | ✅ || lightspeed_retail | HTTP | requests | ✅ || linear | HTTP | requests | ✅ |@@ -1048,7 +1049,6 @@ doesn't conflict with concurrent PRs.- lever- lexware_office- liana-- lightdash- lingo_dev- linkedin_pages- linnworksdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.pyindex 4c697269bfd3..2d15eda3e413 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py@@ -270,6 +270,7 @@ def create_resources(max_retry_attempts=client_config.get("max_retries", DEFAULT_RETRY_ATTEMPTS),allowed_hosts=client_config.get("allowed_hosts"),allow_redirects=client_config.get("allow_redirects", True),+ request_timeout=client_config.get("request_timeout"),)hooks = create_response_hooks(endpoint_config.get("response_actions"))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.pyindex 589482625651..2ed05a7c39c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/rest_client.py@@ -13,6 +13,7 @@ from requests.exceptions import (ConnectionError as RequestsConnectionError,HTTPError,JSONDecodeError as RequestsJSONDecodeError,+ Timeout as RequestsTimeout,)from tenacity import RetryCallState, retry, retry_if_exception_type@@ -181,12 +182,18 @@ class RESTClient:max_retry_attempts: int = DEFAULT_RETRY_ATTEMPTS,allowed_hosts: Optional[list[str]] = None,allow_redirects: bool = True,+ request_timeout: Optional[float | tuple[float, float]] = None,) -> None:self.base_url = base_url or ""self.headers = headers or {}self.auth = authself.paginator = paginatorself._max_retry_attempts = max_retry_attempts+ # Per-request (connect, read) timeout in seconds handed to ``session.send``. Left None,+ # a request can hang forever — a source pointed at a server that accepts the connection+ # then never responds would hold an import worker indefinitely. Sources talking to a+ # customer-controlled host should set this so every sync request is bounded.+ self._request_timeout = request_timeoutself._allow_redirects = allow_redirects# When set (even to an empty list), every outgoing request URL — including# paginator next-page links and seeded resume URLs — must resolve to one of@@ -355,7 +362,7 @@ class RESTClient:# truncated/partial body below rather than letting them skip this retry loop and fail the# whole sync on one bad connection attempt.try:- response = self.session.send(prepared, allow_redirects=self._allow_redirects)+ response = self.session.send(prepared, allow_redirects=self._allow_redirects, timeout=self._request_timeout)except ChunkedEncodingError as e:raise RESTClientRetryableError(self._redact(f"Connection broken while reading response: {e}")) from eexcept RequestsConnectionError as e:@@ -368,6 +375,15 @@ class RESTClient:raise RESTClientRetryableError(self._redact(f"Connection error ({type(e).__name__}) for {_safe_url(prepared.url or '')}")) from e+ except RequestsTimeout as e:+ # A connect/read timeout (a host that accepts the connection then stalls) is transient+ # from our side. Reissue it through the retry loop like the connection failures above —+ # so a stalled request is bounded per attempt instead of hanging the worker forever, yet+ # still gets a few tries before the sync gives up. Built from `_safe_url` for the same+ # credential-in-query-string reason as the ConnectionError branch.+ raise RESTClientRetryableError(+ self._redact(f"Request timed out ({type(e).__name__}) for {_safe_url(prepared.url or '')}")+ ) from e# With redirects disabled, a 3xx is not an error to `raise_for_status` and would fall# through to JSON parsing; reject it explicitly so a redirect can't smuggle the requestdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.pyindex 6b4d3efcba71..4b1126306711 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_rest_client.py@@ -6,7 +6,7 @@ import pytestfrom unittest.mock import MagicMock, patchfrom requests import Response-from requests.exceptions import ChunkedEncodingError, ProxyError+from requests.exceptions import ChunkedEncodingError, ProxyError, ReadTimeoutfrom posthog.temporal.common.errors import NonReportableError@@ -518,6 +518,44 @@ class TestRESTClient:assert mock_session.send.call_count == 5+ @patch("tenacity.nap.time.sleep")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ )+ def test_send_request_retries_read_timeout_then_succeeds(self, MockSession, mock_sleep) -> None:+ # A host that accepts the connection then stalls surfaces from `send` as a ReadTimeout.+ # It's transient from our side, so reissue it through the retry loop rather than letting+ # it escape uncaught and fail the whole sync on one slow response.+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.return_value = MagicMock(url="https://api.example.com/items")++ ok = _make_response({"results": [{"id": 1}]})+ mock_session.send.side_effect = [ReadTimeout("Read timed out."), ok]++ client = RESTClient(base_url="https://api.example.com", request_timeout=(3.05, 30))+ pages = list(client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator()))++ assert pages == [[{"id": 1}]]+ assert mock_session.send.call_count == 2++ @patch("tenacity.nap.time.sleep")+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ )+ def test_request_timeout_is_passed_to_session_send(self, MockSession, mock_sleep) -> None:+ # The configured timeout must reach `session.send` — without it a stalled host holds the+ # import worker forever, the vulnerability this bound closes.+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.return_value = MagicMock(url="https://api.example.com/items")+ mock_session.send.return_value = _make_response({"results": [{"id": 1}]})++ client = RESTClient(base_url="https://api.example.com", request_timeout=(3.05, 30))+ list(client.paginate(path="/items", data_selector="results", paginator=SinglePagePaginator()))++ assert mock_session.send.call_args.kwargs["timeout"] == (3.05, 30)+@patch("tenacity.nap.time.sleep")@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.pyindex 19e463b52056..2feadcad7446 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py@@ -178,6 +178,10 @@ class ClientConfig(TypedDict, total=False):# When False, redirects are not followed and any 3xx is rejected — closes the redirect-based# off-host escape that host-pinning alone would miss. Defaults to True (follow redirects).allow_redirects: bool+ # Per-request (connect, read) timeout in seconds. Left unset, requests never time out and a+ # source pointed at a customer-controlled host that stalls holds an import worker forever.+ # A single float applies to both connect and read; a tuple sets them separately.+ request_timeout: Optional[float | tuple[float, float]]class IncrementalArgs(TypedDict, total=False):diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lightdash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lightdash.pyindex fc293e83a7d2..9bf9855f6564 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lightdash.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lightdash.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass LightdashSourceConfig(config.Config):- pass+ instance_url: str+ api_token: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/canonical_descriptions.pynew file mode 100644index 000000000000..596721277ddd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/canonical_descriptions.py@@ -0,0 +1,112 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "A Lightdash project: one dbt project connected to a warehouse, containing spaces, dashboards, and charts.",+ "docs_url": "https://docs.lightdash.com/api-reference/organizations/list-organization-projects",+ "columns": {+ "projectUuid": "Unique identifier for the project.",+ "name": "Display name of the project.",+ "type": "Project type, e.g. DEFAULT or PREVIEW.",+ "organizationUuid": "Unique identifier of the organization the project belongs to.",+ "createdAt": "Timestamp the project was created.",+ "createdByUserUuid": "Unique identifier of the user who created the project.",+ "createdByUserName": "Display name of the user who created the project.",+ "warehouseType": "The connected warehouse type, e.g. bigquery, snowflake, postgres, redshift, databricks.",+ "upstreamProjectUuid": "Unique identifier of the project this preview project was created from, if any.",+ },+ },+ "spaces": {+ "description": "A Lightdash space: a folder within a project that groups dashboards and charts, with its own access controls.",+ "docs_url": "https://docs.lightdash.com/api-reference/spaces/get-space",+ "columns": {+ "uuid": "Unique identifier for the space.",+ "name": "Display name of the space.",+ "slug": "URL-friendly identifier for the space.",+ "projectUuid": "Unique identifier of the project the space belongs to.",+ "organizationUuid": "Unique identifier of the organization the space belongs to.",+ "parentSpaceUuid": "Unique identifier of the parent space, for a nested space.",+ "path": "Slash-separated path of the space through its parent spaces.",+ "isPrivate": "Whether the space is private (only visible to users granted explicit access).",+ "dashboardCount": "Number of dashboards saved in the space.",+ "chartCount": "Number of charts saved in the space.",+ "childSpaceCount": "Number of nested spaces inside the space.",+ },+ },+ "dashboards": {+ "description": "A Lightdash dashboard: a saved collection of charts and other tiles arranged for viewing together.",+ "docs_url": "https://docs.lightdash.com/api-reference/projects/list-dashboards",+ "columns": {+ "uuid": "Unique identifier for the dashboard.",+ "name": "Display name of the dashboard.",+ "description": "Optional description of the dashboard.",+ "projectUuid": "Unique identifier of the project the dashboard belongs to.",+ "organizationUuid": "Unique identifier of the organization the dashboard belongs to.",+ "spaceUuid": "Unique identifier of the space the dashboard is saved in.",+ "updatedAt": "Timestamp the dashboard was last updated.",+ "views": "Number of times the dashboard has been viewed.",+ "firstViewedAt": "Timestamp the dashboard was first viewed, if ever.",+ "pinnedListUuid": "Unique identifier of the pinned list the dashboard belongs to, if pinned.",+ "tileTypes": "Kinds of tiles the dashboard contains, e.g. saved_chart, markdown, loom.",+ },+ },+ "charts": {+ "description": "A Lightdash saved chart: a query result visualization that can be added to one or more dashboards.",+ "docs_url": "https://docs.lightdash.com/api-reference/projects/list-charts-in-project",+ "columns": {+ "uuid": "Unique identifier for the chart.",+ "name": "Display name of the chart.",+ "description": "Optional description of the chart.",+ "slug": "URL-friendly identifier for the chart.",+ "projectUuid": "Unique identifier of the project the chart belongs to.",+ "organizationUuid": "Unique identifier of the organization the chart belongs to.",+ "spaceUuid": "Unique identifier of the space the chart is saved in.",+ "spaceName": "Display name of the space the chart is saved in.",+ "dashboardUuid": "Unique identifier of the dashboard the chart is embedded in, if any.",+ "dashboardName": "Display name of the dashboard the chart is embedded in, if any.",+ "source": "How the chart's query is defined: dbt_explore or sql.",+ "chartKind": "Visualization kind, e.g. line, bar, scatter, pie, table.",+ "chartType": "Underlying chart config type, e.g. cartesian, table, big_number, pie.",+ "updatedAt": "Timestamp the chart was last updated.",+ "views": "Number of times the chart has been viewed.",+ "firstViewedAt": "Timestamp the chart was first viewed, if ever.",+ },+ },+ "metrics_catalog": {+ "description": "An entry in a Lightdash project's data catalog: a metric or dimension field defined in the underlying dbt project, with its usage and ownership metadata.",+ "docs_url": "https://docs.lightdash.com/api-reference/catalog/list-metrics-in-catalog",+ "columns": {+ "catalogSearchUuid": "Unique identifier for the catalog entry.",+ "name": "Field name as defined in the dbt project.",+ "label": "Human-readable label for the field.",+ "description": "Optional description of the field, from the dbt project's metadata.",+ "tableName": "Name of the dbt model (table) the field belongs to.",+ "tableGroupLabel": "Group label of the table the field belongs to, if configured.",+ "fieldValueType": "The field's metric or dimension type, e.g. sum, average, string, date.",+ "basicType": "Simplified value type: string, number, date, timestamp, or boolean.",+ "type": "Whether the catalog entry is a metric, dimension, or table.",+ "chartUsage": "Number of charts that use this field.",+ "verifiedChartUsage": "Number of verified charts that use this field.",+ "tags": "Tags applied to the field in the underlying dbt project.",+ },+ },+ "org_users": {+ "description": "A member of the Lightdash organization, with their role and account status.",+ "docs_url": "https://docs.lightdash.com/api-reference/organizations/list-organization-members",+ "columns": {+ "userUuid": "Unique identifier for the user.",+ "firstName": "User's first name.",+ "lastName": "User's last name.",+ "email": "User's email address.",+ "organizationUuid": "Unique identifier of the organization the user belongs to.",+ "role": "Organization-level role, e.g. member, viewer, editor, developer, admin.",+ "isActive": "Whether the user has an active account.",+ "isPending": "Whether the user's invite is still pending.",+ "isInviteExpired": "Whether the user's invite link has expired.",+ "userCreatedAt": "Timestamp the user account was created.",+ "userUpdatedAt": "Timestamp the user account was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/lightdash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/lightdash.pynew file mode 100644index 000000000000..a5e44e471581--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/lightdash.py@@ -0,0 +1,234 @@+import re+from collections.abc import Callable, Iterable+from typing import Any, Optional, cast+from urllib.parse import urlparse++import requests++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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.settings import (+ LIGHTDASH_ENDPOINTS,+ LightdashEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60++HOST_NOT_ALLOWED_ERROR = "Lightdash instance URL is not allowed"++# The full-collection response envelope every Lightdash list endpoint shares:+# {"status": "ok", "results": [...] | {"data": [...], "pagination": {...}}}.+_PAGINATED_TOTAL_PATH = "results.pagination.totalPageCount"++# Loopback hosts where plaintext HTTP carries no network-exposure risk (local dev / self-hosted on+# the same box). Every other host is forced to HTTPS so the personal access token never travels in+# cleartext.+LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}++# Lightdash instance hostnames are a plain DNS name or IP (with optional port) — anything else+# (path, query, userinfo) could disagree with what the HTTP client actually connects to.+_HOSTNAME_RE = re.compile(r"^[A-Za-z0-9.\-]+(?::\d+)?$")+++class LightdashHostNotAllowedError(Exception):+ pass+++def normalize_host(instance_url: str) -> str:+ """Turn whatever the user typed into a bare instance base URL (scheme + host, no path).++ Accepts ``https://app.lightdash.cloud``, ``app.lightdash.cloud``, and+ ``https://app.lightdash.cloud/api/v1`` and returns ``https://app.lightdash.cloud``. Forces+ https for any non-loopback host so the personal access token is never sent over the network+ in cleartext.+ """+ host = instance_url.strip()+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):+ host = f"https://{host}"+ parsed = urlparse(host)+ scheme = parsed.scheme.lower()+ if scheme == "http" and (parsed.hostname or "").lower() not in LOOPBACK_HOSTS:+ scheme = "https"+ return f"{scheme}://{parsed.netloc}"+++def _hostname(instance_url: str) -> str:+ return (urlparse(normalize_host(instance_url)).hostname or "").lower()+++def _client_config(base_url: str, api_token: str) -> ClientConfig:+ return {+ "base_url": base_url,+ "headers": {"Accept": "application/json"},+ # Lightdash personal access tokens authenticate via `Authorization: ApiKey <token>` —+ # a fixed scheme, not the framework's built-in "bearer" (`Bearer <token>`).+ "auth": {"type": "api_key", "name": "Authorization", "api_key": f"ApiKey {api_token}", "location": "header"},+ # The host is customer-controlled (self-hosted Lightdash); refusing redirects closes the+ # redirect-based off-host escape that the host check alone would miss.+ "allow_redirects": False,+ # Bound every sync request so a host that accepts the connection then stalls can't hold an+ # import worker indefinitely (the credential probe in validate_credentials is already+ # bounded separately).+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }+++def validate_credentials(+ instance_url: str, api_token: str, team_id: Optional[int] = None, schema_name: Optional[str] = None+) -> tuple[bool, str | None]:+ """Confirm the credentials are genuine with a cheap ``GET /api/v1/user`` probe.++ ``schema_name`` is unused (a personal access token grants the same access everywhere; there+ are no per-endpoint OAuth scopes to probe) but kept for the base-class signature. The instance+ URL is customer-controlled, so block internal/private addresses (SSRF, cloud only) and refuse+ to follow redirects.+ """+ hostname = _hostname(instance_url)+ if not hostname or not _HOSTNAME_RE.match(hostname):+ return False, "Invalid Lightdash instance URL"++ if team_id is not None:+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ base_url = normalize_host(instance_url)+ session = make_tracked_session(redact_values=(api_token,))+ try:+ response = session.get(+ f"{base_url}/api/v1/user",+ headers={"Authorization": f"ApiKey {api_token}", "Accept": "application/json"},+ timeout=10,+ allow_redirects=False,+ )+ except requests.exceptions.RequestException as e:+ return False, f"Could not reach the Lightdash instance: {e}"++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR+ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Lightdash rejected the personal access token. Generate a new token and reconnect."+ if response.status_code == 403:+ # A personal access token grants the same access as its owning user everywhere, so a 403+ # here means the user itself lacks access rather than a missing scope — still let source+ # creation through and surface it per-table via the sync-time non-retryable error.+ if schema_name is None:+ return True, None+ return False, "Your Lightdash personal access token does not have access to this resource."+ return False, f"Lightdash returned an unexpected response (HTTP {response.status_code})."+++def _paginator(config: LightdashEndpointConfig) -> BasePaginator:+ if not config.paginated:+ return SinglePagePaginator()+ return PageNumberPaginator(base_page=1, page_param="page", total_path=_PAGINATED_TOTAL_PATH)+++def get_resource(config: LightdashEndpointConfig) -> EndpointResource:+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{config.name}' must use the fan-out path")++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": {"pageSize": config.page_size} if config.paginated else {},+ "data_selector": config.data_selector,+ "paginator": _paginator(config),+ }+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _make_source_response(config: LightdashEndpointConfig, items_fn: Callable[[], Any]) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=config.primary_key if isinstance(config.primary_key, list) else [config.primary_key],+ # Full refresh only — Lightdash exposes no server-side updated-since filter on any endpoint.+ sort_mode="asc",+ 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,+ )+++def lightdash_source(+ instance_url: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+) -> SourceResponse:+ config = LIGHTDASH_ENDPOINTS[endpoint]+ base_url = normalize_host(instance_url)++ # Re-check at run time (not just source-create) in case the instance URL was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(_hostname(instance_url), team_id)+ if not host_ok:+ raise LightdashHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ client_config = _client_config(base_url, api_token)++ if config.fanout is not None:+ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=LIGHTDASH_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ # `GET /api/v1/org/projects` (the parent) takes no page-size param at all — it+ # always returns the full collection — so no size param is added to it. Only+ # metrics_catalog's child request needs one, added below via child_params_extra.+ page_size_param=None,+ parent_endpoint_extra={+ "paginator": SinglePagePaginator(),+ "data_selector": "results",+ },+ child_endpoint_extra={+ "paginator": _paginator(config),+ "data_selector": config.data_selector,+ },+ child_params_extra={"pageSize": config.page_size} if config.paginated else None,+ ),+ )+ return _make_source_response(config, lambda: dependent_resource)++ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(config)],+ }+ resource = rest_api_resource(rest_config, team_id, job_id, None)+ return _make_source_response(config, lambda: resource)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.pynew file mode 100644index 000000000000..cab6959be3db--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.py@@ -0,0 +1,124 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++# Lightdash documents no default/max page size for its paginated endpoints (org/users,+# dataCatalog/metrics); 100 keeps individual pages small without excessive round trips.+PAGE_SIZE = 100+++@dataclass+class LightdashEndpointConfig:+ name: str+ path: str+ # jsonpath selector into the response body: every Lightdash list endpoint wraps its rows in+ # {"status": "ok", "results": ...} — "results" for a bare array, "results.data" for the+ # paginated {"data": [...], "pagination": {...}} shape.+ data_selector: str+ primary_key: str | list[str]+ # Lightdash has no server-side updated-since/created-since filter on any list endpoint, so+ # every stream is full-refresh only. Left empty; kept for the fan-out helper's endpoint protocol.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ # Stable creation-time field used for datetime partitioning. Left None when the resource has no+ # reliably-present, non-mutating creation timestamp (spaces/dashboards/charts only expose+ # `updatedAt`, which the skill's partitioning rule excludes).+ partition_key: str | None = None+ paginated: bool = False+ page_size: int = PAGE_SIZE+ fanout: DependentEndpointConfig | None = None+++LIGHTDASH_ENDPOINTS: dict[str, LightdashEndpointConfig] = {+ "projects": LightdashEndpointConfig(+ name="projects",+ path="/api/v1/org/projects",+ data_selector="results",+ primary_key="projectUuid",+ partition_key="createdAt",+ ),+ "spaces": LightdashEndpointConfig(+ name="spaces",+ path="/api/v1/projects/{projectUuid}/spaces",+ data_selector="results",+ # `uuid` is a Lightdash-generated identifier, globally unique by construction (not a+ # per-project sequential id), so no parent id is needed to keep it unique table-wide.+ primary_key="uuid",+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="projectUuid",+ resolve_field="projectUuid",+ include_from_parent=["projectUuid"],+ # The framework injects the parent value under `_projects_projectUuid`; renaming it+ # back to `projectUuid` guarantees the column even if a future Lightdash response+ # ever omitted its own copy of the field.+ parent_field_renames={"projectUuid": "projectUuid"},+ ),+ ),+ "dashboards": LightdashEndpointConfig(+ name="dashboards",+ path="/api/v1/projects/{projectUuid}/dashboards",+ data_selector="results",+ primary_key="uuid",+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="projectUuid",+ resolve_field="projectUuid",+ include_from_parent=["projectUuid"],+ # The framework injects the parent value under `_projects_projectUuid`; renaming it+ # back to `projectUuid` guarantees the column even if a future Lightdash response+ # ever omitted its own copy of the field.+ parent_field_renames={"projectUuid": "projectUuid"},+ ),+ ),+ "charts": LightdashEndpointConfig(+ name="charts",+ path="/api/v1/projects/{projectUuid}/charts",+ data_selector="results",+ primary_key="uuid",+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="projectUuid",+ resolve_field="projectUuid",+ include_from_parent=["projectUuid"],+ # The framework injects the parent value under `_projects_projectUuid`; renaming it+ # back to `projectUuid` guarantees the column even if a future Lightdash response+ # ever omitted its own copy of the field.+ parent_field_renames={"projectUuid": "projectUuid"},+ ),+ ),+ "metrics_catalog": LightdashEndpointConfig(+ name="metrics_catalog",+ path="/api/v1/projects/{projectUuid}/dataCatalog/metrics",+ data_selector="results.data",+ primary_key="catalogSearchUuid",+ paginated=True,+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="projectUuid",+ resolve_field="projectUuid",+ include_from_parent=["projectUuid"],+ # The framework injects the parent value under `_projects_projectUuid`; renaming it+ # back to `projectUuid` guarantees the column even if a future Lightdash response+ # ever omitted its own copy of the field.+ parent_field_renames={"projectUuid": "projectUuid"},+ ),+ ),+ "org_users": LightdashEndpointConfig(+ name="org_users",+ path="/api/v1/org/users",+ data_selector="results.data",+ primary_key="userUuid",+ partition_key="userCreatedAt",+ paginated=True,+ ),+}++ENDPOINTS = tuple(LIGHTDASH_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LIGHTDASH_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/source.pyindex 638c3d1cce8c..204bb66efc9a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/source.py@@ -1,32 +1,143 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)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,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.lightdash import (LightdashSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.lightdash import (+ HOST_NOT_ALLOWED_ERROR,+ lightdash_source,+ validate_credentials as validate_lightdash_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass LightdashSource(SimpleSource[LightdashSourceConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in public docs without credentials.+ lists_tables_without_credentials = True+ api_docs_url = "https://docs.lightdash.com/api-reference/v1/introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LIGHTDASH+ @property+ def connection_host_fields(self) -> list[str]:+ # `instance_url` determines which host the stored personal access token is sent to;+ # retargeting it must force the editor to re-enter the token.+ return ["instance_url"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Lightdash rejected your personal access token. Generate a new token in your user settings and reconnect.",+ "403 Client Error": "Your Lightdash personal access token does not have permission to read this data. Check the token owner's project access and reconnect.",+ HOST_NOT_ALLOWED_ERROR: "The Lightdash instance URL is not allowed. Please use your instance's public URL.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: LightdashSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: LightdashSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_lightdash_credentials(+ instance_url=config.instance_url,+ api_token=config.api_token,+ team_id=team_id,+ schema_name=schema_name,+ )++ def source_for_pipeline(self, config: LightdashSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return lightdash_source(+ instance_url=config.instance_url,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.LIGHTDASH,category=DataWarehouseSourceCategory.ANALYTICS,label="Lightdash",+ caption=(+ "Connect Lightdash with a **personal access token**, created under "+ "**Settings → Personal access tokens**. Enter the URL of your Lightdash instance "+ "(Lightdash Cloud, e.g. `https://app.lightdash.cloud`, or your self-hosted domain). "+ "The token inherits its owner's project access, so use a token from a user with "+ "access to every project you want to sync."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/lightdash",iconPath="/static/services/lightdash.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["bi", "dashboards", "analytics"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="instance_url",+ label="Instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://app.lightdash.cloud",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash.pynew file mode 100644index 000000000000..1607717119eb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash.py@@ -0,0 +1,284 @@+from typing import Any, cast++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash import lightdash as lightdash_module+from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.lightdash import (+ HOST_NOT_ALLOWED_ERROR,+ LightdashHostNotAllowedError,+ get_resource,+ lightdash_source,+ normalize_host,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.settings import LIGHTDASH_ENDPOINTS+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++class TestNormalizeHost:+ @parameterized.expand(+ [+ ("bare_host", "app.lightdash.cloud", "https://app.lightdash.cloud"),+ ("https_host", "https://app.lightdash.cloud", "https://app.lightdash.cloud"),+ ("trailing_slash", "https://app.lightdash.cloud/", "https://app.lightdash.cloud"),+ ("trailing_api_path", "https://app.lightdash.cloud/api/v1", "https://app.lightdash.cloud"),+ ("whitespace", " app.lightdash.cloud ", "https://app.lightdash.cloud"),+ ("loopback_http_kept", "http://localhost:8080", "http://localhost:8080"),+ ("loopback_ip_http_kept", "http://127.0.0.1:8080", "http://127.0.0.1:8080"),+ ("remote_http_upgraded", "http://lightdash.example.com", "https://lightdash.example.com"),+ ("uppercase_scheme", "HTTP://lightdash.example.com/api/v1/", "https://lightdash.example.com"),+ ]+ )+ def test_normalize_host(self, _name: str, raw: str, expected: str) -> None:+ assert normalize_host(raw) == expected+++class TestValidateCredentials:+ def _patch_session(self, get_response: Any = None, raises: Exception | None = None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = get_response+ return mock.patch.object(lightdash_module, "make_tracked_session", return_value=session)++ @staticmethod+ def _response(status_code: int) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.is_redirect = status_code in (301, 302, 303, 307, 308)+ response.is_permanent_redirect = status_code in (301, 308)+ return response++ def test_success(self) -> None:+ with self._patch_session(self._response(200)):+ assert validate_credentials("https://x.lightdash.cloud", "tok") == (True, None)++ def test_invalid_token(self) -> None:+ with self._patch_session(self._response(401)):+ valid, msg = validate_credentials("https://x.lightdash.cloud", "tok")+ assert valid is False+ assert msg is not None++ def test_403_at_source_create_is_accepted(self) -> None:+ with self._patch_session(self._response(403)):+ assert validate_credentials("https://x.lightdash.cloud", "tok", schema_name=None) == (True, None)++ def test_403_for_scoped_probe_fails(self) -> None:+ with self._patch_session(self._response(403)):+ valid, msg = validate_credentials("https://x.lightdash.cloud", "tok", schema_name="projects")+ assert valid is False+ assert msg is not None++ @pytest.mark.parametrize("bad_host", ["", "https://", "not a host!"])+ def test_invalid_host_short_circuits(self, bad_host: str) -> None:+ valid, msg = validate_credentials(bad_host, "tok")+ assert valid is False+ assert msg == "Invalid Lightdash instance URL"++ def test_rejects_redirect_response(self) -> None:+ with self._patch_session(self._response(302)) as patched:+ valid, msg = validate_credentials("https://x.lightdash.cloud", "tok")+ assert valid is False+ assert msg == HOST_NOT_ALLOWED_ERROR+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_blocks_unsafe_host(self) -> None:+ with (+ mock.patch.object(lightdash_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(self._response(200)) as patched,+ ):+ valid, msg = validate_credentials("https://10.0.0.1", "tok", team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()++ def test_unexpected_status(self) -> None:+ with self._patch_session(self._response(500)):+ valid, msg = validate_credentials("https://x.lightdash.cloud", "tok")+ assert valid is False+ assert msg is not None and "500" in msg++ def test_handles_request_exception(self) -> None:+ with self._patch_session(raises=requests.exceptions.RequestException("boom")):+ valid, msg = validate_credentials("https://x.lightdash.cloud", "tok")+ assert valid is False+ assert msg is not None and "boom" in msg++ def test_probes_user_endpoint_with_api_key_header(self) -> None:+ with self._patch_session(self._response(200)) as patched:+ validate_credentials("https://x.lightdash.cloud", "tok")+ call = patched.return_value.get.call_args+ assert call.args[0] == "https://x.lightdash.cloud/api/v1/user"+ assert call.kwargs["headers"]["Authorization"] == "ApiKey tok"+++class TestGetResource:+ def test_projects_unpaginated_bare_results(self) -> None:+ resource = cast(dict[str, Any], get_resource(LIGHTDASH_ENDPOINTS["projects"]))+ assert resource["name"] == "projects"+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["path"] == "/api/v1/org/projects"+ assert resource["endpoint"]["data_selector"] == "results"+ assert isinstance(resource["endpoint"]["paginator"], SinglePagePaginator)+ assert resource["endpoint"]["params"] == {}++ def test_org_users_paginated_nested_results(self) -> None:+ resource = cast(dict[str, Any], get_resource(LIGHTDASH_ENDPOINTS["org_users"]))+ assert resource["endpoint"]["data_selector"] == "results.data"+ paginator = resource["endpoint"]["paginator"]+ assert isinstance(paginator, PageNumberPaginator)+ assert paginator.total_path == "results.pagination.totalPageCount"+ assert resource["endpoint"]["params"] == {"pageSize": LIGHTDASH_ENDPOINTS["org_users"].page_size}++ def test_fanout_endpoint_raises_via_get_resource(self) -> None:+ with pytest.raises(ValueError, match="fan-out path"):+ get_resource(LIGHTDASH_ENDPOINTS["spaces"])+++class TestLightdashSourceResponse:+ @parameterized.expand(+ [+ ("projects", ["projectUuid"], "createdAt"),+ ("spaces", ["uuid"], None),+ ("dashboards", ["uuid"], None),+ ("charts", ["uuid"], None),+ ("metrics_catalog", ["catalogSearchUuid"], None),+ ("org_users", ["userUuid"], "userCreatedAt"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.lightdash.rest_api_resource"+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_response_shape(+ self,+ endpoint: str,+ primary_keys: list[str],+ partition_key: str | None,+ mock_rest_api_resources: mock.MagicMock,+ mock_rest_api_resource: mock.MagicMock,+ ) -> None:+ mock_rest_api_resource.return_value = mock.MagicMock()+ mock_rest_api_resources.return_value = [+ _FakeDltResource("projects", [{"projectUuid": "p1"}]),+ _FakeDltResource(endpoint, [{"_projects_projectUuid": "p1"}]),+ ]++ response = lightdash_source(+ instance_url="https://x.lightdash.cloud", api_token="tok", endpoint=endpoint, team_id=1, job_id="job-1"+ )++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestLightdashSourceTransport:+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.lightdash.rest_api_resource"+ )+ def test_projects_top_level_uses_rest_api_resource(self, mock_rest_api_resource: mock.MagicMock) -> None:+ mock_rest_api_resource.return_value = mock.MagicMock()+ lightdash_source(+ instance_url="https://x.lightdash.cloud", api_token="tok", endpoint="projects", team_id=1, job_id="job-1"+ )++ rest_config = mock_rest_api_resource.call_args.args[0]+ assert rest_config["client"]["base_url"] == "https://x.lightdash.cloud"+ assert rest_config["client"]["auth"] == {+ "type": "api_key",+ "name": "Authorization",+ "api_key": "ApiKey tok",+ "location": "header",+ }+ assert rest_config["client"]["allow_redirects"] is False++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.lightdash.build_dependent_resource"+ )+ def test_spaces_fanout_wires_parent_and_child(self, mock_build_dependent_resource: mock.MagicMock) -> None:+ mock_build_dependent_resource.return_value = iter([])++ lightdash_source(+ instance_url="https://x.lightdash.cloud", api_token="tok", endpoint="spaces", team_id=1, job_id="job-1"+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["page_size_param"] is None+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "results"+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], SinglePagePaginator)+ assert kwargs["child_endpoint_extra"]["data_selector"] == "results"+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], SinglePagePaginator)+ assert kwargs["child_params_extra"] is None+ assert kwargs["db_incremental_field_last_value"] is None++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.lightdash.build_dependent_resource"+ )+ def test_metrics_catalog_fanout_paginates_child_only(self, mock_build_dependent_resource: mock.MagicMock) -> None:+ mock_build_dependent_resource.return_value = iter([])++ lightdash_source(+ instance_url="https://x.lightdash.cloud",+ api_token="tok",+ endpoint="metrics_catalog",+ team_id=1,+ job_id="job-1",+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["page_size_param"] is None+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], PageNumberPaginator)+ assert kwargs["child_endpoint_extra"]["data_selector"] == "results.data"+ assert kwargs["child_params_extra"] == {"pageSize": LIGHTDASH_ENDPOINTS["metrics_catalog"].page_size}++ def test_blocks_unsafe_host_at_runtime(self) -> None:+ with mock.patch.object(lightdash_module, "_is_host_safe", return_value=(False, "internal address")):+ with pytest.raises(LightdashHostNotAllowedError):+ lightdash_source(+ instance_url="https://10.0.0.1", api_token="tok", endpoint="projects", team_id=1, job_id="job-1"+ )++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_spaces_fanout_injects_parent_project_id(self, mock_rest_api_resources: mock.MagicMock) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("projects", [{"projectUuid": "proj_1"}]),+ _FakeDltResource("spaces", [{"uuid": "space_1", "_projects_projectUuid": "proj_1"}]),+ ]++ response = lightdash_source(+ instance_url="https://x.lightdash.cloud", api_token="tok", endpoint="spaces", team_id=1, job_id="job-1"+ )++ rows = list(cast(Any, response.items()))+ assert rows == [{"uuid": "space_1", "projectUuid": "proj_1"}]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash_source.pynew file mode 100644index 000000000000..6ef63a19b384--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash_source.py@@ -0,0 +1,134 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.lightdash import (+ LightdashSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.source import LightdashSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestLightdashSource:+ def setup_method(self) -> None:+ self.source = LightdashSource()+ self.team_id = 123+ self.config = LightdashSourceConfig(instance_url="https://app.lightdash.cloud", api_token="tok")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.LIGHTDASH++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Lightdash"+ assert config.category == DataWarehouseSourceCategory.ANALYTICS+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/lightdash"+ assert config.iconPath == "/static/services/lightdash.png"++ def test_source_is_released_not_hidden(self) -> None:+ # A finished source must be visible: `unreleasedSource` hides it from every user.+ assert not self.source.get_source_config.unreleasedSource++ def test_source_config_fields(self) -> None:+ config = self.source.get_source_config+ input_fields = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert input_fields == ["instance_url", "api_token"]++ def test_api_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_instance_url_field_is_not_secret(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "instance_url")+ assert field.secret is False+ assert field.required is True++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_are_all_full_refresh(self) -> None:+ # Lightdash exposes no server-side updated-since filter, so no stream is incremental.+ for schema in self.source.get_schemas(self.config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["projects"])+ assert [s.name for s in schemas] == ["projects"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — powers the public docs table list.+ assert self.source.lists_tables_without_credentials is True++ def test_connection_host_fields_cover_token_destination(self) -> None:+ # Dropping this would let an editor retarget the stored token at a host they control+ # without re-entering it (the update serializer keys off this list).+ assert self.source.connection_host_fields == ["instance_url"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://x.lightdash.cloud/api/v1/user",+ "403 Client Error: Forbidden for url: https://x.lightdash.cloud/api/v1/user",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_non_retryable_errors_ignore_transient(self) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(+ key in "503 Server Error for url: https://x.lightdash.cloud/api/v1/user" for key in non_retryable+ )++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.source.validate_lightdash_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="projects")++ assert result == (True, None)+ kwargs = mock_validate.call_args.kwargs+ assert kwargs["instance_url"] == "https://app.lightdash.cloud"+ assert kwargs["api_token"] == "tok"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["schema_name"] == "projects"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.lightdash.source.lightdash_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_lightdash_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "spaces"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"++ self.source.source_for_pipeline(self.config, inputs)++ kwargs = mock_lightdash_source.call_args.kwargs+ assert kwargs["instance_url"] == "https://app.lightdash.cloud"+ assert kwargs["api_token"] == "tok"+ assert kwargs["endpoint"] == "spaces"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"