: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(warehouse-sources): don't disable customer syncs for our own credential failures (#88279)
Tom Owerse7fc8bb5b0c5
diff --git a/posthog/integration_secrets/client.py b/posthog/integration_secrets/client.pyindex 9c076239c9d9..17587cee09b1 100644--- a/posthog/integration_secrets/client.py+++ b/posthog/integration_secrets/client.py@@ -40,6 +40,7 @@ from typing import Anyfrom django.conf import settings+import requestsimport structlogimport posthoganalyticsfrom prometheus_client import Counter@@ -50,7 +51,12 @@ from posthog.security.outbound_proxy import internal_requestsfrom posthog.settings.utils import get_listfrom .callers import IntegrationCaller-from .errors import IntegrationServiceMisconfiguredError, SecretInRecoveryError, SecretMissingError+from .errors import (+ IntegrationServiceMisconfiguredError,+ IntegrationServiceUnreachableError,+ SecretInRecoveryError,+ SecretMissingError,+)logger = structlog.get_logger(__name__)@@ -189,13 +195,7 @@ class IntegrationSecretsClient:return self._fetch(keys, caller)def _fetch(self, keys: list[str], caller: IntegrationCaller) -> dict[str, SecretValue]:- response = internal_requests.post(- f"{settings.INTEGRATION_SERVICE_URL.rstrip('/')}{RESOLVE_PATH}",- headers=self._auth_headers(keys, caller),- timeout=REQUEST_TIMEOUT_SECONDS,- )- response.raise_for_status()- body: dict[str, Any] = response.json()+ body = self._post(keys, caller)missing = set(body.get("missing") or [])secrets: dict[str, Any] = body.get("secrets") or {}@@ -219,6 +219,36 @@ class IntegrationSecretsClient:return resolved+ def _post(self, keys: list[str], caller: IntegrationCaller) -> dict[str, Any]:+ """The request itself, with every transport failure wearing this client's own type.++ No `requests` exception may escape. Callers sit in the middle of talking to some third+ party, so a bare `HTTPError` from here is indistinguishable from one raised by the API+ they were actually calling — and the difference decides whose problem it is. A misrouted+ `INTEGRATION_SERVICE_URL` answering 404 is our deploy error, not a dead endpoint of+ theirs, and a caller reading the status code alone cannot tell.+ """+ # Minted outside the try: signing is local work, and a failure there is a bug in this+ # process, not the service being unreachable. Catching it here would file it under the+ # one label nobody investigates.+ headers = self._auth_headers(keys, caller)+ try:+ response = internal_requests.post(+ f"{settings.INTEGRATION_SERVICE_URL.rstrip('/')}{RESOLVE_PATH}",+ headers=headers,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ # ValueError covers a body that is not JSON. Modern `requests` raises its own+ # JSONDecodeError (a RequestException), but the stdlib/simplejson ValueError still+ # surfaces on older paths, and nothing else in this block raises one.+ return response.json()+ except (requests.RequestException, ValueError) as e:+ INTEGRATION_SECRET_FETCH_COUNTER.labels(outcome="unreachable").inc()+ raise IntegrationServiceUnreachableError(+ f"The integration service did not answer a credential request: {e}"+ ) from e+def _auth_headers(self, keys: list[str], caller: IntegrationCaller) -> dict[str, str]:token = encode_jwt({"caller": str(caller), "keys": sorted(set(keys))},diff --git a/posthog/integration_secrets/errors.py b/posthog/integration_secrets/errors.pyindex 6cdc32a7dfdd..7b58d83e75a9 100644--- a/posthog/integration_secrets/errors.py+++ b/posthog/integration_secrets/errors.py@@ -1,11 +1,41 @@-class IntegrationSecretError(Exception):+class IntegrationSecretsFailure(Exception):+ """Base for everything the integration secrets client raises.++ One base type so a caller states the policy once, instead of listing subclasses it will+ forget to update when a new one appears. Every failure below shares two properties, and+ those properties are the reason the base exists:++ 1. **It is never the fault of whoever asked for the credential.** These are the OAuth app+ secrets and API keys PostHog itself owns. A product reading one cannot cause any of+ these states, cannot detect them in advance, and cannot fix them. So a caller must not+ turn one into a user-facing "your configuration is broken", and must not disable work+ the user set up. A rotation or an incident is ours to carry, not theirs.+ 2. **It is never permanent.** Recovery ends when the credential is re-provisioned, a+ missing key ends when someone adds it, and an unreachable service comes back. Retrying+ is always the right shape, even when the wait is long.++ `reportable` splits them on the one axis that does differ: whether a human has to be told.+ It defaults to True so a new subclass is loud until someone decides otherwise.+ """++ reportable: bool = True+++class IntegrationSecretError(IntegrationSecretsFailure):+ """A failure about one specific credential, which names it."""+def __init__(self, key: str, message: str) -> None:self.key = keysuper().__init__(message)class SecretMissingError(IntegrationSecretError):- """The key is unknown to the service, or has no value in this environment."""+ """The key is unknown to the service, or has no value in this environment.++ Reportable: nothing resolves this on its own. Either a key never made it into the service+ for this environment, or a caller is asking for a name that does not exist. Both need a+ person, and until one looks, every read of that credential fails.+ """def __init__(self, key: str, disabled_reason: str | None = None) -> None:if disabled_reason is None:@@ -20,7 +50,7 @@ class SecretMissingError(IntegrationSecretError):)-class IntegrationServiceMisconfiguredError(Exception):+class IntegrationServiceMisconfiguredError(IntegrationSecretsFailure):"""Half-configured: one of the two variables is set and the other is not.Both unset is a valid state — self-hosted and local development don't run the service, and@@ -28,6 +58,8 @@ class IntegrationServiceMisconfiguredError(Exception):nobody chose, and it is invisible: it reads as "not configured", so credentials still mountedas environment variables resolve as if the service answered, while the ones that have actuallymoved raise SecretMissingError. Refuse instead, and name the variable to set.++ Reportable: a deployment is wrong and only a deploy fixes it."""def __init__(self, missing: str) -> None:@@ -44,7 +76,31 @@ class SecretInRecoveryError(IntegrationSecretError):Raised instead of returning a value that cannot work, so the caller surfaces"reconnect needed" rather than hammering a third party with a dead credential.++ Not reportable: somebody put this key into recovery on purpose, so an alert would tell them+ a thing they just did. Every caller of that credential fails at once, so reporting it would+ also arrive as a flood proportional to traffic rather than to the size of the problem."""+ reportable = False+def __init__(self, key: str) -> None:super().__init__(key, f"{key} is in recovery — the credential needs to be re-provisioned")+++class IntegrationServiceUnreachableError(IntegrationSecretsFailure):+ """The service could not be reached, refused the request, or did not answer with usable JSON.++ Exists so no `requests` exception escapes this client. A caller that catches a bare+ `HTTPError` cannot tell our own service refusing a request from the third-party API the+ caller was actually trying to reach — and at least one caller reads a bare 404 as "the+ user's endpoint is gone" and stops their work over it. A misrouted `INTEGRATION_SERVICE_URL`+ returns 404 too, so without this type our own deploy error would be reported as their+ mistake.++ Not reportable: the service has its own availability alerting, which sees the outage once.+ Capturing here instead would report it once per credential read, which is a measure of how+ busy PostHog is rather than of what is wrong.+ """++ reportable = Falsediff --git a/posthog/integration_secrets/test/test_client.py b/posthog/integration_secrets/test/test_client.pyindex 0d898b5b0da5..d988c691c071 100644--- a/posthog/integration_secrets/test/test_client.py+++ b/posthog/integration_secrets/test/test_client.py@@ -17,7 +17,9 @@ from posthog.integration_secrets.client import (integration_service_signing_keys,)from posthog.integration_secrets.errors import (+ IntegrationSecretsFailure,IntegrationServiceMisconfiguredError,+ IntegrationServiceUnreachableError,SecretInRecoveryError,SecretMissingError,)@@ -124,7 +126,52 @@ class TestIntegrationSecretsClient(SimpleTestCase):return {"error": "Secret store unavailable"}with patch(POST, return_value=ErrorResponse()):- with pytest.raises(requests.HTTPError):+ with pytest.raises(IntegrationServiceUnreachableError):+ self.secrets.get(KEY, CALLER)++ # No `requests` exception may escape, whatever the status. A caller is mid-conversation with+ # some third party, so a bare HTTPError from here is indistinguishable from one that API+ # raised — and callers act on that difference. The 404 is the case that bites: a misrouted+ # INTEGRATION_SERVICE_URL is our deploy error, but a caller seeing a raw 404 reads it as the+ # user's endpoint being gone and can stop their work over it.+ @parameterized.expand(+ [+ ("404 misrouted url", requests.HTTPError("404 Client Error", response=requests.Response())),+ ("401 unaccepted signing key", requests.HTTPError("401 Unauthorized", response=requests.Response())),+ ("connection refused", requests.ConnectionError("connection refused")),+ ("read timeout", requests.Timeout("timed out")),+ ]+ )+ def test_transport_failure_wears_this_clients_type_for(self, _name: str, raised: Exception) -> None:+ class ErrorResponse:+ def raise_for_status(self) -> None:+ raise raised++ def json(self) -> dict[str, Any]:+ return {}++ # Raised from the call itself for a connection failure, from raise_for_status for a status.+ side_effect = raised if isinstance(raised, requests.ConnectionError | requests.Timeout) else None+ patched = patch(POST, side_effect=side_effect) if side_effect else patch(POST, return_value=ErrorResponse())+ with patched:+ with pytest.raises(IntegrationServiceUnreachableError) as exc_info:+ self.secrets.get(KEY, CALLER)+ # The cause is kept so error tracking and logs still show what actually went wrong.+ assert exc_info.value.__cause__ is raised+ assert not isinstance(exc_info.value, requests.RequestException)++ # A body that isn't JSON is the same class of failure as no answer at all: something is+ # between us and the service, or the service is broken. It must not surface as a missing key.+ def test_an_unparseable_body_is_unreachable_not_missing(self) -> None:+ class HtmlResponse:+ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict[str, Any]:+ raise ValueError("Expecting value: line 1 column 1 (char 0)")++ with patch(POST, return_value=HtmlResponse()):+ with pytest.raises(IntegrationServiceUnreachableError):self.secrets.get(KEY, CALLER)# With no cache there is no last known good, so an outage is an outage. This is the@@ -134,18 +181,34 @@ class TestIntegrationSecretsClient(SimpleTestCase):with patch(POST, return_value=FakeResponse(body({KEY: steady("sec")}))):self.secrets.get(KEY, CALLER)- with patch(POST, side_effect=ConnectionError("integration service is down")):- with pytest.raises(ConnectionError):+ with patch(POST, side_effect=requests.ConnectionError("integration service is down")):+ with pytest.raises(IntegrationServiceUnreachableError):self.secrets.get(KEY, CALLER)def test_does_not_fall_back_to_the_environment_when_the_service_is_down(self) -> None:with (- patch(POST, side_effect=ConnectionError("integration service is down")),+ patch(POST, side_effect=requests.ConnectionError("integration service is down")),patch.dict("os.environ", {KEY: "from-env"}),):- with pytest.raises(ConnectionError):+ with pytest.raises(IntegrationServiceUnreachableError):self.secrets.get(KEY, CALLER)+ # The base type is the whole contract a caller depends on: catch one thing, and a subclass+ # added later is covered without every call site being revisited.+ @parameterized.expand(+ [+ ("missing", SecretMissingError(KEY), True),+ ("in recovery", SecretInRecoveryError(KEY), False),+ ("half-configured", IntegrationServiceMisconfiguredError("INTEGRATION_SERVICE_URL"), True),+ ("unreachable", IntegrationServiceUnreachableError("no answer"), False),+ ]+ )+ def test_every_failure_shares_the_base_type_and_declares_reportability(+ self, _name: str, error: Exception, reportable: bool+ ) -> None:+ assert isinstance(error, IntegrationSecretsFailure)+ assert error.reportable is reportable+@override_settings(**SERVICE_SETTINGS)class TestRolloutFlag(SimpleTestCase):diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex fc3d69b0d27d..360ca20bcbea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -15,6 +15,8 @@ from structlog.typing import FilteringBoundLoggerfrom temporalio import activityfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.exceptions_capture import capture_exception+from posthog.integration_secrets.errors import IntegrationSecretsFailurefrom posthog.models.integration import UndecryptedIntegrationSecretErrorfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.activity_context import current_activity_attempt@@ -415,6 +417,12 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:try:config = new_source.parse_config(model.pipeline.job_inputs)+ except IntegrationSecretsFailure as e:+ # A source whose config carries a PostHog-owned credential resolves it here, so a+ # failure at this point is ours and not a corrupt `job_inputs`. Route it through the+ # shared policy: the branch below would read it as an unparseable config and disable+ # the customer's schema over a rotation they can't see and didn't cause.+ await _handle_import_error(job_inputs, logger, e)except Exception as e:# A stored config that can't be parsed (corrupt or double-encoded `job_inputs`)# fails identically on every attempt — there is nothing to retry. Treat it as@@ -513,6 +521,16 @@ def _get_models(return ImportJobModels(job=job, schema=schema, source=source, table=table)+# What a customer reads when a PostHog-managed credential is unavailable. Deliberately says+# nothing about which credential: the name is ours (`HUBSPOT_APP_CLIENT_SECRET`), it means nothing+# to them, and naming it invites them to go looking for a setting they do not have. The full+# detail goes to the logs and, when a person needs to act, to error tracking.+INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE = (+ "A PostHog-managed credential for this source is temporarily unavailable. This sync will "+ "retry automatically — no action is needed on your side."+)++async def _handle_import_error(job_inputs: PipelineInputs,logger: FilteringBoundLogger,@@ -569,6 +587,35 @@ async def _handle_import_error(job_inputs.team_id, str(job_inputs.source_id), job_inputs.run_id, error_msg, logger, error)+ # Every credential the integration service holds is PostHog's own — the OAuth app secrets and+ # API keys we own, not anything the customer configured. So none of its failure states are+ # theirs to fix, and none are permanent: a key in recovery is re-provisioned, a missing key is+ # added, an unreachable service comes back. Retry, and if the budget runs out let the run fail+ # and the next scheduled sync pick it up.+ #+ # What must not happen is `handle_non_retryable_error`, which disables the schema and makes a+ # customer re-enable a sync they never broke. That is the whole reason this is classified here+ # by type rather than left to fall through: one credential going into recovery would otherwise+ # disable every sync of that source type, across every customer, until each was re-enabled by+ # hand — turning a reversible platform action into a wide manual recovery.+ #+ # Checked before the bare-404 rule below on purpose. That rule reads a 404 as "the customer's+ # endpoint is gone", and a misrouted INTEGRATION_SERVICE_URL answers 404 as well; the client+ # wraps its transport failures so the two can't be confused, and this ordering keeps that true+ # even if something later leaks a raw HTTPError.+ if isinstance(error, IntegrationSecretsFailure):+ if error.reportable:+ # A gap only PostHog can close (a key never added for this environment, a+ # half-configured deployment). Capture explicitly rather than letting it escape raw:+ # the message the customer ends up reading must not carry an internal credential name,+ # and error tracking still needs the real exception to group and route it.+ capture_exception(error)+ await logger.aexception(error_msg)+ else:+ await logger.awarning(error_msg)+ await logger.adebug("Integration service credential unavailable - re-raising for Temporal retry")+ raise NonReportableError(INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE) from error+# A 404 from the shared REST engine's fallback `raise_for_status()` path means the configured# endpoint/resource doesn't exist — every retry replays the identical request against the same# dead URL. Unlike 401 (a token needing refresh, which the REST engine's own retry re-mints) ordiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 36170245a5f4..6f2907882407 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -13,6 +13,12 @@ from jsonpath_ng.exceptions import JsonPathParserErrorfrom parameterized import parameterizedfrom requests.exceptions import HTTPError+from posthog.integration_secrets.errors import (+ IntegrationServiceMisconfiguredError,+ IntegrationServiceUnreachableError,+ SecretInRecoveryError,+ SecretMissingError,+)from posthog.temporal.common.errors import NonReportableErrorfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -773,3 +779,116 @@ async def test_parent_gate_inert_for_sources_without_requirements():assert result is Falseflag_check.assert_not_called()+++# Credentials the integration service holds are PostHog's own — the OAuth app secrets and API keys+# we own, not anything a customer configured. Every failure state it has is therefore ours, and+# every one of them ends on its own (a key in recovery is re-provisioned, a missing key is added, an+# unreachable service comes back). The classification has to reflect both facts: retry, and never+# reach handle_non_retryable_error, which disables the schema and makes the customer re-enable a+# sync they never broke. Without this, one key going into recovery would disable every sync of that+# source type across every customer.+ "error,reported",+ [+ (SecretInRecoveryError("HUBSPOT_APP_CLIENT_SECRET"), False),+ (SecretMissingError("HUBSPOT_APP_CLIENT_SECRET"), True),+ (SecretMissingError("HUBSPOT_APP_CLIENT_SECRET", disabled_reason="unconfigured"), True),+ (IntegrationServiceMisconfiguredError("INTEGRATION_SERVICE_URL"), True),+ (IntegrationServiceUnreachableError("connection refused"), False),+ ],+)+async def test_integration_secret_failure_retries_without_disabling_the_schema(error, reported):+ source = mock.MagicMock(spec=SimpleSource)+ source.get_non_retryable_errors.return_value = {}+ source.get_retryable_errors.return_value = set()++ logger = mock.MagicMock()+ logger.awarning = mock.AsyncMock()+ logger.aexception = mock.AsyncMock()+ logger.adebug = mock.AsyncMock()++ with (+ mock.patch.object(module.SourceRegistry, "get_source", return_value=source),+ mock.patch.object(module, "handle_non_retryable_error", new=mock.AsyncMock()) as handle_mock,+ mock.patch.object(module, "capture_exception") as capture_mock,+ ):+ with pytest.raises(NonReportableError) as exc_info:+ await module._handle_import_error(mock.MagicMock(), logger, error)++ # Never disabled: that is the behaviour this whole branch exists to prevent.+ handle_mock.assert_not_awaited()+ assert exc_info.value.__cause__ is error++ # The customer reads a message that names no internal credential and asks nothing of them.+ assert str(exc_info.value) == module.INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE+ assert "HUBSPOT_APP_CLIENT_SECRET" not in str(exc_info.value)+ assert "INTEGRATION_SERVICE_URL" not in str(exc_info.value)++ # Reported only when a person has to act. NonReportableError already keeps the activity+ # interceptor from capturing on escape, so an explicit capture is the only way these reach+ # error tracking at all — and the only way the ones that don't need a human stay quiet.+ assert capture_mock.call_count == (1 if reported else 0)+ if reported:+ assert capture_mock.call_args.args[0] is error+ logger.aexception.assert_awaited_once()+ else:+ logger.awarning.assert_awaited_once()+ logger.aexception.assert_not_awaited()+++# The bare-404 rule below this branch reads a 404 as "the customer's configured endpoint is gone"+# and stops the sync for good. A misrouted INTEGRATION_SERVICE_URL answers 404 too, so ordering+# decides whether our own deploy error is charged to the customer. The client wraps its transport+# failures precisely so the two can't collide; this pins the ordering that keeps it true anyway.+async def test_integration_failure_is_classified_before_the_bare_404_rule():+ error = IntegrationServiceUnreachableError("404 Client Error: Not Found for url: http://integration-service")+ source = mock.MagicMock(spec=SimpleSource)+ source.get_non_retryable_errors.return_value = {}+ source.get_retryable_errors.return_value = set()++ logger = mock.MagicMock()+ logger.awarning = mock.AsyncMock()+ logger.aexception = mock.AsyncMock()+ logger.adebug = mock.AsyncMock()++ with (+ mock.patch.object(module.SourceRegistry, "get_source", return_value=source),+ mock.patch.object(module, "handle_non_retryable_error", new=mock.AsyncMock()) as handle_mock,+ mock.patch.object(module, "capture_exception"),+ ):+ with pytest.raises(NonReportableError):+ await module._handle_import_error(mock.MagicMock(), logger, error)++ handle_mock.assert_not_awaited()+++# The retry budget can run out while the credential is still unavailable. When it does, the+# customer-facing message above becomes the run's `internal_error`, and finalization+# (update_external_data_job_model) matches that text against every non-retryable pattern — a+# case-insensitive substring test. A match there would disable the schema, which is the exact+# outcome the whole classification exists to avoid, arriving by the back door.+#+# So the message is not free text: no pattern may be a substring of it. This sweeps every+# registered source rather than the shared dict alone, because a source-specific pattern+# (a bare word like "unavailable") would do it just as well.+def test_the_customer_facing_message_matches_no_non_retryable_pattern():+ from products.warehouse_sources.backend.temporal.data_imports.external_data_job import Any_Source_Errors+ from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches++ patterns = set(Any_Source_Errors.keys())+ for source in SourceRegistry.get_all_sources().values():+ patterns |= set(source.get_non_retryable_errors().keys())++ # Guard the guard: if the registry ever fails to load, an empty pattern set would make this+ # test pass while checking nothing.+ assert len(patterns) > 20, f"expected the source registry to contribute patterns, got {len(patterns)}"++ offenders = [p for p in patterns if error_message_matches(module.INTEGRATION_CREDENTIAL_UNAVAILABLE_MESSAGE, [p])]+ assert offenders == [], (+ f"These non-retryable patterns match the integration-credential message, so an exhausted "+ f"retry budget would disable the customer's schema: {offenders}"+ )