: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(custom): omit compressed and non-text bodies from probe error (#65440)
Tom Owers6f545273ee8b
diff --git a/posthog/temporal/data_imports/sources/custom/source.py b/posthog/temporal/data_imports/sources/custom/source.pyindex cd592e48d4b8..a22feb9733ae 100644--- a/posthog/temporal/data_imports/sources/custom/source.py+++ b/posthog/temporal/data_imports/sources/custom/source.py@@ -682,11 +682,14 @@ class CustomSource(SimpleSource[CustomSourceConfig]):# surfaces on the first sync instead.try:if response.status_code in (401, 403):- return False, (+ message = (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)}"+ f"HTTP {response.status_code} from {url} — check the configured auth credentials.")+ snippet = _read_capped_text(response)+ if snippet:+ message += f" The upstream responded: {snippet}"+ return False, messagefinally:response.close()@@ -816,14 +819,24 @@ def _read_capped_text(response: Response) -> str:``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.+ bomb can't expand a tiny read into megabytes. The flip side is that a compressed or+ otherwise non-text body would decode to binary garbage, so it is omitted from the+ snippet rather than echoed into a user-facing error."""+ # ``identity`` means "no transformation", so its body is plain bytes worth surfacing;+ # any other encoding (gzip, br, …) would decode to garbage, so omit the snippet.+ if response.headers.get("Content-Encoding", "").lower() not in ("", "identity"):+ return ""try:raw = response.raw.read(PROBE_ERROR_SNIPPET_BYTES, decode_content=False)except Exception:return ""- return raw.decode("utf-8", errors="replace")+ text = raw.decode("utf-8", errors="replace")+ # A replacement char means the bytes weren't valid UTF-8 — a binary or still-encoded+ # body — so drop it rather than surface garbage to the user.+ if "�" in text:+ return ""+ return text.strip()def _static_probe_params(params: Any) -> dict[str, Any]:diff --git a/posthog/temporal/data_imports/sources/custom/test_custom_source.py b/posthog/temporal/data_imports/sources/custom/test_custom_source.pyindex 3e623c2bc358..727b5bfe5b22 100644--- a/posthog/temporal/data_imports/sources/custom/test_custom_source.py+++ b/posthog/temporal/data_imports/sources/custom/test_custom_source.py@@ -15,7 +15,6 @@ 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,FanoutChain,@@ -408,6 +407,7 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):# 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.headers = {}response.raw.read.return_value = b"forbidden: token expired"mock_session.return_value.request.return_value = response@@ -421,22 +421,45 @@ class TestCustomSourceValidateCredentials(SimpleTestCase):assert mock_session.return_value.request.call_args.kwargs["stream"] is Trueresponse.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.+ def test_read_capped_text_omits_compressed_body(self):+ # A gzip-encoded body would decode to binary garbage, so it must be omitted from+ # the snippet rather than echoed into a user-facing error — and never materialized.payload = b"\x00" * (20 * 1024 * 1024)compressed = gzip.compress(payload)assert len(payload) / len(compressed) > 100 # it really is a decompression bombresponse = MagicMock()+ response.headers = {"Content-Encoding": "gzip"}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+ assert _read_capped_text(response) == ""++ @parameterized.expand(+ [+ # A body that isn't valid UTF-8 (binary, or still-encoded) is dropped rather than+ # surfaced as replacement-character garbage.+ ("non_utf8", b"\x1f\x8b\x08\x00garbage\xff\xfe", ""),+ # A plain-text body is returned, stripped of surrounding whitespace.+ ("plain_text", b" forbidden: token expired ", "forbidden: token expired"),+ ]+ )+ def test_read_capped_text_non_compressed(self, _name, raw_bytes, expected):+ response = MagicMock()+ response.headers = {}+ response.raw.read.return_value = raw_bytes+ assert _read_capped_text(response) == expected++ def test_read_capped_text_returns_identity_encoded_body(self):+ # `Content-Encoding: identity` means no transformation, so the plain-text body+ # is still readable and must be surfaced rather than dropped.+ response = MagicMock()+ response.headers = {"Content-Encoding": "identity"}+ response.raw.read.return_value = b"forbidden: token expired"+ assert _read_capped_text(response) == "forbidden: token expired"@patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")def test_probe_attaches_query_location_api_key(self, mock_session):