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): make the cohort-seeder client token-aware (#106217)

Tommy Gilmore86474494e583
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 1d512754a06b..e0bccc980a1d 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2712,6 +2712,7 @@ dependencies = [
"anyhow",
"async-trait",
"axum 0.7.9",
+ "base64 0.22.1",
"chrono",
"chrono-tz",
"clap",
diff --git a/rust/cohort-seeder/Cargo.toml b/rust/cohort-seeder/Cargo.toml
index d5e523d0620b..3f85ad4ec7b3 100644
--- a/rust/cohort-seeder/Cargo.toml
+++ b/rust/cohort-seeder/Cargo.toml
@@ -19,6 +19,7 @@ path = "src/bin/reconcile_dispatch.rs"
anyhow = { workspace = true }
async-trait = { workspace = true }
axum = { workspace = true }
+base64 = { workspace = true }
chrono = { workspace = true }
chrono-tz = { workspace = true }
clap = { workspace = true }
diff --git a/rust/cohort-seeder/src/clickhouse/client.rs b/rust/cohort-seeder/src/clickhouse/client.rs
index d11b743a5246..da77aa93cc41 100644
--- a/rust/cohort-seeder/src/clickhouse/client.rs
+++ b/rust/cohort-seeder/src/clickhouse/client.rs
@@ -17,8 +17,31 @@ use rustls::pki_types::pem::{self, PemObject};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
+use super::credential::ClickHouseCredential;
use crate::config::Config;
+#[derive(Clone)]
+pub struct ClickHouseClient {
+ client: clickhouse::Client,
+ credential: Arc<ClickHouseCredential>,
+}
+
+impl ClickHouseClient {
+ pub fn new(client: clickhouse::Client, credential: ClickHouseCredential) -> Self {
+ Self {
+ client,
+ credential: Arc::new(credential),
+ }
+ }
+
+ pub fn query(&self, sql: &str) -> clickhouse::query::Query {
+ self.client
+ .clone()
+ .with_password(self.credential.current())
+ .query(sql)
+ }
+}
+
/// The resolved ClickHouse HTTP endpoint. Precedence is explicit URL > offline cluster host > host;
/// the scheme comes from `secure`, and a bare host gets the canonical port (8443 secure, 8123 plain).
/// Resolved exactly once by [`ClickHouseEndpoint::resolve`].
@@ -262,7 +285,7 @@ fn client_with_tls_config(tls_config: ClientConfig) -> clickhouse::Client {
)
}
-pub fn build_client(config: &Config) -> Result<clickhouse::Client, ClickHouseClientError> {
+pub fn build_client(config: &Config) -> Result<ClickHouseClient, ClickHouseClientError> {
let join_algorithm = config
.seeder_ch_join_algorithm
.parse::<ClickHouseJoinAlgorithm>()?;
@@ -281,10 +304,9 @@ pub fn build_client(config: &Config) -> Result<clickhouse::Client, ClickHouseCli
} else {
client_with_tls_config(unverified_tls_config()?)
};
- Ok(client
+ let client = client
.with_url(endpoint.as_str())
.with_user(&config.clickhouse_user)
- .with_password(&config.clickhouse_password)
.with_database(&config.clickhouse_database)
.with_option(
"max_execution_time",
@@ -304,7 +326,11 @@ pub fn build_client(config: &Config) -> Result<clickhouse::Client, ClickHouseCli
"max_bytes_in_set",
config.seeder_ch_max_bytes_in_set.to_string(),
)
- .with_option("join_algorithm", join_algorithm.as_str()))
+ .with_option("join_algorithm", join_algorithm.as_str());
+ Ok(ClickHouseClient::new(
+ client,
+ ClickHouseCredential::from_config(config),
+ ))
}
#[cfg(test)]
@@ -494,4 +520,43 @@ LaIcbwSaQpbb1SSltcQ0krF2y351IH79a2fmV57qw3VZ5u17KbO4
);
}
}
+
+ #[tokio::test]
+ async fn each_query_sends_the_token_file_as_it_is_when_the_query_is_built() {
+ let (sent_keys, mut received_keys) = tokio::sync::mpsc::unbounded_channel();
+ let server = axum::Router::new().fallback(move |headers: axum::http::HeaderMap| {
+ let sent_keys = sent_keys.clone();
+ async move {
+ let key = headers
+ .get("x-clickhouse-key")
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned);
+ sent_keys.send(key).unwrap();
+ }
+ });
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, server).await.unwrap() });
+
+ let scratch = tempfile::tempdir().unwrap();
+ let token_file = scratch.path().join("token");
+ let mut config = default_config();
+ config.clickhouse_url = format!("http://{address}");
+ config.clickhouse_password = "static".to_string();
+ let static_client = build_client(&config).unwrap();
+ static_client.query("SELECT 1").execute().await.unwrap();
+ assert_eq!(
+ received_keys.recv().await.unwrap().as_deref(),
+ Some("static")
+ );
+
+ config.clickhouse_password_file = token_file.to_string_lossy().into_owned();
+ let client = build_client(&config).unwrap();
+
+ for token in ["first-token", "rotated-token"] {
+ std::fs::write(&token_file, token).unwrap();
+ client.query("SELECT 1").execute().await.unwrap();
+ assert_eq!(received_keys.recv().await.unwrap().as_deref(), Some(token));
+ }
+ }
}
diff --git a/rust/cohort-seeder/src/clickhouse/credential.rs b/rust/cohort-seeder/src/clickhouse/credential.rs
new file mode 100644
index 000000000000..a65a7e8ab4e5
--- /dev/null
+++ b/rust/cohort-seeder/src/clickhouse/credential.rs
@@ -0,0 +1,241 @@
+use std::fs;
+use std::path::PathBuf;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
+use base64::Engine;
+use metrics::counter;
+use tracing::warn;
+
+use crate::config::Config;
+use crate::observability::metrics::CLICKHOUSE_PASSWORD_FALLBACK;
+
+const TOKEN_EXPIRY_LEEWAY_SECS: f64 = 10.0;
+
+#[derive(Default)]
+pub struct ClickHouseCredential {
+ static_password: String,
+ token_file: Option<PathBuf>,
+}
+
+impl ClickHouseCredential {
+ pub fn new(static_password: String, token_file: &str) -> Self {
+ Self {
+ static_password,
+ token_file: (!token_file.is_empty()).then(|| PathBuf::from(token_file)),
+ }
+ }
+
+ pub fn from_config(config: &Config) -> Self {
+ Self::new(
+ config.clickhouse_password.clone(),
+ &config.clickhouse_password_file,
+ )
+ }
+
+ pub fn current(&self) -> String {
+ self.current_at(SystemTime::now())
+ }
+
+ fn current_at(&self, now: SystemTime) -> String {
+ let Some(token_file) = &self.token_file else {
+ return self.static_password.clone();
+ };
+ let path = token_file.display();
+ let token = match fs::read_to_string(token_file) {
+ Ok(contents) => contents.trim().to_owned(),
+ Err(error) => {
+ warn!(%error, %path, "ClickHouse token file is not readable, using the static password");
+ counter!(CLICKHOUSE_PASSWORD_FALLBACK, "reason" => "unreadable").increment(1);
+ return self.static_password.clone();
+ }
+ };
+ if token.is_empty() {
+ warn!(%path, "ClickHouse token file is empty, using the static password");
+ counter!(CLICKHOUSE_PASSWORD_FALLBACK, "reason" => "empty").increment(1);
+ return self.static_password.clone();
+ }
+ // The kubelet stops refreshing the token of a terminating pod, so a slow shutdown can leave
+ // an expired token that ClickHouse rejects.
+ if !self.static_password.is_empty() && token_expired(&token, now) {
+ warn!(%path, "ClickHouse token has expired, using the static password");
+ counter!(CLICKHOUSE_PASSWORD_FALLBACK, "reason" => "expired").increment(1);
+ return self.static_password.clone();
+ }
+ token
+ }
+}
+
+/// Whether a JWT's `exp` claim has passed. The signature is not verified, because the ch-podauth
+/// bridge validates the token. A token whose `exp` cannot be read counts as not expired.
+fn token_expired(token: &str, now: SystemTime) -> bool {
+ let Some(exp) = token_expiry(token) else {
+ return false;
+ };
+ let now = now
+ .duration_since(UNIX_EPOCH)
+ .map_or(0.0, |elapsed| elapsed.as_secs_f64());
+ now >= exp - TOKEN_EXPIRY_LEEWAY_SECS
+}
+
+fn token_expiry(token: &str) -> Option<f64> {
+ let mut parts = token.split('.');
+ let (Some(_header), Some(payload), Some(_signature), None) =
+ (parts.next(), parts.next(), parts.next(), parts.next())
+ else {
+ return None;
+ };
+ let claims = URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?;
+ let claims: serde_json::Value = serde_json::from_slice(&claims).ok()?;
+ claims.get("exp")?.as_f64()
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::HashMap;
+ use std::time::Duration;
+
+ use envconfig::Envconfig;
+
+ use super::*;
+
+ const NOW_SECS: u64 = 1_000_000;
+
+ fn now() -> SystemTime {
+ UNIX_EPOCH + Duration::from_secs(NOW_SECS)
+ }
+
+ fn jwt(payload: &str) -> String {
+ format!(
+ "{}.{}.signature",
+ URL_SAFE_NO_PAD.encode(r#"{"alg":"RS256"}"#),
+ URL_SAFE_NO_PAD.encode(payload)
+ )
+ }
+
+ fn jwt_expiring_at(exp: u64) -> String {
+ jwt(&format!(r#"{{"exp":{exp}}}"#))
+ }
+
+ #[test]
+ fn the_token_file_supersedes_the_static_password_only_while_it_is_usable() {
+ let scratch = tempfile::tempdir().unwrap();
+ let live = jwt_expiring_at(NOW_SECS + 3600);
+ // `?>?>?>` encodes to `-` and `_`, where the URL-safe and standard alphabets differ.
+ let expired = jwt(&format!(r#"{{"exp":{},"sub":"?>?>?>"}}"#, NOW_SECS - 60));
+ let within_leeway = jwt_expiring_at(NOW_SECS + 5);
+ let padded_expired = {
+ let (header_and_payload, _signature) = expired.rsplit_once('.').unwrap();
+ format!("{header_and_payload}==.signature")
+ };
+ let no_exp = jwt(r#"{"sub":"system:serviceaccount:posthog:cohort-seeder"}"#);
+
+ let cases = [
+ (
+ "live token",
+ Some(format!("{live}\n")),
+ "static",
+ live.clone(),
+ None,
+ ),
+ (
+ "missing file",
+ None,
+ "static",
+ "static".into(),
+ Some("unreadable"),
+ ),
+ (
+ "empty file",
+ Some(" \n".into()),
+ "static",
+ "static".into(),
+ Some("empty"),
+ ),
+ (
+ "expired token",
+ Some(expired.clone()),
+ "static",
+ "static".into(),
+ Some("expired"),
+ ),
+ (
+ "expired token, no static",
+ Some(expired.clone()),
+ "",
+ expired.clone(),
+ None,
+ ),
+ (
+ "inside the leeway",
+ Some(within_leeway),
+ "static",
+ "static".into(),
+ Some("expired"),
+ ),
+ (
+ "padded payload",
+ Some(padded_expired),
+ "static",
+ "static".into(),
+ Some("expired"),
+ ),
+ ("no exp claim", Some(no_exp.clone()), "static", no_exp, None),
+ (
+ "opaque token",
+ Some("not-a-jwt".into()),
+ "static",
+ "not-a-jwt".into(),
+ None,
+ ),
+ ];
+ for (case, contents, static_password, expected, fallback_reason) in cases {
+ let token_file = scratch.path().join(case.replace(' ', "_"));
+ if let Some(contents) = contents {
+ std::fs::write(&token_file, contents).unwrap();
+ }
+ let credential =
+ ClickHouseCredential::new(static_password.into(), token_file.to_str().unwrap());
+ let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder();
+ let handle = recorder.handle();
+ let password = metrics::with_local_recorder(&recorder, || credential.current_at(now()));
+ assert_eq!(password, expected, "{case}");
+ let rendered = handle.render();
+ match fallback_reason {
+ Some(reason) => assert!(
+ rendered.contains(&format!(
+ "{CLICKHOUSE_PASSWORD_FALLBACK}{{reason=\"{reason}\"}} 1"
+ )),
+ "{case} did not count a {reason} fallback:\n{rendered}"
+ ),
+ None => assert!(
+ !rendered.contains(CLICKHOUSE_PASSWORD_FALLBACK),
+ "{case} counted a fallback:\n{rendered}"
+ ),
+ }
+ }
+ }
+
+ #[test]
+ fn the_token_file_comes_from_clickhouse_password_file() {
+ let scratch = tempfile::tempdir().unwrap();
+ let token_file = scratch.path().join("token");
+ std::fs::write(&token_file, "the-token").unwrap();
+ let mut env = HashMap::from([("CLICKHOUSE_PASSWORD".to_string(), "static".to_string())]);
+ let static_only = Config::init_from_hashmap(&env).unwrap();
+ assert_eq!(
+ ClickHouseCredential::from_config(&static_only).current(),
+ "static"
+ );
+
+ env.insert(
+ "CLICKHOUSE_PASSWORD_FILE".to_string(),
+ token_file.to_string_lossy().into_owned(),
+ );
+ let with_token = Config::init_from_hashmap(&env).unwrap();
+ assert_eq!(
+ ClickHouseCredential::from_config(&with_token).current(),
+ "the-token"
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/clickhouse/mod.rs b/rust/cohort-seeder/src/clickhouse/mod.rs
index babdf3b9ae36..7c9e8cdd5055 100644
--- a/rust/cohort-seeder/src/clickhouse/mod.rs
+++ b/rust/cohort-seeder/src/clickhouse/mod.rs
@@ -3,6 +3,7 @@
//! `config` (plus the `clickhouse` crate); never on `store` or `kafka`.
pub mod client;
+pub mod credential;
pub mod log_comment;
pub mod person_scanner;
pub mod person_sql;
@@ -12,8 +13,10 @@ pub mod scanner;
pub mod sql;
pub use client::{
- build_client, ClickHouseClientError, ClickHouseEndpoint, ClickHouseJoinAlgorithm,
+ build_client, ClickHouseClient, ClickHouseClientError, ClickHouseEndpoint,
+ ClickHouseJoinAlgorithm,
};
+pub use credential::ClickHouseCredential;
pub use log_comment::{ScanLogComment, LOG_COMMENT_OPTION};
pub use person_scanner::{PersonRow, PersonScanError, PersonScanner};
pub use person_sql::PersonScanSpec;
diff --git a/rust/cohort-seeder/src/clickhouse/person_scanner.rs b/rust/cohort-seeder/src/clickhouse/person_scanner.rs
index 308d46169913..ccefd96b8ff5 100644
--- a/rust/cohort-seeder/src/clickhouse/person_scanner.rs
+++ b/rust/cohort-seeder/src/clickhouse/person_scanner.rs
@@ -12,6 +12,7 @@ use tokio_util::sync::CancellationToken;
use tracing::warn;
use uuid::Uuid;
+use super::client::ClickHouseClient;
use super::log_comment::{ScanLogComment, LOG_COMMENT_OPTION};
use super::person_sql::{person_boundaries_sql, person_scan_sql, PersonScanSpec};
use super::scan_volume::{self, ScanKind};
@@ -31,11 +32,11 @@ struct PersonIdRow {
#[derive(Clone)]
pub struct PersonScanner {
- client: clickhouse::Client,
+ client: ClickHouseClient,
}
impl PersonScanner {
- pub fn new(client: clickhouse::Client) -> Self {
+ pub fn new(client: ClickHouseClient) -> Self {
Self { client }
}
diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rs
index 04cdc7285879..c6d326e0ab0e 100644
--- a/rust/cohort-seeder/src/clickhouse/scanner.rs
+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs
@@ -17,6 +17,7 @@ use metrics::{counter, histogram};
use tokio_util::sync::CancellationToken;
use tracing::{info, warn};
+use super::client::ClickHouseClient;
use super::log_comment::{ScanLogComment, LOG_COMMENT_OPTION};
use super::row::{row_to_event, EventRow};
use super::scan_volume::{self, ScanKind};
@@ -36,7 +37,7 @@ use crate::observability::metrics::{
#[derive(Clone)]
pub struct ChunkScanner {
- client: clickhouse::Client,
+ client: ClickHouseClient,
/// Only what bounds the `team_id` label on the projection metrics. The scanner makes no
/// admission decision from it — discovery already did, and re-deciding here would give one
/// chunk a second, quieter place to be dropped.
@@ -51,7 +52,7 @@ pub struct ChunkScanner {
}
impl ChunkScanner {
- pub fn new(client: clickhouse::Client, allowlist: TeamAllowlist, shadow_compare: bool) -> Self {
+ pub fn new(client: ClickHouseClient, allowlist: TeamAllowlist, shadow_compare: bool) -> Self {
Self {
client,
allowlist,
@@ -794,7 +795,7 @@ mod tests {
#[test]
fn the_projection_metrics_report_each_blob_by_its_own_rule() {
let scanner = ChunkScanner::new(
- clickhouse::Client::default(),
+ ClickHouseClient::new(clickhouse::Client::default(), Default::default()),
TeamAllowlist::Only(std::collections::HashSet::from([2])),
false,
);
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index 962de7c955ff..f153136783ce 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -129,6 +129,9 @@ pub struct Config {
#[envconfig(default = "")]
pub clickhouse_password: String,
+ #[envconfig(default = "")]
+ pub clickhouse_password_file: String,
+
#[envconfig(default = "default")]
pub clickhouse_database: String,
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index 14c54888c626..8c1821095263 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -108,6 +108,7 @@ pub const CHUNK_SCAN_DURATION_SECONDS: &str = "seeder_chunk_scan_duration_second
pub const SCAN_RECEIVED_BYTES: &str = "seeder_scan_received_bytes_total";
/// Decompressed bytes a scan cursor produced, labelled by `kind` (counter).
pub const SCAN_DECODED_BYTES: &str = "seeder_scan_decoded_bytes_total";
+pub const CLICKHOUSE_PASSWORD_FALLBACK: &str = "seeder_clickhouse_password_fallback_total";
pub const ROWS_SCANNED: &str = "seeder_rows_scanned_total";
pub const EVENTS_SKIPPED: &str = "seeder_events_skipped_total";
pub const CONDITIONS_EVALUATED: &str = "seeder_conditions_evaluated_total";
diff --git a/rust/cohort-seeder/tests/ch_person_key_filter.rs b/rust/cohort-seeder/tests/ch_person_key_filter.rs
index 02437e23bef5..77e1329d4e5b 100644
--- a/rust/cohort-seeder/tests/ch_person_key_filter.rs
+++ b/rust/cohort-seeder/tests/ch_person_key_filter.rs
@@ -22,9 +22,10 @@
use std::collections::{BTreeMap, BTreeSet};
-use clickhouse::{Client, Row};
+use clickhouse::Row;
use cohort_seeder::clickhouse::client::build_client;
use cohort_seeder::clickhouse::person_sql::{person_scan_sql, PersonScanSpec};
+use cohort_seeder::clickhouse::ClickHouseClient;
use cohort_seeder::config::Config;
use cohort_seeder::domain::{PersonRange, ProjectedKeys, UtcMillis};
use envconfig::Envconfig;
@@ -227,13 +228,13 @@ async fn the_repeated_aggregate_is_computed_once() {
);
}
-fn connect() -> Client {
+fn connect() -> ClickHouseClient {
let config = Config::init_from_env().expect("the seeder config falls back to its defaults");
build_client(&config).expect("the default ClickHouse client builds")
}
/// Run the production predicate over `blobs`, in the blobs' own order.
-async fn admit_all(client: &Client, keys: &[&str], blobs: &[&str]) -> Vec<bool> {
+async fn admit_all(client: &ClickHouseClient, keys: &[&str], blobs: &[&str]) -> Vec<bool> {
let sql = format!(
"WITH ? AS blobs\nSELECT index, {} AS admitted\nFROM (SELECT arrayJoin(arrayEnumerate(blobs)) AS index, blobs[index] AS blob)\nORDER BY index",
predicate_over("blob", keys),
diff --git a/rust/cohort-seeder/tests/ch_rebuild_equivalence.rs b/rust/cohort-seeder/tests/ch_rebuild_equivalence.rs
index a01358ef35b1..11a2973031ea 100644
--- a/rust/cohort-seeder/tests/ch_rebuild_equivalence.rs
+++ b/rust/cohort-seeder/tests/ch_rebuild_equivalence.rs
@@ -17,9 +17,10 @@
use std::collections::{BTreeMap, BTreeSet};
-use clickhouse::{Client, Row};
+use clickhouse::Row;
use cohort_seeder::clickhouse::client::build_client;
use cohort_seeder::clickhouse::sql::rebuild_expr;
+use cohort_seeder::clickhouse::ClickHouseClient;
use cohort_seeder::config::Config;
use cohort_seeder::domain::ProjectedKeys;
use envconfig::Envconfig;
@@ -223,13 +224,13 @@ async fn a_number_clickhouse_cannot_represent_passes_the_whole_blob_through() {
}
}
-fn connect() -> Client {
+fn connect() -> ClickHouseClient {
let config = Config::init_from_env().expect("the seeder config falls back to its defaults");
build_client(&config).expect("the default ClickHouse client builds")
}
/// Run the production rebuild expression over `blobs`, in the blobs' own order.
-async fn rebuild_all(client: &Client, keys: &[&str], blobs: &[&str]) -> Vec<String> {
+async fn rebuild_all(client: &ClickHouseClient, keys: &[&str], blobs: &[&str]) -> Vec<String> {
let keys = ProjectedKeys::new(keys.iter().map(|key| (*key).to_owned()).collect())
.expect("every corpus case names at least one key");
let sql = format!(