Skip to content

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

23.2 KB
Raw Blame
import re
import json
import hashlib
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_if_exception_type, stop_after_attempt, wait_exponential_jitter

from products.warehouse_sources.sources.datahub.settings import (
    DATAHUB_ENDPOINTS,
    TIMESERIES_ROW_ID_COLUMN,
    DatahubEndpointConfig,
)
from products.warehouse_sources.sources.sdk import (
    ResumableSourceManager,
    SourceResponse,
    _is_host_safe,
    frozen,
    is_cloud,
    make_tracked_session,
    retry_with_deadline,
)

# 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"
# The OpenAPI v2 timeseries endpoint only started returning a scroll cursor in DataHub v1.4.0
# (datahub-project/datahub#15784). An older instance answers every page with results and no cursor,
# so a sweep would end after the first page and truncate the table without any error. A fixed
# instance always returns a cursor alongside a full page, which makes a full page with no cursor an
# exact signature of the old server. This string is matched by `get_non_retryable_errors`.
MIN_TIMESERIES_SCROLL_VERSION = "v1.4.0"
TIMESERIES_SCROLL_UNSUPPORTED_ERROR = "returned a full page of timeseries events with no scroll cursor"


class DatahubRetryableError(Exception):
    pass


class DatahubHostNotAllowedError(Exception):
    pass


class DatahubResponseTooLargeError(Exception):
    pass


class DatahubTooManyPagesError(Exception):
    pass


class DatahubTimeseriesScrollUnsupportedError(Exception):
    pass


@dataclasses.dataclass(frozen=False)
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 _timeseries_url(base_url: str, entity_type: str, aspect_name: str) -> str:
    return f"{base_url}/openapi/v2/timeseries/{entity_type}/{aspect_name}"


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 _timeseries_params(scroll_id: str | None, start_time_millis: int | None, count: int = PAGE_SIZE) -> dict[str, Any]:
    # The timeseries endpoint takes no sort parameter. It always returns timestampMillis
    # descending, which is why the response declares sort_mode="desc".
    params: dict[str, Any] = {"count": count}
    if scroll_id:
        params["scrollId"] = scroll_id
    # Re-sent on every page: the cursor is a stateless search_after token, so the server only
    # keeps the window bound if we keep passing it, and an incremental sweep would otherwise walk
    # back through all history after the first page.
    if start_time_millis is not None:
        params["startTimeMillis"] = start_time_millis
    return params


@frozen
class _PageRequest:
    url: str
    params: dict[str, Any]
    # Top-level key the page's rows live under in the response envelope.
    items_key: str


def _page_request(
    config: DatahubEndpointConfig,
    base_url: str,
    scroll_id: str | None = None,
    start_time_millis: int | None = None,
    count: int = PAGE_SIZE,
) -> _PageRequest:
    if config.timeseries_aspect:
        return _PageRequest(
            url=_timeseries_url(base_url, config.entity_type, config.timeseries_aspect),
            params=_timeseries_params(scroll_id, start_time_millis, count=count),
            items_key="results",
        )
    return _PageRequest(
        url=_entity_url(base_url, config.entity_type),
        params=_scroll_params(scroll_id, count=count),
        items_key="entities",
    )


def _extract_page(data: Any, url: str, items_key: str) -> tuple[list[dict[str, Any]], str | None]:
    """Pull the rows and next-page cursor out of a scroll response.

    The scroll envelope is ``{"scrollId": "...", "<items_key>": [...]}``, where the items key is
    ``entities`` for the entity endpoints and ``results`` for the timeseries ones. The final page
    omits ``scrollId``. A missing items 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__}")
    rows = data.get(items_key) or []
    if not isinstance(rows, list):
        raise DatahubRetryableError(f"DataHub returned an unexpected '{items_key}' payload for {url}")
    scroll_id = data.get("scrollId")
    return rows, scroll_id if isinstance(scroll_id, str) and scroll_id else None


def _timeseries_row_id(row: dict[str, Any]) -> str:
    """Deterministic surrogate key matching DataHub's own uniqueness rule for a timeseries row.

    A timeseries document is keyed by timestamp, event granularity, urn, message id and partition
    spec: urn plus timestamp alone is not unique, because one dataset can carry both a daily and an
    hourly bucket, or one row per partition. Hash exactly those identity fields, and never the
    metric values, so a bucket the instance restates merges onto itself instead of landing twice.
    """
    event = row.get("event")
    event = event if isinstance(event, dict) else {}
    parts = (
        row.get("timestampMillis"),
        event.get("eventGranularity"),
        row.get("urn"),
        row.get("messageId"),
        event.get("partitionSpec"),
    )
    # Serialize each part so a nested partitionSpec hashes stably, and use a sentinel for the
    # absent ones so a missing field can never collide with an empty-string value.
    joined = "|".join("\x00" if part is None else json.dumps(part, sort_keys=True, default=str) for part in parts)
    return hashlib.sha256(joined.encode()).hexdigest()


def _with_timeseries_row_ids(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    return [{**row, TIMESERIES_ROW_ID_COLUMN: _timeseries_row_id(row)} for row in rows]


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_with_deadline(
    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],
    db_incremental_field_last_value: Optional[Any] = None,
) -> 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)
    session = _get_session(api_token)
    start_time_millis = int(db_incremental_field_last_value) if db_incremental_field_last_value is not None else None

    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:
        page = _page_request(config, base_url, scroll_id, start_time_millis, count=PAGE_SIZE)
        url = page.url
        try:
            data = _fetch(session, url, page.params, 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

        rows, next_scroll_id = _extract_page(data, url, page.items_key)

        # Raise before yielding, so a sync against an instance too old to paginate fails instead of
        # writing a table silently truncated to one page.
        if config.timeseries_aspect and not next_scroll_id and len(rows) >= PAGE_SIZE:
            raise DatahubTimeseriesScrollUnsupportedError(
                f"DataHub {TIMESERIES_SCROLL_UNSUPPORTED_ERROR} for {endpoint}. The timeseries API "
                f"paginates from DataHub {MIN_TIMESERIES_SCROLL_VERSION} onwards."
            )

        if rows:
            yield _with_timeseries_row_ids(rows) if config.timeseries_aspect else rows

        # 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 rows:
            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],
    db_incremental_field_last_value: Optional[Any] = None,
) -> 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,
            db_incremental_field_last_value=db_incremental_field_last_value,
        ),
        primary_keys=config.primary_keys,
        # The timeseries endpoint offers no sort parameter and always returns newest first.
        sort_mode="desc" if config.timeseries_aspect else "asc",
        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 the endpoint the scoped schema would actually read. A timeseries aspect needs the
    # timeseries read privilege on top of the entity one, so the entity list is not a stand-in.
    probe_config = DATAHUB_ENDPOINTS.get(schema_name) if schema_name is not None else None
    if probe_config is None:
        probe_config = DatahubEndpointConfig(name=DEFAULT_PROBE_ENTITY, entity_type=DEFAULT_PROBE_ENTITY)
    probe = _page_request(probe_config, base_url, count=1)

    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(probe.url, params=probe.params, 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
        probe = _page_request(config, base_url, count=1)
        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(probe.url, params=probe.params, 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 results