: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): run migrations as a dedicated clickhouse user (#115795)
Tommy Gilmoreac8920fac1f9
diff --git a/posthog/clickhouse/client/AGENTS.md b/posthog/clickhouse/client/AGENTS.mdindex 0315bef56cb9..60837a30f667 100644--- a/posthog/clickhouse/client/AGENTS.md+++ b/posthog/clickhouse/client/AGENTS.md@@ -15,9 +15,10 @@ It routes through `get_client_from_pool`, which uses the token-aware `get_pool`The async temporal client `get_client` in `posthog/temporal/common/clickhouse.py` is token-aware too, because `_request_headers` calls `read_password` on each request.Use these paths and token auth is automatic.-`get_cluster` in `posthog/clickhouse/cluster.py` is token-aware for the pod default user: the per-host pools carry a credential provider that re-stamps the live token on each checkout.+`get_cluster` in `posthog/clickhouse/cluster.py` is token-aware for the user that its `ch_user` argument resolves to, which is the pod default user unless you set it: the per-host pools carry a credential provider that re-stamps the live token on each checkout.Its bootstrap discovery client is long-lived, so each discovery attempt stamps the live token onto it first, including the discovery that `sibling()` runs hours into a job.-A caller that connects as a different user through `connection_overrides` owns its own credential.+Pass `ch_user` to connect as a dedicated user, the way `get_migrations_cluster` does, because discovery and the pools then both use that user.+A caller that connects as a different user through `connection_overrides` owns its own credential, and its discovery still runs as the pod default user.The backups and part_breaker Dagster resources do this: each sets `credential_provider` itself when its user is file-backed, the way `get_pool` does.Token-awareness is lost when you pass your own `sync_client` to `sync_execute`, or build your own pool or client.diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex d49421f2027d..49773103d3ea 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -523,6 +523,7 @@ def default_client(host=settings.CLICKHOUSE_HOST,password=None,*,+ user: str | None = None,database: str = "system",send_receive_timeout: int | None = None,):@@ -530,7 +531,8 @@ def default_client(Return a bare bones client for use in places where we are only interested in general ClickHouse stateDO NOT USE THIS FOR QUERYING DATA- password overrides the static CLICKHOUSE_PASSWORD, for example with a resolved file-backed token.+ user and password override CLICKHOUSE_USER and the static CLICKHOUSE_PASSWORD, for example with a+ dedicated user's resolved file-backed token.send_receive_timeout bounds each socket read and write; None keeps the driver default."""return ClickHouseClient(@@ -544,7 +546,7 @@ def default_client(# access to various other tables e.g. to handle async migrations.database=database,secure=settings.CLICKHOUSE_SECURE,- user=settings.CLICKHOUSE_USER,+ user=settings.CLICKHOUSE_USER if user is None else user,password=settings.CLICKHOUSE_PASSWORD if password is None else password,ca_certs=settings.CLICKHOUSE_CA,verify=settings.CLICKHOUSE_VERIFY,diff --git a/posthog/clickhouse/client/migration_tools.py b/posthog/clickhouse/client/migration_tools.pyindex 8a206aa0dabf..ee9a97cf3611 100644--- a/posthog/clickhouse/client/migration_tools.py+++ b/posthog/clickhouse/client/migration_tools.py@@ -5,7 +5,7 @@ from typing import Optionalfrom infi.clickhouse_orm import migrationsfrom posthog import settings-from posthog.clickhouse.client.connection import DATA_NODE_ROLES, SINGLE_SHARD_DATA_NODE_ROLES, NodeRole+from posthog.clickhouse.client.connection import DATA_NODE_ROLES, SINGLE_SHARD_DATA_NODE_ROLES, ClickHouseUser, NodeRolefrom posthog.clickhouse.cluster import ClickhouseCluster, Query, get_clusterfrom posthog.run_mode import run_modefrom posthog.settings.data_stores import (@@ -25,6 +25,7 @@ def get_migrations_cluster() -> ClickhouseCluster:cluster=CLICKHOUSE_MIGRATIONS_CLUSTER,data_cluster=CLICKHOUSE_CLUSTER,satellite_clusters=CLICKHOUSE_SATELLITE_CLUSTERS or None,+ ch_user=ClickHouseUser.MIGRATIONS,)diff --git a/posthog/clickhouse/cluster.py b/posthog/clickhouse/cluster.pyindex de0df49776b5..fda9aafa61b6 100644--- a/posthog/clickhouse/cluster.py+++ b/posthog/clickhouse/cluster.py@@ -638,20 +638,26 @@ def get_cluster(retry_policy: RetryPolicy | None = None,host: str = settings.CLICKHOUSE_HOST,connection_overrides: Mapping[str, Any] | None = None,+ ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,) -> ClickhouseCluster:extra_hosts = []for host_config in map(copy, CLICKHOUSE_PER_TEAM_SETTINGS.values()):extra_hosts.append(ConnectionInfo(host_config.pop("host"), None))assert len(host_config) == 0, f"unexpected values: {host_config!r}"- creds = get_clickhouse_creds(ClickHouseUser.DEFAULT)+ creds = get_clickhouse_creds(ch_user)overrides = dict(connection_overrides or {})+ caller_owns_credential = bool(overrides.keys() & {"user", "password", "credential_provider"})bootstrap_credential_provider: Callable[[], str] | None = Noneif is_file_backed_user(creds, creds.user):bootstrap_credential_provider = creds.read_password- bootstrap_client = default_client(host=host, password=creds.read_password())- if not overrides.keys() & {"user", "password", "credential_provider"}:- overrides["credential_provider"] = creds.read_password+ bootstrap_client = default_client(host=host, user=creds.user, password=creds.read_password())+ if not caller_owns_credential:+ overrides.update(user=creds.user, credential_provider=creds.read_password)+ elif creds.user != settings.CLICKHOUSE_USER:+ bootstrap_client = default_client(host=host, user=creds.user, password=creds.password)+ if not caller_owns_credential:+ overrides.update(user=creds.user, password=creds.password)else:bootstrap_client = default_client(host=host)diff --git a/posthog/clickhouse/test/test_cluster.py b/posthog/clickhouse/test/test_cluster.pyindex bee21ddf2c90..16cc5e62a008 100644--- a/posthog/clickhouse/test/test_cluster.py+++ b/posthog/clickhouse/test/test_cluster.py@@ -42,60 +42,107 @@ def cluster(django_db_setup) -> Iterator[ClickhouseCluster]:@pytest.mark.parametrize(- "static_password, password_file_set, overrides_arg, expect_token_bootstrap, expect_provider",+ "ch_user, static_password, password_file_set, overrides_arg, expected_bootstrap, expected_overrides, expect_provider",[- pytest.param("static-fallback", True, None, True, True, id="dual_armed_default_bootstraps_on_token"),- pytest.param("", True, None, True, True, id="token_first_default_bootstraps_on_token"),- pytest.param("static-only", False, None, False, False, id="static_default_uses_password"),pytest.param(+ ClickHouseUser.DEFAULT,"static-fallback",True,- {"user": "backups", "password": "bkp-static"},+ None,+ {"user": "default", "password": "live-token"},+ {"user": "default"},+ True,+ id="dual_armed_default_bootstraps_on_token",+ ),+ pytest.param(+ ClickHouseUser.DEFAULT,+ "",+ True,+ None,+ {"user": "default", "password": "live-token"},+ {"user": "default"},+ True,+ id="token_first_default_bootstraps_on_token",+ ),+ pytest.param(+ ClickHouseUser.DEFAULT, "static-only", False, None, {}, {}, False, id="static_default_uses_password"+ ),+ pytest.param(+ ClickHouseUser.DEFAULT,+ "static-fallback",True,+ {"user": "backups", "password": "bkp-static"},+ {"user": "default", "password": "live-token"},+ {"user": "backups", "password": "bkp-static"},False,id="override_user_keeps_its_own_credential",),+ pytest.param(+ ClickHouseUser.MIGRATIONS,+ "",+ True,+ None,+ {"user": "migrations", "password": "live-token"},+ {"user": "migrations"},+ True,+ id="dedicated_user_connects_on_its_token",+ ),+ pytest.param(+ ClickHouseUser.MIGRATIONS,+ "migrations-static",+ False,+ None,+ {"user": "migrations", "password": "migrations-static"},+ {"user": "migrations", "password": "migrations-static"},+ False,+ id="static_dedicated_user_connects_on_its_password",+ ),],)def test_get_cluster_bootstraps_a_file_backed_user_on_its_live_token(- monkeypatch, tmp_path, static_password, password_file_set, overrides_arg, expect_token_bootstrap, expect_provider+ monkeypatch,+ tmp_path,+ ch_user,+ static_password,+ password_file_set,+ overrides_arg,+ expected_bootstrap,+ expected_overrides,+ expect_provider,) -> None:- token = "live-token"token_file = tmp_path / "token"- token_file.write_text(token)+ token_file.write_text("live-token")creds = ClickHouseCredentials(- user="default",+ user=ch_user.value,password=static_password,password_file=str(token_file) if password_file_set else None,)- monkeypatch.setattr(connection, "__user_dict", {ClickHouseUser.DEFAULT: creds})+ users = {ClickHouseUser.DEFAULT: ClickHouseCredentials(user="default", password="default-static")}+ users[ch_user] = creds+ monkeypatch.setattr(connection, "__user_dict", users)with (patch("posthog.clickhouse.cluster.default_client") as mock_default_client,patch("posthog.clickhouse.cluster.ClickhouseCluster") as mock_cluster,):- get_cluster(connection_overrides=overrides_arg)+ get_cluster(connection_overrides=overrides_arg, ch_user=ch_user)- bootstrap_password = mock_default_client.call_args.kwargs.get("password")+ bootstrap = {key: value for key, value in mock_default_client.call_args.kwargs.items() if key != "host"}bootstrap_provider = mock_cluster.call_args.kwargs["bootstrap_credential_provider"]- overrides = mock_cluster.call_args.kwargs["connection_overrides"]+ overrides = dict(mock_cluster.call_args.kwargs["connection_overrides"])+ provider = overrides.pop("credential_provider", None)token_file.write_text("rotated-token")- if expect_token_bootstrap:- assert bootstrap_password == token+ assert bootstrap == expected_bootstrap+ assert overrides == expected_overrides+ if password_file_set:assert bootstrap_provider() == "rotated-token"else:- assert bootstrap_password is Noneassert bootstrap_provider is None-if expect_provider:- assert overrides["credential_provider"]() == "rotated-token"+ assert provider is not None and provider() == "rotated-token"else:- assert "credential_provider" not in overrides-- if overrides_arg is not None:- assert overrides["user"] == overrides_arg["user"]- assert overrides["password"] == overrides_arg["password"]+ assert provider is Nonedef test_mutation_runner_rejects_invalid_parameters() -> None:diff --git a/posthog/management/commands/migrate_clickhouse.py b/posthog/management/commands/migrate_clickhouse.pyindex 0c57b7ac24ec..aa993e44eb20 100644--- a/posthog/management/commands/migrate_clickhouse.py+++ b/posthog/management/commands/migrate_clickhouse.py@@ -10,14 +10,29 @@ from cachetools import cachedfrom infi.clickhouse_orm import Databasefrom infi.clickhouse_orm.migrations import MigrationHistoryfrom infi.clickhouse_orm.utils import import_submodules--from posthog.clickhouse.client.connection import ClickHouseCredentials, default_client-from posthog.settings import CLICKHOUSE_DATABASE, CLICKHOUSE_HTTP_URL, CLICKHOUSE_PASSWORD, CLICKHOUSE_USER-from posthog.settings.data_stores import CLICKHOUSE_MIGRATIONS_CLUSTER, CLICKHOUSE_PASSWORD_FILE+from requests import PreparedRequest+from requests.auth import AuthBase, HTTPBasicAuth++from posthog.clickhouse.client.connection import (+ ClickHouseCredentials,+ ClickHouseUser,+ default_client,+ get_clickhouse_creds,+)+from posthog.settings import CLICKHOUSE_DATABASE, CLICKHOUSE_HTTP_URL+from posthog.settings.data_stores import CLICKHOUSE_MIGRATIONS_CLUSTERMIGRATIONS_PACKAGE_NAME = "posthog.clickhouse.migrations"+class _PerRequestPasswordAuth(AuthBase):+ def __init__(self, creds: ClickHouseCredentials) -> None:+ self._creds = creds++ def __call__(self, request: PreparedRequest) -> PreparedRequest:+ return HTTPBasicAuth(self._creds.user, self._creds.read_password())(request)++class Command(BaseCommand):help = "Migrate clickhouse"@@ -53,35 +68,25 @@ class Command(BaseCommand):self.migrate(CLICKHOUSE_HTTP_URL, options)def migrate(self, host, options):- # Read-only --check and --plan finish in seconds, so they use the short-lived- # token from CLICKHOUSE_PASSWORD_FILE, and fall back to the static password when- # no token file is set. infi.clickhouse_orm never re-reads the password, and an- # apply can outlast the token, so the apply keeps the static password. The setup- # steps below share this password, so they never authenticate differently than- # the migration itself.- if options["check"] or options["plan"]:- password = ClickHouseCredentials(- user=CLICKHOUSE_USER, password=CLICKHOUSE_PASSWORD, password_file=CLICKHOUSE_PASSWORD_FILE- ).read_password()- else:- password = CLICKHOUSE_PASSWORD+ creds = get_clickhouse_creds(ClickHouseUser.MIGRATIONS)# Infi only creates the DB in one node, but not the rest. Create it before running migrations.- self._create_database_if_not_exists(CLICKHOUSE_DATABASE, CLICKHOUSE_MIGRATIONS_CLUSTER, password)- self._create_migration_tracking_tables_if_not_exist(- CLICKHOUSE_DATABASE, CLICKHOUSE_MIGRATIONS_CLUSTER, password- )+ self._create_database_if_not_exists(CLICKHOUSE_DATABASE, CLICKHOUSE_MIGRATIONS_CLUSTER, creds)+ self._create_migration_tracking_tables_if_not_exist(CLICKHOUSE_DATABASE, CLICKHOUSE_MIGRATIONS_CLUSTER, creds)database = Database(CLICKHOUSE_DATABASE,db_url=host,- username=CLICKHOUSE_USER,- password=password,+ username=creds.user,+ password=creds.read_password(),cluster=CLICKHOUSE_MIGRATIONS_CLUSTER,verify_ssl_cert=False,randomize_replica_paths=settings.TEST or settings.E2E_TESTING,# don't use the egress proxy, clickhouse is internaltrust_env=False,)+ # infi.clickhouse_orm sends the password it was built with on every request, and an apply+ # can outlast a short-lived token, so each request reads the password again.+ database.request_session.auth = _PerRequestPasswordAuth(creds)if options["plan"] or options["check"]:print("List of clickhouse migrations to be applied:")@@ -135,19 +140,21 @@ class Command(BaseCommand):def get_applied_migrations(self, database) -> set[str]:return database._get_applied_migrations(MIGRATIONS_PACKAGE_NAME, replicated=True)- def _create_database_if_not_exists(self, database: str, cluster: str, password: str):+ def _create_database_if_not_exists(self, database: str, cluster: str, creds: ClickHouseCredentials) -> None:# MULTINODE_CLICKHOUSE: infi.clickhouse_orm creates the Distributed# migration-tracking table across the migrations cluster before the# first migration runs, so the database has to exist on every node up# front — otherwise the CREATE TABLE fans out to satellites that have# no `posthog` database yet and fails with UNKNOWN_DATABASE.if settings.TEST or settings.E2E_TESTING or settings.MULTINODE_CLICKHOUSE:- with default_client(password=password) as client:+ with default_client(user=creds.user, password=creds.read_password()) as client:client.execute(f"CREATE DATABASE IF NOT EXISTS {database} ON CLUSTER {cluster}",)- def _create_migration_tracking_tables_if_not_exist(self, database: str, cluster: str, password: str):+ def _create_migration_tracking_tables_if_not_exist(+ self, database: str, cluster: str, creds: ClickHouseCredentials+ ) -> None:# MULTINODE_CLICKHOUSE only: infi.clickhouse_orm's auto-create path# issues `CREATE TABLE` without `ON CLUSTER`, so the underlying# ReplicatedMergeTree only lands on the migrations host. With a real@@ -163,7 +170,7 @@ class Command(BaseCommand):# pre-create will silently diverge — keep the two in sync.if not settings.MULTINODE_CLICKHOUSE:return- with default_client(password=password) as client:+ with default_client(user=creds.user, password=creds.read_password()) as client:client.execute(f"""CREATE TABLE IF NOT EXISTS {database}.infi_clickhouse_orm_migrationsdiff --git a/posthog/management/commands/test/test_migrate_clickhouse.py b/posthog/management/commands/test/test_migrate_clickhouse.pynew file mode 100644index 000000000000..308ca8cc453b--- /dev/null+++ b/posthog/management/commands/test/test_migrate_clickhouse.py@@ -0,0 +1,80 @@+import base64+from pathlib import Path++import pytest+from unittest.mock import patch++import responses+from infi.clickhouse_orm import Database+from requests import PreparedRequest++from posthog.clickhouse.client import connection+from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser+from posthog.management.commands.migrate_clickhouse import Command++CLICKHOUSE_URL = "http://clickhouse.example.com:8123/"+APPLY_OPTIONS = {"upto": 99_999, "fake": False, "check": False, "plan": False, "print_sql": False}+SERVER_ANSWERS = {+ "SELECT count() FROM system.databases": "1",+ "SELECT version()": "25.8.1.1",+ "SELECT timezone()": "UTC",+}+++def basic_auth(user: str, password: str) -> str:+ return "Basic " + base64.b64encode(f"{user}:{password}".encode()).decode()+++ "migrations_user_registered, first_request_auth, request_after_rotation_auth",+ [+ pytest.param(+ True,+ basic_auth("migrations", "token-1"),+ basic_auth("migrations", "token-2"),+ id="migrations_user_reads_its_token_per_request",+ ),+ pytest.param(+ False,+ basic_auth("default", "default-static"),+ basic_auth("default", "default-static"),+ id="unset_migrations_user_falls_back_to_default",+ ),+ ],+)+def test_migrate_authenticates_each_request_with_the_current_password(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ migrations_user_registered: bool,+ first_request_auth: str,+ request_after_rotation_auth: str,+) -> None:+ token_file = tmp_path / "token"+ token_file.write_text("token-1")+ users = {ClickHouseUser.DEFAULT: ClickHouseCredentials(user="default", password="default-static")}+ if migrations_user_registered:+ users[ClickHouseUser.MIGRATIONS] = ClickHouseCredentials(+ user="migrations", password="", password_file=str(token_file)+ )+ monkeypatch.setattr(connection, "__user_dict", users)+ sent_auth: list[str] = []++ def answer(request: PreparedRequest) -> tuple[int, dict[str, str], str]:+ sent_auth.append(str(request.headers["Authorization"]))+ body = request.body.decode() if isinstance(request.body, bytes) else str(request.body)+ return 200, {}, next((text for query, text in SERVER_ANSWERS.items() if body.startswith(query)), "")++ def apply_past_a_token_rotation(database: Database, *args: object, **kwargs: object) -> None:+ token_file.write_text("token-2")+ database._send("SELECT 1")++ with (+ responses.RequestsMock() as server,+ patch.object(Database, "migrate", autospec=True, side_effect=apply_past_a_token_rotation),+ patch("posthog.management.commands.migrate_clickhouse.default_client"),+ ):+ server.add_callback(responses.POST, CLICKHOUSE_URL, callback=answer)+ Command().migrate(CLICKHOUSE_URL, APPLY_OPTIONS)++ assert sent_auth[0] == first_request_auth+ assert sent_auth[-1] == request_after_rotation_auth