: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
feat(warehouse-sources): read platform credentials from the integration service (#88458)
Tom Owersd59b966285f7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.pyindex 79a79f4fa4a7..53191d2bffc7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/source.py@@ -1,7 +1,5 @@from typing import Optional, cast-from django.conf import settings-from posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,@@ -14,6 +12,7 @@ from posthog.schema import (from posthog.exceptions_capture import capture_exception+from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secretsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (MARKETING_ANALYTICS_SUGGESTED_TABLE_TOOLTIP,FieldType,@@ -258,7 +257,8 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], O"The linked Bing Ads integration could not be found. Please reconnect your Bing Ads integration.") from e- if not settings.BING_ADS_DEVELOPER_TOKEN:+ developer_token = integration_secrets.get_secret("BING_ADS_DEVELOPER_TOKEN")+ if not developer_token:raise ValueError("Bing Ads developer token not configured")if not integration.access_token:raise IntegrationAccountListingError(@@ -272,7 +272,7 @@ class BingAdsSource(ResumableSource[BingAdsSourceConfig, BingAdsResumeConfig], Oclient = BingAdsClient(access_token=integration.access_token,refresh_token=integration.refresh_token,- developer_token=settings.BING_ADS_DEVELOPER_TOKEN,+ developer_token=developer_token,)try:return client.list_accounts()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_secrets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_secrets.pyindex d0a9e0070148..c0c82a078e44 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_secrets.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_secrets.py@@ -19,26 +19,44 @@ Reading through here changes nothing until a key is actually moved into the servservice off (self-hosted, local development, the flag disabled) the client reads the same`os.environ`/settings value the source reads today, so a migrated call site behaves identically.-**Sequencing, which is the part that bites.** Once the service is on, a key that is NOT in it-raises `SecretMissingError` — the client does not fall back to settings, by design, because a-silent fallback is how a half-finished rollout looks exactly like a working one. So a call site-moves to this module only after its key exists in the service for every environment that runs it.-Migrate one key at a time, in that order, not the other way round.+**Sequencing.** Call sites and keys cannot move at the same instant, and the service is already+live on the data-warehouse worker — so `_resolve_one` below keeps reading settings for a key that+has not reached the service yet, counting every time it does. That makes the order of the two+moves not matter, and makes "is the rollout finished?" a metric rather than a belief. It is+temporary; the removal condition is on `_resolve_one`."""from __future__ import annotations+import os++from django.conf import settings+import requests+import structlog+from prometheus_client import Counterfrom urllib3.util.retry import Retryfrom posthog.integration_secrets import client as integration_secrets_clientfrom posthog.integration_secrets.callers import IntegrationCallerfrom posthog.integration_secrets.client import RotatingSecret+from posthog.integration_secrets.errors import SecretMissingErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+logger = structlog.get_logger(__name__)+CALLER = IntegrationCaller.WAREHOUSE_SOURCES+SETTINGS_FALLBACK_COUNTER = Counter(+ "posthog_warehouse_integration_secret_settings_fallback_total",+ "Platform credential reads the integration service could not serve, by what happened instead",+ # outcome="settings": the key is still only in settings, so the rollout isn't finished for it.+ # outcome="unset": the credential isn't configured anywhere, which is the normal state of an+ # integration a deployment doesn't use. Separated because only the first is a rollout gap.+ labelnames=["key", "outcome"],+)+def _build_session() -> requests.Session:"""The tracked session credential reads go over, with two deliberate departures.@@ -73,14 +91,73 @@ _session = _build_session()_client = integration_secrets_client.IntegrationSecretsClient(session=_session)+def _from_settings(key: str) -> str | None:+ """The value this key had before the service existed, or None."""+ return (os.environ.get(key) or getattr(settings, key, "")) or None+++def _resolve_one(key: str) -> str:+ """One credential, falling back to settings while the key is still on its way into the service.++ TEMPORARY, and the removal condition is exact: when+ `posthog_warehouse_integration_secret_settings_fallback_total` has been zero across a full sync+ cycle, every key has moved and this function collapses back to `_client.get`.++ It exists because the call sites and the keys cannot move at the same instant. The service is+ already live on the data-warehouse worker, so without this, migrating a call site whose key is+ not in the service yet fails every sync for that source the moment it deploys — for Google Ads,+ Analytics, Search Console, Sheets, HubSpot, Salesforce, TikTok and Bing at once. The same code+ also runs in the web app, where the service is not configured at all.++ It is not the silent fallback the client refuses to have. That one is dangerous because it+ hides a half-finished rollout behind apparent success; this one names the key, counts it, and+ is the thing you watch to know when the rollout is finished.++ Only a MISSING key falls back, and the two exclusions are the point:++ - A key in **recovery** must not fall back. Recovery means the credential is known-burned; the+ settings copy is the very value that was burned, so serving it would turn the kill switch+ into a no-op — the one failure mode worse than the sync stopping.+ - An **unreachable service** must not fall back. There is no last known good to fall back to,+ and treating an outage as "the key isn't there" would mask it as a rollout gap.+ """+ try:+ return _client.get(key, CALLER)+ except SecretMissingError:+ value = _from_settings(key)+ if value is not None:+ SETTINGS_FALLBACK_COUNTER.labels(key=key, outcome="settings").inc()+ logger.warning("warehouse_integration_secret.settings_fallback", key=key)+ return value++ # Configured nowhere. Before this migration the call site read `settings.X` and got the+ # empty string its default provides, and an unusable credential surfaced later as a+ # rejection from the vendor. Keep exactly that: this change moves where a credential comes+ # from, and must not also change what happens when there isn't one. Raising here instead+ # would alter behaviour for every deployment that doesn't use a given integration —+ # self-hosted, local development, and every test that never set it — which is a much wider+ # blast radius than the migration itself, and no part of what it is for.+ SETTINGS_FALLBACK_COUNTER.labels(key=key, outcome="unset").inc()+ logger.debug("warehouse_integration_secret.unset", key=key)+ return ""++def get_secret(key: str) -> str:"""One PostHog-owned credential, by the name it has in the service and in settings."""- return _client.get(key, CALLER)+ return _resolve_one(key)def get_secrets(keys: list[str]) -> dict[str, str]:- """Several at once, in a single request — a source usually needs an id and a secret together."""- return _client.get_many(keys, CALLER)+ """Several at once, in a single request — a source usually needs an id and a secret together.++ The batch resolves in one request. If any key in it is missing, the batch cannot say which,+ so the keys are re-resolved one at a time to let the fallback above apply per key. That costs+ an extra round trip only while a source is mid-migration, and disappears with the fallback.+ """+ try:+ return _client.get_many(keys, CALLER)+ except SecretMissingError:+ return {key: _resolve_one(key) for key in keys}def get_secret_with_incoming(key: str) -> RotatingSecret:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_integration_secrets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_integration_secrets.pyindex e4e6e7b1641f..443d015a7db3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_integration_secrets.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_integration_secrets.py@@ -9,7 +9,7 @@ import jwtimport requestsfrom posthog.integration_secrets.callers import IntegrationCaller-from posthog.integration_secrets.errors import SecretMissingError+from posthog.integration_secrets.errors import IntegrationServiceUnreachableError, SecretInRecoveryErrorfrom posthog.jwt import PosthogJwtAudiencefrom products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets@@ -137,15 +137,12 @@ class TestHelper(SimpleTestCase):secret = integration_secrets.get_secret_with_incoming(KEY)assert (secret.current, secret.incoming) == ("live", "staged")- # The sequencing constraint, pinned as behaviour rather than left in a docstring: with the- # service on, a key that isn't in it raises instead of quietly reading settings. A silent- # fallback is how a half-finished rollout looks exactly like a finished one — so a call site- # may only move after its key exists in the service for every environment that runs it.- def test_a_key_not_yet_in_the_service_raises_rather_than_reading_settings(self) -> None:- with mock.patch.dict("os.environ", {KEY: "value-still-in-the-environment"}):- with self._patched_post({"secrets": {}, "missing": [KEY]}):- with pytest.raises(SecretMissingError):- integration_secrets.get_secret(KEY)+ # A key the service holds is read from the service, not from the environment it also still+ # sits in. Otherwise the migration would look complete while changing nothing.+ def test_the_service_wins_over_a_value_still_in_the_environment(self) -> None:+ with mock.patch.dict("os.environ", {KEY: "stale-copy-in-settings"}):+ with self._patched_post():+ assert integration_secrets.get_secret(KEY) == "token"class TestServiceOff(SimpleTestCase):@@ -170,3 +167,107 @@ class TestNoRequestsExceptionEscapes(SimpleTestCase):):with pytest.raises(IntegrationServiceUnreachableError):integration_secrets.get_secret(KEY)+++@override_settings(**SERVICE_SETTINGS)+class TestSettingsFallbackBridge(SimpleTestCase):+ """The temporary bridge that lets call sites move before their keys do.++ Every test here is about a boundary of it. The bridge is the risky part of this migration:+ too wide and it hides a broken rollout, too narrow and it breaks eight sources on deploy.+ """++ def setUp(self) -> None:+ flag = mock.patch(FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)+ integration_secrets.SETTINGS_FALLBACK_COUNTER.clear()++ def _missing(self) -> Any:+ return mock.patch.object(+ integration_secrets._session,+ "post",+ return_value=_FakeResponse({"secrets": {}, "missing": [KEY]}),+ )++ # The whole point: the service is already live on the worker, so a call site whose key hasn't+ # moved must keep working rather than failing every sync for that source.+ def test_a_key_not_in_the_service_falls_back_to_settings(self) -> None:+ with self._missing():+ with mock.patch.dict("os.environ", {KEY: "still-in-settings"}):+ assert integration_secrets.get_secret(KEY) == "still-in-settings"++ # The fallback is what you watch to know the rollout is done, so it has to be countable and+ # name the key. A silent one would be the failure mode the client refuses to have.+ def test_the_fallback_is_counted_and_named(self) -> None:+ with self._missing():+ with mock.patch.dict("os.environ", {KEY: "still-in-settings"}):+ with mock.patch.object(integration_secrets, "logger") as log:+ integration_secrets.get_secret(KEY)++ assert integration_secrets.SETTINGS_FALLBACK_COUNTER.labels(key=KEY, outcome="settings")._value.get() == 1+ assert log.warning.call_args.kwargs["key"] == KEY++ # Recovery means the credential is known-burned. The settings copy is the burned value, so+ # falling back would turn the kill switch into a no-op — worse than the sync stopping.+ def test_recovery_does_not_fall_back(self) -> None:+ payload = {"secrets": {KEY: {"state": "recovery", "version_id": "v1", "fetched_at": "now"}}, "missing": []}+ with mock.patch.object(integration_secrets._session, "post", return_value=_FakeResponse(payload)):+ with mock.patch.dict("os.environ", {KEY: "the-burned-value"}):+ with pytest.raises(SecretInRecoveryError):+ integration_secrets.get_secret(KEY)++ assert integration_secrets.SETTINGS_FALLBACK_COUNTER.labels(key=KEY, outcome="settings")._value.get() == 0++ # An outage is not a rollout gap. There is no last known good here, and treating "no answer"+ # as "the key isn't there" would quietly serve stale credentials through an incident.+ def test_an_unreachable_service_does_not_fall_back(self) -> None:+ with mock.patch.object(integration_secrets._session, "post", side_effect=requests.ConnectionError("refused")):+ with mock.patch.dict("os.environ", {KEY: "still-in-settings"}):+ with pytest.raises(IntegrationServiceUnreachableError):+ integration_secrets.get_secret(KEY)++ # Configured nowhere is the normal state of an integration a deployment doesn't use, and it+ # is what `settings.X` already returned. This migration moves where a credential comes from;+ # changing what happens when there isn't one would reach far past it — every self-hosted+ # install without this integration, and every test that never set it.+ def test_configured_nowhere_returns_what_settings_returned(self) -> None:+ with self._missing():+ with mock.patch.dict("os.environ", {}, clear=True):+ assert integration_secrets.get_secret(KEY) == ""++ counter = integration_secrets.SETTINGS_FALLBACK_COUNTER+ assert counter.labels(key=KEY, outcome="unset")._value.get() == 1+ # Not a rollout gap, so it must not be counted as one.+ assert counter.labels(key=KEY, outcome="settings")._value.get() == 0++ # A part-migrated batch is the normal state during the rollout: the batch can't say which key+ # was missing, so it re-resolves per key and each one takes the path it needs.+ def test_a_batch_with_one_missing_key_resolves_the_rest_per_key(self) -> None:+ other = "GOOGLE_ADS_APP_CLIENT_ID"+ in_service = {"state": "steady", "value": "from-service", "version_id": "v1", "fetched_at": "now"}++ def post(*args: Any, **kwargs: Any) -> Any:+ asked = _keys_asked_for(kwargs["headers"]["Authorization"])+ if KEY in asked and other in asked:+ return _FakeResponse({"secrets": {other: in_service}, "missing": [KEY]})+ if asked == [other]:+ return _FakeResponse({"secrets": {other: in_service}, "missing": []})+ return _FakeResponse({"secrets": {}, "missing": [KEY]})++ with mock.patch.object(integration_secrets._session, "post", side_effect=post):+ with mock.patch.dict("os.environ", {KEY: "still-in-settings"}):+ assert integration_secrets.get_secrets([KEY, other]) == {+ KEY: "still-in-settings",+ other: "from-service",+ }+++def _keys_asked_for(authorization: str) -> list[str]:+ claims = jwt.decode(+ authorization.removeprefix("Bearer "),+ "signing-key",+ algorithms=["HS256"],+ audience=PosthogJwtAudience.INTEGRATION_SERVICE.value,+ )+ return list(claims["keys"])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.pyindex efc52eb5306e..bd550219acff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_ads/google_ads.py@@ -3,7 +3,6 @@ import typingimport datetime as dtimport collections.abc-from django.conf import settingsfrom django.db import OperationalError, close_old_connectionsimport grpc@@ -37,6 +36,7 @@ from posthog.models.integration import Integrationfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import incremental_type_to_initial_value+from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secretsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.grpc import tracked_interceptorsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import Column, Table@@ -206,11 +206,14 @@ def google_ads_client(config: GoogleAdsSourceConfigUnion, team_id: int) -> Googlif config.is_mcc_account and config.is_mcc_account.enabled:login_customer_id = clean_customer_id(config.is_mcc_account.mcc_client_id)+ resolved = integration_secrets.get_secrets(+ ["GOOGLE_ADS_DEVELOPER_TOKEN", "GOOGLE_ADS_APP_CLIENT_ID", "GOOGLE_ADS_APP_CLIENT_SECRET"]+ )config_dict: dict[str, object] = {- "developer_token": settings.GOOGLE_ADS_DEVELOPER_TOKEN,+ "developer_token": resolved["GOOGLE_ADS_DEVELOPER_TOKEN"],"refresh_token": integration.refresh_token,- "client_id": settings.GOOGLE_ADS_APP_CLIENT_ID,- "client_secret": settings.GOOGLE_ADS_APP_CLIENT_SECRET,+ "client_id": resolved["GOOGLE_ADS_APP_CLIENT_ID"],+ "client_secret": resolved["GOOGLE_ADS_APP_CLIENT_SECRET"],"use_proto_plus": False,}if login_customer_id is not None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.pyindex 153761d91fc5..23c5c48907ac 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_analytics/google_analytics.py@@ -4,7 +4,6 @@ import dataclassesimport collections.abcfrom typing import Any-from django.conf import settingsfrom django.db import OperationalError, close_old_connectionsimport requests@@ -16,6 +15,7 @@ from google.oauth2.credentials import Credentials as OAuthCredentialsfrom posthog.models.integration import Integrationfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secretsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapterfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -108,11 +108,12 @@ def _get_integration(integration_id: int, team_id: int) -> Integration:def _credentials(integration_id: int, team_id: int) -> OAuthCredentials:integration = _get_integration(integration_id, team_id)+ resolved = integration_secrets.get_secrets(["GOOGLE_ANALYTICS_APP_CLIENT_ID", "GOOGLE_ANALYTICS_APP_CLIENT_SECRET"])return OAuthCredentials(token=None,refresh_token=integration.refresh_token,- client_id=settings.GOOGLE_ANALYTICS_APP_CLIENT_ID,- client_secret=settings.GOOGLE_ANALYTICS_APP_CLIENT_SECRET,+ client_id=resolved["GOOGLE_ANALYTICS_APP_CLIENT_ID"],+ client_secret=resolved["GOOGLE_ANALYTICS_APP_CLIENT_SECRET"],token_uri="https://oauth2.googleapis.com/token",scopes=["https://www.googleapis.com/auth/analytics.readonly"],)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.pyindex 56aac2128704..540fe4d1271e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_search_console/google_search_console.py@@ -6,7 +6,6 @@ import collections.abcfrom typing import Anyfrom urllib.parse import parse_qs, quote, unquote, urlparse, urlunparse-from django.conf import settingsfrom django.db import OperationalError, close_old_connectionsimport requests@@ -18,6 +17,7 @@ from google.oauth2.credentials import Credentials as OAuthCredentialsfrom posthog.models.integration import Integrationfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secretsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapterfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -207,11 +207,14 @@ def _get_integration(integration_id: int, team_id: int) -> Integration:def _credentials(integration_id: int, team_id: int) -> OAuthCredentials:integration = _get_integration(integration_id, team_id)+ resolved = integration_secrets.get_secrets(+ ["GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID", "GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET"]+ )return OAuthCredentials(token=None,refresh_token=integration.refresh_token,- client_id=settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID,- client_secret=settings.GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET,+ client_id=resolved["GOOGLE_SEARCH_CONSOLE_APP_CLIENT_ID"],+ client_secret=resolved["GOOGLE_SEARCH_CONSOLE_APP_CLIENT_SECRET"],token_uri="https://oauth2.googleapis.com/token",# No `scopes=` on purpose. With a refresh-token grant, google-auth forwards the# requested scopes to Google's token endpoint, which rejects anything that isn't andiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.pyindex d6e1685203cc..6fd25b1c1358 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_sheets/google_sheets.py@@ -5,8 +5,6 @@ from collections import Counterfrom collections.abc import Callablefrom typing import Any, Optional, TypeVar, cast-from django.conf import settings-import gspreadimport requestsfrom cachetools import Cache, TTLCache, cached@@ -17,6 +15,7 @@ from gspread.utils import numericise_allfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list+from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secretsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapterfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googlesheets import (@@ -44,12 +43,20 @@ GOOGLE_SHEETS_API_VERSION_V4 = "v4"def google_sheets_client() -> gspread.Client:+ resolved = integration_secrets.get_secrets(+ [+ "GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY",+ "GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY_ID",+ "GOOGLE_SHEETS_SERVICE_ACCOUNT_TOKEN_URI",+ "GOOGLE_SHEETS_SERVICE_ACCOUNT_CLIENT_EMAIL",+ ]+ )credentials = service_account.Credentials.from_service_account_info({- "private_key": settings.GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY,- "private_key_id": settings.GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY_ID,- "token_uri": settings.GOOGLE_SHEETS_SERVICE_ACCOUNT_TOKEN_URI,- "client_email": settings.GOOGLE_SHEETS_SERVICE_ACCOUNT_CLIENT_EMAIL,+ "private_key": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY"],+ "private_key_id": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_PRIVATE_KEY_ID"],+ "token_uri": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_TOKEN_URI"],+ "client_email": resolved["GOOGLE_SHEETS_SERVICE_ACCOUNT_CLIENT_EMAIL"],},scopes=["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive"],)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.pyindex fcfdef221421..80edb0b601e6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubspot/auth.py@@ -1,9 +1,8 @@-from django.conf import settings-import requestsimport structlogfrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secretsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionlogger = structlog.get_logger(__name__)@@ -52,6 +51,15 @@ def _error_message_from_response(res: requests.Response) -> str:return res.text+def _hubspot_app_credentials() -> dict[str, str]:+ """PostHog's own HubSpot app id and secret, as the token endpoint wants them named."""+ resolved = integration_secrets.get_secrets(["HUBSPOT_APP_CLIENT_ID", "HUBSPOT_APP_CLIENT_SECRET"])+ return {+ "client_id": resolved["HUBSPOT_APP_CLIENT_ID"],+ "client_secret": resolved["HUBSPOT_APP_CLIENT_SECRET"],+ }++@retry(# A 429/5xx from HubSpot's OAuth token endpoint is transient. The data-fetch paths already# back off and retry on HubspotRetryableError; this refresh is also reached at source-setup@@ -67,8 +75,7 @@ def hubspot_refresh_access_token(refresh_token: str, source_id: str | None = Non"https://api.hubapi.com/oauth/v1/token",data={"grant_type": "refresh_token",- "client_id": settings.HUBSPOT_APP_CLIENT_ID,- "client_secret": settings.HUBSPOT_APP_CLIENT_SECRET,+ **_hubspot_app_credentials(),"refresh_token": refresh_token,},)@@ -126,8 +133,7 @@ def get_hubspot_access_token_from_code(code: str, redirect_uri: str) -> tuple[st"https://api.hubapi.com/oauth/v1/token",data={"grant_type": "authorization_code",- "client_id": settings.HUBSPOT_APP_CLIENT_ID,- "client_secret": settings.HUBSPOT_APP_CLIENT_SECRET,+ **_hubspot_app_credentials(),"redirect_uri": redirect_uri,"code": code,},diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.pyindex f4fecc8ac18b..c122cd6a073f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py@@ -2,8 +2,6 @@ import timefrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional-from django.conf import settings-from requests import Responsefrom requests.exceptions import (ConnectionError as RequestsConnectionError,@@ -11,6 +9,7 @@ from requests.exceptions import (Timeout as RequestsTimeout,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secretsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth@@ -89,11 +88,23 @@ _TRANSIENT_TOKEN_REQUEST_ERROR = "token request is already being processed"_MAX_TOKEN_REFRESH_ATTEMPTS = 4+def _salesforce_app_credentials() -> dict[str, str]:+ """PostHog's own Salesforce connected-app key and secret, named as the token endpoint wants."""+ resolved = integration_secrets.get_secrets(["SALESFORCE_CONSUMER_KEY", "SALESFORCE_CONSUMER_SECRET"])+ return {+ "client_id": resolved["SALESFORCE_CONSUMER_KEY"],+ "client_secret": resolved["SALESFORCE_CONSUMER_SECRET"],+ }++def salesforce_refresh_access_token(refresh_token: str, instance_url: str, *, capture: bool = True) -> str:# capture=False lets a caller keep this exchange out of HTTP sample capture: the request body# carries the refresh token and the shared client secret, and the response carries a freshly# minted access token, none of which the name-based scrubbers reliably redact.session = make_tracked_session(redact_values=(refresh_token,), capture=capture)+ # Resolved once, outside the loop: a retry is for a transient token-endpoint failure, and+ # re-reading the same credential on each attempt would add a hop per attempt for nothing.+ app_credentials = _salesforce_app_credentials()attempt = 0while True:try:@@ -101,8 +112,7 @@ def salesforce_refresh_access_token(refresh_token: str, instance_url: str, *, caf"{instance_url}/services/oauth2/token",data={"grant_type": "refresh_token",- "client_id": settings.SALESFORCE_CONSUMER_KEY,- "client_secret": settings.SALESFORCE_CONSUMER_SECRET,+ **app_credentials,"refresh_token": refresh_token,},)@@ -134,8 +144,7 @@ def get_salesforce_access_token_from_code(code: str, redirect_uri: str, instancef"{instance_url}/services/oauth2/token",data={"grant_type": "authorization_code",- "client_id": settings.SALESFORCE_CONSUMER_KEY,- "client_secret": settings.SALESFORCE_CONSUMER_SECRET,+ **_salesforce_app_credentials(),"redirect_uri": redirect_uri,"code": code,},diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.pyindex 74bd208eab04..904562352ffc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py@@ -3,13 +3,12 @@ from collections.abc import Iterablefrom datetime import UTC, date, datetime, timedeltafrom typing import Any, Optional-from django.conf import settings-import structlogfrom dateutil import parserfrom requests import PreparedRequest, Request, Responsefrom requests.exceptions import HTTPError, RequestException, Timeout+from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secretsfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBasefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator@@ -61,13 +60,15 @@ def list_advertisers(access_token: str) -> list[dict]:# Mask the app secret (a query param) and the access token (a header) so neither lands in# request telemetry / captured samples. `timeout` guards the oauth_accounts web worker: TikTok# has no default timeout, so a hung connection would otherwise pin the worker indefinitely.+ resolved = integration_secrets.get_secrets(["TIKTOK_ADS_CLIENT_ID", "TIKTOK_ADS_CLIENT_SECRET"])+ app_secret = resolved["TIKTOK_ADS_CLIENT_SECRET"]session = make_tracked_session(headers={"Access-Token": access_token, "Content-Type": "application/json"},- redact_values=(settings.TIKTOK_ADS_CLIENT_SECRET, access_token),+ redact_values=(app_secret, access_token),)response = session.get(f"{BASE_URL}/oauth2/advertiser/get/",- params={"app_id": settings.TIKTOK_ADS_CLIENT_ID, "secret": settings.TIKTOK_ADS_CLIENT_SECRET},+ params={"app_id": resolved["TIKTOK_ADS_CLIENT_ID"], "secret": app_secret},timeout=10,)# A proxy/gateway failure answers with a non-2xx and an HTML body, which `.json()` can't parse.