Skip to content

: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.

feat(clickhouse): refresh file-backed credential on the HTTP path (#92038)

Tommy Gilmoreab4443377f23
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index fb3b9009a262..390ec05315b2 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -6,7 +6,7 @@ from dataclasses import field
from enum import StrEnum
from functools import cache
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from django.conf import settings
@@ -296,6 +296,32 @@ def get_kwargs_for_client(
return base_kwargs
+def _is_file_backed_user(creds: ClickHouseCredentials, workload: Workload, user: str | None) -> bool:
+ # True when the resolved connection authenticates as a user whose credential comes from a
+ # rotating token file. The LOGS and readonly paths resolve to their own static credentials, so
+ # they are excluded and keep the static password.
+ return bool(creds.password_file) and workload != Workload.LOGS and user == creds.user
+
+
+def get_http_kwargs(
+ workload: Workload = Workload.DEFAULT,
+ team_id: int | None = None,
+ readonly: bool = False,
+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,
+) -> dict[str, Any]:
+ """Build kwargs for the short-lived HTTP client, reading a file-backed credential fresh.
+
+ The HTTP client is rebuilt on every call, so one read here is enough to send a rotated token.
+ The native pool path does not use this helper because RefreshingChPool already re-reads the file
+ on every checkout, which means a read here would only duplicate it on the hot query path.
+ """
+ kwargs = get_kwargs_for_client(workload=workload, team_id=team_id, readonly=readonly, ch_user=ch_user)
+ creds = get_clickhouse_creds(ch_user)
+ if _is_file_backed_user(creds, workload, kwargs.get("user")):
+ kwargs["password"] = creds.read_password()
+ return kwargs
+
+
@patchable
def get_client_from_pool(
workload: Workload = Workload.DEFAULT,
@@ -310,10 +336,7 @@ def get_client_from_pool(
"""
if settings.CLICKHOUSE_USE_HTTP or team_id in settings.CLICKHOUSE_USE_HTTP_PER_TEAM:
- # File-backed credential refresh currently covers only the native pool below. This HTTP path
- # (and default_client / ClickhouseCluster) still send the static CLICKHOUSE_*_PASSWORD, so a
- # user must keep its static password until the HTTP path also reads the token file.
- kwargs = get_kwargs_for_client(workload=workload, team_id=team_id, readonly=readonly, ch_user=ch_user)
+ kwargs = get_http_kwargs(workload=workload, team_id=team_id, readonly=readonly, ch_user=ch_user)
return get_http_client(**kwargs)
return get_pool(workload=workload, team_id=team_id, readonly=readonly, ch_user=ch_user).get_client()
@@ -334,9 +357,7 @@ def get_pool(
creds = get_clickhouse_creds(ch_user)
# A file-backed user reads its credential fresh on every checkout, so the pool is keyed on
# identity rather than the rotating credential and stamps the credential in RefreshingChPool.pull.
- # Only when the resolved pool authenticates as this user: the LOGS and readonly paths resolve to
- # their own static credentials and keep a plain pool.
- if creds.password_file and workload != Workload.LOGS and kwargs.get("user") == creds.user:
+ if _is_file_backed_user(creds, workload, kwargs.get("user")):
kwargs.pop("password", None)
return make_ch_pool(credential_provider=creds.read_password, **kwargs)
return make_ch_pool(**kwargs)
diff --git a/posthog/clickhouse/client/test/test_connection.py b/posthog/clickhouse/client/test/test_connection.py
index bee0a9762aa4..641dc8d1e62d 100644
--- a/posthog/clickhouse/client/test/test_connection.py
+++ b/posthog/clickhouse/client/test/test_connection.py
@@ -1,4 +1,5 @@
import pytest
+from unittest.mock import patch
from clickhouse_pool import ChPool
@@ -9,6 +10,7 @@ from posthog.clickhouse.client.connection import (
RefreshingChPool,
Workload,
get_http_client,
+ get_http_kwargs,
get_pool,
init_clickhouse_users,
make_ch_pool,
@@ -129,6 +131,32 @@ def test_file_backed_pool_is_stable_across_credential_rotation(settings, monkeyp
assert make_ch_pool.cache_info().currsize == 1
+def test_get_http_kwargs_reads_file_backed_credential_fresh(monkeypatch, tmp_path):
+ token = tmp_path / "token"
+ token.write_text("tok-0")
+ _file_backed_default(monkeypatch, token)
+
+ assert get_http_kwargs(Workload.ONLINE)["password"] == "tok-0"
+
+ token.write_text("tok-1") # a rotation must reach the short-lived HTTP client, not a value cached at build
+ assert get_http_kwargs(Workload.ONLINE)["password"] == "tok-1"
+
+
+def test_get_client_from_pool_http_branch_sends_fresh_token(settings, monkeypatch, tmp_path):
+ settings.CLICKHOUSE_USE_HTTP = True
+ token = tmp_path / "token"
+ token.write_text("tok-0")
+ _file_backed_default(monkeypatch, token)
+
+ with patch.object(connection, "get_http_client") as mock_http_client:
+ connection.get_client_from_pool(Workload.ONLINE)
+
+ # The HTTP dispatch must route through get_http_kwargs so a rotated token reaches the client.
+ # Asserting the credential handed to get_http_client, not that the helper was called, keeps this
+ # green if the kwargs building is ever inlined.
+ assert mock_http_client.call_args.kwargs["password"] == "tok-0"
+
+
def test_refreshing_pool_stamps_current_credential(tmp_path):
token = tmp_path / "token"
token.write_text("tok-0")
diff --git a/posthog/dags/sessions.py b/posthog/dags/sessions.py
index eb85338c454c..cc2a7feb62ad 100644
--- a/posthog/dags/sessions.py
+++ b/posthog/dags/sessions.py
@@ -22,13 +22,7 @@ from dagster import (
from posthog.schema import ProductKey
from posthog.clickhouse.client import sync_execute
-from posthog.clickhouse.client.connection import (
- ClickHouseUser,
- NodeRole,
- Workload,
- get_http_client,
- get_kwargs_for_client,
-)
+from posthog.clickhouse.client.connection import ClickHouseUser, NodeRole, Workload, get_http_client, get_http_kwargs
from posthog.clickhouse.cluster import get_cluster
from posthog.clickhouse.query_tagging import Feature, tags_context
from posthog.cloud_utils import is_cloud
@@ -742,9 +736,7 @@ def _do_experimental_backfill(
if debug_url := metabase_debug_query_url(context.run_id):
context.log.info(f"Debug query: {debug_url}")
- kwargs = get_kwargs_for_client(
- workload=Workload.OFFLINE, team_id=None, readonly=False, ch_user=ClickHouseUser.DEFAULT
- )
+ kwargs = get_http_kwargs(workload=Workload.OFFLINE, team_id=None, readonly=False, ch_user=ClickHouseUser.DEFAULT)
# The experimental cluster uses the non-sharded table name (raw_sessions_v3),
# and is a standalone node not in the main ClickHouse cluster
target_table = DISTRIBUTED_RAW_SESSIONS_TABLE_V3()
diff --git a/posthog/dags/tests/test_sessions.py b/posthog/dags/tests/test_sessions.py
index 0c8438755ff9..018d989706d7 100644
--- a/posthog/dags/tests/test_sessions.py
+++ b/posthog/dags/tests/test_sessions.py
@@ -69,7 +69,7 @@ def _patch_experimental_backfill_deps(redis_get_return=None):
mock_redis.get.return_value = redis_get_return
with (
- patch("posthog.dags.sessions.get_kwargs_for_client", return_value={}),
+ patch("posthog.dags.sessions.get_http_kwargs", return_value={}),
patch("posthog.dags.sessions.get_http_client") as mock_get_http_client,
patch("posthog.dags.sessions.sync_execute") as mock_sync_execute,
patch("posthog.dags.sessions.wait_for_parts_to_merge"),