: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): source dictionary creds via dict_reader user (#64384)
Tommy Gilmore36888bf36dc5
diff --git a/.agents/skills/clickhouse-migrations/SKILL.md b/.agents/skills/clickhouse-migrations/SKILL.mdindex d540c464d538..778fa9b709c8 100644--- a/.agents/skills/clickhouse-migrations/SKILL.md+++ b/.agents/skills/clickhouse-migrations/SKILL.md@@ -89,6 +89,8 @@ If you create a new table inside such a guard, you must also add its SQL functioThe only exception is tables whose definition intentionally differs per environment and is not tracked in the repo (e.g. the no-go zone `events_json_ws_mv` table).+**Dictionary credentials:** when a dictionary uses a `SOURCE(CLICKHOUSE(...))`, resolve the source user/password via `get_clickhouse_creds(ClickHouseUser.DICT_READER)` and interpolate them into the `USER`/`PASSWORD` clause — do not hardcode `default`/`CLICKHOUSE_USER` or omit credentials. This keeps dictionary auth on the dedicated low-privilege `dict_reader` user, decoupled from `default`; it falls back to `default` creds when the env vars are unset. See `posthog/models/exchange_rate/sql.py` for the pattern.+### TestingDelete entry from `infi_clickhouse_orm_migrations` table to re-run a migration.diff --git a/.env.services b/.env.servicesindex 37c661a61232..252aaabf533a 100644--- a/.env.services+++ b/.env.services@@ -23,6 +23,8 @@ CLICKHOUSE_APP_USER=appCLICKHOUSE_APP_PASSWORD=apppassCLICKHOUSE_BILLING_USER=billingCLICKHOUSE_BILLING_PASSWORD=billingpass+CLICKHOUSE_DICT_READER_USER=dict_reader+CLICKHOUSE_DICT_READER_PASSWORD=dictreaderpass# RedisREDIS_URL=redis://redis7:6379/diff --git a/docker/clickhouse/users-dev.xml b/docker/clickhouse/users-dev.xmlindex 69a516d0506b..49f2d9b83463 100644--- a/docker/clickhouse/users-dev.xml+++ b/docker/clickhouse/users-dev.xml@@ -208,6 +208,23 @@<quota>default</quota></billing>+ <!-- Low-privilege reader baked into dictionary SOURCE(CLICKHOUSE(...)) clauses.+ Mirrors prod's dict_reader: read-only, database-wide SELECT (not table-enumerated,+ so new dictionary source tables are covered without editing this file). -->+ <dict_reader>+ <password>dictreaderpass</password>+ <networks>+ <ip>::/0</ip>+ </networks>+ <profile>readonly</profile>+ <quota>default</quota>+ <access_management>0</access_management>+ <grants>+ <query>GRANT SELECT ON default.*</query>+ <query>GRANT SELECT ON posthog_test.*</query>+ </grants>+ </dict_reader>+<!-- Of course this is local dev, but mirrors prod to make tests useful.- no table-function grants (url / s3 / file / executable / jdbc / ...)- no DDLdiff --git a/docker/clickhouse/users.xml b/docker/clickhouse/users.xmlindex 43675e6fcc1b..ebcfd44ef97b 100644--- a/docker/clickhouse/users.xml+++ b/docker/clickhouse/users.xml@@ -174,6 +174,27 @@<quota>default</quota></app>++ <!-- Low-privilege reader baked into dictionary SOURCE(CLICKHOUSE(...)) clauses.+ Mirrors prod's dict_reader: read-only, database-wide SELECT (not table-enumerated,+ so new dictionary source tables are covered without editing this file). -->+ <dict_reader>+ <password>dictreaderpass</password>++ <networks>+ <ip>::/0</ip>+ </networks>++ <profile>readonly</profile>++ <quota>default</quota>++ <access_management>0</access_management>+ <grants>+ <query>GRANT SELECT ON default.*</query>+ <query>GRANT SELECT ON posthog_test.*</query>+ </grants>+ </dict_reader></users><!-- Quotas. -->diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.pyindex f5563dee1184..5cbef65629ce 100644--- a/posthog/clickhouse/client/connection.py+++ b/posthog/clickhouse/client/connection.py@@ -80,6 +80,9 @@ class ClickHouseUser(StrEnum):OPS = "ops"# Only for migrations - do not normally useMIGRATIONS = "migrations"+ # Low-privilege reader baked into dictionary SOURCE blocks, decoupling+ # dictionary credentials from the default user.+ DICT_READER = "dict_reader"__user_dict: Mapping[ClickHouseUser, tuple[str, str]] | None = Nonediff --git a/posthog/clickhouse/dictionaries.py b/posthog/clickhouse/dictionaries.pyindex 1314d3265c49..9a8bdbc7a003 100644--- a/posthog/clickhouse/dictionaries.py+++ b/posthog/clickhouse/dictionaries.py@@ -1,13 +1,16 @@from django.conf import settings+from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds+def dictionary_source_clickhouse(table: str) -> str:- """- Returns- """+ """Build a dictionary SOURCE(CLICKHOUSE(...)) clause authed as the dedicated+ low-privilege dict_reader user (falls back to the default user when the+ CLICKHOUSE_DICT_READER_* env vars are unset)."""+ user, password = get_clickhouse_creds(ClickHouseUser.DICT_READER)connection_settings = f"TABLE {table} DB '{settings.CLICKHOUSE_DATABASE}'"- if settings.CLICKHOUSE_USER:- connection_settings += f" USER '{settings.CLICKHOUSE_USER}'"- if settings.CLICKHOUSE_PASSWORD:- connection_settings += f" PASSWORD '{settings.CLICKHOUSE_PASSWORD}'"+ if user:+ connection_settings += f" USER '{user}'"+ if password:+ connection_settings += f" PASSWORD '{password}'"return f"SOURCE(CLICKHOUSE({connection_settings}))"diff --git a/posthog/models/channel_type/sql.py b/posthog/models/channel_type/sql.pyindex 939a2b6d3e73..1891da175e2e 100644--- a/posthog/models/channel_type/sql.py+++ b/posthog/models/channel_type/sql.py@@ -2,9 +2,10 @@ import osimport jsonfrom posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_credsfrom posthog.clickhouse.cluster import ON_CLUSTER_CLAUSEfrom posthog.clickhouse.table_engines import MergeTreeEngine, ReplicationScheme-from posthog.settings import CLICKHOUSE_CLUSTER, CLICKHOUSE_PASSWORD+from posthog.settings import CLICKHOUSE_CLUSTERCHANNEL_DEFINITION_TABLE_NAME = "channel_definition"CHANNEL_DEFINITION_DICTIONARY_NAME = "channel_definition_dict"@@ -58,6 +59,8 @@ INSERT INTO channel_definition (domain, kind, domain_type, type_if_paid, type_if""")+CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)+# Use COMPLEX_KEY_HASHED, as we have a composite keyCHANNEL_DEFINITION_DICTIONARY_SQL = lambda on_cluster=True: (f"""@@ -69,7 +72,7 @@ CREATE DICTIONARY IF NOT EXISTS {CHANNEL_DEFINITION_DICTIONARY_NAME} {ON_CLUSTERtype_if_organic Nullable(String))PRIMARY KEY domain, kind-SOURCE(CLICKHOUSE(TABLE '{CHANNEL_DEFINITION_TABLE_NAME}' PASSWORD '{CLICKHOUSE_PASSWORD}'))+SOURCE(CLICKHOUSE(TABLE '{CHANNEL_DEFINITION_TABLE_NAME}' USER '{CLICKHOUSE_DICT_READER_USER}' PASSWORD '{CLICKHOUSE_DICT_READER_PASSWORD}'))LIFETIME(MIN 3000 MAX 3600)LAYOUT(COMPLEX_KEY_HASHED())"""diff --git a/posthog/models/dmat_slot_assignments/sql.py b/posthog/models/dmat_slot_assignments/sql.pyindex aa6a39077ad5..13697fd1d8da 100644--- a/posthog/models/dmat_slot_assignments/sql.py+++ b/posthog/models/dmat_slot_assignments/sql.py@@ -15,9 +15,10 @@ and append-only would leave stale rows in the dict that silently overwritecolumns no longer assigned to that (team, slot_index)."""+from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_credsfrom posthog.clickhouse.cluster import ON_CLUSTER_CLAUSEfrom posthog.clickhouse.table_engines import ReplacingMergeTree, ReplicationScheme-from posthog.settings.data_stores import CLICKHOUSE_DATABASE, CLICKHOUSE_PASSWORD, CLICKHOUSE_USER+from posthog.settings.data_stores import CLICKHOUSE_DATABASEDMAT_SLOT_ASSIGNMENTS_TABLE_NAME = "dmat_slot_assignments"DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME = "dmat_slot_assignments_dict"@@ -63,6 +64,9 @@ FINAL""".replace("\n", " ").strip()+CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)++def DMAT_SLOT_ASSIGNMENTS_DICTIONARY_SQL(on_cluster: bool = False) -> str:return """CREATE DICTIONARY IF NOT EXISTS {dictionary_name} {on_cluster_clause} (@@ -77,8 +81,8 @@ LAYOUT(COMPLEX_KEY_HASHED())""".format(dictionary_name=f"`{DMAT_SLOT_ASSIGNMENTS_DICTIONARY_NAME}`",on_cluster_clause=ON_CLUSTER_CLAUSE(on_cluster),query=DMAT_SLOT_ASSIGNMENTS_DICTIONARY_QUERY(),- clickhouse_user=CLICKHOUSE_USER,- clickhouse_password=CLICKHOUSE_PASSWORD,+ clickhouse_user=CLICKHOUSE_DICT_READER_USER,+ clickhouse_password=CLICKHOUSE_DICT_READER_PASSWORD,)diff --git a/posthog/models/exchange_rate/sql.py b/posthog/models/exchange_rate/sql.pyindex 72884087b677..7fb311f6ee94 100644--- a/posthog/models/exchange_rate/sql.py+++ b/posthog/models/exchange_rate/sql.py@@ -3,9 +3,9 @@ import reimport csvimport datetime+from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_credsfrom posthog.clickhouse.cluster import ON_CLUSTER_CLAUSEfrom posthog.clickhouse.table_engines import ReplacingMergeTree-from posthog.settings import CLICKHOUSE_PASSWORD, CLICKHOUSE_USERfrom posthog.settings.data_stores import CLICKHOUSE_DATABASEfrom .currencies import SUPPORTED_CURRENCY_CODES@@ -204,6 +204,8 @@ WINDOW w AS ()EXCHANGE_RATE_DICTIONARY_QUERY = re.sub(r"\s\s+", " ", EXCHANGE_RATE_DICTIONARY_QUERY)+CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)+# Use RANGE_HASHED to simplify queries by date#@@ -236,8 +238,8 @@ RANGE(MIN start_date MAX end_date)""".format(on_cluster_clause=ON_CLUSTER_CLAUSE(on_cluster),decimal_precision=EXCHANGE_RATE_DECIMAL_PRECISION,query=EXCHANGE_RATE_DICTIONARY_QUERY,- clickhouse_user=CLICKHOUSE_USER,- clickhouse_password=CLICKHOUSE_PASSWORD,+ clickhouse_user=CLICKHOUSE_DICT_READER_USER,+ clickhouse_password=CLICKHOUSE_DICT_READER_PASSWORD,)diff --git a/posthog/models/person/sql.py b/posthog/models/person/sql.pyindex b9a600e691e9..e3da80ced03d 100644--- a/posthog/models/person/sql.py+++ b/posthog/models/person/sql.py@@ -1,6 +1,7 @@from django.conf import settingsfrom posthog.clickhouse.base_sql import COPY_ROWS_BETWEEN_TEAMS_BASE_SQL+from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_credsfrom posthog.clickhouse.cluster import ON_CLUSTER_CLAUSEfrom posthog.clickhouse.indexes import index_by_kafka_timestampfrom posthog.clickhouse.kafka_engine import (@@ -741,6 +742,7 @@ def CREATE_PERSON_DISTINCT_ID_OVERRIDES_DICTIONARY():This must be a function to ensure CLICKHOUSE_DATABASE is evaluated at runtime,not at module import time (which causes issues in E2E tests where env vars aren't loaded yet)."""+ clickhouse_user, clickhouse_password = get_clickhouse_creds(ClickHouseUser.DICT_READER)return """CREATE OR REPLACE DICTIONARY {database}.person_distinct_id_overrides_dict ON CLUSTER {cluster} (`team_id` Int64, -- team_id could be made hierarchical to save some space.@@ -750,7 +752,7 @@ CREATE OR REPLACE DICTIONARY {database}.person_distinct_id_overrides_dict ON CLUPRIMARY KEY team_id, distinct_id-- For our own sanity, we explicitly write out the group by query.SOURCE(CLICKHOUSE(- query 'SELECT team_id, distinct_id, argMax(person_id, version) AS person_id FROM {database}.person_distinct_id_overrides GROUP BY team_id, distinct_id'+ query 'SELECT team_id, distinct_id, argMax(person_id, version) AS person_id FROM {database}.person_distinct_id_overrides GROUP BY team_id, distinct_id' USER '{clickhouse_user}' PASSWORD '{clickhouse_password}'))LAYOUT(complex_key_hashed())-- ClickHouse will choose a time uniformly within 1 to 5 hours to reload the dictionary (update if necessary to meet SLAs).@@ -758,4 +760,6 @@ LIFETIME(MIN 3600 MAX 18000)""".format(cluster=settings.CLICKHOUSE_CLUSTER,database=settings.CLICKHOUSE_DATABASE,+ clickhouse_user=clickhouse_user,+ clickhouse_password=clickhouse_password,)diff --git a/posthog/models/person_overrides/sql.py b/posthog/models/person_overrides/sql.pyindex 0d472a1c8dfb..dd7ce9ab13f2 100644--- a/posthog/models/person_overrides/sql.py+++ b/posthog/models/person_overrides/sql.py@@ -2,6 +2,7 @@# `person_distinct_id_overrides` in `posthog.models.person.sql` for its replacement tables, or# https://github.com/PostHog/posthog/pull/23616 for additional context.+from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_credsfrom posthog.clickhouse.cluster import ON_CLUSTER_CLAUSEfrom posthog.clickhouse.table_engines import ReplacingMergeTree, ReplicationSchemefrom posthog.kafka_client.topics import KAFKA_PERSON_OVERRIDE@@ -147,6 +148,7 @@ GROUP BY"""# ClickHouse dictionaries allow us to JOIN events with their new override_person_ids (if any).+CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)PERSON_OVERRIDES_CREATE_DICTIONARY_SQL = f"""CREATE DICTIONARY IF NOT EXISTS `{CLICKHOUSE_DATABASE}`.`person_overrides_dict`{ON_CLUSTER_CLAUSE()} (@@ -155,7 +157,7 @@ PERSON_OVERRIDES_CREATE_DICTIONARY_SQL = f"""override_person_id UUID)PRIMARY KEY team_id, old_person_id- SOURCE(CLICKHOUSE(QUERY '{GET_LATEST_PERSON_OVERRIDE_ID_SQL}'))+ SOURCE(CLICKHOUSE(QUERY '{GET_LATEST_PERSON_OVERRIDE_ID_SQL}' USER '{CLICKHOUSE_DICT_READER_USER}' PASSWORD '{CLICKHOUSE_DICT_READER_PASSWORD}'))LAYOUT(COMPLEX_KEY_HASHED(PREALLOCATE 1))-- The LIFETIME setting indicates to ClickHouse to automatically update this dictionarydiff --git a/posthog/models/web_preaggregated/team_selection.py b/posthog/models/web_preaggregated/team_selection.pyindex 4181f5d479a6..4ae07514f377 100644--- a/posthog/models/web_preaggregated/team_selection.py+++ b/posthog/models/web_preaggregated/team_selection.py@@ -1,6 +1,7 @@+from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_credsfrom posthog.clickhouse.cluster import ON_CLUSTER_CLAUSEfrom posthog.clickhouse.table_engines import ReplacingMergeTree-from posthog.settings.data_stores import CLICKHOUSE_DATABASE, CLICKHOUSE_PASSWORD, CLICKHOUSE_USER+from posthog.settings.data_stores import CLICKHOUSE_DATABASEWEB_PRE_AGGREGATED_TEAM_SELECTION_TABLE_NAME = "web_pre_aggregated_teams"WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_NAME = "web_pre_aggregated_teams_dict"@@ -117,6 +118,9 @@ WHERE version > 0""".replace("\n", " ").strip()+CLICKHOUSE_DICT_READER_USER, CLICKHOUSE_DICT_READER_PASSWORD = get_clickhouse_creds(ClickHouseUser.DICT_READER)++def WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_SQL(on_cluster=True):return """CREATE DICTIONARY IF NOT EXISTS {dictionary_name} {on_cluster_clause} (@@ -129,8 +133,8 @@ LAYOUT(HASHED())""".format(dictionary_name=f"`{WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_NAME}`",on_cluster_clause=ON_CLUSTER_CLAUSE(on_cluster),query=WEB_PRE_AGGREGATED_TEAM_SELECTION_DICTIONARY_QUERY(),- clickhouse_user=CLICKHOUSE_USER,- clickhouse_password=CLICKHOUSE_PASSWORD,+ clickhouse_user=CLICKHOUSE_DICT_READER_USER,+ clickhouse_password=CLICKHOUSE_DICT_READER_PASSWORD,)