: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(clickhouse): rebuild Temporal HTTP auth header per request (#92048)
Tommy Gilmore68be3425596f
diff --git a/posthog/temporal/common/clickhouse.py b/posthog/temporal/common/clickhouse.pyindex a00353749e4f..bb2bea4d0776 100644--- a/posthog/temporal/common/clickhouse.py+++ b/posthog/temporal/common/clickhouse.py@@ -22,6 +22,7 @@ from temporalio import activityimport posthog.temporal.common.asyncpa as asyncpafrom posthog.clickhouse import query_tagging+from posthog.clickhouse.client.connection import ClickHouseCredentialsfrom posthog.clickhouse.query_tagging import QueryTags, TemporalTags, get_query_tagsfrom posthog.security.outbound_proxy import internal_requests_session@@ -290,10 +291,11 @@ class ClickHouseClient:database: str = "default",timeout: None | aiohttp.ClientTimeout = None,ssl: ssl.SSLContext | bool = True,+ password_file: str | None = None,**kwargs,):self.url = url- self.headers = {}+ self.headers: dict[str, str] = {}self.params = {}self.timeout = timeoutself.ssl = ssl@@ -301,10 +303,11 @@ class ClickHouseClient:self.session: None | aiohttp.ClientSession = Noneself.logger = LOGGER.bind(url=url, database=database, user=user)- if user:- self.headers["X-ClickHouse-User"] = user- if password:- self.headers["X-ClickHouse-Key"] = password+ # Build auth per request from the credential, which may read a rotating token file. A long+ # batch export holds one session for hours, longer than a short-lived token lives, so the+ # auth header cannot be stamped once at construction.+ self._credentials = ClickHouseCredentials(user=user, password=password, password_file=password_file)+if database:self.params["database"] = database@@ -312,6 +315,15 @@ class ClickHouseClient:self.params.update(kwargs)+ def _request_headers(self) -> dict[str, str]:+ headers = dict(self.headers)+ if self._credentials.user:+ headers["X-ClickHouse-User"] = self._credentials.user+ key = self._credentials.read_password()+ if key:+ headers["X-ClickHouse-Key"] = key+ return headers+@classmethoddef from_posthog_settings(cls, settings, **kwargs):"""Initialize a ClickHouseClient from PostHog settings."""@@ -319,6 +331,7 @@ class ClickHouseClient:url=settings.CLICKHOUSE_URL,user=settings.CLICKHOUSE_USER,password=settings.CLICKHOUSE_PASSWORD,+ password_file=settings.CLICKHOUSE_PASSWORD_FILE,database=settings.CLICKHOUSE_DATABASE,**kwargs,)@@ -337,7 +350,7 @@ class ClickHouseClient:try:await self.session.get(url=ping_url,- headers=self.headers,+ headers=self._request_headers(),raise_for_status=True,timeout=aiohttp.ClientTimeout(total=timeout),)@@ -454,7 +467,7 @@ class ClickHouseClient:add_log_comment_param(params)- async with self.session.get(url=self.url, headers=self.headers, params=params) as response:+ async with self.session.get(url=self.url, headers=self._request_headers(), params=params) as response:await self.acheck_response(response, query)yield response@@ -526,7 +539,7 @@ class ClickHouseClient:try:async with self.session.post(- url=self.url, params=params, headers=self.headers, data=request_data, timeout=client_timeout+ url=self.url, params=params, headers=self._request_headers(), data=request_data, timeout=client_timeout) as response:await self.acheck_response(response, query)yield response@@ -588,7 +601,7 @@ class ClickHouseClient:response = s.post(url=self.url,params=params,- headers=self.headers,+ headers=self._request_headers(),data=request_data,stream=True,verify=False,@@ -1043,6 +1056,7 @@ async def get_client(url=url,user=settings.CLICKHOUSE_USER,password=settings.CLICKHOUSE_PASSWORD,+ password_file=settings.CLICKHOUSE_PASSWORD_FILE,database=settings.CLICKHOUSE_DATABASE,timeout=timeout,ssl=False,diff --git a/posthog/temporal/tests/test_clickhouse.py b/posthog/temporal/tests/test_clickhouse.pyindex c4597619db47..868c00fa2f7a 100644--- a/posthog/temporal/tests/test_clickhouse.py+++ b/posthog/temporal/tests/test_clickhouse.py@@ -215,6 +215,22 @@ def test_post_query_disables_http_compression(clickhouse_client):assert call_kwargs["params"]["enable_http_compression"] == "0"+def test_post_query_sends_freshly_read_token(tmp_path):+ token = tmp_path / "token"+ token.write_text("tok-0")+ client = ClickHouseClient(user="default", password="static-fallback", password_file=str(token))++ with _mock_internal_session_post(MagicMock(status_code=200)) as mock_factory:+ with client.post_query("SELECT 1", query_parameters={}, query_id=None):+ pass+ assert mock_factory.return_value.post.call_args.kwargs["headers"]["X-ClickHouse-Key"] == "tok-0"++ token.write_text("tok-1") # a rotation must reach the next request on the long-lived session+ with client.post_query("SELECT 1", query_parameters={}, query_id=None):+ pass+ assert mock_factory.return_value.post.call_args.kwargs["headers"]["X-ClickHouse-Key"] == "tok-1"++@pytest.mark.parametrize("query,query_parameters,expected",[