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 recording-api client token-aware (#106837)

Tommy Gilmore9bf0e4ae2ee1
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
index 5c29aa7a6596..ed8c82b96258 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
@@ -45,6 +45,7 @@ export type SessionRecordingApiConfig = {
CLICKHOUSE_DATABASE: string
CLICKHOUSE_USER: string
CLICKHOUSE_PASSWORD: string | undefined
+ CLICKHOUSE_PASSWORD_FILE: string
CLICKHOUSE_SECURE: boolean
}
@@ -104,6 +105,7 @@ export type SessionRecordingConfig = {
export function getDefaultSessionRecordingApiConfig(): SessionRecordingApiConfig {
return {
...getDefaultClickhouseConfig(),
+ CLICKHOUSE_PASSWORD_FILE: '',
SESSION_RECORDING_API_REDIS_HOST: '127.0.0.1',
SESSION_RECORDING_API_REDIS_PORT: 6379,
SESSION_RECORDING_KMS_ENDPOINT: undefined,
diff --git a/nodejs/src/session-replay/recording-api/clickhouse-credential.test.ts b/nodejs/src/session-replay/recording-api/clickhouse-credential.test.ts
new file mode 100644
index 000000000000..9bed57dd9911
--- /dev/null
+++ b/nodejs/src/session-replay/recording-api/clickhouse-credential.test.ts
@@ -0,0 +1,102 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { register } from 'prom-client'
+
+import { overrideConfigWithEnv } from '~/common/config/config'
+import { logger } from '~/common/utils/logger'
+import { getDefaultSessionRecordingApiConfig } from '~/ingestion/pipelines/sessionreplay/config'
+
+import { ClickHouseCredential } from './clickhouse-credential'
+
+const NOW = 1_000_000
+const FALLBACK_METRIC = 'recording_api_clickhouse_password_fallback_total'
+
+const base64url = (text: string): string => Buffer.from(text).toString('base64url')
+const unsignedToken = (payload: string): string =>
+ `${base64url('{"alg":"RS256","typ":"JWT"}')}.${base64url(payload)}.signature`
+const tokenExpiringAt = (exp: number): string => unsignedToken(JSON.stringify({ exp }))
+const liveToken = tokenExpiringAt(NOW + 3600)
+const expiredToken = tokenExpiringAt(NOW - 60)
+const withinLeewayToken = tokenExpiringAt(NOW + 5)
+const noExpToken = unsignedToken(JSON.stringify({ sub: 'system:serviceaccount:recording-api:recording-api' }))
+const malformedPayloadToken = unsignedToken('not-json')
+
+describe('ClickHouseCredential', () => {
+ let dir: string
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'clickhouse-credential-'))
+ register.getSingleMetric(FALLBACK_METRIC)?.reset()
+ })
+
+ afterEach(() => {
+ rmSync(dir, { recursive: true, force: true })
+ jest.restoreAllMocks()
+ })
+
+ it.each([
+ ['live token', `${liveToken}\n`, 'static', liveToken, undefined],
+ ['no token file configured', null, 'static', 'static', undefined],
+ ['missing file', undefined, 'static', 'static', 'unreadable'],
+ ['missing file, no static', undefined, '', '', 'unreadable'],
+ ['empty file', ' \n', 'static', 'static', 'empty'],
+ ['expired token', expiredToken, 'static', 'static', 'expired'],
+ ['expired token, no static', expiredToken, '', expiredToken, undefined],
+ ['inside the leeway', withinLeewayToken, 'static', 'static', 'expired'],
+ ['no exp claim', noExpToken, 'static', noExpToken, undefined],
+ ['malformed payload', malformedPayloadToken, 'static', malformedPayloadToken, undefined],
+ ['opaque token', 'not-a-jwt', 'static', 'not-a-jwt', undefined],
+ ])('%s', async (_case, contents, staticPassword, expected, fallbackReason) => {
+ const tokenFile = contents === null ? '' : join(dir, 'token')
+ if (typeof contents === 'string') {
+ writeFileSync(tokenFile, contents)
+ }
+ const credential = new ClickHouseCredential('recording_api', staticPassword, tokenFile)
+
+ await expect(credential.password(NOW)).resolves.toEqual(expected)
+ const fallbacks = (await register.getSingleMetric(FALLBACK_METRIC)?.get())?.values ?? []
+ expect(fallbacks.map(({ labels }) => labels.reason)).toEqual(fallbackReason ? [fallbackReason] : [])
+ })
+
+ it('counts every fallback but warns only when the fallback reason changes', async () => {
+ const warn = jest.spyOn(logger, 'warn').mockImplementation(() => undefined)
+ const tokenFile = join(dir, 'token')
+ const credential = new ClickHouseCredential('recording_api', 'static', tokenFile)
+
+ await credential.password(NOW)
+ await credential.password(NOW)
+ writeFileSync(tokenFile, '')
+ await credential.password(NOW)
+ writeFileSync(tokenFile, liveToken)
+ await credential.password(NOW)
+ writeFileSync(tokenFile, '')
+ await credential.password(NOW)
+
+ expect(warn.mock.calls.map(([message]) => message)).toEqual([
+ expect.stringContaining('not readable'),
+ expect.stringContaining('empty'),
+ expect.stringContaining('empty'),
+ ])
+ const fallbacks = (await register.getSingleMetric(FALLBACK_METRIC)?.get())?.values ?? []
+ expect(fallbacks.map(({ labels, value }) => [labels.reason, value])).toEqual([
+ ['unreadable', 2],
+ ['empty', 2],
+ ])
+ })
+
+ it('reads the token file named by CLICKHOUSE_PASSWORD_FILE', async () => {
+ const tokenFile = join(dir, 'token')
+ writeFileSync(tokenFile, 'the-token')
+ const config = overrideConfigWithEnv(getDefaultSessionRecordingApiConfig(), {
+ CLICKHOUSE_USER: 'recording_api',
+ CLICKHOUSE_PASSWORD: 'static',
+ CLICKHOUSE_PASSWORD_FILE: tokenFile,
+ })
+
+ await expect(ClickHouseCredential.fromConfig(config).auth()).resolves.toEqual({
+ username: 'recording_api',
+ password: 'the-token',
+ })
+ })
+})
diff --git a/nodejs/src/session-replay/recording-api/clickhouse-credential.ts b/nodejs/src/session-replay/recording-api/clickhouse-credential.ts
new file mode 100644
index 000000000000..610a748d1705
--- /dev/null
+++ b/nodejs/src/session-replay/recording-api/clickhouse-credential.ts
@@ -0,0 +1,91 @@
+import { readFile } from 'fs/promises'
+import jwt from 'jsonwebtoken'
+
+import { logger, serializeError } from '~/common/utils/logger'
+
+import { ClickHousePasswordFallbackReason, RecordingApiMetrics } from './metrics'
+import { RecordingApiConfig } from './types'
+
+const TOKEN_EXPIRY_LEEWAY_SECONDS = 10
+
+export class ClickHouseCredential {
+ private lastFallbackReason: ClickHousePasswordFallbackReason | null = null
+
+ constructor(
+ private readonly username: string,
+ private readonly staticPassword: string,
+ private readonly tokenFile: string
+ ) {}
+
+ static fromConfig(
+ config: Pick<RecordingApiConfig, 'CLICKHOUSE_USER' | 'CLICKHOUSE_PASSWORD' | 'CLICKHOUSE_PASSWORD_FILE'>
+ ): ClickHouseCredential {
+ return new ClickHouseCredential(
+ config.CLICKHOUSE_USER,
+ config.CLICKHOUSE_PASSWORD ?? '',
+ config.CLICKHOUSE_PASSWORD_FILE
+ )
+ }
+
+ async auth(): Promise<{ username: string; password: string }> {
+ return { username: this.username, password: await this.password() }
+ }
+
+ async password(nowSeconds: number = Date.now() / 1000): Promise<string> {
+ if (!this.tokenFile) {
+ return this.staticPassword
+ }
+ const path = this.tokenFile
+ let token: string
+ try {
+ token = (await readFile(path, 'utf8')).trim()
+ } catch (error) {
+ return this.fallBackToStaticPassword(
+ 'unreadable',
+ '[RecordingApi] ClickHouse token file is not readable, using the static password',
+ { path, error: serializeError(error) }
+ )
+ }
+ if (!token) {
+ return this.fallBackToStaticPassword(
+ 'empty',
+ '[RecordingApi] ClickHouse token file is empty, using the static password',
+ { path }
+ )
+ }
+ // The kubelet stops refreshing the token of a terminating pod, and ClickHouse rejects an expired token.
+ if (this.staticPassword && tokenExpired(token, nowSeconds)) {
+ return this.fallBackToStaticPassword(
+ 'expired',
+ '[RecordingApi] ClickHouse token has expired, using the static password',
+ { path }
+ )
+ }
+ this.lastFallbackReason = null
+ return token
+ }
+
+ private fallBackToStaticPassword(
+ reason: ClickHousePasswordFallbackReason,
+ message: string,
+ context: Record<string, unknown>
+ ): string {
+ RecordingApiMetrics.incrementClickhousePasswordFallback(reason)
+ // This runs for every query and the counter counts each fallback, so warn only when the reason changes.
+ if (reason !== this.lastFallbackReason) {
+ logger.warn(message, context)
+ this.lastFallbackReason = reason
+ }
+ return this.staticPassword
+ }
+}
+
+function tokenExpired(token: string, nowSeconds: number): boolean {
+ let exp: unknown
+ try {
+ exp = jwt.decode(token, { json: true })?.exp
+ } catch {
+ return false
+ }
+ return typeof exp === 'number' && nowSeconds >= exp - TOKEN_EXPIRY_LEEWAY_SECONDS
+}
diff --git a/nodejs/src/session-replay/recording-api/metrics.ts b/nodejs/src/session-replay/recording-api/metrics.ts
index 83b30f81062d..38875d8658ff 100644
--- a/nodejs/src/session-replay/recording-api/metrics.ts
+++ b/nodejs/src/session-replay/recording-api/metrics.ts
@@ -1,5 +1,7 @@
import { Counter, Histogram } from 'prom-client'
+export type ClickHousePasswordFallbackReason = 'unreadable' | 'empty' | 'expired'
+
export class RecordingApiMetrics {
private static readonly getBlockDuration = new Histogram({
name: 'recording_api_get_block_duration_seconds',
@@ -63,4 +65,14 @@ export class RecordingApiMetrics {
public static incrementCleanupFailure(step: 'kafka' | 'postgres' | 'activity_log'): void {
this.cleanupFailures.labels({ step }).inc()
}
+
+ private static readonly clickhousePasswordFallbacks = new Counter({
+ name: 'recording_api_clickhouse_password_fallback_total',
+ help: 'ClickHouse queries that sent the static password instead of the token file',
+ labelNames: ['reason'],
+ })
+
+ public static incrementClickhousePasswordFallback(reason: ClickHousePasswordFallbackReason): void {
+ this.clickhousePasswordFallbacks.labels({ reason }).inc()
+ }
}
diff --git a/nodejs/src/session-replay/recording-api/recording-api.ts b/nodejs/src/session-replay/recording-api/recording-api.ts
index 5dee568b4ef3..69ee72c7ee87 100644
--- a/nodejs/src/session-replay/recording-api/recording-api.ts
+++ b/nodejs/src/session-replay/recording-api/recording-api.ts
@@ -17,6 +17,7 @@ import { ReplayEventsOutput, SessionFeaturesOutput } from '~/ingestion/pipelines
import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginServerService, RedisPool } from '~/types'
import { createRecordingApiAuthMiddleware } from './auth'
+import { ClickHouseCredential } from './clickhouse-credential'
import { RecordingService } from './recording-service'
import { DeleteRecordingsBodySchema, GetBlockQuerySchema, RecordingParamsSchema, TeamParamsSchema } from './schemas'
import { KeyStore, RecordingApiConfig, RecordingDecryptor } from './types'
@@ -135,7 +136,7 @@ export class RecordingApi {
metadataStore,
featureStore,
this.postgres,
- this.clickhouseClient
+ { client: this.clickhouseClient, credential: ClickHouseCredential.fromConfig(this.config) }
)
logger.info('[RecordingApi] Started successfully')
diff --git a/nodejs/src/session-replay/recording-api/recording-service.test.ts b/nodejs/src/session-replay/recording-api/recording-service.test.ts
index a7ac43623ee1..a28b5ff73b25 100644
--- a/nodejs/src/session-replay/recording-api/recording-service.test.ts
+++ b/nodejs/src/session-replay/recording-api/recording-service.test.ts
@@ -1,11 +1,15 @@
import { NoSuchKey, S3Client } from '@aws-sdk/client-s3'
import { ClickHouseClient } from '@clickhouse/client'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import snappy from 'snappy'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
+import { ClickHouseCredential } from './clickhouse-credential'
import { RecordingService } from './recording-service'
import { KeyStore, RecordingDecryptor, SessionKeyDeletedError } from './types'
@@ -66,7 +70,7 @@ describe('RecordingService', () => {
mockMetadataStore,
mockFeatureStore,
mockPostgres,
- mockClickhouse
+ { client: mockClickhouse, credential: new ClickHouseCredential('recording_api', 'static', '') }
)
})
@@ -440,6 +444,38 @@ describe('RecordingService', () => {
await expect(service.listBlocks('sess-1', 1)).rejects.toThrow('Connection refused')
})
+
+ it('sends the token file contents as they are when each query runs', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'recording-service-'))
+ try {
+ const tokenFile = join(dir, 'token')
+ const serviceWithToken = new RecordingService(
+ mockS3Client,
+ 'test-bucket',
+ 'session_recordings',
+ mockKeyStore,
+ mockDecryptor,
+ mockMetadataStore,
+ mockFeatureStore,
+ mockPostgres,
+ {
+ client: mockClickhouse,
+ credential: new ClickHouseCredential('recording_api', 'static', tokenFile),
+ }
+ )
+ mockClickhouseResult([])
+
+ for (const token of ['first-token', 'rotated-token']) {
+ writeFileSync(tokenFile, token)
+ await serviceWithToken.listBlocks('sess-1', 1)
+ expect(mockClickhouse.query).toHaveBeenLastCalledWith(
+ expect.objectContaining({ auth: { username: 'recording_api', password: token } })
+ )
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
})
describe('deleteRecordings', () => {
diff --git a/nodejs/src/session-replay/recording-api/recording-service.ts b/nodejs/src/session-replay/recording-api/recording-service.ts
index 6ebdd9397951..2ff11fde49c3 100644
--- a/nodejs/src/session-replay/recording-api/recording-service.ts
+++ b/nodejs/src/session-replay/recording-api/recording-service.ts
@@ -9,6 +9,7 @@ import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/
import { createDeletionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
+import { ClickHouseCredential } from './clickhouse-credential'
import { RecordingApiMetrics } from './metrics'
import { KeyStore, RecordingBlock, RecordingDecryptor, SessionKeyDeletedError } from './types'
@@ -48,7 +49,7 @@ export class RecordingService {
private metadataStore?: SessionMetadataStore,
private featureStore?: SessionFeatureStore,
private postgres?: PostgresRouter,
- private clickhouse?: ClickHouseClient
+ private clickhouse?: { client: ClickHouseClient; credential: ClickHouseCredential }
) {}
validateS3Key(key: string): boolean {
@@ -167,13 +168,14 @@ export class RecordingService {
if (!this.clickhouse) {
throw new Error('ClickHouse client not initialized')
}
+ const { client, credential } = this.clickhouse
const startTime = performance.now()
logger.debug('[RecordingService] listBlocks request', { teamId, sessionId })
try {
- const result = await this.clickhouse.query({
+ const result = await client.query({
query: `/* team_id:${teamId} query_type:recording_api_list_blocks */ SELECT
min(min_first_timestamp) as start_time,
groupArrayArray(block_first_timestamps) as block_first_timestamps,
@@ -196,6 +198,7 @@ export class RecordingService {
session_id: sessionId,
},
format: 'JSONEachRow',
+ auth: await credential.auth(),
clickhouse_settings: {
date_time_output_format: 'iso',
log_comment: JSON.stringify({
diff --git a/nodejs/src/session-replay/recording-api/types.ts b/nodejs/src/session-replay/recording-api/types.ts
index e2c00b917f01..9160eff20285 100644
--- a/nodejs/src/session-replay/recording-api/types.ts
+++ b/nodejs/src/session-replay/recording-api/types.ts
@@ -75,6 +75,7 @@ export type RecordingApiConfig = Pick<
| 'CLICKHOUSE_DATABASE'
| 'CLICKHOUSE_USER'
| 'CLICKHOUSE_PASSWORD'
+ | 'CLICKHOUSE_PASSWORD_FILE'
| 'CLICKHOUSE_SECURE'
> &
Pick<