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.

fix(data-warehouse): correct custom source incremental sync and validation (#59612)

Marcus Hofe10173f1e5de
diff --git a/posthog/temporal/data_imports/sources/custom/source.py b/posthog/temporal/data_imports/sources/custom/source.py
index d30def88ba47..84a68bf6b79b 100644
--- a/posthog/temporal/data_imports/sources/custom/source.py
+++ b/posthog/temporal/data_imports/sources/custom/source.py
@@ -4,7 +4,7 @@ from urllib.parse import urlparse
from django.conf import settings
-from pydantic import BaseModel, Field, ValidationError, model_validator
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
@@ -14,14 +14,16 @@ from posthog.schema import (
)
from posthog.cloud_utils import is_cloud
-from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SortMode, SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
from posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resource
+from posthog.temporal.data_imports.sources.common.rest_source.config_setup import create_auth
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import CustomSourceConfig
+from posthog.temporal.data_imports.util import NonRetryableException
from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalField, IncrementalFieldType
@@ -46,7 +48,16 @@ class ManifestValidationError(ValueError):
class _ManifestAuth(BaseModel):
+ # Only the non-secret auth fields are modelled, and extras are forbidden:
+ # a misspelled key (e.g. `header` instead of `name`) fails manifest
+ # validation here with a clear message instead of crashing the REST
+ # engine's `create_auth` with an unexpected-kwarg TypeError at sync time.
+ model_config = ConfigDict(extra="forbid")
+
type: Literal["bearer", "api_key", "http_basic"]
+ name: str | None = None
+ location: Literal["header", "query", "param", "cookie"] | None = None
+ username: str | None = None
@model_validator(mode="before")
@classmethod
@@ -69,14 +80,28 @@ class _ManifestClient(BaseModel):
class _ManifestEndpoint(BaseModel):
path: str = Field(min_length=1)
- # Read verbs only — write verbs (PUT/PATCH/DELETE) are excluded so a
- # misconfigured manifest can't mutate or delete upstream data.
+ # GET and POST only. Data-warehouse syncs only ever read upstream data;
+ # POST is permitted because some read/query-style endpoints require it, but
+ # PUT/PATCH/DELETE are excluded so a misconfigured manifest can't mutate or
+ # delete upstream data.
method: Literal["GET", "POST", "get", "post"] | None = None
+ # Query params and request body. Modelled only so a malformed `params`/`json`
+ # (e.g. a JSON array where an object is expected) is caught at manifest time;
+ # both still pass through untouched to the REST engine. `params` values may be
+ # plain scalars or the engine's incremental/resolver specs, so the type stays
+ # permissive. `json` is aliased because `json` shadows a `BaseModel` attribute.
+ params: dict[str, Any] | None = None
+ json_body: dict[str, Any] | None = Field(default=None, alias="json")
class _ManifestResource(BaseModel):
name: str = Field(min_length=1)
endpoint: _ManifestEndpoint
+ # How the upstream API orders this resource's rows. Incremental syncs commit
+ # the high-watermark per batch for "asc"; for a source whose order is
+ # unknown or descending, declaring "desc" here avoids skipping rows on a
+ # resumed sync. Defaults to "asc" when omitted.
+ sort_mode: Literal["asc", "desc"] | None = None
class _Manifest(BaseModel):
@@ -263,25 +288,22 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
return False, err
# Probe every resource so we surface auth/connection errors at create-time
- # rather than waiting for the first sync. Failure to reach any endpoint is
- # treated as a credential failure with the underlying error message returned
- # to the user. The auth/header setup comes from the shared client config, so
- # it is built once and reused across the per-resource requests.
+ # rather than waiting for the first sync. The auth/header setup comes from
+ # the shared client config, so it is built once and reused across the
+ # per-resource requests.
client = manifest["client"]
base_url = client["base_url"]
headers: dict[str, str] = dict(client.get("headers") or {})
- auth: dict[str, Any] = dict(client.get("auth") or {})
- auth_type = auth.get("type")
- if auth_type == "bearer" and auth.get("token"):
- headers.setdefault("Authorization", f"Bearer {auth['token']}")
- elif auth_type == "api_key" and auth.get("api_key"):
- if (auth.get("location") or "header") == "header":
- headers[auth.get("name") or "Authorization"] = auth["api_key"]
-
- basic_auth: tuple[str, str] | None = None
- if auth_type == "http_basic":
- basic_auth = (str(auth.get("username", "")), str(auth.get("password", "")))
+ # Build the probe's auth exactly the way the REST engine will at sync
+ # time (`create_auth`) instead of reconstructing it by hand — so the
+ # probe and the sync agree on which credential is sent and where
+ # (header / query / cookie), and a malformed auth config surfaces here
+ # as a clear error rather than crashing the first sync.
+ try:
+ probe_auth = create_auth(client.get("auth"))
+ except (ValueError, TypeError) as exc:
+ return False, f"Invalid auth configuration: {exc}"
session = make_tracked_session(headers=headers)
@@ -290,14 +312,28 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
method = (endpoint.get("method") or "GET").upper()
path = endpoint.get("path", "")
url = path if path.startswith(("http://", "https://")) else f"{base_url.rstrip('/')}/{path.lstrip('/')}"
+ # Replay the configured query params and request body so the probe
+ # matches what the sync sends — an endpoint that needs them shouldn't
+ # answer differently at probe vs sync time.
+ probe_params = _static_probe_params(endpoint.get("params"))
+ probe_json = endpoint.get("json")
try:
- response = session.request(method, url, auth=basic_auth, timeout=15)
+ response = session.request(
+ method, url, params=probe_params or None, json=probe_json, auth=probe_auth, timeout=15
+ )
except Exception as exc:
return False, f"Resource {resource['name']!r}: could not reach {url}: {exc}"
- if response.status_code >= 400:
+ # Only an auth rejection (401/403) is a credential problem. Other
+ # statuses — 404 (resource not yet provisioned), 405, 429 (rate
+ # limited during the probe burst), 5xx — are not credential errors
+ # and must not block source creation; a real, persistent failure
+ # surfaces on the first sync instead.
+ if response.status_code in (401, 403):
return False, (
- f"Resource {resource['name']!r}: HTTP {response.status_code} from {url}: {response.text[:200]}"
+ f"Resource {resource['name']!r}: the upstream API rejected the request with "
+ f"HTTP {response.status_code} from {url} — check the configured auth credentials: "
+ f"{response.text[:200]}"
)
return True, None
@@ -327,21 +363,29 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
return schemas
def source_for_pipeline(self, config: CustomSourceConfig, inputs: SourceInputs) -> SourceResponse:
- manifest = self._assemble_manifest(config)
- ok, err = validate_manifest_urls(manifest, inputs.team_id)
- if not ok:
- raise ManifestValidationError(err or "Manifest URL validation failed")
-
- chosen = next(
- (r for r in manifest["resources"] if isinstance(r, dict) and r.get("name") == inputs.schema_name),
- None,
- )
- if chosen is None:
- raise ValueError(f"Resource {inputs.schema_name!r} not found in config")
+ try:
+ manifest = self._assemble_manifest(config)
+ ok, err = validate_manifest_urls(manifest, inputs.team_id)
+ if not ok:
+ raise ManifestValidationError(err or "Manifest URL validation failed")
+
+ chosen = next(
+ (r for r in manifest["resources"] if isinstance(r, dict) and r.get("name") == inputs.schema_name),
+ None,
+ )
+ if chosen is None:
+ raise ValueError(f"Resource {inputs.schema_name!r} not found in config")
+ except ValueError as exc:
+ # A malformed manifest or a missing resource is a permanent,
+ # deterministic failure — retrying the sync cannot fix it. Raise
+ # NonRetryableException (the only type Temporal treats as
+ # non-retryable for this activity) so the job fails fast instead of
+ # burning the whole retry budget on an error that will always recur.
+ raise NonRetryableException(str(exc)) from exc
single_resource_manifest = cast(
RESTAPIConfig,
- {**manifest, "resources": [chosen]},
+ {**manifest, "resources": [_strip_engine_unsupported_incremental_keys(chosen)]},
)
resource = rest_api_resource(
@@ -362,6 +406,22 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
else:
primary_keys = None
+ # The manifest declares the upstream's row ordering; default "asc" to
+ # match PostHog's other REST sources. An incorrect "asc" assumption on a
+ # non-ascending API can skip rows on a resumed incremental sync.
+ #
+ # "desc" only defers committing the high-watermark until the run finishes
+ # (so a partial run can't advance the cursor past rows it never reached on
+ # the next scheduled sync). It does NOT make a single run resumable: the
+ # generic REST engine has no earliest-value sweep, so an interrupted "desc"
+ # run restarts from the newest page rather than continuing older rows. This
+ # is deliberately non-resumable — duplicate work is collapsed by
+ # primary_keys, and the only failure mode is an endpoint too large to
+ # finish within one worker window. A proper fix would slice the cursor into
+ # windows with per-window state (cf. Airbyte's DatetimeBasedCursor), which
+ # the generic engine doesn't support today.
+ sort_mode: SortMode = "desc" if chosen.get("sort_mode") == "desc" else "asc"
+
return SourceResponse(
name=inputs.schema_name,
items=lambda: resource,
@@ -369,9 +429,23 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
partition_count=1,
partition_size=1,
partition_mode="md5",
+ sort_mode=sort_mode,
)
+def _static_probe_params(params: Any) -> dict[str, Any]:
+ """The literal query params safe to replay in the create-time probe.
+
+ A RESTAPIConfig ``params`` map can hold the engine's incremental / parent-
+ resolver specs (dict values) that are only resolved against cursor or parent
+ state at sync time — the probe has neither, so it forwards just the plain
+ (non-dict) values and lets the engine handle the rest on the first sync.
+ """
+ if not isinstance(params, dict):
+ return {}
+ return {key: value for key, value in params.items() if not isinstance(value, dict)}
+
+
def _inject_auth_secrets(manifest: dict[str, Any], config: CustomSourceConfig) -> None:
"""Inject credential values from the secret config fields into ``client.auth``.
@@ -395,6 +469,44 @@ def _inject_auth_secrets(manifest: dict[str, Any], config: CustomSourceConfig) -
auth["password"] = config.auth_password
+def _incremental_field_type(raw: Any) -> IncrementalFieldType:
+ """Map a manifest-declared cursor type to an :class:`IncrementalFieldType`.
+
+ Defaults to ``DateTime`` — the common case for REST cursors — but a manifest
+ can declare ``cursor_type`` (``integer``, ``date``, ``timestamp``, …) so an
+ integer or string cursor is stored and compared with the right type rather
+ than being misinterpreted as a timestamp.
+ """
+ if isinstance(raw, str):
+ try:
+ return IncrementalFieldType(raw.strip().lower())
+ except ValueError:
+ pass
+ return IncrementalFieldType.DateTime
+
+
+# Keys the Custom source understands on ``endpoint.incremental`` that the generic
+# REST engine's ``Incremental(**config)`` constructor does NOT accept. They inform
+# how the cursor is typed (see ``_incremental_field_type``) but must be removed
+# before the engine builds its incremental tracker, or it raises an unexpected
+# keyword-argument error at sync setup.
+_ENGINE_UNSUPPORTED_INCREMENTAL_KEYS = frozenset({"cursor_type"})
+
+
+def _strip_engine_unsupported_incremental_keys(resource: dict[str, Any]) -> dict[str, Any]:
+ """Return a copy of ``resource`` with REST-engine-incompatible keys removed
+ from ``endpoint.incremental``. The input is left untouched so schema typing
+ can still read the full incremental config."""
+ endpoint = resource.get("endpoint")
+ if not isinstance(endpoint, dict):
+ return resource
+ incremental = endpoint.get("incremental")
+ if not isinstance(incremental, dict) or not _ENGINE_UNSUPPORTED_INCREMENTAL_KEYS.intersection(incremental):
+ return resource
+ cleaned = {k: v for k, v in incremental.items() if k not in _ENGINE_UNSUPPORTED_INCREMENTAL_KEYS}
+ return {**resource, "endpoint": {**endpoint, "incremental": cleaned}}
+
+
def _schema_from_resource(resource: dict[str, Any]) -> SourceSchema:
name = resource["name"]
endpoint = resource.get("endpoint", {})
@@ -404,12 +516,13 @@ def _schema_from_resource(resource: dict[str, Any]) -> SourceSchema:
if isinstance(incremental_cfg, dict):
cursor_path = incremental_cfg.get("cursor_path")
if isinstance(cursor_path, str) and cursor_path:
+ cursor_type = _incremental_field_type(incremental_cfg.get("cursor_type"))
incremental_fields = [
IncrementalField(
label=cursor_path,
field=cursor_path,
- type=IncrementalFieldType.DateTime,
- field_type=IncrementalFieldType.DateTime,
+ type=cursor_type,
+ field_type=cursor_type,
)
]
diff --git a/posthog/temporal/data_imports/sources/custom/test_custom_source.py b/posthog/temporal/data_imports/sources/custom/test_custom_source.py
index 6cc0598e8037..3927c6fca648 100644
--- a/posthog/temporal/data_imports/sources/custom/test_custom_source.py
+++ b/posthog/temporal/data_imports/sources/custom/test_custom_source.py
@@ -6,6 +6,7 @@ from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
+from posthog.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth, BearerTokenAuth, HttpBasicAuth
from posthog.temporal.data_imports.sources.custom.source import (
CustomSource,
ManifestValidationError,
@@ -14,6 +15,9 @@ from posthog.temporal.data_imports.sources.custom.source import (
validate_manifest_urls,
)
from posthog.temporal.data_imports.sources.generated_configs import CustomSourceConfig
+from posthog.temporal.data_imports.util import NonRetryableException
+
+from products.data_warehouse.backend.types import IncrementalFieldType
def _minimal_manifest(base_url: str = "https://api.example.com") -> dict:
@@ -82,6 +86,30 @@ class TestValidateManifest(SimpleTestCase):
validate_manifest(manifest)
assert "method" in str(ctx.exception)
+ @parameterized.expand(["GET", "POST", "get", "post"])
+ def test_accepts_read_http_method(self, method):
+ manifest = _minimal_manifest()
+ manifest["resources"][0]["endpoint"]["method"] = method
+ validate_manifest(manifest)
+
+ def test_accepts_endpoint_params_and_json_body(self):
+ manifest = _minimal_manifest()
+ manifest["resources"][0]["endpoint"] = {
+ "path": "/search",
+ "method": "POST",
+ "params": {"limit": 100},
+ "json": {"query": "foo"},
+ }
+ validate_manifest(manifest)
+
+ @parameterized.expand([("json", ["not", "an", "object"]), ("params", ["nope"])])
+ def test_rejects_non_object_params_or_json(self, field, value):
+ manifest = _minimal_manifest()
+ manifest["resources"][0]["endpoint"][field] = value
+ with self.assertRaises(ManifestValidationError) as ctx:
+ validate_manifest(manifest)
+ assert field in str(ctx.exception)
+
@parameterized.expand(
[
("token", {"type": "bearer", "token": "leaked"}),
@@ -127,6 +155,21 @@ class TestValidateManifestUrls(SimpleTestCase):
assert not ok
assert "users" in (err or "")
+ @parameterized.expand(
+ [
+ ("http_public", "http://api.example.com"),
+ ("http_private", "http://10.0.0.1/api"),
+ ("https_loopback", "https://127.0.0.1/api"),
+ ]
+ )
+ @override_settings(CLOUD_DEPLOYMENT="")
+ def test_self_hosted_skips_host_check(self, _name: str, base_url: str):
+ # _is_host_safe is a no-op outside of cloud, and http:// is permitted.
+ # A self-hosted instance must be able to reach internal/private hosts.
+ manifest = _minimal_manifest(base_url=base_url)
+ ok, err = validate_manifest_urls(manifest, team_id=999)
+ assert ok, err
+
class TestCustomSourceAssembleManifest(SimpleTestCase):
def test_rejects_invalid_json(self):
@@ -205,6 +248,26 @@ class TestCustomSourceGetSchemas(SimpleTestCase):
schemas = source.get_schemas(config, team_id=999, names=["nonexistent"])
assert schemas == []
+ @parameterized.expand(
+ [
+ ("default_datetime", None, IncrementalFieldType.DateTime),
+ ("declared_integer", "integer", IncrementalFieldType.Integer),
+ ("unknown_falls_back", "bogus", IncrementalFieldType.DateTime),
+ ]
+ )
+ def test_incremental_cursor_type_from_manifest(self, _name, declared, expected):
+ manifest = _minimal_manifest()
+ incremental: dict = {"cursor_path": "cursor"}
+ if declared is not None:
+ incremental["cursor_type"] = declared
+ manifest["resources"][0]["endpoint"]["incremental"] = incremental
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ schema = source.get_schemas(config, team_id=999)[0]
+ assert schema.incremental_fields[0]["type"] == expected
+ assert schema.incremental_fields[0]["field_type"] == expected
+
class TestCustomSourceValidateCredentials(SimpleTestCase):
@patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
@@ -218,25 +281,38 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):
assert ok, err
assert err is None
+ @parameterized.expand([401, 403])
@patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
- def test_returns_false_on_4xx(self, mock_session):
- response = MagicMock(status_code=401, text="unauthorized")
+ def test_returns_false_on_auth_rejection(self, status_code, mock_session):
+ response = MagicMock(status_code=status_code, text="unauthorized")
mock_session.return_value.request.return_value = response
source = CustomSource()
config = CustomSourceConfig(manifest_json=json.dumps(_minimal_manifest()), auth_token="abc")
ok, err = source.validate_credentials(config, team_id=999)
assert not ok
- assert "401" in (err or "")
+ assert str(status_code) in (err or "")
+
+ @parameterized.expand([404, 405, 429, 500])
+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_non_auth_error_status_does_not_block_creation(self, status_code, mock_session):
+ # A 404/405/429/5xx is not a credential problem — it must not block
+ # source creation; the real sync surfaces it if it persists.
+ mock_session.return_value.request.return_value = MagicMock(status_code=status_code, text="nope")
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_minimal_manifest()), auth_token="abc")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
@patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
def test_probes_every_resource(self, mock_session):
- # The second resource fails — validation must catch it, not stop at the first.
+ # The second resource fails auth — validation must catch it, not stop at the first.
manifest = _minimal_manifest()
manifest["resources"].append({"name": "orders", "endpoint": {"path": "/orders"}})
mock_session.return_value.request.side_effect = [
MagicMock(status_code=200, text="{}"),
- MagicMock(status_code=404, text="not found"),
+ MagicMock(status_code=403, text="forbidden"),
]
source = CustomSource()
@@ -244,7 +320,141 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):
ok, err = source.validate_credentials(config, team_id=999)
assert not ok
assert "orders" in (err or "")
- assert "404" in (err or "")
+ assert "403" in (err or "")
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_probe_attaches_query_location_api_key(self, mock_session):
+ # An api_key with location 'query' must reach the probe request — the
+ # probe builds auth via create_auth, the same path the real sync uses.
+ mock_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = {"type": "api_key", "name": "apikey", "location": "query"}
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest), auth_api_key="sk_test")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
+
+ probe_auth = mock_session.return_value.request.call_args.kwargs["auth"]
+ assert isinstance(probe_auth, APIKeyAuth)
+ assert probe_auth.location == "query"
+ assert probe_auth.api_key == "sk_test"
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_probe_replays_json_body(self, mock_session):
+ # A POST endpoint with a JSON body must send that body in the probe, so
+ # an endpoint that needs it doesn't answer differently at probe vs sync.
+ mock_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")
+ manifest = _minimal_manifest()
+ manifest["resources"][0]["endpoint"] = {"path": "/search", "method": "POST", "json": {"query": "foo"}}
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest), auth_token="abc")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
+ assert mock_session.return_value.request.call_args.kwargs["json"] == {"query": "foo"}
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_probe_replays_static_query_params(self, mock_session):
+ mock_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")
+ manifest = _minimal_manifest()
+ manifest["resources"][0]["endpoint"]["params"] = {"limit": 100, "order": "asc"}
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest), auth_token="abc")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
+ assert mock_session.return_value.request.call_args.kwargs["params"] == {"limit": 100, "order": "asc"}
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_probe_skips_incremental_param_specs(self, mock_session):
+ # Dict-valued params are the engine's incremental/resolver specs, resolved
+ # against cursor state at sync time — the probe has none, so it forwards
+ # only the plain scalar params and drops the spec.
+ mock_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")
+ manifest = _minimal_manifest()
+ manifest["resources"][0]["endpoint"]["params"] = {
+ "limit": 100,
+ "since": {"type": "incremental", "cursor_path": "updated_at", "initial_value": "2020-01-01"},
+ }
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest), auth_token="abc")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
+ assert mock_session.return_value.request.call_args.kwargs["params"] == {"limit": 100}
+
+ @parameterized.expand(
+ [
+ (
+ "bearer",
+ {"type": "bearer"},
+ {"auth_token": "ya29.secret"},
+ BearerTokenAuth,
+ {"token": "ya29.secret"},
+ ),
+ (
+ "api_key_header",
+ {"type": "api_key", "name": "X-API-Key", "location": "header"},
+ {"auth_api_key": "sk_h"},
+ APIKeyAuth,
+ {"api_key": "sk_h", "location": "header", "name": "X-API-Key"},
+ ),
+ (
+ "api_key_cookie",
+ {"type": "api_key", "name": "session", "location": "cookie"},
+ {"auth_api_key": "sk_c"},
+ APIKeyAuth,
+ {"api_key": "sk_c", "location": "cookie", "name": "session"},
+ ),
+ (
+ "api_key_param",
+ {"type": "api_key", "name": "key", "location": "param"},
+ {"auth_api_key": "sk_p"},
+ APIKeyAuth,
+ {"api_key": "sk_p", "location": "param", "name": "key"},
+ ),
+ (
+ "http_basic",
+ {"type": "http_basic", "username": "alice"},
+ {"auth_password": "hunter2"},
+ HttpBasicAuth,
+ {"username": "alice", "password": "hunter2"},
+ ),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_probe_attaches_auth_for_each_type(
+ self, _name, auth_manifest, secret_kwargs, expected_cls, expected_attrs, mock_session
+ ):
+ # Every supported (auth type, location) combination must reach the probe
+ # request via create_auth — the same code path the real sync uses.
+ mock_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")
+ manifest = _minimal_manifest()
+ manifest["client"]["auth"] = auth_manifest
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest), **secret_kwargs)
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
+
+ probe_auth = mock_session.return_value.request.call_args.kwargs["auth"]
+ assert isinstance(probe_auth, expected_cls)
+ for attr, expected in expected_attrs.items():
+ assert getattr(probe_auth, attr) == expected, f"{attr} mismatch"
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_returns_false_on_network_error(self, mock_session):
+ # A connection-level failure (DNS, TLS, timeout) must surface as a
+ # credential validation error pointing at the offending resource.
+ mock_session.return_value.request.side_effect = ConnectionError("boom")
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_minimal_manifest()), auth_token="abc")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert not ok
+ assert "could not reach" in (err or "")
+ assert "users" in (err or "")
def test_returns_false_on_invalid_manifest(self):
source = CustomSource()
@@ -268,3 +478,125 @@ class TestIsCustomSourceAvailableForTeam(SimpleTestCase):
@override_settings(CLOUD_DEPLOYMENT="US")
def test_rejects_other_teams_even_on_us(self, team_id):
assert is_custom_source_available_for_team(team_id) is False
+
+
+class TestCustomSourceSourceForPipeline(SimpleTestCase):
+ def test_invalid_manifest_raises_non_retryable(self):
+ # A permanent config error must fail fast, not burn the Temporal retry budget.
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json="{not json}")
+ with self.assertRaises(NonRetryableException):
+ source.source_for_pipeline(config, MagicMock(team_id=999))
+
+ def test_missing_resource_raises_non_retryable(self):
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_minimal_manifest()))
+ inputs = MagicMock(team_id=999, schema_name="nonexistent")
+ with self.assertRaises(NonRetryableException):
+ source.source_for_pipeline(config, inputs)
+
+ @parameterized.expand(
+ [("default_asc", None, "asc"), ("explicit_asc", "asc", "asc"), ("explicit_desc", "desc", "desc")]
+ )
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resource")
+ def test_sort_mode_threaded_to_source_response(self, _name, declared, expected, _mock_resource):
+ manifest = _minimal_manifest()
+ if declared is not None:
+ manifest["resources"][0]["sort_mode"] = declared
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="users",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ response = source.source_for_pipeline(config, inputs)
+ assert response.sort_mode == expected
+
+ @parameterized.expand(
+ [
+ ("opted_in", True, "2024-01-01T00:00:00Z", "2024-01-01T00:00:00Z"),
+ ("opted_out_drops_value", False, "2024-01-01T00:00:00Z", None),
+ ("opted_in_none", True, None, None),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resource")
+ def test_incremental_last_value_threaded_to_rest_engine(
+ self, _name, should_use_incremental, last_value, expected, mock_resource
+ ):
+ # The high-watermark must only reach the REST engine when the schema is
+ # configured for incremental sync — otherwise a full refresh would skip rows.
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_minimal_manifest()))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="users",
+ job_id="job-1",
+ should_use_incremental_field=should_use_incremental,
+ db_incremental_field_last_value=last_value,
+ )
+ source.source_for_pipeline(config, inputs)
+
+ assert mock_resource.call_args.kwargs["db_incremental_field_last_value"] == expected
+
+ @parameterized.expand(
+ [
+ ("auto", {"type": "auto"}),
+ ("single_page", {"type": "single_page"}),
+ ("json_response", {"type": "json_response", "next_url_path": "next"}),
+ ("header_link", {"type": "header_link"}),
+ ("cursor", {"type": "cursor", "cursor_path": "next_cursor", "cursor_param": "cursor"}),
+ ("offset", {"type": "offset", "limit": 100}),
+ ("page_number", {"type": "page_number", "page_param": "page"}),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resource")
+ def test_paginator_config_threaded_to_rest_engine(self, _name, paginator_config, mock_resource):
+ # Every PaginatorType the REST engine knows about must round-trip through
+ # the custom source — paginator config is passed through untouched and the
+ # REST engine selects the paginator at sync time.
+ manifest = _minimal_manifest()
+ manifest["client"]["paginator"] = paginator_config
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest), auth_token="abc")
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="users",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ source.source_for_pipeline(config, inputs)
+
+ threaded_config = mock_resource.call_args.args[0]
+ assert threaded_config["client"]["paginator"] == paginator_config
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resource")
+ def test_cursor_type_stripped_before_rest_engine(self, mock_resource):
+ # cursor_type informs schema field typing but is not a valid kwarg for the
+ # engine's Incremental(**config) — it must be removed before the manifest
+ # reaches rest_api_resource, while the other incremental keys survive.
+ manifest = _minimal_manifest()
+ manifest["resources"][0]["endpoint"]["incremental"] = {
+ "cursor_path": "updated_at",
+ "start_param": "since",
+ "cursor_type": "integer",
+ }
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest), auth_token="abc")
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="users",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ source.source_for_pipeline(config, inputs)
+
+ threaded_incremental = mock_resource.call_args.args[0]["resources"][0]["endpoint"]["incremental"]
+ assert threaded_incremental == {"cursor_path": "updated_at", "start_param": "since"}