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.

fix(clickhouse): fall back to static password on an expired token (#104064)

Tommy Gilmore277d8694e5af
diff --git a/posthog/clickhouse/client/AGENTS.md b/posthog/clickhouse/client/AGENTS.md
index aa0f516dba33..e6a7483899d9 100644
--- a/posthog/clickhouse/client/AGENTS.md
+++ b/posthog/clickhouse/client/AGENTS.md
@@ -26,7 +26,8 @@ A pool that skips this branch stays on the static password with no error.
Resolve the credentials with `get_clickhouse_creds`.
When `_is_file_backed_user` is true, pop the static `password` and pass `credential_provider=creds.read_password` to `make_ch_pool`.
`read_password` reads the token file on each call.
-It falls back to the static password only when the file is unreadable or empty.
+It falls back to the static password when the file is unreadable or empty.
+For a user that keeps a static password, it also falls back when the token has expired or is about to expire.
`RefreshingChPool` re-stamps the live token on each checkout, so one pool survives a rotation.
The canonical native implementation is `get_pool`.
diff --git a/posthog/clickhouse/client/connection.py b/posthog/clickhouse/client/connection.py
index 236bd0ced3c8..95bc7b783f36 100644
--- a/posthog/clickhouse/client/connection.py
+++ b/posthog/clickhouse/client/connection.py
@@ -1,4 +1,7 @@
import os
+import json
+import time
+import base64
import logging
from collections.abc import Callable, Mapping
from contextlib import contextmanager
@@ -12,6 +15,7 @@ from django.conf import settings
from clickhouse_driver import Client as SyncClient
from clickhouse_pool import ChPool
+from prometheus_client import Counter
from posthog.dataclasses import frozen
@@ -114,6 +118,40 @@ class ClickHouseUser(StrEnum):
DICT_READER = "dict_reader"
+EXPIRED_TOKEN_PASSWORD_FALLBACK_COUNTER = Counter(
+ "posthog_clickhouse_expired_token_password_fallback",
+ "Times a ClickHouse user with a static password used it because its token file had expired.",
+ labelnames=["user"],
+)
+
+_TOKEN_EXPIRY_LEEWAY_SECONDS = 10
+
+
+def _token_expiry(token: str) -> float | None:
+ """Return the exp claim of a JWT, or None when it cannot be read.
+
+ The token is a projected ServiceAccount JWT. Decode the exp without verifying the signature. The
+ ch-podauth bridge still validates the token, so this only decides whether the token is worth sending.
+ """
+ parts = token.split(".")
+ if len(parts) != 3:
+ return None
+ try:
+ padding = "=" * (-len(parts[1]) % 4)
+ claims = json.loads(base64.urlsafe_b64decode(parts[1] + padding))
+ if not isinstance(claims, dict):
+ return None
+ exp = claims.get("exp")
+ return float(exp) if isinstance(exp, int | float) and not isinstance(exp, bool) else None
+ except (ValueError, TypeError, OverflowError):
+ return None
+
+
+def _token_is_expired(token: str) -> bool:
+ exp = _token_expiry(token)
+ return exp is not None and time.time() >= exp - _TOKEN_EXPIRY_LEEWAY_SECONDS
+
+
@frozen
class ClickHouseCredentials:
user: str
@@ -132,6 +170,12 @@ class ClickHouseCredentials:
logging.warning("clickhouse: %s is not readable, using the static fallback", path)
return self._validated_password(self.password)
if token:
+ # The kubelet stops refreshing a terminating pod's token, so a long drain can present
+ # an expired token the bridge rejects. The static password recovers it when the user keeps one.
+ if self.password and _token_is_expired(token):
+ logging.warning("clickhouse: %s has expired, using the static fallback", path)
+ EXPIRED_TOKEN_PASSWORD_FALLBACK_COUNTER.labels(user=self.user).inc()
+ return self._validated_password(self.password)
return token
logging.warning("clickhouse: %s is empty, using the static fallback", path)
return self._validated_password(self.password)
diff --git a/posthog/clickhouse/client/test/test_connection.py b/posthog/clickhouse/client/test/test_connection.py
index ae5385617783..a09010ddb4e1 100644
--- a/posthog/clickhouse/client/test/test_connection.py
+++ b/posthog/clickhouse/client/test/test_connection.py
@@ -1,8 +1,13 @@
+import json
+import time
+import base64
+
import pytest
from unittest.mock import patch
from posthog.clickhouse.client import connection
from posthog.clickhouse.client.connection import (
+ _TOKEN_EXPIRY_LEEWAY_SECONDS,
ClickHouseChPool,
ClickHouseCredentials,
ClickHouseUser,
@@ -105,6 +110,46 @@ def test_read_password_falls_back_when_file_unusable(tmp_path, state):
assert creds.read_password() == "fallback-secret"
+def _sa_token(exp: int) -> str:
+ def _seg(obj: dict) -> str:
+ return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()
+
+ return f"{_seg({'alg': 'RS256', 'typ': 'JWT'})}.{_seg({'aud': ['clickhouse-auth'], 'exp': exp})}.signature"
+
+
+ "password,token_kind,expect_static",
+ [
+ pytest.param("static-secret", "expired", True, id="armed-and-expired-uses-static"),
+ pytest.param("static-secret", "valid", False, id="armed-and-valid-uses-token"),
+ pytest.param("", "expired", False, id="token-only-keeps-expired-token"),
+ pytest.param("static-secret", "malformed", False, id="unparseable-token-is-sent"),
+ pytest.param("static-secret", "non_dict_payload", False, id="non-dict-payload-is-sent"),
+ pytest.param("static-secret", "oversized_exp", False, id="oversized-exp-is-sent"),
+ pytest.param("static-secret", "near_expiry", True, id="near-expiry-uses-static"),
+ ],
+)
+def test_read_password_uses_static_only_for_an_armed_user_with_an_expired_token(
+ tmp_path, password, token_kind, expect_static
+):
+ if token_kind == "malformed":
+ token = "not-a-jwt"
+ elif token_kind == "non_dict_payload":
+ payload = base64.urlsafe_b64encode(json.dumps([1, 2, 3]).encode()).rstrip(b"=").decode()
+ token = f"header.{payload}.signature"
+ elif token_kind == "oversized_exp":
+ token = _sa_token(10**400)
+ elif token_kind == "near_expiry":
+ token = _sa_token(int(time.time()) + _TOKEN_EXPIRY_LEEWAY_SECONDS - 1)
+ else:
+ token = _sa_token(int(time.time()) + (-3600 if token_kind == "expired" else 3600))
+ token_file = tmp_path / "token"
+ token_file.write_text(token)
+ creds = ClickHouseCredentials(user="datawarehouse", password=password, password_file=str(token_file))
+
+ assert creds.read_password() == (password if expect_static else token)
+
+
def test_password_file_env_registers_file_backed_user(monkeypatch, tmp_path):
token = tmp_path / "cohorts-token"
token.write_text("cohorts-token-value")