: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): one way to read PostHog's own credentials (#88388)
Tom Owers0358b103aaaa
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.pynew file mode 100644index 000000000000..d0a9e0070148--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/integration_secrets.py@@ -0,0 +1,94 @@+"""How warehouse sources read PostHog's own credentials.++These are the OAuth app client ids/secrets, developer tokens, and API keys PostHog owns — the+ones a source presents as *itself*, not the per-team credentials a customer connected. Today a+source reads them straight off Django settings (`settings.GOOGLE_ADS_DEVELOPER_TOKEN`), which+means rotating one is a charts PR and a restart of everything that mounts it.++This module is the single place sources go instead. It binds the two things every warehouse call+would otherwise repeat, and gets wrong differently each time:++- **The caller identity.** `IntegrationCaller.WAREHOUSE_SOURCES` is what the service writes to its+ audit log, so it is how "who read this credential" gets answered. Pinning it here means a new+ source cannot label its reads as something else by copying the wrong line.+- **The transport.** A session that meters and logs like the rest of a job's HTTP traffic, with+ two properties that are easy to lose and expensive to lose: no sample capture, and no egress+ proxy. Both are explained on `_session` below.++Reading through here changes nothing until a key is actually moved into the service. With the+service 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.+"""++from __future__ import annotations++import requests+from urllib3.util.retry import Retry++from posthog.integration_secrets import client as integration_secrets_client+from posthog.integration_secrets.callers import IntegrationCaller+from posthog.integration_secrets.client import RotatingSecret++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session++CALLER = IntegrationCaller.WAREHOUSE_SOURCES+++def _build_session() -> requests.Session:+ """The tracked session credential reads go over, with two deliberate departures.++ `capture=False` — **required, not a preference.** The response body on this path is the+ credential in plaintext. HTTP sample capture stores request and response bodies in Redis so+ they can be read back while debugging a source, and the name-based scrubbers cannot recognise+ a value they have never seen. Metering and the log line survive; only the body capture is off.++ `trust_env=False` — the integration service is an internal, in-cluster address. Warehouse+ outbound traffic goes through the Smokescreen egress proxy, which re-resolves every hop and+ blocks internal and metadata hosts. That is exactly right for a customer's API and exactly+ wrong here: left on, every credential read would be handed to a proxy whose job is to refuse+ it. This is the same reason `posthog.security.outbound_proxy.internal_requests` exists, and+ the reason we cannot simply reuse a plain tracked session.++ `Retry(total=0)` — the client holds no cache, so there is no last known good and a retry here+ would only add latency in front of a failure Temporal already retries with backoff. It matches+ the shared internal session, whose adapter also does not retry. (`DEFAULT_RETRY` would be a+ no-op anyway, since it retries only GET/HEAD/OPTIONS and this is a POST — stated explicitly so+ it stays true if that policy changes.)+ """+ session = make_tracked_session(retry=Retry(total=0), capture=False)+ session.trust_env = False+ return session+++# One session for the process, like the shared internal one. The tracked adapter reads the job+# context from contextvars at request time, so a single session still labels each request with the+# team and source it was made for.+_session = _build_session()+_client = integration_secrets_client.IntegrationSecretsClient(session=_session)+++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)+++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)+++def get_secret_with_incoming(key: str) -> RotatingSecret:+ """The live value plus the staged replacement, while a rotation is in flight.++ For a source that can retry against the third party: try `current`, and on an auth failure+ retry with `incoming`. That covers the window where the credential has already been rotated at+ the provider but the promotion has not happened here yet — the one case where a rotation is+ visible to a source at all.+ """+ return _client.get_with_incoming(key, CALLER)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --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.pynew file mode 100644index 000000000000..e4e6e7b1641f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/tests/test_integration_secrets.py@@ -0,0 +1,172 @@+from typing import Any++import pytest+from unittest import mock++from django.test import SimpleTestCase, override_settings++import jwt+import requests++from posthog.integration_secrets.callers import IntegrationCaller+from posthog.integration_secrets.errors import SecretMissingError+from posthog.jwt import PosthogJwtAudience++from products.warehouse_sources.backend.temporal.data_imports.sources.common import integration_secrets+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import TrackedHTTPAdapter++SERVICE_SETTINGS: dict[str, Any] = {+ "INTEGRATION_SERVICE_URL": "http://integration-service.posthog.svc.cluster.local",+ "INTEGRATION_SERVICE_JWT_SECRET": "signing-key",+}++KEY = "GOOGLE_ADS_DEVELOPER_TOKEN"+FLAG = "posthog.integration_secrets.client.posthoganalytics.feature_enabled"+++class _FakeResponse:+ status_code = 200++ def __init__(self, payload: dict[str, Any]) -> None:+ self._payload = payload++ def raise_for_status(self) -> None:+ pass++ def json(self) -> dict[str, Any]:+ return self._payload+++def _body(value: str) -> dict[str, Any]:+ return {+ "secrets": {KEY: {"state": "steady", "value": value, "version_id": "v1", "fetched_at": "now"}},+ "missing": [],+ }+++class TestSessionProperties(SimpleTestCase):+ """Two properties of the session that are cheap to lose and expensive to have lost."""++ # The response body on this path is the credential in plaintext. Sample capture stores request+ # and response bodies in Redis for later inspection, and the name-based scrubbers can't+ # recognise a value they've never seen — so capture must be off at the adapter, not filtered+ # afterwards.+ def test_http_sample_capture_is_disabled(self) -> None:+ session = integration_secrets._build_session()+ adapters = [session.get_adapter("https://x"), session.get_adapter("http://x")]+ assert adapters, "expected tracked adapters to be mounted"+ for adapter in adapters:+ assert isinstance(adapter, TrackedHTTPAdapter)+ assert adapter._capture is False++ # The service is an internal in-cluster address. Warehouse traffic otherwise goes through the+ # Smokescreen egress proxy, which re-resolves each hop and blocks internal hosts — right for a+ # customer's API, and the exact wrong thing here: every credential read would be handed to a+ # proxy whose job is to refuse it.+ def test_the_egress_proxy_is_bypassed(self) -> None:+ assert integration_secrets._build_session().trust_env is False++ # No cache means no last known good, so a retry here only delays a failure Temporal already+ # retries with backoff. Matches the shared internal session, whose adapter also doesn't retry.+ def test_the_transport_does_not_retry(self) -> None:+ session = integration_secrets._build_session()+ adapter = session.get_adapter("https://x")+ assert isinstance(adapter, TrackedHTTPAdapter)+ assert adapter.max_retries.total == 0+++@override_settings(**SERVICE_SETTINGS)+class TestHelper(SimpleTestCase):+ def setUp(self) -> None:+ flag = mock.patch(FLAG, return_value=True)+ flag.start()+ self.addCleanup(flag.stop)++ @staticmethod+ def _patched_post(payload: dict[str, Any] | None = None, **kwargs: Any) -> Any:+ return mock.patch.object(+ integration_secrets._session,+ "post",+ return_value=_FakeResponse(payload or _body("token")),+ **kwargs,+ )++ # Attribution is what the service writes to its audit log, so "who read this credential" is+ # only answerable if every warehouse read carries the same caller. Pinning it here means a new+ # source can't label its reads as something else by copying the wrong line.+ def test_every_read_is_attributed_to_warehouse_sources(self) -> None:+ with self._patched_post() as post:+ assert integration_secrets.get_secret(KEY) == "token"++ token = post.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer ")+ claims = jwt.decode(+ token,+ "signing-key",+ algorithms=["HS256"],+ audience=PosthogJwtAudience.INTEGRATION_SERVICE.value,+ )+ assert claims["caller"] == str(IntegrationCaller.WAREHOUSE_SOURCES)+ assert claims["keys"] == [KEY]++ def test_several_keys_resolve_in_one_request(self) -> None:+ keys = [KEY, "GOOGLE_ADS_APP_CLIENT_ID"]+ payload = {+ "secrets": {+ k: {"state": "steady", "value": f"v-{k}", "version_id": "v1", "fetched_at": "now"} for k in keys+ },+ "missing": [],+ }+ with self._patched_post(payload) as post:+ assert integration_secrets.get_secrets(keys) == {k: f"v-{k}" for k in keys}+ assert post.call_count == 1++ def test_a_rotation_exposes_both_values(self) -> None:+ payload = {+ "secrets": {+ KEY: {+ "state": "rotating",+ "value": "live",+ "previous": "staged",+ "version_id": "v2",+ "fetched_at": "now",+ }+ },+ "missing": [],+ }+ with self._patched_post(payload):+ 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)+++class TestServiceOff(SimpleTestCase):+ # With the service unconfigured — self-hosted, local development — the client reads the same+ # environment value the source reads today. This is what makes a migrated call site a no-op+ # until the key actually moves.+ @override_settings(INTEGRATION_SERVICE_URL=None, INTEGRATION_SERVICE_JWT_SECRET=None)+ def test_falls_back_to_the_environment_without_calling_out(self) -> None:+ with mock.patch.object(integration_secrets._session, "post", side_effect=AssertionError("called out")):+ with mock.patch.dict("os.environ", {KEY: "from-env"}):+ assert integration_secrets.get_secret(KEY) == "from-env"+++class TestNoRequestsExceptionEscapes(SimpleTestCase):+ @override_settings(**SERVICE_SETTINGS)+ def test_transport_failure_is_typed(self) -> None:+ from posthog.integration_secrets.errors import IntegrationServiceUnreachableError++ with mock.patch(FLAG, return_value=True):+ with mock.patch.object(+ integration_secrets._session, "post", side_effect=requests.ConnectionError("refused")+ ):+ with pytest.raises(IntegrationServiceUnreachableError):+ integration_secrets.get_secret(KEY)