: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): recover over-encrypted integration secrets (#78211)
Tom Owers616f88036c93
diff --git a/posthog/helpers/encrypted_fields.py b/posthog/helpers/encrypted_fields.pyindex 6d92bb6c8afe..d3dadca84d47 100644--- a/posthog/helpers/encrypted_fields.py+++ b/posthog/helpers/encrypted_fields.py@@ -14,6 +14,14 @@ from cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC+# Fernet tokens always start with this marker (version byte 0x80 + timestamp, base64-encoded).+FERNET_TOKEN_PREFIX = "gAAAAA"++# How many nested encryption layers `decrypt_all_layers` will peel. One extra layer is what a+# single read-then-save of an undecryptable value produces; the cap just stops a pathological+# row from looping.+MAX_ENCRYPTION_LAYERS = 4+class EncryptedFieldMixin:# Useful if migrating to an encrypted field from a non encrypted field@@ -65,6 +73,26 @@ class EncryptedFieldMixin:return valueraise+ def decrypt_all_layers(self, value: str) -> str | None:+ """Decrypt a value that may carry more than one layer of encryption.++ A field with `ignore_decrypt_errors` hands back raw ciphertext when a value can't be+ decrypted, so any code that reads such a row and saves it writes the ciphertext back+ *encrypted again*. Reading that row then peels one layer and still yields ciphertext.+ Peel until the result no longer looks like a Fernet token.++ Returns None when a layer can't be opened by any configured key — the value was written+ under a key we no longer hold, so no amount of peeling recovers it.+ """+ for _ in range(MAX_ENCRYPTION_LAYERS):+ try:+ value = self.f.decrypt(bytes(value, "utf-8")).decode("utf-8")+ except (InvalidToken, UnicodeDecodeError):+ return None+ if not value.startswith(FERNET_TOKEN_PREFIX):+ return value+ return None+def encrypt(self, value: str) -> str:return self.f.encrypt(bytes(value, "utf-8")).decode("utf-8")diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex fe0826f16729..723acff28536 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -8,7 +8,7 @@ import secretsfrom collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom datetime import datetime, timedelta-from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional, Self+from typing import TYPE_CHECKING, Any, Literal, NamedTuple, NoReturn, Optional, Self, castfrom urllib.parse import parse_qs, urlencode, urlparsefrom products.workflows.backend.providers import MAILDEV_MOCK_DNS_RECORDS@@ -49,7 +49,7 @@ from posthog.credentials import AWSKeyPairfrom posthog.egress.github.transport import github_requestfrom posthog.egress.limiter.policies import Priorityfrom posthog.exceptions_capture import capture_exception-from posthog.helpers.encrypted_fields import EncryptedJSONField+from posthog.helpers.encrypted_fields import FERNET_TOKEN_PREFIX, EncryptedJSONFieldfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationErrorfrom posthog.models.instance_setting import get_instance_settingsfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthRefreshToken@@ -69,29 +69,73 @@ 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.+ ciphertext instead of the decrypted secret, and no configured key can open it.`sensitive_config` sets `ignore_decrypt_errors=True` so integrations written beforeencryption 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+ decrypt under every configured key (a lost 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, hidingthe actual cause behind what looks like a bad customer-supplied key.++ The message is user-facing: it lands on the failed data warehouse job as `latest_error`."""+ def __init__(self) -> None:+ super().__init__(+ "We couldn't read the saved credentials for this connection. Reconnect the account to start syncing again."+ )+++# Reading a still-encrypted secret means the row is either recoverably over-encrypted or+# permanently unreadable. Both are invisible from the sync failure alone, so count them by kind:+# a rising `unreadable` rate means live customer credentials are being lost.+integration_secret_decrypt_counter = Counter(+ "integration_sensitive_config_decrypt_recovery",+ "Reads of an Integration secret that came back still encrypted, by recovery outcome",+ labelnames=["kind", "result"],+)+++def _decrypted_sensitive_value(integration: "Integration", field_name: str) -> str | None:+ """Read a secret off `sensitive_config`, peeling any extra encryption layers it picked up.++ A read-then-save of a row whose secret failed to decrypt writes that ciphertext back+ encrypted again, so the stored value ends up double-encrypted. One decrypt (the field's+ own) then leaves ciphertext behind. Peel the rest here: the underlying secret is intact+ and the connection keeps working.+ """+ value = integration.sensitive_config.get(field_name)+ if not isinstance(value, str) or not value.startswith(FERNET_TOKEN_PREFIX):+ return value-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"+ # django-stubs can't see through `field_access_control`, so it doesn't know this field name.+ field = cast(EncryptedJSONField, integration._meta.get_field("sensitive_config")) # type: ignore[misc]+ recovered = field.decrypt_all_layers(value)++ if recovered is None:+ integration_secret_decrypt_counter.labels(kind=integration.kind, result="unreadable").inc()+ logger.error(+ "integration_sensitive_config_unreadable",+ integration_id=integration.pk,+ team_id=integration.team_id,+ kind=integration.kind,+ field=field_name,)- return value+ raise UndecryptedIntegrationSecretError()++ integration_secret_decrypt_counter.labels(kind=integration.kind, result="recovered").inc()+ logger.warning(+ "integration_sensitive_config_over_encrypted",+ integration_id=integration.pk,+ team_id=integration.team_id,+ kind=integration.kind,+ field=field_name,+ )+ return recovereddef _decode_jwt_payload(token: str) -> dict | None:@@ -239,6 +283,9 @@ REFRESH_FAILURE_REASON_HTTP_5XX = "http_5xx"REFRESH_FAILURE_REASON_NETWORK = "network"REFRESH_FAILURE_REASON_RATE_LIMITED = "rate_limited"REFRESH_FAILURE_REASON_OTHER = "other"+# Not a provider response: the stored refresh token itself can't be decrypted, so no request was+# made. Terminal on the first occurrence, since no later attempt can make the secret readable.+REFRESH_FAILURE_REASON_UNREADABLE_SECRET = "unreadable_secret"def oauth_refresh_failure_reason(status_code: int, body: dict, kind: str | None = None) -> str:@@ -275,9 +322,10 @@ def record_refresh_failure(integration: "Integration", *, reason: str = REFRESH_itself is dead and only a customer re-auth can fix it, so after an unbroken streak of them theintegration goes terminal and the sweep stops retrying entirely. The streak is trackedseparately from the total failure count and resets on any other reason, so one transient- invalid_grant amid e.g. a 5xx outage can't brick the integration. Other reasons- (invalid_client, 5xx, network, rate_limited) never go terminal - a platform-side credential- fix must let the fleet self-recover.+ invalid_grant amid e.g. a 5xx outage can't brick the integration. `unreadable_secret` goes+ terminal on the first occurrence - we never even reached the provider, and retrying can't make+ an undecryptable token readable. Other reasons (invalid_client, 5xx, network, rate_limited)+ never go terminal - a platform-side credential fix must let the fleet self-recover.Returns "first"/"retry" for the metric's `attempt` label - a spike in first failures meansconnections are newly breaking, regardless of retry noise.@@ -289,7 +337,12 @@ def record_refresh_failure(integration: "Integration", *, reason: str = REFRESH_integration.config["refresh_next_attempt_at"] = int(time.time()) + min(REFRESH_BACKOFF_BASE_SECONDS * 2 ** (count - 1), REFRESH_BACKOFF_MAX_SECONDS)- if reason == REFRESH_FAILURE_REASON_INVALID_GRANT:+ if reason == REFRESH_FAILURE_REASON_UNREADABLE_SECRET:+ integration.config.pop("refresh_invalid_grant_count", None)+ if not integration.config.get("refresh_terminal"):+ integration.config["refresh_terminal"] = True+ oauth_refresh_terminal_counter.labels(kind=integration.kind).inc()+ elif reason == REFRESH_FAILURE_REASON_INVALID_GRANT:grant_streak = int(integration.config.get("refresh_invalid_grant_count") or 0) + 1integration.config["refresh_invalid_grant_count"] = grant_streak# Guarded so on-demand refreshes (which bypass the backoff) can't re-count a dead row@@ -619,11 +672,11 @@ class Integration(models.Model):@propertydef access_token(self) -> str | None:- return _decrypted_sensitive_value(self.sensitive_config.get("access_token"), "access_token")+ return _decrypted_sensitive_value(self, "access_token")@propertydef refresh_token(self) -> str | None:- return _decrypted_sensitive_value(self.sensitive_config.get("refresh_token"), "refresh_token")+ return _decrypted_sensitive_value(self, "refresh_token")def defer_repository_cache_fields(queryset: models.QuerySet[Integration]) -> models.QuerySet[Integration]:@@ -1764,7 +1817,13 @@ class OauthIntegration:return time.time() > refreshed_at + expires_in - time_threshold.total_seconds()def _post_token_refresh(self, oauth_config: OauthConfig, client_id: str, client_secret: str) -> requests.Response:- refresh_token = self.integration.sensitive_config["refresh_token"]+ # Via the property, so a token that picked up an extra encryption layer is peeled back to+ # the real one instead of being posted to the provider as ciphertext.+ refresh_token = self.integration.refresh_token+ if refresh_token is None:+ # A grant with no refresh token at all is a caller error, not a provider rejection -+ # keep failing loudly rather than posting `None` and reading the 400 back as one.+ raise KeyError("refresh_token")kind = self.integration.kind# Reddit uses HTTP Basic Auth for token refresh@@ -1851,6 +1910,25 @@ class OauthIntegration:# e.g. an HTML error page from a proxy/5xx - still a failed refresh, not an exceptionreturn {}+ def _record_terminal_unreadable_secret(self) -> None:+ logger.error(+ "integration_refresh_secret_unreadable",+ integration_id=self.integration.pk,+ team_id=self.integration.team_id,+ kind=self.integration.kind,+ )+ self.integration.errors = ERROR_TOKEN_REFRESH_FAILED+ attempt = record_refresh_failure(self.integration, reason=REFRESH_FAILURE_REASON_UNREADABLE_SECRET)+ oauth_refresh_counter.labels(+ kind=self.integration.kind,+ result="failed",+ reason=REFRESH_FAILURE_REASON_UNREADABLE_SECRET,+ attempt=attempt,+ ).inc()+ # `sensitive_config` is deliberately excluded: saving it would re-encrypt the ciphertext+ # this integration already can't read, adding another layer to the stored value.+ self.integration.save(update_fields=["errors", "config"])+def refresh_access_token(self):"""Refresh the access token for the integration if necessary@@ -1867,6 +1945,12 @@ class OauthIntegration:try:res = self._post_token_refresh(oauth_config, oauth_config.client_id, oauth_config.client_secret)config = self._parse_token_refresh_response(res)+ except UndecryptedIntegrationSecretError:+ # The stored refresh token can't be read, so there is nothing to refresh with and no+ # later attempt can change that. Go terminal immediately: the sweep stops retrying,+ # and the UI shows the reconnect prompt.+ self._record_terminal_unreadable_secret()+ returnexcept requests.RequestException as e:# A network error (timeout, connection reset) is a failed refresh, not a crash. Without# this the Celery sweep task errors out before recording the failure, so the backoff and@@ -1906,6 +1990,11 @@ class OauthIntegration:oauth_refresh_counter.labels(kind=self.integration.kind, result="failed", reason=reason, attempt=attempt).inc()+ # A failed refresh leaves `sensitive_config` untouched, so writing it back only risks+ # harm: `ignore_decrypt_errors` hands back raw ciphertext for a secret that couldn't be+ # decrypted, and saving re-encrypts it, permanently adding a layer to the stored value.+ self.integration.save(update_fields=["errors", "config"])+ returnelse:logger.info(f"Refreshed access token for {self}")record_refresh_success(self.integration)diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 4a46fa5a10d0..249b99cece28 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -3,7 +3,7 @@ import timeimport base64import hashlibfrom datetime import UTC, datetime, timedelta-from typing import Optional+from typing import Optional, castfrom urllib.parse import parse_qs, urlencodeimport pytest@@ -28,6 +28,7 @@ from posthog.egress.github.transport import (raise_if_github_rate_limited,)from posthog.egress.limiter.policies import Priority+from posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.github_integration_base import GITHUB_BRANCH_CACHE_TTL_SECONDS, GITHUB_REPOSITORY_CACHE_TTL_SECONDSfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.integration import (@@ -60,6 +61,7 @@ from posthog.models.integration import (invalidate_github_repository_caches_for_installation,oauth_refresh_failure_reason,oauth_refresh_terminal_counter,+ refresh_backoff_active,)from posthog.models.organization import Organizationfrom posthog.models.team.team import Team@@ -143,6 +145,24 @@ class TestIntegrationModel(BaseTest):integration = Integration(team=self.team, kind="stripe", sensitive_config={field_name: "a-real-token"})assert getattr(integration, field_name) == "a-real-token"+ @parameterized.expand([("access_token",), ("refresh_token",)])+ def test_oauth_token_property_recovers_an_over_encrypted_value(self, field_name: str) -> None:+ # Saving an integration whose secret failed to decrypt re-encrypts the ciphertext, so the+ # stored value ends up with an extra layer and one decrypt still leaves ciphertext behind.+ # The secret is intact underneath, so the connection must keep working.+ integration = self.create_integration("stripe", sensitive_config={field_name: "a-real-token"})+ field = cast(EncryptedJSONField, Integration._meta.get_field("sensitive_config")) # type: ignore[misc]+ stored = json.loads(get_db_field_value("sensitive_config", integration.id))+ update_db_field_value(+ "sensitive_config",+ integration.id,+ json.dumps({**stored, field_name: field.encrypt(stored[field_name])}),+ )++ integration.refresh_from_db()++ 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)@@ -633,6 +653,41 @@ class TestOauthIntegrationModel(BaseTest):mock_reload.assert_not_called()+ @patch("posthog.models.integration.reload_integrations_on_workers")+ @patch("posthog.models.integration.requests.post")+ def test_failed_refresh_leaves_stored_secrets_byte_identical(self, mock_post, mock_reload):+ # A failed refresh has no new secrets to store, and rewriting the ones already there is how+ # a secret that couldn't be decrypted (handed back as raw ciphertext by+ # `ignore_decrypt_errors`) gains a permanent extra encryption layer.+ mock_post.return_value.status_code = 401+ mock_post.return_value.json.return_value = {"error": "BROKEN"}++ integration = self.create_integration(kind="hubspot", config={"expires_in": 1000})+ stored_before = get_db_field_value("sensitive_config", integration.id)++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ assert get_db_field_value("sensitive_config", integration.id) == stored_before+ assert integration.errors == "TOKEN_REFRESH_FAILED"++ @patch("posthog.models.integration.requests.post")+ def test_refresh_with_unreadable_secret_goes_terminal_without_calling_the_provider(self, mock_post):+ # Posting ciphertext as the refresh token just earns an invalid_grant every minute forever.+ # Nothing about the stored secret can change, so the sweep must stop and the reconnect+ # prompt must show instead.+ integration = self.create_integration(kind="hubspot", sensitive_config={"refresh_token": "gAAAAAleftover=="})++ with self.settings(**self.mock_settings):+ OauthIntegration(integration).refresh_access_token()++ mock_post.assert_not_called()+ assert integration.errors == "TOKEN_REFRESH_FAILED"+ assert refresh_backoff_active(integration) is True++ integration.refresh_from_db()+ assert integration.config["refresh_terminal"] is True+def _mock_token_response(self, status_code: int, token: Optional[str]) -> MagicMock:response = MagicMock()response.status_code = status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.pyindex 08c9d58bc0d2..8edc212c5a76 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_sync_new_schemas.py@@ -80,9 +80,7 @@ def test_undecrypted_integration_secret_error_is_skipped():# failure and spams error tracking every cycle.source_mock = mock.MagicMock()source_mock.parse_config.return_value = {}- source_mock.get_schemas.side_effect = UndecryptedIntegrationSecretError(- "Integration.sensitive_config['refresh_token'] is still encrypted; the stored credentials could not be decrypted"- )+ source_mock.get_schemas.side_effect = UndecryptedIntegrationSecretError()source_mock.get_non_retryable_errors.return_value = {}_run_activity(source_mock)