: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): refresh native-tcp pool credentials from a file (#90537)
Tommy Gilmore993ef0f8f6fb
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex 75356728f318..3b1dcfd12e92 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -1,10 +1,11 @@import osimport logging-from collections.abc import Mapping+from collections.abc import Callable, Mappingfrom contextlib import contextmanagerfrom dataclasses import fieldfrom enum import StrEnumfrom functools import cache+from pathlib import Pathfrom typing import TYPE_CHECKINGfrom django.conf import settings@@ -107,6 +108,22 @@ class ClickHouseUser(StrEnum):class ClickHouseCredentials:user: strpassword: str = field(repr=False)+ # Path to a file holding the live password. When set, read_password re-reads it on each call,+ # so a rotated short-lived token reaches ClickHouse without rebuilding the pool.+ password_file: str | None = None++ def read_password(self) -> str:+ path = self.password_file+ if path:+ try:+ token = Path(path).read_text().strip()+ except OSError:+ logging.warning("clickhouse: %s is not readable, using the static fallback", path)+ return self.password+ if token:+ return token+ logging.warning("clickhouse: %s is empty, using the static fallback", path)+ return self.password__user_dict: Mapping[ClickHouseUser, ClickHouseCredentials] | None = None@@ -115,15 +132,19 @@ __user_dict: Mapping[ClickHouseUser, ClickHouseCredentials] | None = Nonedef init_clickhouse_users() -> Mapping[ClickHouseUser, ClickHouseCredentials]:user_dict = {ClickHouseUser.DEFAULT: ClickHouseCredentials(- user=data_stores.CLICKHOUSE_USER, password=data_stores.CLICKHOUSE_PASSWORD+ user=data_stores.CLICKHOUSE_USER,+ password=data_stores.CLICKHOUSE_PASSWORD,+ password_file=data_stores.CLICKHOUSE_PASSWORD_FILE,),}for u in ClickHouseUser:user = os.getenv(f"CLICKHOUSE_{u.name.upper()}_USER")password = os.getenv(f"CLICKHOUSE_{u.name.upper()}_PASSWORD")- if user and password:- user_dict[u] = ClickHouseCredentials(user=user, password=password)- elif bool(user) != bool(password):+ password_file = os.getenv(f"CLICKHOUSE_{u.name.upper()}_PASSWORD_FILE")+ secret = password or password_file+ if user and secret:+ user_dict[u] = ClickHouseCredentials(user=user, password=password or "", password_file=password_file)+ elif bool(user) != bool(secret):logging.warning(f"only one of clickhouse user/password provided, check your config")user_names = ",".join([x.name for x in user_dict.keys()])logging.warning(f"initialized clickhouse users: {user_names}")@@ -282,6 +303,9 @@ 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)return get_http_client(**kwargs)@@ -300,6 +324,14 @@ def get_pool(Note that the same pool should be returned every call."""kwargs = get_kwargs_for_client(workload=workload, team_id=team_id, readonly=readonly, ch_user=ch_user)+ 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:+ kwargs.pop("password", None)+ return make_ch_pool(credential_provider=creds.read_password, **kwargs)return make_ch_pool(**kwargs)@@ -325,7 +357,31 @@ def default_client(host=settings.CLICKHOUSE_HOST):)-def _make_ch_pool(*, client_settings: Mapping[str, str] | None = None, **overrides) -> ChPool:+class RefreshingChPool(ChPool):+ """ChPool that stamps the current credential onto every pulled client.++ The pool is keyed on identity rather than the credential, so one pool survives credential+ rotation instead of leaking a new pool per rotation. The stamp lands on the client's next+ (re)connect, since ClickHouse authenticates at connection time, not per query: a warm pooled+ connection keeps its session until it is reopened, and the overlapping token TTL covers that gap.+ """++ def __init__(self, *, credential_provider: Callable[[], str], **kwargs) -> None:+ self._credential_provider = credential_provider+ super().__init__(**kwargs)++ def pull(self, key: str | None = None) -> SyncClient:+ client = super().pull(key)+ client.connection.password = self._credential_provider()+ return client+++def _make_ch_pool(+ *,+ client_settings: Mapping[str, str] | None = None,+ credential_provider: Callable[[], str] | None = None,+ **overrides,+) -> ChPool:kwargs = {"host": settings.CLICKHOUSE_HOST,"database": settings.CLICKHOUSE_DATABASE,@@ -345,6 +401,10 @@ def _make_ch_pool(*, client_settings: Mapping[str, str] | None = None, **overrid**overrides,}+ if credential_provider is not None:+ # kwargs["password"] is only the lazy seed here; RefreshingChPool re-stamps every pulled client.+ return RefreshingChPool(credential_provider=credential_provider, **kwargs)+return ChPool(**kwargs)diff --git a/posthog/clickhouse/client/test/test_connection.py b/posthog/clickhouse/client/test/test_connection.pyindex fc904d1a13e6..bee0a9762aa4 100644--- a/posthog/clickhouse/client/test/test_connection.py+++ b/posthog/clickhouse/client/test/test_connection.py@@ -1,15 +1,28 @@import pytest+from clickhouse_pool import ChPool++from posthog.clickhouse.client import connectionfrom posthog.clickhouse.client.connection import (+ ClickHouseCredentials,+ ClickHouseUser,+ RefreshingChPool,Workload,get_http_client,get_pool,+ init_clickhouse_users,make_ch_pool,set_default_clickhouse_workload_type,)from posthog.clickhouse.client.execute import sync_execute+def _file_backed_default(monkeypatch, path, *, fallback="fallback"):+ creds = ClickHouseCredentials(user="default", password=fallback, password_file=str(path))+ monkeypatch.setattr(connection, "__user_dict", {ClickHouseUser.DEFAULT: creds})+ return creds++@pytest.mark.django_dbdef test_insert_with_http_client():sync_execute("DROP TABLE IF EXISTS _test_http_insert")@@ -29,6 +42,7 @@ def test_connection_pool_creation_without_offline_cluster(settings):settings.CLICKHOUSE_OFFLINE_CLUSTER_HOST = Noneonline_pool = get_pool(Workload.ONLINE)+ assert type(online_pool) is ChPool # a user with no password file keeps a plain, non-refreshing poolassert get_pool(Workload.ONLINE) is online_poolassert get_pool(Workload.OFFLINE) is online_poolassert get_pool(Workload.DEFAULT) is online_pool@@ -68,6 +82,74 @@ def test_connection_pool_creation_with_team_id(settings):assert team_pool.connection_args["host"] == "clicky"+def test_read_password_reads_file_fresh_and_stripped(tmp_path):+ token = tmp_path / "token"+ token.write_text("tok-0\n")+ creds = ClickHouseCredentials(user="u", password="fallback", password_file=str(token))++ assert creds.read_password() == "tok-0"++ token.write_text(" tok-1 ") # a later rotation must be picked up, not cached at construction+ assert creds.read_password() == "tok-1"++[email protected]("state", ["missing", "empty"])+def test_read_password_falls_back_when_file_unusable(tmp_path, state):+ token = tmp_path / "token"+ if state == "empty":+ token.write_text("")++ creds = ClickHouseCredentials(user="u", password="fallback-secret", password_file=str(token))+ assert creds.read_password() == "fallback-secret"+++def test_password_file_env_registers_file_backed_user(monkeypatch, tmp_path):+ token = tmp_path / "cohorts-token"+ token.write_text("cohorts-token-value")+ monkeypatch.setenv("CLICKHOUSE_COHORTS_USER", "cohorts")+ monkeypatch.setenv("CLICKHOUSE_COHORTS_PASSWORD_FILE", str(token))+ monkeypatch.delenv("CLICKHOUSE_COHORTS_PASSWORD", raising=False)++ creds = init_clickhouse_users()[ClickHouseUser.COHORTS]+ assert creds.user == "cohorts"+ assert creds.read_password() == "cohorts-token-value"+++def test_file_backed_pool_is_stable_across_credential_rotation(settings, monkeypatch, tmp_path):+ settings.CLICKHOUSE_OFFLINE_CLUSTER_HOST = None+ token = tmp_path / "token"+ token.write_text("tok-0")+ _file_backed_default(monkeypatch, token)++ pool = get_pool(Workload.ONLINE)+ assert isinstance(pool, RefreshingChPool)++ token.write_text("tok-1") # rotate the projected token in place+ assert get_pool(Workload.ONLINE) is pool+ assert make_ch_pool.cache_info().currsize == 1+++def test_refreshing_pool_stamps_current_credential(tmp_path):+ token = tmp_path / "token"+ token.write_text("tok-0")+ pool = RefreshingChPool(+ credential_provider=lambda: token.read_text().strip(),+ host="localhost",+ port=1,+ connections_min=1,+ connections_max=1,+ )++ client = pool.pull()+ assert client.connection.password == "tok-0"+ pool.push(client)++ token.write_text("tok-1")+ client = pool.pull()+ assert client.connection.password == "tok-1"+ pool.push(client)++@pytest.fixture(autouse=True)def reset_state():make_ch_pool.cache_clear()diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 50a60eb7869a..678207633a47 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -301,6 +301,12 @@ CLICKHOUSE_MIGRATIONS_HOST: str = os.getenv("CLICKHOUSE_MIGRATIONS_HOST", CLICKHCLICKHOUSE_ENDPOINTS_HOST: str = os.getenv("CLICKHOUSE_ENDPOINTS_HOST", CLICKHOUSE_HOST)CLICKHOUSE_USER: str = os.getenv("CLICKHOUSE_USER", "default")CLICKHOUSE_PASSWORD: str = os.getenv("CLICKHOUSE_PASSWORD", "")+# Path to a file holding the live password. When set, it is read fresh per pool checkout so a+# rotated short-lived token is used without a restart. CLICKHOUSE_PASSWORD is the fallback when+# the file is missing or empty. Per-user files use CLICKHOUSE_<USER>_PASSWORD_FILE.+# Unset by default, and left unset on purpose: the deployment sets it per user only when that user+# is migrated to token auth, so native pools keep using the static password until then.+CLICKHOUSE_PASSWORD_FILE: str | None = os.getenv("CLICKHOUSE_PASSWORD_FILE", None)CLICKHOUSE_DATABASE: str = CLICKHOUSE_TEST_DB if TEST else os.getenv("CLICKHOUSE_DATABASE", "default")CLICKHOUSE_CLUSTER: str = os.getenv("CLICKHOUSE_CLUSTER", "posthog")CLICKHOUSE_MIGRATIONS_CLUSTER: str = os.getenv("CLICKHOUSE_MIGRATIONS_CLUSTER", "posthog_migrations")diff --git a/posthog/test/repo_invariants/dataclass_secret_field_exemptions.txt b/posthog/test/repo_invariants/dataclass_secret_field_exemptions.txtindex efb1f8f2652f..a3b086f6e625 100644--- a/posthog/test/repo_invariants/dataclass_secret_field_exemptions.txt+++ b/posthog/test/repo_invariants/dataclass_secret_field_exemptions.txt@@ -1,2 +1,3 @@+posthog/clickhouse/client/connection.py ClickHouseCredentials.password_fileproducts/managed_warehouse/backend/facade/contracts.py DuckLakeCompiledQuery.s3_secretsproducts/warehouse_sources/backend/temporal/data_imports/sources/anthropic/anthropic.py ClaudeCodeActor.api_key_name