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(cohorts): clickhouse client CA setup (#73356)

Matheus Batista190b76dc98f7
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 35975feffbea..d4cb1f8f8441 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2278,14 +2278,18 @@ dependencies = [
"common-types",
"envconfig",
"governor",
+ "hyper-rustls 0.27.7",
+ "hyper-util",
"lifecycle",
"metrics",
"metrics-exporter-prometheus",
"proptest",
"rdkafka",
+ "rustls 0.23.37",
"serde",
"serde_json",
"sqlx",
+ "tempfile",
"thiserror 2.0.18",
"tokio",
"tokio-util",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 1cc5b1f47105..3d4fe29f491a 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -162,6 +162,10 @@ http-body-util = "0.1"
httpmock = "0.7.0"
mockito = "1"
hyper = { version = "1.9.0", features = ["server", "http1", "http2"] }
+# default-features off on purpose: the defaults drag in native-tokio (rustls-native-certs), and the
+# `clickhouse` crate already pins this dependency with defaults off. Enabling them here would flip
+# the feature set for every consumer of the shared dependency.
+hyper-rustls = { version = "0.27.7", default-features = false, features = ["aws-lc-rs", "http1", "tls12"] }
hyper-util = { version = "0.1.20", features = ["server", "server-graceful", "tokio", "http1", "http2"] }
itoa = "1.0.15"
libdeflater = "1"
@@ -177,6 +181,9 @@ prost = "0.13"
rand = "0.8.5"
rdkafka = { version = "0.37.0", features = ["tracing", "ssl-vendored"] }
reqwest = { version = "0.12.3", features = ["json", "stream"] }
+# Matches the provider `clickhouse`'s `rustls-tls` feature selects, so a direct `rustls::ClientConfig`
+# is built against the same crypto backend the crate would have used itself.
+rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs", "std", "tls12"] }
serde = { version = "1.0", features = ["derive"] }
serde_derive = { version = "1.0" }
serde_json = { version = "1.0" }
diff --git a/rust/cohort-seeder/Cargo.toml b/rust/cohort-seeder/Cargo.toml
index aecddb9e0d4e..38166981897f 100644
--- a/rust/cohort-seeder/Cargo.toml
+++ b/rust/cohort-seeder/Cargo.toml
@@ -28,10 +28,15 @@ common-liveness = { path = "../common/liveness" }
common-types = { path = "../common/types" }
envconfig = { workspace = true }
governor = { workspace = true }
+hyper-rustls = { workspace = true }
+# client-legacy: the `clickhouse` crate's `with_http_client` escape hatch only accepts a
+# `hyper_util::client::legacy::Client`.
+hyper-util = { workspace = true, features = ["client-legacy"] }
lifecycle = { path = "../common/lifecycle" }
metrics = { workspace = true }
metrics-exporter-prometheus = { workspace = true }
rdkafka = { workspace = true }
+rustls = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
@@ -44,3 +49,4 @@ uuid = { workspace = true }
[dev-dependencies]
proptest = "1"
+tempfile = "3"
diff --git a/rust/cohort-seeder/src/clickhouse/client.rs b/rust/cohort-seeder/src/clickhouse/client.rs
index 2be7506c180f..297f0cbe3b66 100644
--- a/rust/cohort-seeder/src/clickhouse/client.rs
+++ b/rust/cohort-seeder/src/clickhouse/client.rs
@@ -1,9 +1,21 @@
-//! ClickHouse client construction: endpoint precedence and the typed `join_algorithm` setting.
+//! ClickHouse client construction: endpoint precedence, the TLS posture, and the typed
+//! `join_algorithm` setting.
//!
//! Depends on `config` for the raw env strings; every value that shapes a ClickHouse query option is
//! parsed here so a misconfiguration fails startup instead of silently degrading query behavior.
use std::str::FromStr;
+use std::sync::Arc;
+use std::time::Duration;
+
+use hyper_util::client::legacy::connect::HttpConnector;
+use hyper_util::client::legacy::Client as HyperClient;
+use hyper_util::rt::TokioExecutor;
+use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
+use rustls::crypto::{aws_lc_rs, verify_tls12_signature, verify_tls13_signature, CryptoProvider};
+use rustls::pki_types::pem::{self, PemObject};
+use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
+use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
use crate::config::Config;
@@ -21,6 +33,12 @@ impl ClickHouseEndpoint {
pub fn as_str(&self) -> &str {
&self.0
}
+
+ /// Whether the resolved URL actually carries TLS. `clickhouse_secure` alone does not answer
+ /// this: an explicit `clickhouse_url` or a scheme-qualified host bypasses it entirely.
+ pub fn is_tls(&self) -> bool {
+ self.0.starts_with("https://")
+ }
}
fn resolve_endpoint(config: &Config) -> String {
@@ -115,12 +133,156 @@ impl FromStr for ClickHouseJoinAlgorithm {
#[error("unknown ClickHouse join algorithm {0:?}")]
pub struct UnknownJoinAlgorithm(pub String);
-pub fn build_client(config: &Config) -> Result<clickhouse::Client, UnknownJoinAlgorithm> {
+#[derive(Debug, thiserror::Error)]
+pub enum ClickHouseClientError {
+ #[error(transparent)]
+ JoinAlgorithm(#[from] UnknownJoinAlgorithm),
+ #[error("building the ClickHouse TLS configuration")]
+ Tls(#[from] rustls::Error),
+ #[error("reading the ClickHouse CA bundle at {path}")]
+ CaBundleUnreadable {
+ path: String,
+ #[source]
+ source: pem::Error,
+ },
+ #[error("the ClickHouse CA bundle at {path} contains no certificates")]
+ CaBundleEmpty { path: String },
+ #[error("CLICKHOUSE_CA is set but the endpoint {endpoint} is not https, so nothing would be verified")]
+ CaBundleWithoutTls { endpoint: String },
+}
+
+// Copied from `clickhouse` 0.13's default HTTP client; recheck on upgrade. The idle timeout must
+// stay under ClickHouse's server-side keep-alive or the pool hands out sockets the server closed.
+const TCP_KEEPALIVE: Duration = Duration::from_secs(60);
+const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// Accepts any server certificate, leaving only the handshake signatures checked. The wire stays
+/// encrypted, so the password never crosses in cleartext, but the server is not authenticated and
+/// anything able to redirect traffic can impersonate ClickHouse. Set `CLICKHOUSE_CA` to close that.
+#[derive(Debug)]
+struct AcceptAnyServerCert(Arc<CryptoProvider>);
+
+impl ServerCertVerifier for AcceptAnyServerCert {
+ fn verify_server_cert(
+ &self,
+ _end_entity: &CertificateDer<'_>,
+ _intermediates: &[CertificateDer<'_>],
+ _server_name: &ServerName<'_>,
+ _ocsp_response: &[u8],
+ _now: UnixTime,
+ ) -> Result<ServerCertVerified, rustls::Error> {
+ Ok(ServerCertVerified::assertion())
+ }
+
+ fn verify_tls12_signature(
+ &self,
+ message: &[u8],
+ cert: &CertificateDer<'_>,
+ dss: &DigitallySignedStruct,
+ ) -> Result<HandshakeSignatureValid, rustls::Error> {
+ verify_tls12_signature(
+ message,
+ cert,
+ dss,
+ &self.0.signature_verification_algorithms,
+ )
+ }
+
+ fn verify_tls13_signature(
+ &self,
+ message: &[u8],
+ cert: &CertificateDer<'_>,
+ dss: &DigitallySignedStruct,
+ ) -> Result<HandshakeSignatureValid, rustls::Error> {
+ verify_tls13_signature(
+ message,
+ cert,
+ dss,
+ &self.0.signature_verification_algorithms,
+ )
+ }
+
+ fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
+ self.0.signature_verification_algorithms.supported_schemes()
+ }
+}
+
+/// Validates against `ca_path` alone, hostname verification included. The only mode that
+/// authenticates the server.
+fn pinned_ca_tls_config(ca_path: &str) -> Result<ClientConfig, ClickHouseClientError> {
+ let unreadable = |source| ClickHouseClientError::CaBundleUnreadable {
+ path: ca_path.to_string(),
+ source,
+ };
+ let mut roots = rustls::RootCertStore::empty();
+ for certificate in CertificateDer::pem_file_iter(ca_path).map_err(unreadable)? {
+ roots.add(certificate.map_err(unreadable)?)?;
+ }
+ if roots.is_empty() {
+ return Err(ClickHouseClientError::CaBundleEmpty {
+ path: ca_path.to_string(),
+ });
+ }
+
+ Ok(
+ ClientConfig::builder_with_provider(Arc::new(aws_lc_rs::default_provider()))
+ .with_safe_default_protocol_versions()?
+ .with_root_certificates(roots)
+ .with_no_client_auth(),
+ )
+}
+
+/// Skips certificate validation. Hand-rolled because the crate's `rustls-tls` feature hardwires the
+/// Mozilla public roots and ignores the container trust store, leaving no way to express verify-off.
+fn unverified_tls_config() -> Result<ClientConfig, rustls::Error> {
+ let provider = Arc::new(aws_lc_rs::default_provider());
+ Ok(ClientConfig::builder_with_provider(provider.clone())
+ .with_safe_default_protocol_versions()?
+ .dangerous()
+ .with_custom_certificate_verifier(Arc::new(AcceptAnyServerCert(provider)))
+ .with_no_client_auth())
+}
+
+fn client_with_tls_config(tls_config: ClientConfig) -> clickhouse::Client {
+ let mut http_connector = HttpConnector::new();
+ http_connector.set_keepalive(Some(TCP_KEEPALIVE));
+ // The connector must pass https:// URLs through to the TLS layer below.
+ http_connector.enforce_http(false);
+
+ let connector = hyper_rustls::HttpsConnectorBuilder::new()
+ .with_tls_config(tls_config)
+ .https_or_http()
+ .enable_http1()
+ .wrap_connector(http_connector);
+
+ clickhouse::Client::with_http_client(
+ HyperClient::builder(TokioExecutor::new())
+ .pool_idle_timeout(POOL_IDLE_TIMEOUT)
+ .build(connector),
+ )
+}
+
+pub fn build_client(config: &Config) -> Result<clickhouse::Client, ClickHouseClientError> {
let join_algorithm = config
.seeder_ch_join_algorithm
.parse::<ClickHouseJoinAlgorithm>()?;
- Ok(clickhouse::Client::default()
- .with_url(ClickHouseEndpoint::resolve(config).as_str())
+ let endpoint = ClickHouseEndpoint::resolve(config);
+ // Ordered most to least trusted.
+ let client = if !config.clickhouse_ca.is_empty() {
+ // A CA over a plaintext endpoint verifies nothing; refuse rather than appear authenticated.
+ if !endpoint.is_tls() {
+ return Err(ClickHouseClientError::CaBundleWithoutTls {
+ endpoint: endpoint.as_str().to_string(),
+ });
+ }
+ client_with_tls_config(pinned_ca_tls_config(&config.clickhouse_ca)?)
+ } else if config.clickhouse_verify {
+ clickhouse::Client::default()
+ } else {
+ client_with_tls_config(unverified_tls_config()?)
+ };
+ Ok(client
+ .with_url(endpoint.as_str())
.with_user(&config.clickhouse_user)
.with_password(&config.clickhouse_password)
.with_database(&config.clickhouse_database)
@@ -149,6 +311,30 @@ mod tests {
use super::*;
+ /// Self-signed CA, no private key, only ever parsed as a trust anchor. Trust-anchor extraction
+ /// ignores validity dates, so the expiry is not load-bearing.
+ const TEST_CA_PEM: &str = "\
+-----BEGIN CERTIFICATE-----
+MIIDIzCCAgugAwIBAgIUW2/zpTFXp9JpJJz2hJJDv1pHD54wDQYJKoZIhvcNAQEL
+BQAwIDEeMBwGA1UEAwwVY29ob3J0LXNlZWRlciB0ZXN0IENBMCAXDTI2MDcyMzIz
+NTIyNFoYDzIxMjYwNjI5MjM1MjI0WjAgMR4wHAYDVQQDDBVjb2hvcnQtc2VlZGVy
+IHRlc3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDj3g1r5s1o
+ZADugBcdb+0ncknCRiyMDq57Z4Zb+I1f1PzPk5T+Hq26hNqiq7ijDmcjFmtOoOjQ
+XhoAHWE/iFUj08XX8lJkcnp19d35JwjzoV6h1O6ElBIpmDi/Hikl94I4bXf15Z6h
+cb4llbZLuBzRMnJRX2GTI11pXieX8MC2QZ2IAV7u2SBRWI8lrNhfBvlm81nMgVBP
+mQmzrfJkNagHy8eEtuRALhma+1D8Ic98PkDLCnfT/9N6/rOmqsM3kYX6ZTIHmvbw
+EdkE0LN/9nwZ95toCFbh04AzfiuIQdZdvWHJzvqBQVQ+D5qA8uZnEEYi7emoygw9
+gHTH68suU+jxAgMBAAGjUzBRMB0GA1UdDgQWBBQYGp6w7u6pkyB5CsLtYYcXshu6
+NzAfBgNVHSMEGDAWgBQYGp6w7u6pkyB5CsLtYYcXshu6NzAPBgNVHRMBAf8EBTAD
+AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAGLo61J42/13MsBQIiYAgwCpoGTLEYB5gi
+yXC2p+aYfmT7/2iQjT5CnAUroe00sesCyZizOj44/cirQ/WQpzZ3hK9zoY2zFGbB
+MuM4LnSF68m4Qz/VAyyD8j2x8y7+HPOtgmZMmfI8PVyXmjAEAmGANUEKTjCNBy8t
+G6H8MY0rMzThheRvUmG961VCWUzLLSlskJsjHTuW1iC9gxAJco7xq/rdp4MEYmDl
+uF6iDXFegd8Gus8bg975jX/DMTAahH4CoEV/gvjTCc+9IEEnXGxE/KpvXjyqEzvb
+LaIcbwSaQpbb1SSltcQ0krF2y351IH79a2fmV57qw3VZ5u17KbO4
+-----END CERTIFICATE-----
+";
+
fn default_config() -> Config {
Config::init_from_hashmap(&HashMap::new()).unwrap()
}
@@ -222,9 +408,86 @@ mod tests {
fn build_client_rejects_a_join_algorithm_typo_at_startup() {
let mut config = default_config();
config.seeder_ch_join_algorithm = "grace_hashh".to_string();
- assert_eq!(
- build_client(&config).err(),
- Some(UnknownJoinAlgorithm("grace_hashh".to_string()))
- );
+ assert!(matches!(
+ build_client(&config),
+ Err(ClickHouseClientError::JoinAlgorithm(UnknownJoinAlgorithm(algorithm)))
+ if algorithm == "grace_hashh"
+ ));
+ }
+
+ #[test]
+ fn unverified_tls_config_assembles() {
+ let mut config = default_config();
+ config.clickhouse_verify = false;
+ assert!(build_client(&config).is_ok());
+ }
+
+ /// Verify-off must accept a certificate that real validation would reject, otherwise the
+ /// unblock this mode exists for silently stops working.
+ #[test]
+ fn the_verify_off_verifier_accepts_an_untrusted_certificate() {
+ let verifier = AcceptAnyServerCert(Arc::new(aws_lc_rs::default_provider()));
+ assert!(verifier
+ .verify_server_cert(
+ // Not even a certificate: nothing about the peer is inspected in this mode.
+ &CertificateDer::from(b"garbage".to_vec()),
+ &[],
+ &ServerName::try_from("clickhouse.internal").unwrap(),
+ &[],
+ UnixTime::now(),
+ )
+ .is_ok());
+ assert!(!verifier.supported_verify_schemes().is_empty());
+ }
+
+ #[test]
+ fn a_pinned_ca_bundle_builds_a_verifying_client() {
+ let scratch = tempfile::tempdir().unwrap();
+ let bundle = scratch.path().join("ca.pem");
+ std::fs::write(&bundle, TEST_CA_PEM).unwrap();
+
+ let mut config = default_config();
+ config.clickhouse_secure = true;
+ config.clickhouse_ca = bundle.to_string_lossy().into_owned();
+ assert!(build_client(&config).is_ok());
+
+ // A CA over plaintext would verify nothing, so it must not look like it succeeded.
+ config.clickhouse_secure = false;
+ let Err(error) = build_client(&config) else {
+ panic!("a CA bundle over a plaintext endpoint built a client");
+ };
+ assert!(error.to_string().contains("is not https"), "{error}");
+ }
+
+ #[test]
+ fn an_unusable_ca_bundle_fails_startup_rather_than_downgrading() {
+ let scratch = tempfile::tempdir().unwrap();
+ let empty_bundle = scratch.path().join("empty_ca.pem");
+ std::fs::write(&empty_bundle, b"not a certificate\n").unwrap();
+
+ for (ca_path, expected) in [
+ (
+ "/nonexistent/ca.pem".to_string(),
+ "reading the ClickHouse CA bundle",
+ ),
+ (
+ empty_bundle.to_string_lossy().into_owned(),
+ "contains no certificates",
+ ),
+ ] {
+ let mut config = default_config();
+ config.clickhouse_secure = true;
+ // Verify-off must not rescue a broken CA bundle.
+ config.clickhouse_verify = false;
+ config.clickhouse_ca = ca_path.clone();
+ let Err(error) = build_client(&config) else {
+ panic!("CA bundle {ca_path:?} unexpectedly produced a working client");
+ };
+ let error = error.to_string();
+ assert!(
+ error.contains(expected),
+ "CA bundle {ca_path:?} gave {error:?}, expected it to mention {expected:?}"
+ );
+ }
}
}
diff --git a/rust/cohort-seeder/src/clickhouse/mod.rs b/rust/cohort-seeder/src/clickhouse/mod.rs
index 81fa5e40a399..d9f208a85f1d 100644
--- a/rust/cohort-seeder/src/clickhouse/mod.rs
+++ b/rust/cohort-seeder/src/clickhouse/mod.rs
@@ -6,5 +6,7 @@ pub mod row;
pub mod scanner;
pub mod sql;
-pub use client::{build_client, ClickHouseEndpoint, ClickHouseJoinAlgorithm};
+pub use client::{
+ build_client, ClickHouseClientError, ClickHouseEndpoint, ClickHouseJoinAlgorithm,
+};
pub use scanner::{ChunkScanner, ScanError};
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index 7029d9d75c19..a34ae9cde81f 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -135,6 +135,17 @@ pub struct Config {
#[envconfig(default = "false")]
pub clickhouse_secure: bool,
+ /// Validate the server certificate against the public root CAs. Defaults on so an unconfigured
+ /// deployment fails closed; the chart sets it to `false` for internal ClickHouse.
+ #[envconfig(default = "true")]
+ pub clickhouse_verify: bool,
+
+ /// PEM CA bundle to validate the ClickHouse server certificate against, as Django's
+ /// `CLICKHOUSE_CA`. Naming a CA is an explicit request to authenticate the server, so it wins
+ /// over `clickhouse_verify` rather than being downgraded by an inherited `CLICKHOUSE_VERIFY=false`.
+ #[envconfig(default = "")]
+ pub clickhouse_ca: String,
+
#[envconfig(from = "REALTIME_COHORT_TEAM_ALLOWLIST", default = "2")]
pub team_allowlist: TeamAllowlist,
@@ -288,6 +299,14 @@ mod tests {
);
}
+ /// The fail-closed TLS posture lives entirely in these defaults, so pin them.
+ #[test]
+ fn clickhouse_tls_defaults_are_fail_closed() {
+ let config = default_config();
+ assert!(config.clickhouse_verify);
+ assert!(config.clickhouse_ca.is_empty());
+ }
+
#[test]
fn service_limits_reject_disabled_tile_rate() {
let mut config = default_config();