: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 datahub import source (#71202)
Tom Owers89a1384cccde
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 60a242890bd7..63bf622243f2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -154,6 +154,7 @@ the row lists both.| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) || customerly | HTTP | requests | ✅ || datadog | HTTP | requests | ✅ |+| datahub | HTTP | requests | ✅ || dbt | HTTP | requests | ✅ || decagon | HTTP | requests | ✅ || deel | HTTP | requests | ✅ |@@ -631,7 +632,6 @@ doesn't conflict with concurrent PRs.- curve- dagster_cloud- databricks-- datahub- datascope- datorama- db2diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/canonical_descriptions.pynew file mode 100644index 000000000000..eb0071631879--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/canonical_descriptions.py@@ -0,0 +1,157 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "datasets": {+ "description": "A collection of data such as a table, view, stream, or file, with its schema, ownership, tags, and upstream lineage aspects.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataset",+ "columns": {+ "urn": "Unique resource name identifying the dataset across the metadata graph.",+ "datasetProperties": "Display name, description, custom properties, and created/last-modified timestamps of the dataset.",+ "schemaMetadata": "Column-level schema of the dataset: field paths, native and logical types, and field descriptions.",+ "ownership": "Owners of the dataset and their ownership types.",+ "globalTags": "Tags applied to the dataset.",+ "glossaryTerms": "Business glossary terms attached to the dataset.",+ "domains": "Domains the dataset belongs to.",+ "container": "The container (e.g. database or schema) the dataset lives in.",+ "upstreamLineage": "Upstream lineage edges: the datasets this dataset is derived from, with per-column fine-grained lineage where available.",+ "status": "Soft-deletion status of the entity.",+ "subTypes": "More specific type of the dataset, e.g. table, view, or topic.",+ },+ },+ "containers": {+ "description": "A grouping of datasets such as a database, schema, project, or folder on a data platform.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/container",+ "columns": {+ "urn": "Unique resource name identifying the container.",+ "containerProperties": "Display name, description, and custom properties of the container.",+ "container": "The parent container, when nested (e.g. a schema's database).",+ "ownership": "Owners of the container and their ownership types.",+ "subTypes": "More specific type of the container, e.g. database or schema.",+ },+ },+ "dashboards": {+ "description": "A dashboard in a BI tool, with the charts and datasets it is built from.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dashboard",+ "columns": {+ "urn": "Unique resource name identifying the dashboard.",+ "dashboardInfo": "Title, description, external URL, chart edges, and last-modified audit stamps of the dashboard.",+ "ownership": "Owners of the dashboard and their ownership types.",+ "globalTags": "Tags applied to the dashboard.",+ "domains": "Domains the dashboard belongs to.",+ "status": "Soft-deletion status of the entity.",+ },+ },+ "charts": {+ "description": "A single visualization in a BI tool, with the source datasets it reads from.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/chart",+ "columns": {+ "urn": "Unique resource name identifying the chart.",+ "chartInfo": "Title, description, external URL, chart type, and input dataset edges of the chart.",+ "inputFields": "Schema fields of upstream datasets the chart reads.",+ "ownership": "Owners of the chart and their ownership types.",+ "globalTags": "Tags applied to the chart.",+ "status": "Soft-deletion status of the entity.",+ },+ },+ "data_flows": {+ "description": "An orchestration pipeline (e.g. an Airflow DAG or dbt project) that groups data jobs.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataflow",+ "columns": {+ "urn": "Unique resource name identifying the data flow.",+ "dataFlowInfo": "Name, description, project, and external URL of the pipeline.",+ "ownership": "Owners of the pipeline and their ownership types.",+ "globalTags": "Tags applied to the pipeline.",+ "status": "Soft-deletion status of the entity.",+ },+ },+ "data_jobs": {+ "description": "A task within a data flow (e.g. an Airflow task), with the datasets it consumes and produces.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/datajob",+ "columns": {+ "urn": "Unique resource name identifying the data job.",+ "dataJobInfo": "Name, description, type, and external URL of the task.",+ "dataJobInputOutput": "Lineage edges of the task: input and output datasets and upstream jobs.",+ "ownership": "Owners of the task and their ownership types.",+ "globalTags": "Tags applied to the task.",+ "status": "Soft-deletion status of the entity.",+ },+ },+ "data_platforms": {+ "description": "A data system type known to DataHub (e.g. Snowflake, BigQuery, Kafka) that other entities reference.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataplatform",+ "columns": {+ "urn": "Unique resource name identifying the platform.",+ "dataPlatformInfo": "Name, display name, type, dataset name delimiter, and logo of the platform.",+ },+ },+ "data_products": {+ "description": "A curated data product grouping related data assets within a domain.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataproduct",+ "columns": {+ "urn": "Unique resource name identifying the data product.",+ "dataProductProperties": "Name, description, and the asset edges that make up the data product.",+ "domains": "The domain the data product belongs to.",+ "ownership": "Owners of the data product and their ownership types.",+ },+ },+ "domains": {+ "description": "A top-level business category (e.g. Marketing, Finance) used to organize data assets.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/domain",+ "columns": {+ "urn": "Unique resource name identifying the domain.",+ "domainProperties": "Name, description, and parent domain of the domain.",+ "ownership": "Owners of the domain and their ownership types.",+ },+ },+ "glossary_terms": {+ "description": "A business glossary term that defines shared vocabulary and can be attached to data assets.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/glossaryterm",+ "columns": {+ "urn": "Unique resource name identifying the glossary term.",+ "glossaryTermInfo": "Name, definition, source, and parent node of the term.",+ "glossaryRelatedTerms": "Relationships to other glossary terms (inherits, contains).",+ "ownership": "Owners of the term and their ownership types.",+ },+ },+ "glossary_nodes": {+ "description": "A folder-like grouping node in the business glossary hierarchy.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/glossarynode",+ "columns": {+ "urn": "Unique resource name identifying the glossary node.",+ "glossaryNodeInfo": "Name, definition, and parent node of the glossary node.",+ "ownership": "Owners of the node and their ownership types.",+ },+ },+ "tags": {+ "description": "A label that can be applied to any data asset or schema field for search and governance.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/tag",+ "columns": {+ "urn": "Unique resource name identifying the tag.",+ "tagProperties": "Name, description, and color of the tag.",+ "ownership": "Owners of the tag and their ownership types.",+ },+ },+ "users": {+ "description": "A person (or service account) known to DataHub, referenced as an owner of data assets.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/corpuser",+ "columns": {+ "urn": "Unique resource name identifying the user.",+ "corpUserInfo": "Display name, email, title, and manager of the user as synced from the identity provider.",+ "corpUserEditableInfo": "Profile fields the user edited in DataHub (about, skills, teams).",+ "groupMembership": "Groups the user belongs to.",+ "corpUserStatus": "Whether the user is active or suspended.",+ "status": "Soft-deletion status of the entity.",+ },+ },+ "groups": {+ "description": "A group of users, referenced as an owner of data assets.",+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/corpgroup",+ "columns": {+ "urn": "Unique resource name identifying the group.",+ "corpGroupInfo": "Display name, description, email, and membership of the group.",+ "ownership": "Owners of the group and their ownership types.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/datahub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/datahub.pynew file mode 100644index 000000000000..e709d964eb9b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/datahub.py@@ -0,0 +1,434 @@+import re+import json+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import 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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.settings import (+ DATAHUB_ENDPOINTS,+ DatahubEndpointConfig,+)++# The OpenAPI v3 scroll endpoints default to 10 entities per page; 100 keeps round trips low+# while staying far under any Elasticsearch result-window concern (scroll doesn't use windows).+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# The instance URL is customer-controlled, so a hostile server could stream an unbounded body to+# exhaust a shared worker. Cap the bytes we buffer: a scroll page of PAGE_SIZE metadata entities+# stays comfortably under this, while an error body only needs a short human-readable snippet.+MAX_PAGE_RESPONSE_BYTES = 64 * 1024 * 1024+MAX_ERROR_SNIPPET_BYTES = 64 * 1024+# The instance URL is customer-controlled, so a hostile server can hand back a fresh non-empty+# page and a new scroll cursor forever, pinning a worker and writing junk rows until the activity+# times out. Bound a single sweep to this many pages and abort past it. At PAGE_SIZE this is 10M+# entities — far above any real DataHub instance's metadata volume, so a legitimate sync never+# reaches it, while an otherwise-unbounded loop is stopped.+MAX_PAGES_PER_SWEEP = 100_000+# Cheap probe used to confirm the token is genuine: dataPlatform is a small built-in collection+# (~60 rows) present on every DataHub instance.+DEFAULT_PROBE_ENTITY = "dataPlatform"++HOST_NOT_ALLOWED_ERROR = "DataHub instance URL is not allowed"+++class DatahubRetryableError(Exception):+ pass+++class DatahubHostNotAllowedError(Exception):+ pass+++class DatahubResponseTooLargeError(Exception):+ pass+++class DatahubTooManyPagesError(Exception):+ pass+++class DatahubResumeConfig:+ # Opaque scroll cursor returned by the OpenAPI v3 entity endpoint; passing it back fetches+ # the next page. None means "start from the first page".+ scroll_id: str | None = None+++def normalize_instance_url(instance_url: str) -> str:+ """Turn whatever the user typed into a consistent API base URL.++ DataHub instances live at a per-customer URL that may include a path prefix (DataHub Cloud+ serves the metadata service under ``https://<tenant>.acryl.io/gms``), so the path must be+ preserved — we only default a missing scheme, strip trailing slashes, and drop an+ accidentally-pasted ``/openapi`` suffix.+ """+ url = instance_url.strip().rstrip("/")+ # Only default the scheme for bare hosts — a non-http(s) scheme must survive normalization+ # so _validated_hostname can reject it.+ if url and "://" not in url:+ url = f"https://{url}"+ if url.lower().endswith("/openapi"):+ url = url[: -len("/openapi")]+ return url.rstrip("/")+++def _headers(api_token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}+++def _get_session(api_token: str) -> requests.Session:+ # The instance URL is user-supplied, so pin redirects off so host validation and the+ # outbound request stay on the same target (SSRF defense-in-depth). Redact the token+ # from logs.+ return make_tracked_session(headers=_headers(api_token), redact_values=(api_token,), allow_redirects=False)+++def _validated_hostname(base_url: str) -> Optional[str]:+ """Hostname of the normalized instance URL, or None when the URL is malformed or ambiguous.++ SSRF guard: urlparse treats a backslash as ordinary userinfo and an "@" as a userinfo+ separator, but urllib3/requests treat the backslash as an authority separator, so+ `https://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 (same+ guard as the Unleash source) and require a plain http(s) URL with a clean hostname.+ """+ if "\\" in base_url or "%5c" in base_url.lower():+ return None+ parsed = urlparse(base_url)+ if parsed.scheme not in ("http", "https") or "@" in parsed.netloc:+ return None+ # The PAT rides in the Authorization 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. a+ # GMS 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():+ return None+ hostname = parsed.hostname+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):+ return None+ return hostname+++def _check_host(instance_url: str, team_id: int) -> None:+ hostname = _validated_hostname(normalize_instance_url(instance_url))+ if not hostname:+ raise DatahubHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ raise DatahubHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+++def _entity_url(base_url: str, entity_type: str) -> str:+ return f"{base_url}/openapi/v3/entity/{entity_type}"+++def _scroll_params(scroll_id: str | None, count: int = PAGE_SIZE) -> dict[str, Any]:+ # Sort by urn ascending so page boundaries stay stable while scrolling — entities ingested+ # mid-sync can't shuffle already-walked pages.+ params: dict[str, Any] = {+ "query": "*",+ "count": count,+ "sortCriteria": "urn",+ "sortOrder": "ASCENDING",+ }+ if scroll_id:+ params["scrollId"] = scroll_id+ return params+++def _extract_entities(data: Any, url: str) -> tuple[list[dict[str, Any]], str | None]:+ """Pull the entity rows and next-page cursor out of a scroll response.++ The scroll envelope is ``{"scrollId": "...", "entities": [...]}``; the final page omits+ ``scrollId``. A missing ``entities`` key on a dict payload is treated as an empty result.+ """+ if not isinstance(data, dict):+ raise DatahubRetryableError(f"DataHub returned an unexpected payload for {url}: {type(data).__name__}")+ entities = data.get("entities") or []+ if not isinstance(entities, list):+ raise DatahubRetryableError(f"DataHub returned an unexpected 'entities' payload for {url}")+ scroll_id = data.get("scrollId")+ return entities, scroll_id if isinstance(scroll_id, str) and scroll_id else None+++def _read_capped_bytes(response: requests.Response, max_bytes: int) -> bytes:+ """Read a ``stream=True`` response body under a byte cap without buffering the whole thing.++ The instance URL is customer-controlled, so a hostile server could return an unbounded (or+ continuously streamed) body that would exhaust a shared worker if buffered in full. Because+ the session streams, the body isn't materialised at ``session.get`` time — it's read here.+ Read one byte past the cap so an oversized body is detected without buffering all of it; the+ socket read timeout bounds a slow-drip that stays under the cap.+ """+ raw = response.raw.read(max_bytes + 1, decode_content=True) if response.raw is not None else b""+ if len(raw) > max_bytes:+ raise DatahubResponseTooLargeError(f"DataHub returned an oversized response for {response.url}")+ return raw+++@retry(+ retry=retry_if_exception_type((DatahubRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ url: str,+ params: Optional[dict[str, Any]],+ logger: FilteringBoundLogger,+) -> Any:+ # stream=True so the body isn't buffered at request time — it's read under a byte cap below.+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)++ # The session never follows redirects: a 3xx would move the sync off the validated host+ # (SSRF), so refuse it rather than silently fetching an empty body.+ if 300 <= response.status_code < 400:+ raise DatahubHostNotAllowedError(HOST_NOT_ALLOWED_ERROR)++ if response.status_code == 429 or response.status_code >= 500:+ raise DatahubRetryableError(f"DataHub API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"DataHub API error: status={response.status_code}, body={_error_snippet(response)}, url={url}")+ response.raise_for_status()++ raw = _read_capped_bytes(response, MAX_PAGE_RESPONSE_BYTES)+ if not raw:+ raise DatahubRetryableError(f"DataHub returned an empty response for {url}")+ try:+ return json.loads(raw)+ except ValueError as exc:+ raise DatahubRetryableError(f"DataHub returned a non-JSON response for {url}") from exc+++def get_rows(+ instance_url: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DatahubResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = DATAHUB_ENDPOINTS[endpoint]+ # Re-check at run time (not just at source-create) in case the instance URL was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ _check_host(instance_url, team_id)++ base_url = normalize_instance_url(instance_url)+ url = _entity_url(base_url, config.entity_type)+ session = _get_session(api_token)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ scroll_id = resume.scroll_id if resume else None+ resuming = scroll_id is not None+ if resuming:+ logger.debug(f"DataHub: resuming {endpoint} from saved scroll cursor")++ pages_fetched = 0+ while True:+ try:+ data = _fetch(session, url, _scroll_params(scroll_id), logger)+ except requests.HTTPError as exc:+ # A saved scroll cursor can go stale between attempts (scroll contexts are+ # server-side and expire). If the resumed first request is rejected, restart the+ # sweep from scratch — merge dedupes the re-pulled rows on the primary key.+ status = exc.response.status_code if exc.response is not None else None+ if resuming and status in (400, 404, 410):+ logger.warning(f"DataHub: saved scroll cursor for {endpoint} was rejected, restarting from scratch")+ resumable_source_manager.clear_state()+ scroll_id = None+ resuming = False+ continue+ raise+ resuming = False+ pages_fetched += 1++ entities, next_scroll_id = _extract_entities(data, url)+ if entities:+ yield entities++ # No cursor (or an empty page, guarding against a server that echoes a cursor forever)+ # means the sweep is complete.+ if not next_scroll_id or not entities:+ break++ # A hostile instance can echo a fresh non-empty page and cursor indefinitely. Abort past+ # the page budget rather than let one sweep write rows until the activity times out; don't+ # persist the next cursor first, so a resume restarts from the last good page rather than+ # walking further into the runaway stream.+ if pages_fetched >= MAX_PAGES_PER_SWEEP:+ raise DatahubTooManyPagesError(+ f"DataHub sweep for {endpoint} exceeded {MAX_PAGES_PER_SWEEP} pages; aborting a likely runaway paginated response"+ )++ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages+ # are persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(DatahubResumeConfig(scroll_id=next_scroll_id))+ scroll_id = next_scroll_id+++def datahub_source(+ instance_url: str,+ api_token: str,+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DatahubResumeConfig],+) -> SourceResponse:+ config: DatahubEndpointConfig = DATAHUB_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ instance_url=instance_url,+ api_token=api_token,+ endpoint=endpoint,+ team_id=team_id,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def _error_snippet(response: requests.Response) -> str:+ # Read only a capped slice of a (streamed) error body for logging — never the whole thing,+ # which a hostile instance could inflate. Swallow read failures so logging never masks the+ # real HTTP error.+ try:+ return _read_capped_bytes(response, MAX_ERROR_SNIPPET_BYTES).decode("utf-8", "replace")+ except Exception:+ return ""+++def _error_message(response: requests.Response) -> Optional[str]:+ # DataHub error bodies (when present — 401s are empty) carry a human-readable `message`.+ # Read a capped snippet only: the body is streamed, so an oversized one is never buffered.+ try:+ raw = _read_capped_bytes(response, MAX_ERROR_SNIPPET_BYTES)+ body = json.loads(raw) if raw else None+ if isinstance(body, dict) and isinstance(body.get("message"), str):+ return body["message"]+ except Exception:+ pass+ return None+++def validate_credentials(+ instance_url: str, api_token: str, schema_name: Optional[str] = None, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe a cheap entity list to confirm the token is genuine.++ At source-create (``schema_name is None``) a 403 is accepted: the token is valid but its+ owner may lack the view privilege for this particular entity type. A scoped probe+ (``schema_name`` set) treats 403 as a hard failure.+ """+ base_url = normalize_instance_url(instance_url)+ hostname = _validated_hostname(base_url)+ if not hostname:+ return False, "Invalid DataHub instance URL"++ # The instance URL is fully customer-controlled, so block hosts that resolve to private/+ # internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ 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++ probe_entity = DEFAULT_PROBE_ENTITY+ if schema_name is not None and schema_name in DATAHUB_ENDPOINTS:+ probe_entity = DATAHUB_ENDPOINTS[schema_name].entity_type++ session = _get_session(api_token)+ try:+ # The session never follows redirects: the validated host could 3xx to an internal+ # address, defeating the host check above (SSRF). stream=True so a hostile server can't+ # exhaust the API worker with an unbounded body — a 200 returns without reading it, and+ # error snippets are read under a cap.+ response = session.get(+ _entity_url(base_url, probe_entity), params=_scroll_params(None, count=1), timeout=15, stream=True+ )+ except requests.exceptions.RequestException as e:+ return False, f"Could not connect to DataHub: {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,+ "Invalid DataHub access token. Check that Metadata Service Authentication is enabled on your instance and generate a new personal access token.",+ )++ if response.status_code == 403:+ if schema_name is None:+ # Valid token, missing view privilege for this probe — let source creation through.+ return True, None+ return False, _error_message(response) or "Your DataHub access token lacks the required view privileges"++ return False, _error_message(response) or f"DataHub returned HTTP {response.status_code}"+++def check_endpoint_permissions(+ instance_url: str, api_token: str, endpoints: list[str], team_id: int+) -> dict[str, str | None]:+ """Probe each entity endpoint and report which ones the token cannot read.++ Returns ``{endpoint: None}`` when reachable and ``{endpoint: reason}`` on a real denial+ (401/403). Transient failures (throttles, 5xx, network blips) are not permission problems,+ so they report as reachable rather than blocking the schema picker.+ """+ base_url = normalize_instance_url(instance_url)+ hostname = _validated_hostname(base_url)+ if not hostname:+ return dict.fromkeys(endpoints, "Invalid DataHub instance URL")+ host_ok, host_err = _is_host_safe(hostname, team_id)+ if not host_ok:+ return dict.fromkeys(endpoints, host_err or HOST_NOT_ALLOWED_ERROR)++ session = _get_session(api_token)+ results: dict[str, str | None] = {}+ for endpoint in endpoints:+ config = DATAHUB_ENDPOINTS.get(endpoint)+ if config is None:+ results[endpoint] = None+ continue+ try:+ # stream=True so a hostile instance can't exhaust the API worker with an unbounded+ # body; only a capped error snippet is read below when the status warrants a message.+ response = session.get(+ _entity_url(base_url, config.entity_type),+ params=_scroll_params(None, count=1),+ timeout=15,+ stream=True,+ )+ except requests.exceptions.RequestException:+ results[endpoint] = None+ continue+ if response.status_code == 401:+ results[endpoint] = "Invalid DataHub access token"+ elif response.status_code == 403:+ results[endpoint] = (+ _error_message(response) or "Your DataHub access token lacks the view privilege for this entity type"+ )+ else:+ results[endpoint] = None+ return resultsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/settings.pynew file mode 100644index 000000000000..2672243b83d6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/settings.py@@ -0,0 +1,39 @@+from dataclasses import dataclass, field+++@dataclass+class DatahubEndpointConfig:+ name: str+ # DataHub metadata-model entity name, interpolated into /openapi/v3/entity/{entity_type}.+ # Entity-name lookup is case-insensitive server-side; we use the registry's camelCase names.+ entity_type: str+ # Every DataHub entity is identified by its URN, unique across the whole metadata graph.+ primary_keys: list[str] = field(default_factory=lambda: ["urn"])+++# DataHub OpenAPI v3 entity scroll endpoints. All full refresh only: the generic entity list has+# no server-side updated-since filter (freshness only exists as per-aspect+# systemMetadata.lastObserved, which mutates and isn't filterable here), so there is no timestamp+# cursor to advance an incremental sync. The scroll cursor makes a single full sweep resumable.+# Lineage edges ride along on the entities themselves (datasets carry the upstreamLineage aspect,+# data jobs carry dataJobInputOutput), so no separate per-entity relationship fan-out is needed.+DATAHUB_ENDPOINTS: dict[str, DatahubEndpointConfig] = {+ "datasets": DatahubEndpointConfig(name="datasets", entity_type="dataset"),+ "containers": DatahubEndpointConfig(name="containers", entity_type="container"),+ "dashboards": DatahubEndpointConfig(name="dashboards", entity_type="dashboard"),+ "charts": DatahubEndpointConfig(name="charts", entity_type="chart"),+ "data_flows": DatahubEndpointConfig(name="data_flows", entity_type="dataFlow"),+ "data_jobs": DatahubEndpointConfig(name="data_jobs", entity_type="dataJob"),+ "data_platforms": DatahubEndpointConfig(name="data_platforms", entity_type="dataPlatform"),+ "data_products": DatahubEndpointConfig(name="data_products", entity_type="dataProduct"),+ "domains": DatahubEndpointConfig(name="domains", entity_type="domain"),+ "glossary_terms": DatahubEndpointConfig(name="glossary_terms", entity_type="glossaryTerm"),+ "glossary_nodes": DatahubEndpointConfig(name="glossary_nodes", entity_type="glossaryNode"),+ "tags": DatahubEndpointConfig(name="tags", entity_type="tag"),+ "users": DatahubEndpointConfig(name="users", entity_type="corpuser"),+ "groups": DatahubEndpointConfig(name="groups", entity_type="corpGroup"),+}++ENDPOINTS = tuple(DATAHUB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/source.pyindex d8c5c81d1acc..836bdc748af1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/source.py@@ -1,30 +1,159 @@-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.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 SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.datahub import (+ DatahubResumeConfig,+ check_endpoint_permissions,+ datahub_source,+ validate_credentials as validate_datahub_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.settings import (+ DATAHUB_ENDPOINTS,+ ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DatahubSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DatahubSource(SimpleSource[DatahubSourceConfig]):+class DatahubSource(ResumableSource[DatahubSourceConfig, DatahubResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DATAHUB+ @property+ def connection_host_fields(self) -> list[str]:+ # `instance_url` is where the stored access token is sent; retargeting it must re-require the token.+ return ["instance_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DATAHUB,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="DataHub (DataHub Project / Acryl Data)",+ label="DataHub",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["acryl", "data catalog", "metadata", "lineage"],+ caption="""Enter your DataHub instance URL and an access token to sync your metadata catalog — datasets, dashboards, charts, pipelines, owners, domains, glossary, and tags — into the PostHog Data warehouse.++The instance URL is where your DataHub API is served: for DataHub Cloud (Acryl) that's `https://<your-tenant>.acryl.io/gms`; for self-hosted it's your metadata service (GMS) URL, or the DataHub frontend URL, which proxies the API. Your instance must have [Metadata Service Authentication](https://docs.datahub.com/docs/authentication/introducing-metadata-service-authentication) enabled.++The token is a [personal access token](https://docs.datahub.com/docs/authentication/personal-access-tokens) generated under **Settings → Access Tokens**; it inherits its owner's view privileges, so the owner must be able to view the entity types you want to sync.+""",iconPath="/static/services/datahub.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/datahub",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="instance_url",+ label="Instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://your-tenant.acryl.io/gms",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your DataHub access token is invalid or has expired. Generate a new personal access token under Settings → Access Tokens and reconnect.",+ "Unauthorized for url": "Your DataHub access token is invalid or has expired. Generate a new personal access token under Settings → Access Tokens and reconnect.",+ "403 Client Error": "Your DataHub access token does not have permission to read this data. Check the token owner's view privileges, then reconnect.",+ }++ def get_schemas(+ self,+ config: DatahubSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — the generic entity scroll exposes no server-side+ # updated-since filter, so there is no timestamp cursor to advance an incremental sync+ # (see settings.py).+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: DatahubSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_datahub_credentials(config.instance_url, config.api_token, schema_name, team_id)++ def get_endpoint_permissions(+ self, config: DatahubSourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ # Tokens inherit their owner's privileges, and DataHub policies can scope view access per+ # entity type. Probe each endpoint so the schema picker can flag unreadable tables.+ return check_endpoint_permissions(config.instance_url, config.api_token, endpoints, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DatahubResumeConfig]:+ return ResumableSourceManager[DatahubResumeConfig](inputs, DatahubResumeConfig)++ def source_for_pipeline(+ self,+ config: DatahubSourceConfig,+ resumable_source_manager: ResumableSourceManager[DatahubResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in DATAHUB_ENDPOINTS:+ raise ValueError(f"Unknown DataHub schema '{inputs.schema_name}'")++ return datahub_source(+ instance_url=config.instance_url,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub.pynew file mode 100644index 000000000000..29e6296ff6b0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub.py@@ -0,0 +1,477 @@+import json+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.datahub import datahub+from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.datahub import (+ PAGE_SIZE,+ DatahubHostNotAllowedError,+ DatahubResponseTooLargeError,+ DatahubResumeConfig,+ DatahubRetryableError,+ DatahubTooManyPagesError,+ _extract_entities,+ _headers,+ check_endpoint_permissions,+ datahub_source,+ get_rows,+ normalize_instance_url,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_unwrapped = datahub._fetch.__wrapped__ # type: ignore[attr-defined]++BASE_URL = "https://datahub.example.com"+TOKEN = "eyJhbGciOi-secret-token"+++def _mock_response(+ status_code: int = 200,+ json_data: Any = None,+ is_redirect: bool = False,+ raw_body: bytes | None = None,+) -> MagicMock:+ response = MagicMock(spec=requests.Response)+ response.status_code = status_code+ response.ok = status_code < 400+ response.is_redirect = is_redirect+ response.is_permanent_redirect = False+ response.url = BASE_URL+ # The source streams responses and reads the body via raw.read under a size cap, never+ # response.json(); feed the encoded body through raw.read (which ignores its byte-count arg).+ body = raw_body if raw_body is not None else (b"" if json_data is None else json.dumps(json_data).encode())+ # `raw` is set in Response.__init__, so spec=Response doesn't expose it — attach it ourselves.+ response.raw = MagicMock()+ response.raw.read.return_value = body+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} Client Error", response=response) if status_code >= 400 else None+ )+ return response+++class _FakeResumableManager:+ def __init__(self, state: DatahubResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[DatahubResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> DatahubResumeConfig | None:+ return self._state++ def save_state(self, data: DatahubResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++class TestDatahub:+ # --- URL normalization ---++ @parameterized.expand(+ [+ ("plain", "https://datahub.example.com", "https://datahub.example.com"),+ ("trailing_slash", "https://datahub.example.com/", "https://datahub.example.com"),+ ("openapi_suffix", "https://datahub.example.com/openapi", "https://datahub.example.com"),+ ("no_scheme", "datahub.example.com", "https://datahub.example.com"),+ ("whitespace", " https://datahub.example.com ", "https://datahub.example.com"),+ (+ # DataHub Cloud serves the metadata service under a /gms path prefix — it must be preserved.+ "gms_path_prefix",+ "https://tenant.acryl.io/gms/",+ "https://tenant.acryl.io/gms",+ ),+ (+ "gms_path_prefix_with_openapi_suffix",+ "https://tenant.acryl.io/gms/openapi",+ "https://tenant.acryl.io/gms",+ ),+ ]+ )+ def test_normalize_instance_url(self, _name: str, raw: str, expected: str) -> None:+ assert normalize_instance_url(raw) == expected++ def test_headers_send_bearer_token(self) -> None:+ assert _headers(TOKEN)["Authorization"] == f"Bearer {TOKEN}"++ # --- scroll envelope extraction ---++ @parameterized.expand(+ [+ ("page_with_cursor", {"scrollId": "abc", "entities": [{"urn": "u1"}]}, [{"urn": "u1"}], "abc"),+ ("final_page", {"entities": [{"urn": "u2"}]}, [{"urn": "u2"}], None),+ # An empty final page may omit `entities` entirely — that's a valid empty result.+ ("empty_without_key", {}, [], None),+ # An empty-string scrollId must not be followed as a cursor.+ ("empty_cursor", {"scrollId": "", "entities": []}, [], None),+ ]+ )+ def test_extract_entities(+ self, _name: str, payload: Any, expected_rows: list[dict], expected_cursor: str | None+ ) -> None:+ assert _extract_entities(payload, "http://url") == (expected_rows, expected_cursor)++ @parameterized.expand(+ [+ ("bare_list", [{"urn": "u1"}]),+ ("entities_not_a_list", {"entities": {"urn": "u1"}}),+ ]+ )+ def test_extract_entities_rejects_unexpected_payloads(self, _name: str, payload: Any) -> None:+ with pytest.raises(DatahubRetryableError):+ _extract_entities(payload, "http://url")++ # --- fetch ---++ @parameterized.expand([(429,), (500,), (503,)])+ def test_fetch_raises_retryable_on_transient_statuses(self, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(status_code=status_code)+ with pytest.raises(DatahubRetryableError):+ _fetch_unwrapped(session, "http://url", None, MagicMock())++ @parameterized.expand([(400,), (401,), (403,), (404,)])+ def test_fetch_raises_http_error_on_permanent_statuses(self, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(status_code=status_code)+ with pytest.raises(requests.HTTPError):+ _fetch_unwrapped(session, "http://url", None, MagicMock())++ def test_fetch_streams_and_parses_capped_json(self) -> None:+ # stream=True keeps a hostile unbounded body from being buffered at request time; the+ # body is then read under a cap and JSON-parsed. Dropping either regresses the SSRF/OOM+ # guard, so pin both here.+ session = MagicMock()+ session.get.return_value = _mock_response(200, {"entities": [{"urn": "u1"}]})+ result = _fetch_unwrapped(session, "http://url", None, MagicMock())+ assert result == {"entities": [{"urn": "u1"}]}+ assert session.get.call_args.kwargs["stream"] is True++ def test_read_capped_bytes_rejects_oversized_body(self) -> None:+ # A body larger than the cap must raise rather than buffer the whole thing.+ response = _mock_response(200, raw_body=b"x" * 11)+ with pytest.raises(DatahubResponseTooLargeError):+ datahub._read_capped_bytes(response, max_bytes=10)++ @parameterized.expand([(301,), (302,), (307,)])+ def test_fetch_refuses_redirects(self, status_code: int) -> None:+ # The session never follows redirects — a 3xx would move the sync off the validated+ # host (SSRF), so it must fail rather than be treated as an empty page.+ session = MagicMock()+ session.get.return_value = _mock_response(status_code=status_code)+ with pytest.raises(DatahubHostNotAllowedError):+ _fetch_unwrapped(session, "http://url", None, MagicMock())++ # --- get_rows ---++ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[Any, Any],+ endpoint: str = "datasets",+ ) -> tuple[list[dict], list[dict[str, Any]]]:+ """Run get_rows with a fake _fetch keyed by the `scrollId` param (None = first page)."""+ calls: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, params: Optional[dict], logger: Any) -> Any:+ calls.append({"url": url, "params": params})+ page = pages[params.get("scrollId") if params else None]+ if isinstance(page, Exception):+ raise page+ return page++ monkeypatch.setattr(datahub, "_fetch", fake_fetch)+ monkeypatch.setattr(datahub, "make_tracked_session", lambda **kwargs: MagicMock())+ monkeypatch.setattr(datahub, "_check_host", lambda instance_url, team_id: None)++ rows: list[dict] = []+ for batch in get_rows(+ instance_url=BASE_URL,+ api_token=TOKEN,+ endpoint=endpoint,+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows, calls++ def test_scroll_walks_pages_and_saves_state_after_yield(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages = {+ None: {"scrollId": "cursor-1", "entities": [{"urn": "u1"}, {"urn": "u2"}]},+ "cursor-1": {"entities": [{"urn": "u3"}]},+ }+ rows, calls = self._collect(manager, monkeypatch, pages)++ assert [r["urn"] for r in rows] == ["u1", "u2", "u3"]+ assert calls[0]["url"] == f"{BASE_URL}/openapi/v3/entity/dataset"+ # Stable ascending urn sort keeps page boundaries fixed while scrolling.+ assert all(+ c["params"]["query"] == "*"+ and c["params"]["count"] == PAGE_SIZE+ and c["params"]["sortCriteria"] == "urn"+ and c["params"]["sortOrder"] == "ASCENDING"+ for c in calls+ )+ assert [c["params"].get("scrollId") for c in calls] == [None, "cursor-1"]+ # State is saved once — after the first page yielded, pointing at the next cursor.+ assert [s.scroll_id for s in manager.saved] == ["cursor-1"]++ def test_scroll_stops_on_empty_page_even_with_cursor(self, monkeypatch: Any) -> None:+ # Guard against a server that echoes a cursor forever: an empty page terminates the sweep.+ manager = _FakeResumableManager()+ rows, calls = self._collect(manager, monkeypatch, {None: {"scrollId": "next", "entities": []}})+ assert rows == []+ assert len(calls) == 1+ assert manager.saved == []++ def test_scroll_aborts_past_page_budget(self, monkeypatch: Any) -> None:+ # A hostile instance can echo a fresh non-empty page and cursor forever; the empty-page+ # guard never fires, so the sweep must abort at the page budget instead of writing rows+ # until the activity times out.+ monkeypatch.setattr(datahub, "MAX_PAGES_PER_SWEEP", 3)+ manager = _FakeResumableManager()++ def endless_fetch(session: Any, url: str, params: Optional[dict], logger: Any) -> Any:+ cursor = params.get("scrollId") if params else None+ n = int(cursor) + 1 if cursor else 1+ return {"scrollId": str(n), "entities": [{"urn": f"u{n}"}]}++ monkeypatch.setattr(datahub, "_fetch", endless_fetch)+ monkeypatch.setattr(datahub, "make_tracked_session", lambda **kwargs: MagicMock())+ monkeypatch.setattr(datahub, "_check_host", lambda instance_url, team_id: None)++ collected: list[dict] = []+ with pytest.raises(DatahubTooManyPagesError):+ for batch in get_rows(+ instance_url=BASE_URL,+ api_token=TOKEN,+ endpoint="datasets",+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ collected.extend(batch)++ # Pages up to the budget are still yielded; the cursor past the budget is never persisted,+ # so a resume restarts from the last good page rather than walking deeper into the stream.+ assert [r["urn"] for r in collected] == ["u1", "u2", "u3"]+ assert [s.scroll_id for s in manager.saved] == ["1", "2"]++ def test_scroll_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(DatahubResumeConfig(scroll_id="cursor-9"))+ pages = {"cursor-9": {"entities": [{"urn": "u9"}]}}+ rows, calls = self._collect(manager, monkeypatch, pages)+ assert [r["urn"] for r in rows] == ["u9"]+ assert [c["params"].get("scrollId") for c in calls] == ["cursor-9"]++ # pytest.mark.parametrize (not parameterized.expand) because the test also needs the+ # monkeypatch fixture, which parameterized's wrapper doesn't forward.+ @pytest.mark.parametrize("status_code", [400, 404, 410])+ def test_stale_resumed_cursor_restarts_from_scratch(self, status_code: int, monkeypatch: Any) -> None:+ # Scroll contexts are server-side and expire; a rejected saved cursor must restart the+ # sweep (merge dedupes re-pulled rows) instead of wedging the sync.+ manager = _FakeResumableManager(DatahubResumeConfig(scroll_id="stale"))+ error = requests.HTTPError("rejected", response=_mock_response(status_code))+ pages = {+ "stale": error,+ None: {"entities": [{"urn": "u1"}]},+ }+ rows, calls = self._collect(manager, monkeypatch, pages)+ assert [r["urn"] for r in rows] == ["u1"]+ assert [c["params"].get("scrollId") for c in calls] == ["stale", None]+ assert manager.cleared is True++ def test_stale_cursor_mid_sweep_is_not_swallowed(self, monkeypatch: Any) -> None:+ # Only a cursor loaded from resume state gets the restart treatment — a 4xx on a cursor+ # the server just handed us is a real error and must fail the sync.+ manager = _FakeResumableManager()+ error = requests.HTTPError("rejected", response=_mock_response(400))+ pages = {+ None: {"scrollId": "cursor-1", "entities": [{"urn": "u1"}]},+ "cursor-1": error,+ }+ with pytest.raises(requests.HTTPError):+ self._collect(manager, monkeypatch, pages)++ def test_get_rows_blocks_unsafe_hosts(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(datahub, "_is_host_safe", lambda host, team_id: (False, "blocked"))+ with pytest.raises(DatahubHostNotAllowedError):+ list(+ get_rows(+ instance_url="https://10.0.0.1",+ api_token=TOKEN,+ endpoint="datasets",+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )++ def test_get_rows_blocks_ambiguous_url(self) -> None:+ with pytest.raises(DatahubHostNotAllowedError):+ list(+ get_rows(+ instance_url="https://169.254.169.254\\@datahub.example.com",+ api_token=TOKEN,+ endpoint="datasets",+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )++ # --- SourceResponse assembly ---++ @parameterized.expand([("datasets",), ("users",), ("tags",)])+ def test_datahub_source_uses_urn_primary_key(self, endpoint: str) -> None:+ response = datahub_source(+ instance_url=BASE_URL,+ api_token=TOKEN,+ endpoint=endpoint,+ team_id=1,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ assert response.name == endpoint+ assert response.primary_keys == ["urn"]++ # --- credential validation ---++ def _validate(self, monkeypatch: Any, response: MagicMock, schema_name: Optional[str] = None) -> tuple:+ session = MagicMock()+ session.get.return_value = response+ monkeypatch.setattr(datahub, "make_tracked_session", lambda **kwargs: session)+ monkeypatch.setattr(datahub, "_is_host_safe", lambda host, team_id: (True, None))+ return validate_credentials(BASE_URL, TOKEN, schema_name=schema_name, team_id=1)++ def test_validate_credentials_success(self, monkeypatch: Any) -> None:+ assert self._validate(monkeypatch, _mock_response(200, {"entities": []})) == (True, None)++ def test_validate_credentials_invalid_token(self, monkeypatch: Any) -> None:+ # DataHub 401s carry an empty body, so the message must stand on its own.+ valid, message = self._validate(monkeypatch, _mock_response(401, None))+ assert valid is False+ assert message is not None and "Invalid DataHub access token" in message++ def test_validate_credentials_accepts_403_at_source_create(self, monkeypatch: Any) -> None:+ # A valid token may lack the view privilege for the probe entity; source creation must+ # still go through, and per-schema syncs surface their own permission errors.+ assert self._validate(monkeypatch, _mock_response(403, {"message": "denied"})) == (True, None)++ def test_validate_credentials_rejects_403_for_scoped_probe(self, monkeypatch: Any) -> None:+ valid, message = self._validate(monkeypatch, _mock_response(403, {"message": "denied"}), schema_name="users")+ assert valid is False+ assert message == "denied"++ def test_validate_credentials_scoped_probe_targets_schema_entity(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(200, {"entities": []})+ monkeypatch.setattr(datahub, "make_tracked_session", lambda **kwargs: session)+ monkeypatch.setattr(datahub, "_is_host_safe", lambda host, team_id: (True, None))+ validate_credentials(BASE_URL, TOKEN, schema_name="users", team_id=1)+ assert session.get.call_args.args[0] == f"{BASE_URL}/openapi/v3/entity/corpuser"++ def test_validate_credentials_rejects_redirects(self, monkeypatch: Any) -> None:+ # A redirect could bounce the probe to an internal address, defeating the host check.+ valid, _ = self._validate(monkeypatch, _mock_response(200, {}, is_redirect=True))+ assert valid is False++ def test_validate_credentials_rejects_unsafe_host(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(datahub, "_is_host_safe", lambda host, team_id: (False, "blocked"))+ valid, message = validate_credentials("https://10.0.0.1", TOKEN, team_id=1)+ assert valid is False+ assert message == "blocked"++ @parameterized.expand(+ [+ ("blank", " "),+ ("bad_scheme", "ftp://datahub.example.com"),+ # Parser-differential SSRF guards: urlparse and urllib3 disagree on where the+ # authority ends for backslash/userinfo URLs, so validation could approve one host+ # while requests connects to another.+ ("userinfo", "https://[email protected]"),+ ("backslash", "https://169.254.169.254\\@datahub.example.com"),+ ("encoded_backslash", "https://169.254.169.254%[email protected]"),+ ]+ )+ def test_validate_credentials_rejects_malformed_or_ambiguous_urls(self, _name: str, raw_url: str) -> None:+ valid, message = validate_credentials(raw_url, TOKEN, team_id=1)+ assert valid is False+ assert message == "Invalid DataHub instance URL"++ @parameterized.expand(+ [+ # The token rides in the Authorization header, so plaintext http is rejected on cloud+ # (public egress) but allowed off cloud (self-hosted controls its own network path).+ ("http_on_cloud", True, "http://datahub.example.com", None),+ ("http_off_cloud", False, "http://datahub.example.com", "datahub.example.com"),+ ("https_on_cloud", True, "https://datahub.example.com", "datahub.example.com"),+ ]+ )+ def test_validated_hostname_requires_https_only_on_cloud(+ self, _name: str, cloud: bool, url: str, expected: Optional[str]+ ) -> None:+ with patch.object(datahub, "is_cloud", return_value=cloud):+ assert datahub._validated_hostname(url) == expected++ def test_validate_credentials_handles_connection_errors(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(datahub, "make_tracked_session", lambda **kwargs: session)+ monkeypatch.setattr(datahub, "_is_host_safe", lambda host, team_id: (True, None))+ valid, message = validate_credentials(BASE_URL, TOKEN, team_id=1)+ assert valid is False+ assert message is not None and "Could not connect to DataHub" in message++ # --- per-endpoint permissions ---++ @parameterized.expand(+ [+ # Transient failures are not permission problems — they must not flag the table.+ ("server_error", 500, None),+ ("throttled", 429, None),+ ("invalid_token", 401, "Invalid DataHub access token"),+ ("denied_with_message", 403, "no view privilege"),+ ]+ )+ def test_check_endpoint_permissions_status_mapping(+ self, _name: str, status_code: int, expected: Optional[str]+ ) -> None:+ session = MagicMock()+ session.get.return_value = _mock_response(status_code, {"message": "no view privilege"})+ with (+ patch.object(datahub, "make_tracked_session", lambda **kwargs: session),+ patch.object(datahub, "_is_host_safe", lambda host, team_id: (True, None)),+ ):+ result = check_endpoint_permissions(BASE_URL, TOKEN, ["datasets"], team_id=1)+ assert result["datasets"] == expected++ def test_check_endpoint_permissions_treats_network_blips_as_reachable(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(datahub, "make_tracked_session", lambda **kwargs: session)+ monkeypatch.setattr(datahub, "_is_host_safe", lambda host, team_id: (True, None))+ assert check_endpoint_permissions(BASE_URL, TOKEN, ["datasets"], team_id=1) == {"datasets": None}++ def test_check_endpoint_permissions_blocks_unsafe_host_for_all_endpoints(self, monkeypatch: Any) -> None:+ monkeypatch.setattr(datahub, "_is_host_safe", lambda host, team_id: (False, "blocked"))+ result = check_endpoint_permissions("https://10.0.0.1", TOKEN, ["datasets", "users"], team_id=1)+ assert result == {"datasets": "blocked", "users": "blocked"}++ def test_check_endpoint_permissions_rejects_ambiguous_url_for_all_endpoints(self) -> None:+ result = check_endpoint_permissions(+ "https://169.254.169.254\\@datahub.example.com", TOKEN, ["datasets", "users"], team_id=1+ )+ assert result == {"datasets": "Invalid DataHub instance URL", "users": "Invalid DataHub instance URL"}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub_source.pynew file mode 100644index 000000000000..ef29069196c6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub_source.py@@ -0,0 +1,145 @@+import pytest+from unittest import mock++from parameterized import parameterized++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.datahub.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.datahub import DatahubResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.source import DatahubSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DatahubSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestDatahubSource:+ def setup_method(self) -> None:+ self.source = DatahubSource()+ self.team_id = 123+ self.config = DatahubSourceConfig(instance_url="https://datahub.example.com", api_token="secret-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.DATAHUB++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Datahub"+ assert config.label == "DataHub"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/datahub"+ # A finished source must be visible in the wizard — the scaffold-era hidden flag stays out.+ assert not config.unreleasedSource++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["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_connection_host_fields_covers_instance_url(self) -> None:+ # The stored access token is sent to whatever `instance_url` points at, so retargeting+ # the URL must force the editor to re-enter the token.+ assert self.source.connection_host_fields == ["instance_url"]++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["datasets"])+ assert len(schemas) == 1+ assert schemas[0].name == "datasets"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://datahub.example.com/openapi/v3/entity/dataset",),+ ("403 Client Error: Forbidden for url: https://datahub.example.com/openapi/v3/entity/corpuser",),+ ]+ )+ 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)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://datahub.example.com/openapi/v3/entity/dataset",),+ ("429 Client Error: Too Many Requests for url: https://datahub.example.com/openapi/v3/entity/tag",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.datahub.source.validate_datahub_credentials"+ )+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid DataHub access token")+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="datasets")+ assert result == (False, "Invalid DataHub access token")+ mock_validate.assert_called_once_with("https://datahub.example.com", "secret-token", "datasets", self.team_id)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.datahub.source.check_endpoint_permissions"+ )+ def test_get_endpoint_permissions_delegates_to_shared_helper(self, mock_check: mock.MagicMock) -> None:+ mock_check.return_value = {"users": "needs view privilege", "datasets": None}+ result = self.source.get_endpoint_permissions(self.config, self.team_id, ["users", "datasets"])+ assert result == {"users": "needs view privilege", "datasets": None}+ mock_check.assert_called_once_with(+ "https://datahub.example.com", "secret-token", ["users", "datasets"], self.team_id+ )++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DatahubResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.datahub.source.datahub_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "datasets"+ inputs.team_id = self.team_id+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["instance_url"] == "https://datahub.example.com"+ assert kwargs["api_token"] == "secret-token"+ assert kwargs["endpoint"] == "datasets"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "nope"+ with pytest.raises(ValueError, match="Unknown DataHub schema"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --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 e199c6a1614a..bf4805d7c9ea 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@@ -1147,7 +1147,8 @@ class DatadogSourceConfig(config.Config):@config.configclass DatahubSourceConfig(config.Config):- pass+ instance_url: str+ api_token: str@config.config