Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(pam): clickhouse

Andrey8d4d6b014767
diff --git a/backend/src/ee/services/pam-account/pam-account-connection-test.ts b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
index 64b83667fb..04cd4cdd2b 100644
--- a/backend/src/ee/services/pam-account/pam-account-connection-test.ts
+++ b/backend/src/ee/services/pam-account/pam-account-connection-test.ts
@@ -26,6 +26,7 @@ export enum TestConnectionMode {
Kubernetes = "kubernetes",
SSH = "ssh",
Snowflake = "snowflake",
+ ClickHouse = "clickhouse",
Tcp = "tcp"
}
@@ -103,6 +104,15 @@ export type TestConnectionRequest =
schema?: string;
role?: string;
}
+ | {
+ mode: TestConnectionMode.ClickHouse;
+ username: string;
+ password?: string;
+ database: string;
+ sslEnabled?: boolean;
+ sslRejectUnauthorized?: boolean;
+ sslCertificate?: string;
+ }
| { mode: TestConnectionMode.Tcp };
const SQL_DIALECTS = {
@@ -371,6 +381,30 @@ export const buildGatewayConnectionTest = async (
}
};
}
+ case PamAccountType.ClickHouse: {
+ const cd = connectionDetails as {
+ database: string;
+ sslEnabled?: boolean;
+ sslRejectUnauthorized?: boolean;
+ sslCertificate?: string;
+ };
+ const c = creds as { username: string; password?: string } | null;
+ const username = (c?.username ?? (credentials?.username as string | undefined))?.trim();
+ if (!username) return tcp(host, port);
+ return {
+ host,
+ port,
+ request: {
+ mode: TestConnectionMode.ClickHouse,
+ username,
+ password: c?.password,
+ database: cd.database,
+ sslEnabled: cd.sslEnabled,
+ sslRejectUnauthorized: cd.sslRejectUnauthorized,
+ sslCertificate: cd.sslCertificate
+ }
+ };
+ }
case PamAccountType.Windows:
return tcp(host, port);
default:
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.test.ts b/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
index 097196c87f..4ec73d7fae 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.test.ts
@@ -20,7 +20,13 @@ import {
// These assertions exercise the Zod-introspection path (buildPamAccountTypeMetadata reads schema internals to derive field descriptors)
describe("buildPamAccountTypeMetadata", () => {
const metadata = buildPamAccountTypeMetadata(
- new Set([PamAccountType.Postgres, PamAccountType.MySQL, PamAccountType.SSH, PamAccountType.Redis])
+ new Set([
+ PamAccountType.Postgres,
+ PamAccountType.MySQL,
+ PamAccountType.SSH,
+ PamAccountType.Redis,
+ PamAccountType.ClickHouse
+ ])
);
const byType = new Map(metadata.map((m) => [m.type, m]));
@@ -166,6 +172,44 @@ describe("buildPamAccountTypeMetadata", () => {
expect(fieldByKey(oracle!.credentialFields, "password")).toMatchObject({ widget: "password", secret: true });
});
+ test("derives ClickHouse connection and credential fields from the schema", () => {
+ const clickhouse = byType.get(PamAccountType.ClickHouse);
+ expect(clickhouse).toBeDefined();
+ expect(clickhouse?.name).toBe("ClickHouse");
+ expect(clickhouse?.supportsWebAccess).toBe(true);
+
+ expect(clickhouse?.connectionFields.map((f) => f.key)).toEqual([
+ "host",
+ "port",
+ "database",
+ "sslEnabled",
+ "sslRejectUnauthorized",
+ "sslCertificate"
+ ]);
+
+ expect(fieldByKey(clickhouse!.connectionFields, "port")).toMatchObject({
+ widget: "number",
+ required: true,
+ defaultValue: 8123
+ });
+ expect(fieldByKey(clickhouse!.connectionFields, "database")).toMatchObject({
+ required: true,
+ defaultValue: "default"
+ });
+
+ expect(fieldByKey(clickhouse!.credentialFields, "username")).toMatchObject({
+ widget: "text",
+ required: true,
+ secret: false,
+ defaultValue: "default"
+ });
+ expect(fieldByKey(clickhouse!.credentialFields, "password")).toMatchObject({
+ widget: "password",
+ secret: true,
+ required: false
+ });
+ });
+
test("derives Redis connection and credential fields from the schema", () => {
const redis = byType.get(PamAccountType.Redis);
expect(redis).toBeDefined();
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.ts
index 09728aa23f..21cf91b16e 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts
@@ -593,6 +593,50 @@ export const ACCOUNT_TYPE_CONFIGS = {
}
},
+ [PamAccountType.ClickHouse]: {
+ name: "ClickHouse",
+ icon: "ClickHouse.png",
+ connectionDetails: z.object({
+ host: z.string().trim().min(1).max(255),
+ port: z.coerce.number().int().min(1).max(65535),
+ database: z.string().trim().min(1).max(255),
+ sslEnabled: z.boolean(),
+ sslRejectUnauthorized: z.boolean(),
+ sslCertificate: optionalTrimmedString
+ }),
+ credentials: z.object({
+ username: z.string().trim().min(1).max(255),
+ password: boundedOptionalString(256)
+ }),
+ sanitizedCredentials: z.object({ username: z.string() }),
+ ui: {
+ port: {
+ defaultValue: 8123,
+ tooltip:
+ "The HTTP interface port: 8123 for plain HTTP, 8443 for HTTPS. Sessions never use the native protocol on 9000."
+ },
+ database: {
+ defaultValue: "default",
+ tooltip: "The database sessions open. The explorer lists the tables inside it."
+ },
+ username: {
+ defaultValue: "default",
+ tooltip: "The ClickHouse user sessions connect as. Use 'default' for the built-in user."
+ },
+ password: { widget: PamFieldWidget.Password, secret: true, optional: true },
+ sslEnabled: { label: "SSL Enabled" },
+ sslRejectUnauthorized: {
+ label: "Reject Unauthorized",
+ showWhen: { field: "sslEnabled", equals: true }
+ },
+ sslCertificate: {
+ label: "SSL Certificate",
+ widget: PamFieldWidget.Textarea,
+ showWhen: { field: "sslEnabled", equals: true }
+ }
+ }
+ },
+
[PamAccountType.SSH]: {
name: "SSH",
icon: "SSH.png",
@@ -1009,6 +1053,7 @@ export const extractGatewayTarget = async (
case PamAccountType.MsSQL:
case PamAccountType.OracleDB:
case PamAccountType.Redis:
+ case PamAccountType.ClickHouse:
case PamAccountType.Windows:
return {
host: (validated as { host: string; port: number }).host,
@@ -1151,9 +1196,11 @@ const accountTypeConnectionStringSchemes = (accountType: PamAccountType): string
return config?.connectionStringSchemes ? [...config.connectionStringSchemes] : undefined;
};
-// redis can be reached without credentials
+// redis and clickhouse both accept a passwordless user, so an account without one is still launchable
+const CREDENTIAL_OPTIONAL_ACCOUNT_TYPES: PamAccountType[] = [PamAccountType.Redis, PamAccountType.ClickHouse];
+
export const accountTypeRequiresCredential = (accountType: PamAccountType): boolean =>
- accountType !== PamAccountType.Redis;
+ !CREDENTIAL_OPTIONAL_ACCOUNT_TYPES.includes(accountType);
export const getAccountAccessibilityIssues = (account: {
accountType: PamAccountType | string;
diff --git a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts b/backend/src/ee/services/pam-project/pam-project-bootstrap.ts
index 91ab69fb6b..38b63f5233 100644
--- a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts
+++ b/backend/src/ee/services/pam-project/pam-project-bootstrap.ts
@@ -142,6 +142,14 @@ export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [
recordingEnabled: true,
recordingStorageBackend: PamRecordingStorageBackend.Postgres
}
+ },
+ {
+ name: "clickhouse",
+ type: PamAccountType.ClickHouse,
+ settings: {
+ recordingEnabled: true,
+ recordingStorageBackend: PamRecordingStorageBackend.Postgres
+ }
}
];
diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
index 7f5ab12aa2..a575f12c3e 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -768,7 +768,8 @@ export const pamSessionServiceFactory = ({
account.accountType === PamAccountType.MySQL ||
account.accountType === PamAccountType.MongoDB ||
account.accountType === PamAccountType.MsSQL ||
- account.accountType === PamAccountType.OracleDB) &&
+ account.accountType === PamAccountType.OracleDB ||
+ account.accountType === PamAccountType.ClickHouse) &&
rawConnectionDetails.database
) {
metadata.database = rawConnectionDetails.database as string;
diff --git a/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-client.ts b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-client.ts
new file mode 100644
index 0000000000..32ffe282cc
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-client.ts
@@ -0,0 +1,118 @@
+import { type ClickHouseClient, ClickHouseError, createClient } from "@clickhouse/client";
+import { Readable } from "stream";
+
+import { BadRequestError } from "@app/lib/errors";
+
+const REQUEST_TIMEOUT_MS = 30 * 60 * 1000;
+const CONNECT_TIMEOUT_MS = 30 * 1000;
+
+export const MAX_RESULT_BYTES = 64 * 1024 * 1024;
+
+export const createRelayClient = (opts: {
+ relayPort: number;
+ database?: string;
+ sessionId?: string;
+}): ClickHouseClient =>
+ createClient({
+ url: `http://127.0.0.1:${opts.relayPort}`,
+ database: opts.database || "default",
+ session_id: opts.sessionId,
+ request_timeout: REQUEST_TIMEOUT_MS,
+ max_open_connections: 2,
+ compression: { request: false, response: false },
+ application: "Infisical"
+ });
+
+export const openRelayClient = async (opts: {
+ relayPort: number;
+ database?: string;
+ sessionId: string;
+}): Promise<ClickHouseClient> => {
+ const client = createRelayClient(opts);
+ try {
+ const probe = await client.query({
+ query: "SELECT 1",
+ format: "JSON",
+ abort_signal: AbortSignal.timeout(CONNECT_TIMEOUT_MS)
+ });
+ await probe.json();
+ return client;
+ } catch (err) {
+ await client.close().catch(() => {});
+ throw new BadRequestError({
+ message: `Unable to open a ClickHouse session through the gateway: ${(err as Error)?.message ?? "connection failed"}`
+ });
+ }
+};
+
+export const withOneShotClient = async <T>(
+ opts: { relayPort: number; database?: string },
+ fn: (client: ClickHouseClient) => Promise<T>
+): Promise<T> => {
+ const client = createRelayClient(opts);
+ try {
+ return await fn(client);
+ } finally {
+ await client.close().catch(() => {});
+ }
+};
+
+export const verifyRelayReachable = async (opts: { relayPort: number; database?: string }): Promise<void> => {
+ try {
+ await withOneShotClient(opts, async (client) => {
+ const result = await client.query({
+ query: "SELECT 1",
+ format: "JSON",
+ abort_signal: AbortSignal.timeout(CONNECT_TIMEOUT_MS)
+ });
+ await result.json();
+ });
+ } catch (err) {
+ throw new BadRequestError({
+ message: `Unable to reach ClickHouse through the gateway: ${(err as Error)?.message ?? "connection failed"}`
+ });
+ }
+};
+
+export const readStreamText = async (stream: Readable, maxBytes: number): Promise<string> => {
+ // Stops an unhandled 'error' from taking the process down once iteration has moved on
+ stream.on("error", () => {});
+
+ const chunks: Buffer[] = [];
+ let total = 0;
+ try {
+ for await (const chunk of stream) {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
+ const remaining = maxBytes - total;
+ if (buffer.length >= remaining) {
+ chunks.push(buffer.subarray(0, remaining));
+ total = maxBytes;
+ break;
+ }
+ chunks.push(buffer);
+ total += buffer.length;
+ }
+ } finally {
+ stream.destroy();
+ }
+
+ return Buffer.concat(chunks).toString("utf8");
+};
+
+export const clickhouseErrorFields = (err: unknown): { message?: string; detail?: string } => {
+ if (err instanceof ClickHouseError) {
+ return { message: err.message, detail: err.type ? `${err.type} (code ${err.code})` : `Code ${err.code}` };
+ }
+ return { message: (err as Error)?.message };
+};
+
+const CONNECTION_ERROR_CODES = ["ECONNREFUSED", "ECONNRESET", "EPIPE", "ERR_SOCKET_CONNECTION_TIMEOUT"];
+
+// A ClickHouseError is the server answering, so only transport failures mean the tunnel is gone
+export const isRelayGoneError = (err: unknown): boolean => {
+ if (err instanceof ClickHouseError) return false;
+ const code = (err as { code?: string })?.code;
+ if (code && CONNECTION_ERROR_CODES.includes(code)) return true;
+ const message = (err as Error)?.message ?? "";
+ return message.includes("socket hang up") || message.includes("ECONNREFUSED") || message.includes("ECONNRESET");
+};
diff --git a/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-connection-controller.ts b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-connection-controller.ts
new file mode 100644
index 0000000000..4d15584760
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-connection-controller.ts
@@ -0,0 +1,226 @@
+import { type ClickHouseClient } from "@clickhouse/client";
+import { randomUUID } from "crypto";
+
+import { logger } from "@app/lib/logger";
+
+import { type ControllerParams } from "../pam-data-explorer-session-handler";
+import {
+ DataExplorerClientMessageType,
+ DataExplorerServerMessageType,
+ type TConnectionController,
+ type TTabScopedMessage
+} from "../pam-data-explorer-ws-types";
+import {
+ clickhouseErrorFields,
+ isRelayGoneError,
+ MAX_RESULT_BYTES,
+ openRelayClient,
+ readStreamText,
+ withOneShotClient
+} from "./pam-clickhouse-client";
+import {
+ extractCommand,
+ MAX_ROWS,
+ parseStatementBody,
+ splitClickhouseStatements,
+ TStatementResult
+} from "./pam-clickhouse-data-explorer-fns";
+import { COLUMNS_QUERY, TColumnRow, toColumns, toPrimaryKeys } from "./pam-clickhouse-data-explorer-metadata";
+
+export const createClickhouseConnectionController = async (
+ params: ControllerParams
+): Promise<TConnectionController> => {
+ const { relayPort, database, sessionId, connectionId, sendResponse, onUnexpectedTermination } = params;
+
+ const client: ClickHouseClient = await openRelayClient({
+ relayPort,
+ database,
+ sessionId: `${sessionId}-${connectionId}`
+ });
+
+ let disposing = false;
+ let cancelled = false;
+ let runningQueryId: string | null = null;
+ let abortController: AbortController | null = null;
+
+ // Aborting only drops this side of the request; the statement runs on until ClickHouse is told to kill it
+ const cancelRunningStatement = () => {
+ cancelled = true;
+ abortController?.abort();
+ const queryId = runningQueryId;
+ if (!queryId) return;
+ void withOneShotClient({ relayPort, database }, (killClient) =>
+ killClient.command({
+ query: "KILL QUERY WHERE query_id = {queryId:String}",
+ query_params: { queryId }
+ })
+ ).catch((err) => {
+ logger.debug(err, `Failed to kill ClickHouse query [sessionId=${sessionId}] [connectionId=${connectionId}]`);
+ });
+ };
+
+ const sendQueryError = (id: string, err: unknown) => {
+ // The tunnel is gone once the session is terminated, so the tab is closed rather than left waiting
+ if (!disposing && isRelayGoneError(err)) {
+ disposing = true;
+ onUnexpectedTermination("Session ended");
+ return;
+ }
+
+ const { message, detail } = clickhouseErrorFields(err);
+ sendResponse({
+ type: DataExplorerServerMessageType.Error,
+ id,
+ connectionId,
+ transactionOpen: false,
+ error: cancelled ? "Query cancelled" : (message ?? "Query execution failed"),
+ detail: cancelled ? undefined : detail
+ });
+ };
+
+ const runTableDetail = async (schema: string, table: string) => {
+ const result = await client.query({
+ query: COLUMNS_QUERY,
+ format: "JSON",
+ query_params: { schema, table }
+ });
+ const columns = (await result.json<TColumnRow>()).data;
+ if (columns.length === 0) return null;
+
+ return {
+ columns: toColumns(columns),
+ primaryKeys: toPrimaryKeys(columns),
+ foreignKeys: []
+ };
+ };
+
+ const runStatement = async (statementSql: string): Promise<TStatementResult> => {
+ const queryId = randomUUID();
+ abortController = new AbortController();
+ runningQueryId = queryId;
+
+ const { stream, summary } = await client.exec({
+ query: statementSql,
+ query_id: queryId,
+ abort_signal: abortController.signal,
+ clickhouse_settings: {
+ default_format: "JSONCompact",
+ max_result_rows: String(MAX_ROWS + 1),
+ result_overflow_mode: "break",
+ wait_end_of_query: 1
+ }
+ });
+
+ return parseStatementBody(await readStreamText(stream, MAX_RESULT_BYTES), summary);
+ };
+
+ const runQuery = async (sql: string) => {
+ const startTime = performance.now();
+
+ let last: TStatementResult = { rows: [], fields: [], rowCount: null, isTruncated: false };
+ let lastCommand = "";
+
+ try {
+ for (const statementSql of splitClickhouseStatements(sql)) {
+ lastCommand = extractCommand(statementSql);
+ // eslint-disable-next-line no-await-in-loop
+ last = await runStatement(statementSql);
+ }
+ } finally {
+ runningQueryId = null;
+ abortController = null;
+ }
+
+ return {
+ ...last,
+ command: lastCommand,
+ executionTimeMs: Math.round(performance.now() - startTime)
+ };
+ };
+
+ let processingPromise: Promise<void> = Promise.resolve();
+
+ const handleMessage = (message: TTabScopedMessage) => {
+ if (message.type === DataExplorerClientMessageType.Cancel) {
+ if (disposing) return;
+ cancelRunningStatement();
+ return;
+ }
+
+ processingPromise = processingPromise
+ .then(async () => {
+ if (disposing) return;
+ cancelled = false;
+
+ switch (message.type) {
+ case DataExplorerClientMessageType.GetTableDetail: {
+ try {
+ const detail = await runTableDetail(message.schema, message.table);
+ if (!detail) {
+ sendResponse({
+ type: DataExplorerServerMessageType.Error,
+ id: message.id,
+ connectionId,
+ transactionOpen: false,
+ error: "Table not found or no metadata available"
+ });
+ break;
+ }
+ sendResponse({
+ type: DataExplorerServerMessageType.TableDetail,
+ id: message.id,
+ connectionId,
+ transactionOpen: false,
+ data: detail
+ });
+ } catch (err) {
+ sendQueryError(message.id, err);
+ }
+ break;
+ }
+
+ case DataExplorerClientMessageType.Query: {
+ try {
+ const result = await runQuery(message.sql);
+ sendResponse({
+ type: DataExplorerServerMessageType.QueryResult,
+ id: message.id,
+ connectionId,
+ transactionOpen: false,
+ ...result
+ });
+ } catch (err) {
+ sendQueryError(message.id, err);
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+ })
+ .catch((err) => {
+ logger.error(
+ err,
+ `Error processing ClickHouse message [sessionId=${sessionId}] [connectionId=${connectionId}]`
+ );
+ });
+ };
+
+ const dispose = () => {
+ if (disposing) return;
+ disposing = true;
+ cancelRunningStatement();
+ void client.close().catch((err) => {
+ logger.debug(err, `Error closing ClickHouse client [sessionId=${sessionId}] [connectionId=${connectionId}]`);
+ });
+ };
+
+ return {
+ connectionId,
+ nativeConnectionId: null,
+ handleMessage,
+ dispose,
+ isDisposing: () => disposing
+ };
+};
diff --git a/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-fns.test.ts b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-fns.test.ts
new file mode 100644
index 0000000000..ec8222c95d
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-fns.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, test } from "vitest";
+
+import {
+ extractCommand,
+ MAX_ROWS,
+ parseStatementBody,
+ splitClickhouseStatements,
+ toRowObjects,
+ uniqueFieldNames
+} from "./pam-clickhouse-data-explorer-fns";
+
+describe("splitClickhouseStatements", () => {
+ test("single statement with and without a trailing semicolon", () => {
+ expect(splitClickhouseStatements("SELECT 1")).toEqual(["SELECT 1"]);
+ expect(splitClickhouseStatements("SELECT 1;")).toEqual(["SELECT 1"]);
+ });
+
+ test("multiple statements", () => {
+ expect(splitClickhouseStatements("SELECT 1; SELECT 2; SELECT 3")).toEqual(["SELECT 1", "SELECT 2", "SELECT 3"]);
+ });
+
+ test("drops empty statements and whitespace-only input", () => {
+ expect(splitClickhouseStatements("SELECT 1;; ;SELECT 2")).toEqual(["SELECT 1", "SELECT 2"]);
+ expect(splitClickhouseStatements("")).toEqual([]);
+ expect(splitClickhouseStatements(" \n\t ")).toEqual([]);
+ });
+
+ test("semicolon inside a string literal", () => {
+ expect(splitClickhouseStatements("SELECT 'a;b'; SELECT 2")).toEqual(["SELECT 'a;b'", "SELECT 2"]);
+ });
+
+ test("semicolon inside a double-quoted or backtick identifier", () => {
+ expect(splitClickhouseStatements('SELECT "col;name" FROM t; SELECT 2')).toEqual([
+ 'SELECT "col;name" FROM t',
+ "SELECT 2"
+ ]);
+ expect(splitClickhouseStatements("SELECT `col;name` FROM t; SELECT 2")).toEqual([
+ "SELECT `col;name` FROM t",
+ "SELECT 2"
+ ]);
+ });
+
+ test("escaped and doubled quotes inside a literal", () => {
+ expect(splitClickhouseStatements("SELECT 'it''s;fine'; SELECT 2")).toEqual(["SELECT 'it''s;fine'", "SELECT 2"]);
+ expect(splitClickhouseStatements("SELECT 'a\\';b'; SELECT 2")).toEqual(["SELECT 'a\\';b'", "SELECT 2"]);
+ });
+
+ test("semicolon inside every comment form ClickHouse accepts", () => {
+ expect(splitClickhouseStatements("SELECT 1 -- a;b\n; SELECT 2")).toEqual(["SELECT 1 -- a;b", "SELECT 2"]);
+ expect(splitClickhouseStatements("SELECT 1 # a;b\n; SELECT 2")).toEqual(["SELECT 1 # a;b", "SELECT 2"]);
+ expect(splitClickhouseStatements("SELECT /* a;b */ 1; SELECT 2")).toEqual(["SELECT /* a;b */ 1", "SELECT 2"]);
+ });
+
+ test("an unterminated literal swallows the rest rather than splitting inside it", () => {
+ expect(splitClickhouseStatements("SELECT 'oops; SELECT 2")).toEqual(["SELECT 'oops; SELECT 2"]);
+ });
+});
+
+describe("extractCommand", () => {
+ test("reads the leading keyword, skipping whitespace and comments", () => {
+ expect(extractCommand("select 1")).toBe("SELECT");
+ expect(extractCommand(" \n INSERT INTO t VALUES (1)")).toBe("INSERT");
+ expect(extractCommand("-- a comment\nCREATE TABLE t")).toBe("CREATE");
+ expect(extractCommand("# a comment\nALTER TABLE t")).toBe("ALTER");
+ expect(extractCommand("/* a comment */ OPTIMIZE TABLE t")).toBe("OPTIMIZE");
+ });
+
+ test("stops at a delimiter and handles an empty statement", () => {
+ expect(extractCommand("SELECT(1)")).toBe("SELECT");
+ expect(extractCommand("")).toBe("");
+ });
+});
+
+describe("uniqueFieldNames", () => {
+ test("leaves distinct names alone and disambiguates repeats", () => {
+ expect(uniqueFieldNames(["a", "b"])).toEqual(["a", "b"]);
+ expect(uniqueFieldNames(["a", "a", "a"])).toEqual(["a", "a_1", "a_2"]);
+ });
+});
+
+describe("toRowObjects", () => {
+ test("zips column names onto positional rows", () => {
+ expect(
+ toRowObjects(
+ ["id", "name"],
+ [
+ [1, "one"],
+ [2, "two"]
+ ]
+ )
+ ).toEqual([
+ { id: 1, name: "one" },
+ { id: 2, name: "two" }
+ ]);
+ });
+
+ test("a missing value becomes null rather than undefined", () => {
+ expect(toRowObjects(["id", "name"], [[1]])).toEqual([{ id: 1, name: null }]);
+ });
+});
+
+describe("parseStatementBody", () => {
+ const compact = (meta: string[], data: unknown[][]) =>
+ JSON.stringify({ meta: meta.map((name) => ({ name, type: "String" })), data, rows: data.length });
+
+ test("an empty body takes its row count from the summary", () => {
+ expect(parseStatementBody("", { written_rows: "42" })).toEqual({
+ rows: [],
+ fields: [],
+ rowCount: 42,
+ isTruncated: false
+ });
+ expect(parseStatementBody(" \n ").rowCount).toBeNull();
+ });
+
+ test("reads the JSONCompact shape the session asks for", () => {
+ expect(
+ parseStatementBody(
+ compact(
+ ["id", "name"],
+ [
+ [1, "one"],
+ [2, "two"]
+ ]
+ )
+ )
+ ).toEqual({
+ rows: [
+ { id: 1, name: "one" },
+ { id: 2, name: "two" }
+ ],
+ fields: [{ name: "id" }, { name: "name" }],
+ rowCount: 2,
+ isTruncated: false
+ });
+ });
+
+ test("a statement that asks for FORMAT JSON returns rows as objects already", () => {
+ const body = JSON.stringify({
+ meta: [{ name: "id", type: "UInt64" }],
+ data: [{ id: 1 }, { id: 2 }],
+ rows: 2
+ });
+ expect(parseStatementBody(body).rows).toEqual([{ id: 1 }, { id: 2 }]);
+ });
+
+ test("caps the rows it returns and says it did", () => {
+ const data = Array.from({ length: MAX_ROWS + 1 }, (_, index) => [index]);
+ const result = parseStatementBody(compact(["n"], data));
+ expect(result.rows).toHaveLength(MAX_ROWS);
+ expect(result.rowCount).toBe(MAX_ROWS + 1);
+ expect(result.isTruncated).toBe(true);
+ });
+
+ test("output in a format it cannot read is handed back verbatim", () => {
+ expect(parseStatementBody("1\tone\n2\ttwo\n")).toEqual({
+ rows: [{ result: "1\tone\n2\ttwo\n" }],
+ fields: [{ name: "result" }],
+ rowCount: null,
+ isTruncated: false
+ });
+ });
+
+ test("a repeated column name still reaches the grid", () => {
+ expect(parseStatementBody(compact(["a", "a"], [[1, 2]])).rows).toEqual([{ a: 1, a_1: 2 }]);
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-fns.ts b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-fns.ts
new file mode 100644
index 0000000000..406df89586
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-fns.ts
@@ -0,0 +1,151 @@
+const skipQuoted = (sql: string, pos: number, quote: string): number => {
+ // ClickHouse escapes with a backslash inside every quoted form, and also accepts the quote doubled
+ let i = pos + 1;
+ while (i < sql.length) {
+ if (sql[i] === "\\") {
+ i += 2;
+ } else if (sql[i] === quote) {
+ if (i + 1 < sql.length && sql[i + 1] === quote) {
+ i += 2;
+ } else {
+ return i + 1;
+ }
+ } else {
+ i += 1;
+ }
+ }
+ return sql.length;
+};
+
+const isLineComment = (sql: string, pos: number) => (sql[pos] === "-" && sql[pos + 1] === "-") || sql[pos] === "#";
+
+const isBlockComment = (sql: string, pos: number) => sql[pos] === "/" && sql[pos + 1] === "*";
+
+const skipLineComment = (sql: string, pos: number): number => {
+ let i = pos + 1;
+ while (i < sql.length && sql[i] !== "\n") i += 1;
+ return i;
+};
+
+const skipBlockComment = (sql: string, pos: number): number => {
+ let i = pos + 2;
+ while (i + 1 < sql.length && !(sql[i] === "*" && sql[i + 1] === "/")) i += 1;
+ return Math.min(i + 2, sql.length);
+};
+
+// The HTTP interface runs one statement per request, so an editor tab's script is split here
+export const splitClickhouseStatements = (sql: string): string[] => {
+ const statements: string[] = [];
+ let pos = 0;
+ let statementStart = 0;
+
+ while (pos < sql.length) {
+ const ch = sql[pos];
+
+ if (ch === "'" || ch === '"' || ch === "`") {
+ pos = skipQuoted(sql, pos, ch);
+ } else if (isLineComment(sql, pos)) {
+ pos = skipLineComment(sql, pos);
+ } else if (isBlockComment(sql, pos)) {
+ pos = skipBlockComment(sql, pos);
+ } else if (ch === ";") {
+ const statement = sql.slice(statementStart, pos).trim();
+ if (statement.length > 0) statements.push(statement);
+ pos += 1;
+ statementStart = pos;
+ } else {
+ pos += 1;
+ }
+ }
+
+ const tail = sql.slice(statementStart).trim();
+ if (tail.length > 0) statements.push(tail);
+
+ return statements;
+};
+
+export const extractCommand = (sql: string): string => {
+ let pos = 0;
+
+ while (pos < sql.length) {
+ const ch = sql[pos];
+ if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") {
+ pos += 1;
+ } else if (isLineComment(sql, pos)) {
+ pos = skipLineComment(sql, pos);
+ } else if (isBlockComment(sql, pos)) {
+ pos = skipBlockComment(sql, pos);
+ } else {
+ break;
+ }
+ }
+
+ const start = pos;
+ while (pos < sql.length && !" \t\n\r;(".includes(sql[pos])) pos += 1;
+ return sql.slice(start, pos).toUpperCase();
+};
+
+export const uniqueFieldNames = (names: string[]): string[] => {
+ const seen = new Map<string, number>();
+ return names.map((name) => {
+ const count = seen.get(name) ?? 0;
+ seen.set(name, count + 1);
+ return count === 0 ? name : `${name}_${count}`;
+ });
+};
+
+export const toRowObjects = (fieldNames: string[], data: unknown[][]): Record<string, unknown>[] =>
+ data.map((values) => Object.fromEntries(fieldNames.map((name, index) => [name, values[index] ?? null])));
+
+// The explorer renders at most this many rows
+export const MAX_ROWS = 1000;
+
+export type TStatementResult = {
+ rows: Record<string, unknown>[];
+ fields: { name: string }[];
+ rowCount: number | null;
+ isTruncated: boolean;
+};
+
+const writtenRows = (summary?: { written_rows: string }): number | null => {
+ const value = Number(summary?.written_rows);
+ return Number.isFinite(value) ? value : null;
+};
+
+export const parseStatementBody = (body: string, summary?: { written_rows: string }): TStatementResult => {
+ if (body.trim().length === 0) {
+ return { rows: [], fields: [], rowCount: writtenRows(summary), isTruncated: false };
+ }
+
+ let parsed: { meta?: { name: string }[]; data?: unknown[] } | null = null;
+ try {
+ parsed = JSON.parse(body) as { meta?: { name: string }[]; data?: unknown[] };
+ } catch {
+ parsed = null;
+ }
+
+ if (!parsed || !Array.isArray(parsed.meta) || !Array.isArray(parsed.data)) {
+ return {
+ rows: [{ result: body }],
+ fields: [{ name: "result" }],
+ rowCount: null,
+ isTruncated: false
+ };
+ }
+
+ const fieldNames = uniqueFieldNames(parsed.meta.map((column) => column.name));
+ const isTruncated = parsed.data.length > MAX_ROWS;
+ const data = isTruncated ? parsed.data.slice(0, MAX_ROWS) : parsed.data;
+
+ const rows =
+ data.length > 0 && !Array.isArray(data[0])
+ ? (data as Record<string, unknown>[])
+ : toRowObjects(fieldNames, data as unknown[][]);
+
+ return {
+ rows,
+ fields: fieldNames.map((name) => ({ name })),
+ rowCount: parsed.data.length,
+ isTruncated
+ };
+};
diff --git a/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-metadata.test.ts b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-metadata.test.ts
new file mode 100644
index 0000000000..4f098dc745
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-metadata.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from "vitest";
+
+import { TColumnRow, toColumns, toPrimaryKeys } from "./pam-clickhouse-data-explorer-metadata";
+
+const rows: TColumnRow[] = [
+ { name: "id", type: "UInt64", nullable: 0, isInPrimaryKey: 1 },
+ { name: "tenant", type: "String", nullable: 0, isInPrimaryKey: 1 },
+ { name: "note", type: "Nullable(String)", nullable: 1, isInPrimaryKey: 0 }
+];
+
+describe("toColumns", () => {
+ test("reads nullability off the UInt8 flag and reports no identity columns", () => {
+ expect(toColumns(rows)).toEqual([
+ { name: "id", type: "UInt64", nullable: false, identityGeneration: null },
+ { name: "tenant", type: "String", nullable: false, identityGeneration: null },
+ { name: "note", type: "Nullable(String)", nullable: true, identityGeneration: null }
+ ]);
+ });
+
+ test("accepts the flag as a boolean or a string", () => {
+ expect(toColumns([{ name: "a", type: "String", nullable: true, isInPrimaryKey: 0 }])[0].nullable).toBe(true);
+ expect(
+ toColumns([{ name: "a", type: "String", nullable: "1" as unknown as number, isInPrimaryKey: 0 }])[0].nullable
+ ).toBe(true);
+ });
+});
+
+describe("toPrimaryKeys", () => {
+ test("keeps the sorting key columns in their declared order", () => {
+ expect(toPrimaryKeys(rows)).toEqual(["id", "tenant"]);
+ });
+
+ test("a table with no sorting key has none", () => {
+ expect(toPrimaryKeys([{ name: "a", type: "String", nullable: 0, isInPrimaryKey: 0 }])).toEqual([]);
+ });
+});
diff --git a/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-metadata.ts b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-metadata.ts
new file mode 100644
index 0000000000..e874792e84
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-data-explorer-metadata.ts
@@ -0,0 +1,44 @@
+// ClickHouse has no schema layer under a database, so the explorer's "schemas" are databases.
+export const SCHEMAS_QUERY = `SELECT name AS name
+ FROM system.databases
+ WHERE name NOT IN ('INFORMATION_SCHEMA', 'information_schema')
+ ORDER BY name`;
+
+export const TABLES_QUERY = `SELECT
+ name AS name,
+ multiIf(engine = 'View', 'view', engine = 'MaterializedView', 'materialized_view', 'table') AS tableType
+ FROM system.tables
+ WHERE database = {schema:String}
+ ORDER BY name`;
+
+// Nullability lives in the type itself (Nullable(T)), and the sorting key columns are what ClickHouse
+// calls the primary key -- an index, not a unique constraint, which is why the grid stays read-only.
+export const COLUMNS_QUERY = `SELECT
+ name AS name,
+ type AS type,
+ startsWith(type, 'Nullable(') AS nullable,
+ is_in_primary_key AS isInPrimaryKey
+ FROM system.columns
+ WHERE database = {schema:String} AND table = {table:String}
+ ORDER BY position`;
+
+export type TColumnRow = {
+ name: string;
+ type: string;
+ nullable: number | boolean;
+ isInPrimaryKey: number | boolean;
+};
+
+// UInt8 comes back as a number in JSON and as a string in some driver paths
+const asBool = (value: number | boolean | string): boolean => value === true || value === 1 || value === "1";
+
+export const toColumns = (rows: TColumnRow[]) =>
+ rows.map((row) => ({
+ name: row.name,
+ type: row.type,
+ nullable: asBool(row.nullable),
+ identityGeneration: null
+ }));
+
+export const toPrimaryKeys = (rows: TColumnRow[]): string[] =>
+ rows.filter((row) => asBool(row.isInPrimaryKey)).map((row) => row.name);
diff --git a/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-metadata.ts b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-metadata.ts
new file mode 100644
index 0000000000..1b71839ba1
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-metadata.ts
@@ -0,0 +1,27 @@
+import { type OneShotOptions } from "../pam-data-explorer-session-handler";
+import { verifyRelayReachable, withOneShotClient } from "./pam-clickhouse-client";
+import { SCHEMAS_QUERY, TABLES_QUERY } from "./pam-clickhouse-data-explorer-metadata";
+
+const relayTarget = (opts: OneShotOptions) => ({ relayPort: opts.relayPort, database: opts.database });
+
+export const fetchSchemasOneShot = (opts: OneShotOptions): Promise<{ name: string }[]> =>
+ withOneShotClient(relayTarget(opts), async (client) => {
+ const result = await client.query({ query: SCHEMAS_QUERY, format: "JSON" });
+ return (await result.json<{ name: string }>()).data;
+ });
+
+export const fetchTablesOneShot = (
+ opts: OneShotOptions,
+ schema: string
+): Promise<{ name: string; tableType: string }[]> =>
+ withOneShotClient(relayTarget(opts), async (client) => {
+ const result = await client.query({
+ query: TABLES_QUERY,
+ format: "JSON",
+ query_params: { schema }
+ });
+ return (await result.json<{ name: string; tableType: string }>()).data;
+ });
+
+export const verifyReachabilityOneShot = (opts: OneShotOptions): Promise<void> =>
+ verifyRelayReachable(relayTarget(opts));
diff --git a/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-session-handler.ts b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-session-handler.ts
new file mode 100644
index 0000000000..234cfe85c2
--- /dev/null
+++ b/backend/src/ee/services/pam-web-access/clickhouse/pam-clickhouse-session-handler.ts
@@ -0,0 +1,13 @@
+import { createDataExplorerSessionHandler } from "../pam-data-explorer-session-handler";
+import { clickhouseErrorFields } from "./pam-clickhouse-client";
+import { createClickhouseConnectionController } from "./pam-clickhouse-connection-controller";
+import { fetchSchemasOneShot, fetchTablesOneShot, verifyReachabilityOneShot } from "./pam-clickhouse-metadata";
+
+export const handleClickhouseSession = createDataExplorerSessionHandler({
+ dialectName: "ClickHouse",
+ createController: createClickhouseConnectionController,
+ fetchSchemas: fetchSchemasOneShot,
+ fetchTables: fetchTablesOneShot,
+ verifyReachability: verifyReachabilityOneShot,
+ extractErrorFields: clickhouseErrorFields
+});
diff --git a/backend/src/ee/services/pam-web-access/pam-session-handlers.ts b/backend/src/ee/services/pam-web-access/pam-session-handlers.ts
index 549a54e6b2..4a75572b35 100644
--- a/backend/src/ee/services/pam-web-access/pam-session-handlers.ts
+++ b/backend/src/ee/services/pam-web-access/pam-session-handlers.ts
@@ -1,5 +1,6 @@
import { PamAccountType } from "@app/ee/services/pam/pam-enums";
+import { handleClickhouseSession } from "./clickhouse/pam-clickhouse-session-handler";
import { handleMysqlSession } from "./mysql/pam-mysql-session-handler";
import { TSessionContext, TSessionHandlerResult } from "./pam-web-access-types";
import { handlePostgresSession } from "./postgres/pam-postgres-session-handler";
@@ -35,6 +36,10 @@ export const SESSION_HANDLERS: Partial<Record<PamAccountType, TSessionHandlerEnt
gatewayAccountType: PamAccountType.Snowflake,
handler: handleSnowflakeSession
},
+ [PamAccountType.ClickHouse]: {
+ gatewayAccountType: PamAccountType.ClickHouse,
+ handler: handleClickhouseSession
+ },
[PamAccountType.SSH]: {
gatewayAccountType: PamAccountType.SSH,
handler: handleSSHSession
diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.md
index a56b03f0b7..c43cc64410 100644
--- a/backend/src/ee/services/pam/CLAUDE.md
+++ b/backend/src/ee/services/pam/CLAUDE.md
@@ -138,6 +138,12 @@ live in a process-wide map keyed by the driver's request id rather than on the p
test compares the login's `sessionInfo` against what was asked for, because Snowflake accepts a warehouse
or role the credential can't use and silently leaves it unset.
+**ClickHouse is brokered over its HTTP interface (8123/8443), never the native protocol on 9000**, so the
+gateway can read the statement as text to block and record it (CLI `packages/pam/handlers/clickhouse/`).
+Only the first megabyte of a request body is inspected, so an account carrying a command-blocking policy
+refuses a body longer than that rather than forward the remainder unread. Databases stand in for schemas, and the explorer grid is read-only for every table
+(`supportsRowEditing`): `is_in_primary_key` is a sorting key, not a unique constraint.
+
## Policies & Settings
**Policies** are governance controls on a template (MFA, reason, session duration, command-blocking),
diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.ts
index 336dce1f55..382e69815e 100644
--- a/backend/src/ee/services/pam/pam-enums.ts
+++ b/backend/src/ee/services/pam/pam-enums.ts
@@ -7,6 +7,7 @@ export enum PamAccountType {
MongoDB = "mongodb",
Redis = "redis",
Snowflake = "snowflake",
+ ClickHouse = "clickhouse",
Kubernetes = "kubernetes",
AwsIam = "aws-iam",
GcpServiceAccount = "gcp-service-account",
diff --git a/backend/src/ee/services/pam/pam-policies.ts b/backend/src/ee/services/pam/pam-policies.ts
index b09d7d7ec5..96edf7b75a 100644
--- a/backend/src/ee/services/pam/pam-policies.ts
+++ b/backend/src/ee/services/pam/pam-policies.ts
@@ -105,11 +105,14 @@ export const PAM_POLICY_DEFINITIONS: Record<PamPolicyType, TPamPolicyDefinition>
[PamPolicyType.CommandBlocking]: {
label: "Command Blocking",
description: "Matching commands will be rejected (one regex per line).",
- appliesTo: [PamAccountType.SSH, PamAccountType.Snowflake],
+ appliesTo: [PamAccountType.SSH, PamAccountType.Snowflake, PamAccountType.ClickHouse],
schema: patternsStringSchema(),
typeOverrides: {
[PamAccountType.Snowflake]: {
description: "Matching SQL statements will be rejected (one regex per line)."
+ },
+ [PamAccountType.ClickHouse]: {
+ description: "Matching SQL statements will be rejected (one regex per line)."
}
}
}
diff --git a/docs/docs.json b/docs/docs.json
index 76c06fd079..10812fad35 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -713,6 +713,7 @@
"documentation/platform/pam/accounts/mongodb",
"documentation/platform/pam/accounts/redis",
"documentation/platform/pam/accounts/snowflake",
+ "documentation/platform/pam/accounts/clickhouse",
"documentation/platform/pam/accounts/ssh",
"documentation/platform/pam/accounts/kubernetes",
"documentation/platform/pam/accounts/aws-iam",
diff --git a/docs/documentation/platform/pam/accounts/clickhouse.mdx b/docs/documentation/platform/pam/accounts/clickhouse.mdx
new file mode 100644
index 0000000000..71ab5ed12d
--- /dev/null
+++ b/docs/documentation/platform/pam/accounts/clickhouse.mdx
@@ -0,0 +1,122 @@
+---
+title: "ClickHouse accounts"
+sidebarTitle: "ClickHouse"
+description: "Add and connect to ClickHouse databases."
+---
+
+ClickHouse accounts let you manage access to a ClickHouse database. Users connect through Web Access or the CLI, and every statement they run is recorded in the [session](/documentation/platform/pam/sessions/overview).
+
+Sessions reach ClickHouse over its HTTP interface, on port 8123 or 8443, rather than the native protocol on 9000. Every request passes through the [gateway](/documentation/platform/gateways/overview) in your own network, and the credential never reaches the client.
+
+## Prerequisites
+
+- A ClickHouse user for Infisical to connect as.
+- The HTTP interface enabled on the target. `http_port` (8123) is on by default in a stock ClickHouse configuration. `https_port` (8443) needs a certificate configured, and is what ClickHouse Cloud exposes.
+- A [gateway](/documentation/platform/gateways/overview) that can reach that port. A gateway that predates ClickHouse support refuses the session with a version error.
+
+## Creating an account
+
+<Steps>
+ <Step title="Start adding an account">
+ Go to **Privileged Access Management → Accounts** and select **Add Account**.
+ </Step>
+ <Step title="Select a folder and template">
+ Choose which [folder](/documentation/platform/pam/folders/overview) to add the account to, then select a ClickHouse [template](/documentation/platform/pam/templates/overview).
+ </Step>
+ <Step title="Enter connection details">
+ | Field | Description |
+ |-------|-------------|
+ | **Name** | A descriptive name (e.g., `analytics-prod`) |
+ | **Host** | ClickHouse host |
+ | **Port** | The HTTP interface port. 8123 for plain HTTP, 8443 for HTTPS |
+ | **Database** | The database sessions open. Web Access lists the tables inside it |
+ | **SSL Enabled** | Use HTTPS for the connection. Required for port 8443 and for ClickHouse Cloud |
+ | **Reject Unauthorized** | Reject connections with invalid certificates (only if SSL enabled) |
+ | **SSL Certificate** | Custom CA certificate (only if SSL enabled) |
+ </Step>
+ <Step title="Enter credentials">
+ | Field | Description |
+ |-------|-------------|
+ | **Username** | The ClickHouse user sessions connect as. Use `default` for the built-in user |
+ | **Password** | The user's password. Leave blank for a user created with `no_password` |
+ </Step>
+ <Step title="Save">
+ Select **Create**. Infisical signs in to ClickHouse through the gateway and runs one statement to confirm the credential works before saving the account.
+ </Step>
+</Steps>
+
+## Permissions
+
+What a session can do comes from the ClickHouse grants on the account's user, so grant that user only what the people using the account need. Web Access reads the database, table and column lists from `system.databases`, `system.tables` and `system.columns`, which every user can read for the objects they already have access to.
+
+```sql
+CREATE USER pam_service IDENTIFIED WITH sha256_password BY '<password>';
+GRANT SELECT ON analytics.* TO pam_service;
+```
+
+The account's **Database** sets what a session opens by default, not a boundary it stays inside: a session can query any database the user holds a grant on, and Web Access lists all of them. Scope the grants rather than the account's database field.
+
+Command blocking matches the text of each statement, so a statement that builds SQL at runtime can run something a pattern would otherwise reject. Use ClickHouse grants for restrictions that have to hold.
+
+## Connecting
+
+<Tabs>
+ <Tab title="Web Access">
+ Web Access provides a browser-based interface with two tools:
+
+ - **Data Explorer** — browse tables, view data, filter and sort, export to CSV/JSON
+ - **SQL Editor** — write and run SQL queries
+
+ To connect:
+
+ 1. Go to **Privileged Access Management → Accounts**
+ 2. Find the account and select the rocket icon (or select **Launch Session** from the menu)
+ 3. Select **Connect in Browser**
+
+ ClickHouse has no schema layer inside a database, so the Data Explorer sidebar lists databases where it lists schemas for other account types.
+
+ </Tab>
+ <Tab title="CLI">
+ The CLI starts a local proxy that speaks ClickHouse's HTTP interface on `127.0.0.1`. Connect with TLS off and no certificate to trust, since the hop to the gateway is already an encrypted tunnel. The username and password a client sends are ignored, because the gateway authenticates for you.
+
+ ```bash
+ infisical pam access analytics/clickhouse-prod
+ ```
+
+ The command prints the port and a ready-made connection string. JDBC clients such as DBeaver and DataGrip, `clickhouse-connect`, `@clickhouse/client`, and `curl` all speak this interface. `clickhouse-client` and Python's `clickhouse-driver` speak only the native protocol, so they can't use this port.
+
+ ```bash
+ curl 'http://127.0.0.1:<port>/?query=SELECT+1'
+ ```
+
+ **Flags:**
+ - `--port <port>` — use a specific local port (otherwise one is assigned automatically)
+ - `--reason <reason>` — provide an access reason (if required by template)
+
+ </Tab>
+</Tabs>
+
+The Data Explorer shows the first 1,000 rows a statement produces and tells you when there are more. ClickHouse itself imposes no such limit; use the CLI with your own client to work with a full result set.
+
+<Note>
+ ClickHouse applies row changes as asynchronous mutations rather than as statements that take effect when they return, so the Data Explorer grid is read-only for every table. Run `ALTER TABLE ... UPDATE` or `DELETE FROM` from the SQL Editor instead. The column marked as a key in the grid is the table's sorting key, which ClickHouse calls the primary key: it's an index, not a unique constraint.
+</Note>
+
+## Recording
+
+Every statement a session runs is recorded, along with the outcome of each one, and appears under **Session Logs** on the session. Web Access and the CLI both reach ClickHouse through the gateway, so recording works the same for either. Recordings are encrypted with a per-session key and written to the storage backend the [template](/documentation/platform/pam/templates/overview) selects, the same as any other account type.
+
+The template's **Command Blocking** policy applies to ClickHouse as well: a statement matching one of its patterns is rejected before it reaches ClickHouse, and the rejection is recorded. **Session Log Masking** patterns are applied to the recording before it's written.
+
+Applying that policy means reading the statement first, so on an account that blocks commands a request body over one megabyte is refused, and one compressed with anything other than `gzip` or `deflate` is rejected outright. Send large inserts in smaller batches, or use an account without the policy, where the body streams through and only its first megabyte is recorded.
+
+## Next steps
+
+<CardGroup cols={2}>
+ <Card title="Sessions" icon="display" href="/documentation/platform/pam/sessions/overview">
+ View and manage sessions.
+ </Card>
+ <Card title="Access requests" icon="user-check" href="/documentation/platform/pam/access-requests/overview">
+ Require approval before a session starts.
+ </Card>
+</CardGroup>
diff --git a/docs/documentation/platform/pam/accounts/overview.mdx b/docs/documentation/platform/pam/accounts/overview.mdx
index cda51e9b7d..bf50b886f5 100644
--- a/docs/documentation/platform/pam/accounts/overview.mdx
+++ b/docs/documentation/platform/pam/accounts/overview.mdx
@@ -21,6 +21,7 @@ PAM supports the following account types:
| [**MongoDB**](/documentation/platform/pam/accounts/mongodb) | MongoDB databases | |
| [**Redis**](/documentation/platform/pam/accounts/redis) | Redis databases | ✓ |
| [**Snowflake**](/documentation/platform/pam/accounts/snowflake) | Snowflake accounts | ✓ |
+| [**ClickHouse**](/documentation/platform/pam/accounts/clickhouse) | ClickHouse databases | ✓ |
| [**SSH**](/documentation/platform/pam/accounts/ssh) | Linux/Unix servers | ✓ |
| [**Kubernetes**](/documentation/platform/pam/accounts/kubernetes) | Kubernetes clusters | |
| [**AWS IAM**](/documentation/platform/pam/accounts/aws-iam) | AWS IAM roles | ✓ |
diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts
index 98900ab83c..e052de3a95 100644
--- a/frontend/src/hooks/api/pam/enums.ts
+++ b/frontend/src/hooks/api/pam/enums.ts
@@ -7,6 +7,7 @@ export enum PamAccountType {
MongoDB = "mongodb",
Redis = "redis",
Snowflake = "snowflake",
+ ClickHouse = "clickhouse",
Kubernetes = "kubernetes",
AwsIam = "aws-iam",
GcpServiceAccount = "gcp-service-account",
diff --git a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
index 2d6bd0d07f..86385e80bf 100644
--- a/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
+++ b/frontend/src/pages/pam/PamAccountAccessPage/PamAccountAccessPage.tsx
@@ -133,7 +133,8 @@ const PageContent = () => {
if (
account.accountType === PamAccountType.Postgres ||
account.accountType === PamAccountType.MySQL ||
- account.accountType === PamAccountType.Snowflake
+ account.accountType === PamAccountType.Snowflake ||
+ account.accountType === PamAccountType.ClickHouse
) {
return <PamDataExplorerPage reason={reason} mfaSessionId={mfaSessionId} />;
}
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
index 69b5c1e374..dcc4fd9a4c 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/PamDataExplorerPage.tsx
@@ -28,7 +28,8 @@ import { useQueryTabs } from "./use-query-tabs";
const DIALECT_BY_ACCOUNT_TYPE: Partial<Record<PamAccountType, SqlDialect>> = {
[PamAccountType.MySQL]: "mysql",
- [PamAccountType.Snowflake]: "snowflake"
+ [PamAccountType.Snowflake]: "snowflake",
+ [PamAccountType.ClickHouse]: "clickhouse"
};
type Props = {
@@ -55,6 +56,8 @@ export const PamDataExplorerPage = ({ reason, mfaSessionId }: Props = {}) => {
defaultSchema = connectionDetails?.database ?? "";
} else if (dialect === "snowflake") {
defaultSchema = connectionDetails?.schema ?? "PUBLIC";
+ } else if (dialect === "clickhouse") {
+ defaultSchema = connectionDetails?.database ?? "default";
} else {
defaultSchema = "public";
}
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
index 2febc2dfc5..a3d9d7872c 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerGrid.tsx
@@ -20,6 +20,7 @@ import {
buildInsertQuery,
buildSelectQuery,
buildUpdateQuery,
+ supportsRowEditing,
wrapInTransaction
} from "../sql-generation";
import { DataExplorerToolbar } from "./DataExplorerToolbar";
@@ -47,6 +48,14 @@ type DataExplorerGridProps = {
const ROW_KEY_PREFIX = "__new_";
+function readOnlyReason(dialect: SqlDialect, tableType?: string): string {
+ if (!supportsRowEditing(dialect)) {
+ return "ClickHouse applies row changes as asynchronous mutations, so the grid is read-only. Edit from the SQL editor with ALTER TABLE ... UPDATE or DELETE FROM.";
+ }
+ if (tableType === "view" || tableType === "materialized_view") return "This view is read-only.";
+ return "This table has no primary key. Browsing is read-only — editing requires a primary key.";
+}
+
function cellValuesEqual(a: unknown, b: unknown): boolean {
if (a === null && b === null) return true;
if (a === null || b === null) return false;
@@ -211,7 +220,7 @@ export const DataExplorerGrid = ({
const primaryKeys = tableDetail?.primaryKeys ?? [];
const foreignKeys = tableDetail?.foreignKeys ?? [];
const tableColumns = tableDetail?.columns ?? [];
- const hasPrimaryKey = primaryKeys.length > 0;
+ const canEditRows = primaryKeys.length > 0 && supportsRowEditing(dialect);
const primaryKeysRef = useRef(primaryKeys);
primaryKeysRef.current = primaryKeys;
@@ -224,10 +233,10 @@ export const DataExplorerGrid = ({
// Build TanStack Table column definitions from PG metadata
const columnDefs = useMemo(
() =>
- hasPrimaryKey
+ canEditRows
? [SELECT_COLUMN, ...buildColumnDefs(tableColumns, primaryKeys, foreignKeys)]
: buildColumnDefs(tableColumns, primaryKeys, foreignKeys),
- [hasPrimaryKey, tableColumns, primaryKeys, foreignKeys]
+ [canEditRows, tableColumns, primaryKeys, foreignKeys]
);
const fetchData = useCallback(
@@ -599,11 +608,11 @@ export const DataExplorerGrid = ({
columns: columnDefs,
onDataChange: handleDataChange,
getRowId,
- readOnly: !hasPrimaryKey,
+ readOnly: !canEditRows,
rowHeight: "short",
enableSearch: true,
- enablePaste: hasPrimaryKey,
- onRowsDelete: hasPrimaryKey ? handleRowsDelete : undefined,
+ enablePaste: canEditRows,
+ onRowsDelete: canEditRows ? handleRowsDelete : undefined,
onRowSelectionChange: (rowSelection) => {
const selectedIds = new Set(Object.keys(rowSelection).filter((k) => rowSelection[k]));
setSelectedRowCount(selectedIds.size);
@@ -723,7 +732,7 @@ export const DataExplorerGrid = ({
onOffsetChange={handleOffsetChange}
onPageSizeChange={handlePageSizeChange}
executionTimeMs={executionTimeMs}
- hasPrimaryKey={hasPrimaryKey}
+ canEditRows={canEditRows}
isDataLoading={isDataLoading}
onRefresh={async () => {
if (onRefresh) await onRefresh();
@@ -748,15 +757,11 @@ export const DataExplorerGrid = ({
dialect={dialect}
/>
- {!hasPrimaryKey && (
+ {!canEditRows && (
<div className="shrink-0 px-3 py-3">
<Alert variant="info" className="py-2">
<EyeIcon />
- <AlertDescription>
- {tableType === "view" || tableType === "materialized_view"
- ? "This view is read-only."
- : "This table has no primary key. Browsing is read-only — editing requires a primary key."}
- </AlertDescription>
+ <AlertDescription>{readOnlyReason(dialect, tableType)}</AlertDescription>
</Alert>
</div>
)}
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx
index c7898719e1..db2dbf986c 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx
+++ b/frontend/src/pages/pam/PamDataExplorerPage/components/DataExplorerToolbar.tsx
@@ -39,7 +39,7 @@ type DataExplorerToolbarProps = {
onOffsetChange: (offset: number) => void;
onPageSizeChange: (size: number) => void;
executionTimeMs: number | null;
- hasPrimaryKey: boolean;
+ canEditRows: boolean;
isDataLoading?: boolean;
onRefresh: () => void;
isRefreshing?: boolean;
@@ -68,7 +68,7 @@ export const DataExplorerToolbar = ({
onOffsetChange,
onPageSizeChange,
executionTimeMs,
- hasPrimaryKey,
+ canEditRows,
isDataLoading = false,
onRefresh,
isRefreshing = false,
@@ -101,7 +101,7 @@ export const DataExplorerToolbar = ({
disabled={isDataLoading}
/>
- {hasPrimaryKey && (
+ {canEditRows && (
<>
<div className="h-4 w-px bg-border" />
<Button variant="outline" size="xs" onClick={onAddRecord} className="gap-1">
@@ -111,7 +111,7 @@ export const DataExplorerToolbar = ({
</>
)}
- {selectedRowCount > 0 && hasPrimaryKey && (
+ {selectedRowCount > 0 && canEditRows && (
<Button variant="danger" size="xs" onClick={onDeleteSelected} className="gap-1">
<Trash2Icon className="size-3" />
Delete {selectedRowCount} record{selectedRowCount !== 1 ? "s" : ""}
diff --git a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
index eb39af818b..9ae0d2dcf2 100644
--- a/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
+++ b/frontend/src/pages/pam/PamDataExplorerPage/sql-generation.ts
@@ -1,7 +1,18 @@
// Client-side SQL generation for the Data Explorer.
// All identifiers are properly quoted to prevent SQL injection.
-export type SqlDialect = "postgres" | "mysql" | "snowflake";
+export type SqlDialect = "postgres" | "mysql" | "snowflake" | "clickhouse";
+
+export function supportsRowEditing(dialect: SqlDialect): boolean {
+ return dialect !== "clickhouse";
+}
+
+function assertRowEditingSupported(dialect: SqlDialect): void {
+ if (supportsRowEditing(dialect)) return;
+ throw new Error(
+ "ClickHouse rows can't be edited from the grid. Use the SQL editor with ALTER TABLE ... UPDATE or DELETE FROM."
+ );
+}
function quoteIdent(name: string, dialect: SqlDialect = "postgres"): string {
if (dialect === "mysql") return `\`${name.replace(/`/g, "``")}\``;
@@ -141,6 +152,7 @@ export function buildInsertQuery(params: {
dialect?: SqlDialect;
}): string {
const { schema, table, row, dialect = "postgres" } = params;
+ assertRowEditingSupported(dialect);
const tableName = `${quoteIdent(schema, dialect)}.${quoteIdent(table, dialect)}`;
const entries = Object.entries(row).filter(([, v]) => v !== undefined && v !== "");
if (entries.length === 0) {
@@ -164,6 +176,7 @@ export function buildUpdateQuery(params: {
dialect?: SqlDialect;
}): string {
const { schema, table, changes, primaryKeyMatch, dialect = "postgres" } = params;
+ assertRowEditingSupported(dialect);
if (Object.keys(primaryKeyMatch).length === 0) {
throw new Error("UPDATE requires at least one primary key condition");
}
@@ -185,6 +198,7 @@ export function buildDeleteQuery(params: {
dialect?: SqlDialect;
}): string {
const { schema, table, primaryKeyMatch, dialect = "postgres" } = params;
+ assertRowEditingSupported(dialect);
if (Object.keys(primaryKeyMatch).length === 0) {
throw new Error("DELETE requires at least one primary key condition");
}
diff --git a/frontend/src/pages/pam/components/policyEditors/index.tsx b/frontend/src/pages/pam/components/policyEditors/index.tsx
index 8045d43f8c..3845d4ca1c 100644
--- a/frontend/src/pages/pam/components/policyEditors/index.tsx
+++ b/frontend/src/pages/pam/components/policyEditors/index.tsx
@@ -13,7 +13,8 @@ const DEFAULT_PATTERN_PLACEHOLDER =
const SQL_PATTERN_PLACEHOLDER = "^\\s*drop\\b\n\\btruncate\\b\n^\\s*grant\\b";
const COMMAND_BLOCKING_PLACEHOLDERS: Partial<Record<PamAccountType, string>> = {
- [PamAccountType.Snowflake]: SQL_PATTERN_PLACEHOLDER
+ [PamAccountType.Snowflake]: SQL_PATTERN_PLACEHOLDER,
+ [PamAccountType.ClickHouse]: SQL_PATTERN_PLACEHOLDER
};
const CommandBlockingEditor = ({ accountType, ...props }: PolicyEditorProps) => (