: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
fix(data-warehouse): bound custom source credential probe (#61630)
Marcus Hof0b6464283b5c
diff --git a/posthog/temporal/data_imports/sources/custom/source.py b/posthog/temporal/data_imports/sources/custom/source.pyindex df86b9e397fe..70abf6be7dc8 100644--- a/posthog/temporal/data_imports/sources/custom/source.py+++ b/posthog/temporal/data_imports/sources/custom/source.py@@ -5,6 +5,8 @@ from urllib.parse import urlparsefrom django.conf import settingsfrom pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator+from requests import Response+from urllib3.util.retry import Retryfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,@@ -34,6 +36,26 @@ from products.data_warehouse.backend.types import ExternalDataSourceType, Increm# the dedicated secret `auth_*` config fields so the API layer can redact them.INLINE_SECRET_KEYS = ("token", "api_key", "password")+# Outbound create-time probe tunables. The probe runs inline on the API request+# thread, the same as business_knowledge's URL fetch, so it borrows that feature's+# limits (products/business_knowledge/backend/constants.py): short connect/read+# timeouts and a hard upper bound on declared resources. Defined locally rather+# than imported so data_imports doesn't couple to an unrelated product.+PROBE_CONNECT_TIMEOUT = 5+PROBE_READ_TIMEOUT = 10+# Auth/header config is shared across resources and the probe only acts on 401/403,+# so one reachable resource validates the credential. Probe a small prefix instead+# of one request per declared resource — otherwise the endpoint is an on-demand+# outbound-request amplifier (one API call -> N outbound requests).+PROBE_MAX_RESOURCES = 5+# Bytes read from a 401/403 body for the error snippet. The probe opens responses+# with stream=True and never ingests the body, so a bounded slice keeps a large or+# hostile response from being buffered into worker memory (cf. URL_MAX_BYTES, sized+# down here because the probe only needs a short diagnostic snippet).+PROBE_ERROR_SNIPPET_BYTES = 2048+# Upper bound on declared resources, matching business_knowledge MAX_URLS_PER_SOURCE.+MAX_MANIFEST_RESOURCES = 500+def is_custom_source_available_for_team(team_id: int | None) -> bool:# While the custom source is in development it is restricted to a single@@ -113,7 +135,7 @@ class _Manifest(BaseModel):data_selector, incremental, …) passes through untouched to the REST engine."""client: _ManifestClient- resources: list[_ManifestResource] = Field(min_length=1)+ resources: list[_ManifestResource] = Field(min_length=1, max_length=MAX_MANIFEST_RESOURCES)@model_validator(mode="after")def _resource_names_unique(self) -> "_Manifest":@@ -393,10 +415,10 @@ class CustomSource(SimpleSource[CustomSourceConfig]):if not ok:return False, err- # Probe every resource so we surface auth/connection errors at create-time- # 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.+ # Probe a small prefix of resources so we surface auth/connection errors+ # at create-time 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"]@@ -411,12 +433,20 @@ class CustomSource(SimpleSource[CustomSourceConfig]):except (ValueError, TypeError) as exc:return False, f"Invalid auth configuration: {exc}"- # Register the credential values so they're redacted from the probe's- # request logs/samples even when injected under a manifest-chosen- # query-param or header name the denylist scrubber can't anticipate.- session = make_tracked_session(headers=headers, redact_values=auth_secret_values(probe_auth))+ # The probe runs inline on the request thread, so keep it cheap and+ # bounded: no retries (don't multiply outbound volume at create time),+ # no redirects (Smokescreen re-resolves each hop; keep the credential+ # pinned to the validated host), and credential values registered for+ # redaction even when injected under a manifest-chosen param/header name+ # the denylist scrubber can't anticipate.+ session = make_tracked_session(+ headers=headers,+ redact_values=auth_secret_values(probe_auth),+ retry=Retry(total=0),+ allow_redirects=False,+ )- for resource in manifest["resources"]:+ for resource in manifest["resources"][:PROBE_MAX_RESOURCES]:endpoint = resource.get("endpoint", {})method = (endpoint.get("method") or "GET").upper()path = endpoint.get("path", "")@@ -428,8 +458,16 @@ class CustomSource(SimpleSource[CustomSourceConfig]):probe_params = _static_probe_params(endpoint.get("params"))probe_json = endpoint.get("json")try:+ # stream=True so the body isn't buffered into memory; only a 401/403+ # snippet is read below, and the response is always closed.response = session.request(- method, url, params=probe_params or None, json=probe_json, auth=probe_auth, timeout=15+ method,+ url,+ params=probe_params or None,+ json=probe_json,+ auth=probe_auth,+ timeout=(PROBE_CONNECT_TIMEOUT, PROBE_READ_TIMEOUT),+ stream=True,)except Exception as exc:return False, f"Resource {resource['name']!r}: could not reach {url}: {exc}"@@ -439,12 +477,15 @@ class CustomSource(SimpleSource[CustomSourceConfig]):# 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}: the upstream API rejected the request with "- f"HTTP {response.status_code} from {url} — check the configured auth credentials: "- f"{response.text[:200]}"- )+ try:+ if response.status_code in (401, 403):+ return False, (+ 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"{_read_capped_text(response)}"+ )+ finally:+ response.close()return True, None@@ -543,6 +584,26 @@ class CustomSource(SimpleSource[CustomSourceConfig]):)+def _read_capped_text(response: Response) -> str:+ """Read at most ``PROBE_ERROR_SNIPPET_BYTES`` of a streamed body for an error snippet.++ The probe opens responses with ``stream=True`` and never ingests the body, so a+ bounded slice keeps a large or hostile upstream response from being materialized+ into worker memory. Reads the raw stream directly (rather than ``response.text``,+ which buffers and decompresses the whole body).++ ``decode_content=False`` is deliberate: it reads exactly ``PROBE_ERROR_SNIPPET_BYTES``+ raw bytes and never inflates a ``Content-Encoding: gzip`` body, so a decompression+ bomb can't expand a tiny read into megabytes. The snippet is only a human-readable+ diagnostic — a (rare) compressed error body just shows as bytes.+ """+ try:+ raw = response.raw.read(PROBE_ERROR_SNIPPET_BYTES, decode_content=False)+ except Exception:+ return ""+ return raw.decode("utf-8", errors="replace")++def _static_probe_params(params: Any) -> dict[str, Any]:"""The literal query params safe to replay in the create-time probe.diff --git a/posthog/temporal/data_imports/sources/custom/test_custom_source.py b/posthog/temporal/data_imports/sources/custom/test_custom_source.pyindex f1aef652e890..70be0830c5ff 100644--- a/posthog/temporal/data_imports/sources/custom/test_custom_source.py+++ b/posthog/temporal/data_imports/sources/custom/test_custom_source.py@@ -1,3 +1,5 @@+import io+import gzipimport jsonfrom unittest.mock import MagicMock, patch@@ -5,11 +7,16 @@ from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized+from urllib3.response import HTTPResponsefrom posthog.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth, BearerTokenAuth, HttpBasicAuthfrom posthog.temporal.data_imports.sources.custom.source import (+ MAX_MANIFEST_RESOURCES,+ PROBE_ERROR_SNIPPET_BYTES,+ PROBE_MAX_RESOURCES,CustomSource,ManifestValidationError,+ _read_capped_text,is_custom_source_available_for_team,manifest_request_hosts,validate_manifest,@@ -70,6 +77,24 @@ class TestValidateManifest(SimpleTestCase):validate_manifest(manifest)assert "Duplicate" in str(ctx.exception)+ def test_rejects_too_many_resources(self):+ # An unbounded resource count turns the create-time probe into an outbound+ # request amplifier — the manifest is capped at MAX_MANIFEST_RESOURCES.+ manifest = _minimal_manifest()+ manifest["resources"] = [+ {"name": f"r{i}", "endpoint": {"path": f"/r{i}"}} for i in range(MAX_MANIFEST_RESOURCES + 1)+ ]+ with self.assertRaises(ManifestValidationError) as ctx:+ validate_manifest(manifest)+ assert "at most" in str(ctx.exception)++ def test_accepts_resource_count_at_limit(self):+ manifest = _minimal_manifest()+ manifest["resources"] = [+ {"name": f"r{i}", "endpoint": {"path": f"/r{i}"}} for i in range(MAX_MANIFEST_RESOURCES)+ ]+ validate_manifest(manifest)+def test_rejects_unknown_auth_type(self):manifest = _minimal_manifest()manifest["client"]["auth"] = {"type": "oauth"}@@ -321,13 +346,13 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):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 auth — validation must catch it, not stop at the first.+ def test_probes_resources_until_auth_failure(self, mock_session):+ # A later (within-cap) 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=403, text="forbidden"),+ MagicMock(status_code=200),+ MagicMock(status_code=403),]source = CustomSource()@@ -337,6 +362,57 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):assert "orders" in (err or "")assert "403" in (err or "")+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")+ def test_probe_caps_resource_count(self, mock_session):+ # The probe must hit at most PROBE_MAX_RESOURCES upstreams regardless of how many+ # resources the manifest declares — so the endpoint can't fan out one request per resource.+ manifest = _minimal_manifest()+ manifest["resources"] = [+ {"name": f"r{i}", "endpoint": {"path": f"/r{i}"}} for i in range(PROBE_MAX_RESOURCES + 3)+ ]+ mock_session.return_value.request.return_value = MagicMock(status_code=200)++ 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_count == PROBE_MAX_RESOURCES++ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")+ def test_probe_streams_and_caps_error_body(self, mock_session):+ # The probe opens responses with stream=True and reads only a bounded slice+ # of a 401/403 body for the error snippet — never buffering the full body.+ response = MagicMock(status_code=403)+ response.raw.read.return_value = b"forbidden: token expired"+ 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+ # The snippet came from the bounded raw read; had the code used response.text[:200]+ # the message would contain a MagicMock repr instead of the decoded bytes.+ assert "forbidden: token expired" in (err or "")+ assert mock_session.return_value.request.call_args.kwargs["stream"] is True+ response.close.assert_called_once()++ def test_read_capped_text_is_decompression_bomb_proof(self):+ # A gzip body that inflates ~1000x must not be materialized — reading the raw+ # (undecoded) stream caps the snippet regardless of Content-Encoding.+ payload = b"\x00" * (20 * 1024 * 1024)+ compressed = gzip.compress(payload)+ assert len(payload) / len(compressed) > 100 # it really is a decompression bomb++ response = MagicMock()+ response.raw = HTTPResponse(+ body=io.BytesIO(compressed),+ headers={"content-encoding": "gzip", "content-length": str(len(compressed))},+ status=403,+ preload_content=False,+ )+ snippet = _read_capped_text(response)+ assert len(snippet) <= PROBE_ERROR_SNIPPET_BYTES+@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