: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-imports): raise clearly when an OAuth integration secret is still encrypted (#74400)
Tom Owersa7705a2f554f
diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 9e1e295a1dfa..5bf5520fe060 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -64,6 +64,30 @@ from products.workflows.backend.providers import SESProvider, TwilioProviderlogger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)+# Fernet tokens always start with this marker (version byte 0x80 + timestamp, base64-encoded).+_ENCRYPTED_VALUE_PREFIX = "gAAAAA"+++class UndecryptedIntegrationSecretError(ValueError):+ """Raised when a value read off `Integration.sensitive_config` still looks like Fernet+ ciphertext instead of the decrypted secret.++ `sensitive_config` sets `ignore_decrypt_errors=True` so integrations written before+ encryption existed keep loading, but that same leniency means a value that fails to+ decrypt under every configured key (a lost/rotated key, a corrupted row) comes back as+ raw ciphertext rather than raising. Left unchecked, that ciphertext gets sent to the+ third-party API as if it were the real credential, which rejects it as invalid — hiding+ the actual cause behind what looks like a bad customer-supplied key.+ """+++def _decrypted_sensitive_value(value: str | None, field_name: str) -> str | None:+ if value is not None and value.startswith(_ENCRYPTED_VALUE_PREFIX):+ raise UndecryptedIntegrationSecretError(+ f"Integration.sensitive_config['{field_name}'] is still encrypted; the stored credentials could not be decrypted"+ )+ return value+def _decode_jwt_payload(token: str) -> dict | None:"""@@ -493,11 +517,11 @@ class Integration(models.Model):@propertydef access_token(self) -> str | None:- return self.sensitive_config.get("access_token")+ return _decrypted_sensitive_value(self.sensitive_config.get("access_token"), "access_token")@propertydef refresh_token(self) -> str | None:- return self.sensitive_config.get("refresh_token")+ return _decrypted_sensitive_value(self.sensitive_config.get("refresh_token"), "refresh_token")def defer_repository_cache_fields(queryset: models.QuerySet[Integration]) -> models.QuerySet[Integration]:diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex a92e4091992a..17d7564f0b97 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -54,6 +54,7 @@ from posthog.models.integration import (SlackIntegration,SnowflakeIntegration,SnowflakeIntegrationError,+ UndecryptedIntegrationSecretError,invalidate_github_repository_caches_for_installation,oauth_refresh_failure_reason,oauth_refresh_terminal_counter,@@ -125,6 +126,21 @@ class TestIntegrationModel(BaseTest):== '{"id_token": null, "refresh_token": "gAAAAABlkgC8AAAAAAAAAAAAAAAAAAAAAHlWz9QOMnXDvmix-z5lNG4v0VcO9lGWejmcE_BXHXPZ1wNkb-38JupntWbshBrfFQ=="}')+ @parameterized.expand([("access_token",), ("refresh_token",)])+ def test_oauth_token_property_raises_if_still_encrypted(self, field_name: str) -> None:+ # `sensitive_config` uses `ignore_decrypt_errors=True`, so a value that fails to decrypt+ # under every configured key comes back as raw Fernet ciphertext instead of raising. If the+ # `access_token`/`refresh_token` properties didn't check for that, this ciphertext would+ # get sent straight to the third-party API as the live credential.+ integration = Integration(team=self.team, kind="stripe", sensitive_config={field_name: "gAAAAABleftover=="})+ with pytest.raises(UndecryptedIntegrationSecretError):+ getattr(integration, field_name)++ @parameterized.expand([("access_token",), ("refresh_token",)])+ def test_oauth_token_property_passes_through_decrypted_value(self, field_name: str) -> None:+ integration = Integration(team=self.team, kind="stripe", sensitive_config={field_name: "a-real-token"})+ assert getattr(integration, field_name) == "a-real-token"+def test_slack_integration_config(self):set_instance_setting("SLACK_APP_CLIENT_ID", None)set_instance_setting("SLACK_APP_CLIENT_SECRET", None)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 fe7f3553374f..a9a02de1a9db 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@@ -11,6 +11,7 @@ from structlog.typing import FilteringBoundLoggerfrom temporalio import activityfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.models.integration import UndecryptedIntegrationSecretErrorfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.activity_context import current_activity_attemptfrom posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater@@ -352,6 +353,16 @@ async def _handle_import_error(job_inputs.team_id, str(job_inputs.source_id), job_inputs.run_id, error_msg, logger, error)+ # An OAuth `Integration.access_token`/`refresh_token` that still looks like Fernet ciphertext+ # (a lost/rotated encryption key, a corrupted row) fails identically on every retry — the+ # third-party API sees the same garbage credential every time. Classify by type here, shared+ # across every OAuth-based source, rather than depending on each source's+ # get_non_retryable_errors to recognise this message.+ if isinstance(error, UndecryptedIntegrationSecretError):+ await handle_non_retryable_error(+ job_inputs.team_id, str(job_inputs.source_id), job_inputs.run_id, error_msg, logger, error+ )+# RESTClientRetryableError only escapes the shared REST engine's own tenacity retry loop once# that budget (rate limits, transient 5xx, connection resets/timeouts) is exhausted — the same# "reaches us only after internal retries exhaust" contract as get_retryable_errors below.