Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(audit-log): add ClickHouse migration status and alert system
Victor Hugo dos Santos09443665ac1f
diff --git a/backend/src/ee/services/audit-log/audit-log-dal.ts b/backend/src/ee/services/audit-log/audit-log-dal.tsindex b2204553e4..7995bee322 100644--- a/backend/src/ee/services/audit-log/audit-log-dal.ts+++ b/backend/src/ee/services/audit-log/audit-log-dal.ts@@ -15,6 +15,7 @@ import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, filterableSecretEvents } fromexport interface TAuditLogDALFactory extends Omit<TOrmify<TableName.AuditLog>, "find"> {pruneAuditLog: () => Promise<void>;+ getApproximateRowCount: () => Promise<number>;find: (arg: Omit<TFindQuery, "actor" | "eventType"> & {actorId?: string | undefined;@@ -202,6 +203,26 @@ export const auditLogDALFactory = (db: TDbClient) => {logger.info(`${QueueName.DailyResourceCleanUp}: audit log completed`);};+ const getApproximateRowCount: TAuditLogDALFactory["getApproximateRowCount"] = async () => {+ try {+ const result = await db.raw<{ rows: Array<{ count: string | number }> }>(+ `SELECT n_live_tup::bigint AS count FROM pg_stat_user_tables WHERE relname = ?`,+ [TableName.AuditLog]+ );+ if (!result.rows?.[0]?.count) {+ const fallback = await db.raw<{ rows: Array<{ count: string | number }> }>(+ `SELECT reltuples::bigint AS count FROM pg_class WHERE relname = ?`,+ [TableName.AuditLog]+ );+ return Number(fallback.rows?.[0]?.count ?? 0);+ }+ return Number(result.rows[0].count);+ } catch (error) {+ logger.error(error, "Failed to get approximate audit log row count");+ return 0;+ }+ };+const create: TAuditLogDALFactory["create"] = async (tx) => {const config = getConfig();@@ -217,5 +238,5 @@ export const auditLogDALFactory = (db: TDbClient) => {return auditLogOrm.create(tx);};- return { ...auditLogOrm, create, pruneAuditLog, find };+ return { ...auditLogOrm, create, pruneAuditLog, getApproximateRowCount, find };};diff --git a/backend/src/ee/services/audit-log/audit-log-service.ts b/backend/src/ee/services/audit-log/audit-log-service.tsindex b2560f4b08..dd2c5eabff 100644--- a/backend/src/ee/services/audit-log/audit-log-service.ts+++ b/backend/src/ee/services/audit-log/audit-log-service.ts@@ -1,11 +1,16 @@import { ForbiddenError } from "@casl/ability";import { requestContext } from "@fastify/request-context";-import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";+import { ActionProjectType, OrganizationActionScope, TUsers } from "@app/db/schemas";+import { TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { ActorType } from "@app/services/auth/auth-type";+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";+import { NotificationType } from "@app/services/notification/notification-types";+import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";+import { TUserDALFactory } from "@app/services/user/user-dal";import { OrgPermissionAuditLogsActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";@@ -15,18 +20,29 @@ import { TAuditLogDALFactory } from "./audit-log-dal";import { TAuditLogQueueServiceFactory } from "./audit-log-queue";import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, TAuditLogServiceFactory } from "./audit-log-types";+const AUDIT_LOG_ROW_WARNING_THRESHOLD = 300_000_000;+const AUDIT_LOG_ALERT_ROW_INCREMENT = 10_000_000;+type TAuditLogServiceFactoryDep = {auditLogDAL: TAuditLogDALFactory;clickhouseAuditLogDAL?: TClickHouseAuditLogDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;auditLogQueue: TAuditLogQueueServiceFactory;+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;+ smtpService: Pick<TSmtpService, "sendMail">;+ userDAL: Pick<TUserDALFactory, "getUsersByFilter">;+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;};export const auditLogServiceFactory = ({auditLogDAL,clickhouseAuditLogDAL,auditLogQueue,- permissionService+ permissionService,+ keyStore,+ smtpService,+ userDAL,+ notificationService}: TAuditLogServiceFactoryDep): TAuditLogServiceFactory => {const listAuditLogs: TAuditLogServiceFactory["listAuditLogs"] = async ({actorAuthMethod,@@ -128,8 +144,87 @@ export const auditLogServiceFactory = ({return auditLogQueue.pushToLog(el);};+ const getAuditLogMigrationStatus = async () => {+ const appCfg = getConfig();+ const clickHouseConfigured = Boolean(appCfg.isClickHouseConfigured && appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED);+ const auditLogGenerationDisabled = Boolean(appCfg.DISABLE_AUDIT_LOG_GENERATION);+ const auditLogStorageDisabled = Boolean(appCfg.DISABLE_AUDIT_LOG_STORAGE);+ const auditLogRowCount = await auditLogDAL.getApproximateRowCount();++ return {+ clickHouseConfigured,+ auditLogGenerationDisabled,+ auditLogStorageDisabled,+ auditLogRowCount+ };+ };++ const checkClickHouseMigrationAlert = async () => {+ const appCfg = getConfig();+ const isClickHouseConfigured = appCfg.isClickHouseConfigured && appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED;+ if (isClickHouseConfigured) return;++ const rowCount: number = await auditLogDAL.getApproximateRowCount();++ if (rowCount < AUDIT_LOG_ROW_WARNING_THRESHOLD) return;++ const lastAlertedAt: string | null = await keyStore.getItem("audit-log-migration-alert-last-row-count");+ const lastAlertedRowCount = lastAlertedAt ? Number(lastAlertedAt) : 0;++ if (lastAlertedRowCount > 0 && rowCount < lastAlertedRowCount + AUDIT_LOG_ALERT_ROW_INCREMENT) return;++ logger.info(+ `checkClickHouseMigrationAlert: alert triggered (rowCount=${rowCount}, lastAlerted=${lastAlertedRowCount})`+ );++ const superAdminsResult: { users: TUsers[]; total: number } = await userDAL.getUsersByFilter({+ limit: 1000,+ offset: 0,+ searchTerm: "",+ adminsOnly: true+ });++ if (superAdminsResult.users.length === 0) return;++ await Promise.all(+ superAdminsResult.users.map((admin: TUsers) =>+ smtpService.sendMail({+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ template: SmtpTemplates.AuditLogMigrationAlert,+ subjectLine: "Action recommended: Audit log storage is large",+ recipients: [admin.email!],+ substitutions: {+ siteUrl: appCfg.SITE_URL+ }+ })+ )+ ).catch((error) => {+ logger.error(error, "Failed to send audit log migration alert emails");+ });++ await notificationService+ .createUserNotifications(+ superAdminsResult.users.map((admin: TUsers) => ({+ userId: admin.id,+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ type: NotificationType.AUDIT_LOG_MIGRATION_RECOMMENDED,+ title: "Audit log migration recommended",+ body: "Your audit log table has grown large. Consider configuring ClickHouse as your audit log storage backend to maintain query performance.",+ link: "/admin/audit-logs"+ }))+ )+ .catch((error) => {+ logger.error(error, "Failed to create audit log migration alert notifications");+ });++ await keyStore.setItemWithExpiry("audit-log-migration-alert-last-row-count", 31536000, String(rowCount));+ logger.info(`checkClickHouseMigrationAlert: alert sent to super admins (rowCount=${rowCount})`);+ };+return {createAuditLog,- listAuditLogs+ listAuditLogs,+ getAuditLogMigrationStatus,+ checkClickHouseMigrationAlert};};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex e9726fa2fc..2aaf67f629 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -117,6 +117,13 @@ export type TAuditLogServiceFactory = {projectName?: string | null | undefined;}[]>;+ getAuditLogMigrationStatus: () => Promise<{+ clickHouseConfigured: boolean;+ auditLogGenerationDisabled: boolean;+ auditLogStorageDisabled: boolean;+ auditLogRowCount: number;+ }>;+ checkClickHouseMigrationAlert: () => Promise<void>;};export type AuditLogInfo = Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor">;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 62c1f40bc5..d6d5339d68 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -826,7 +826,11 @@ export const registerRoutes = async (auditLogDAL,clickhouseAuditLogDAL,permissionService,- auditLogQueue+ auditLogQueue,+ keyStore,+ smtpService,+ userDAL,+ notificationService});const secretApprovalPolicyService = secretApprovalPolicyServiceFactory({projectEnvDAL,@@ -2130,6 +2134,7 @@ export const registerRoutes = async (const dailyResourceCleanUp = dailyResourceCleanUpQueueServiceFactory({scimService,auditLogDAL,+ auditLogService,queueService,secretVersionDAL,secretFolderVersionDAL: folderVersionDAL,diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.tsindex 50e64b6bb1..414697bdf9 100644--- a/backend/src/server/routes/v1/organization-router.ts+++ b/backend/src/server/routes/v1/organization-router.ts@@ -261,6 +261,28 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "GET",+ url: "/audit-logs/migration-status",+ config: {+ rateLimit: readLimit+ },+ schema: {+ response: {+ 200: z.object({+ clickHouseConfigured: z.boolean(),+ auditLogGenerationDisabled: z.boolean(),+ auditLogStorageDisabled: z.boolean(),+ auditLogRowCount: z.number()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async () => {+ return server.services.auditLog.getAuditLogMigrationStatus();+ }+ });+server.route({method: "GET",url: "/:organizationId/users",diff --git a/backend/src/services/notification/notification-types.ts b/backend/src/services/notification/notification-types.tsindex e75aa87868..a49113e0e4 100644--- a/backend/src/services/notification/notification-types.ts+++ b/backend/src/services/notification/notification-types.ts@@ -20,7 +20,8 @@ export enum NotificationType {RELAY_HEALTH_ALERT = "relay-health-alert",APPROVAL_REQUIRED = "approval-required",PKI_ALERT_CHANNEL_FAILED = "pki-alert-channel-failed",- CREDENTIAL_ROTATION_FAILED = "credential-rotation-failed"+ CREDENTIAL_ROTATION_FAILED = "credential-rotation-failed",+ AUDIT_LOG_MIGRATION_RECOMMENDED = "audit-log-migration-recommended"}export interface TCreateUserNotificationDTO {diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.tsindex 3bc04bac64..cf76ed933c 100644--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts@@ -1,4 +1,5 @@import { TAuditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";+import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { TScepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";import { TScimServiceFactory } from "@app/ee/services/scim/scim-types";import { TSnapshotDALFactory } from "@app/ee/services/secret-snapshot/snapshot-dal";@@ -22,6 +23,7 @@ import { TServiceTokenServiceFactory } from "../service-token/service-token-servtype TDailyResourceCleanUpQueueServiceFactoryDep = {auditLogDAL: Pick<TAuditLogDALFactory, "pruneAuditLog">;+ auditLogService: Pick<TAuditLogServiceFactory, "checkClickHouseMigrationAlert">;identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "removeExpiredTokens">;identityUniversalAuthClientSecretDAL: Pick<TIdentityUaClientSecretDALFactory, "removeExpiredClientSecrets">;secretVersionDAL: Pick<TSecretVersionDALFactory, "pruneExcessVersions">;@@ -46,6 +48,7 @@ export type TDailyResourceCleanUpQueueServiceFactory = ReturnType<typeof dailyReexport const dailyResourceCleanUpQueueServiceFactory = ({auditLogDAL,+ auditLogService,queueService,snapshotDAL,secretVersionDAL,@@ -90,6 +93,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({await scimService.notifyExpiringTokens();await orgService.notifyInvitedUsers();await auditLogDAL.pruneAuditLog();+ await auditLogService.checkClickHouseMigrationAlert();await userNotificationDAL.pruneNotifications();await keyValueStoreDAL.pruneExpiredKeys();await queueJobsDAL.pruneQueueJobs();diff --git a/backend/src/services/smtp/emails/AuditLogMigrationAlertTemplate.tsx b/backend/src/services/smtp/emails/AuditLogMigrationAlertTemplate.tsxnew file mode 100644index 0000000000..31b29bb340--- /dev/null+++ b/backend/src/services/smtp/emails/AuditLogMigrationAlertTemplate.tsx@@ -0,0 +1,43 @@+import { Heading, Section, Text } from "@react-email/components";++import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";+import { BaseLink } from "./BaseLink";++type AuditLogMigrationAlertTemplateProps = Omit<BaseEmailWrapperProps, "title" | "preview" | "children">;++export const AuditLogMigrationAlertTemplate = ({ siteUrl }: AuditLogMigrationAlertTemplateProps) => {+ return (+ <BaseEmailWrapper+ title="Action recommended: Audit log storage is large"+ preview="Your audit log table has grown to a size that may impact query performance."+ siteUrl={siteUrl}+ >+ <Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">+ Action Recommended: Audit Log Storage is Large+ </Heading>+ <Section className="px-[24px] mt-[36px] pt-[12px] pb-[8px] border border-solid border-gray-200 rounded-md bg-gray-50">+ <Text className="text-black text-[14px] leading-[24px]">+ Your Infisical audit log table has grown to a size where PostgreSQL analytical queries will degrade over time+ regardless of hardware tier.+ </Text>+ <Text className="text-black text-[14px] leading-[24px]">+ To maintain query performance and reduce storage costs, we recommend configuring ClickHouse as your audit log+ storage backend. ClickHouse provides columnar storage with superior compression and query performance+ optimized for audit log analytics at scale.+ </Text>+ <Text className="text-black text-[14px] leading-[24px]">+ Learn more:{" "}+ <BaseLink href={`${siteUrl}/docs/documentation/platform/audit-logs-clickhouse-setup`}>+ ClickHouse Setup Guide+ </BaseLink>+ </Text>+ </Section>+ </BaseEmailWrapper>+ );+};++export default AuditLogMigrationAlertTemplate;++AuditLogMigrationAlertTemplate.PreviewProps = {+ siteUrl: "https://infisical.com"+} as AuditLogMigrationAlertTemplateProps;diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.tsindex 5f347c56b2..1cbad3ef31 100644--- a/backend/src/services/smtp/emails/index.ts+++ b/backend/src/services/smtp/emails/index.ts@@ -1,6 +1,7 @@export * from "./AccessApprovalRequestTemplate";export * from "./AccessApprovalRequestUpdatedTemplate";export * from "./AccountDeletionConfirmationTemplate";+export * from "./AuditLogMigrationAlertTemplate";export * from "./CredentialRotationFailedTemplate";export * from "./EmailMfaTemplate";export * from "./EmailVerificationTemplate";diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.tsindex 4e37013726..3449029836 100644--- a/backend/src/services/smtp/smtp-service.ts+++ b/backend/src/services/smtp/smtp-service.ts@@ -10,6 +10,7 @@ import {AccessApprovalRequestTemplate,AccessApprovalRequestUpdatedTemplate,AccountDeletionConfirmationTemplate,+ AuditLogMigrationAlertTemplate,CredentialRotationFailedTemplate,EmailMfaTemplate,EmailVerificationTemplate,@@ -97,7 +98,8 @@ export enum SmtpTemplates {AccountDeletionConfirmation = "accountDeletionConfirmation",HealthAlert = "healthAlert",DynamicSecretLeaseRevocationFailed = "dynamicSecretLeaseRevocationFailed",- CredentialRotationFailed = "credentialRotationFailed"+ CredentialRotationFailed = "credentialRotationFailed",+ AuditLogMigrationAlert = "auditLogMigrationAlert"}export enum SmtpHost {@@ -149,7 +151,8 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {[SmtpTemplates.AccountDeletionConfirmation]: AccountDeletionConfirmationTemplate,[SmtpTemplates.HealthAlert]: HealthAlertTemplate,[SmtpTemplates.DynamicSecretLeaseRevocationFailed]: DynamicSecretLeaseRevocationFailedTemplate,- [SmtpTemplates.CredentialRotationFailed]: CredentialRotationFailedTemplate+ [SmtpTemplates.CredentialRotationFailed]: CredentialRotationFailedTemplate,+ [SmtpTemplates.AuditLogMigrationAlert]: AuditLogMigrationAlertTemplate};export const smtpServiceFactory = (cfg: TSmtpConfig) => {diff --git a/docs/docs.json b/docs/docs.jsonindex f202e0bed6..538c8adf55 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -94,6 +94,7 @@"group": "Audit Logs","pages": ["documentation/platform/audit-logs",+ "documentation/platform/audit-logs-clickhouse-setup","documentation/platform/audit-log-streams/audit-log-streams","documentation/platform/audit-log-streams/audit-log-streams-with-fluentbit"]diff --git a/docs/documentation/platform/audit-logs-clickhouse-setup.mdx b/docs/documentation/platform/audit-logs-clickhouse-setup.mdxnew file mode 100644index 0000000000..371788ad16--- /dev/null+++ b/docs/documentation/platform/audit-logs-clickhouse-setup.mdx@@ -0,0 +1,162 @@+---+title: "ClickHouse Setup"+description: "Configure ClickHouse as your audit log storage backend for high-volume deployments"+---++<Info>+This guide is for self-hosted Infisical deployments experiencing performance degradation with large audit log tables. ClickHouse is optional and only recommended for deployments with 300 million+ audit log rows.+</Info>++## Why ClickHouse?++For high-volume audit log workloads, ClickHouse provides significant advantages over PostgreSQL:++- **Superior compression**: ClickHouse's [columnar storage](https://clickhouse.com/docs/en/intro#why-columnar-databases-are-better-suited-for-olap) significantly reduces disk footprint compared to PostgreSQL's row-oriented storage.+- **Query performance**: Analytical queries with complex filters and aggregations are substantially faster due to ClickHouse's vectorized execution engine.++At high row counts, PostgreSQL analytical queries with JSON filter predicates begin to degrade regardless of hardware tier. ClickHouse is purpose-built for this scale.++## Prerequisites++1. A running ClickHouse instance (version 21.3+). See [ClickHouse deployment documentation](https://clickhouse.com/docs/en/install) for installation options.+2. A database created in ClickHouse for audit logs.+3. Network connectivity from your Infisical backend to the ClickHouse instance.++## Configuration++Set the following environment variables in your Infisical backend configuration:++```bash+# Required: ClickHouse connection URL+CLICKHOUSE_URL=http://username:password@clickhouse-host:8123/database_name++# Optional: Enable audit log writes to ClickHouse (default: true)+CLICKHOUSE_AUDIT_LOG_ENABLED=true++# Optional: Enable reading audit logs from ClickHouse instead of Postgres (default: false)+CLICKHOUSE_AUDIT_LOG_QUERY_ENABLED=false+```++### Connection URL Format++The `CLICKHOUSE_URL` follows this format:+```+http(s)://username:password@host:port/database+```++Example:+```+CLICKHOUSE_URL=http://infisical:[email protected]:8123/audit_logs+```++### Table Name (Optional)++By default, Infisical uses the `audit_logs` table in ClickHouse. Override with:++```bash+CLICKHOUSE_AUDIT_LOG_TABLE_NAME=custom_audit_logs+```++## How It Works++Once configured, Infisical automatically:++1. **Async batch writes**: Audit events are queued in Redis and batch-inserted into ClickHouse every 5 seconds via a background worker.+2. **Automatic schema creation**: On first startup, Infisical creates the audit log table in ClickHouse with an optimized schema (partitioned by day, primary key on `orgId`, `projectId`, `createdAt`).+3. **Dual-write mode**: Audit logs continue writing to PostgreSQL (for backward compatibility) unless you set `DISABLE_AUDIT_LOG_STORAGE=true`.+4. **Query routing**: When `CLICKHOUSE_AUDIT_LOG_QUERY_ENABLED=true`, the audit log API automatically reads from ClickHouse instead of PostgreSQL.++### Migration Strategy++**Recommended approach for existing deployments:**++1. **Phase 1** — Enable writes only:+ - Set `CLICKHOUSE_URL` and `CLICKHOUSE_AUDIT_LOG_ENABLED=true`+ - Keep `CLICKHOUSE_AUDIT_LOG_QUERY_ENABLED=false`+ - New audit logs write to both PostgreSQL and ClickHouse+ - Queries continue using PostgreSQL++2. **Phase 2** — Historical data migration (optional):+ - Use the `clickhouse-client` CLI to bulk-load historical audit logs from PostgreSQL into ClickHouse+ - Example: `INSERT INTO audit_logs SELECT * FROM postgresql('host:5432', 'db', 'audit_logs', 'user', 'password')`++3. **Phase 3** — Switch reads:+ - Set `CLICKHOUSE_AUDIT_LOG_QUERY_ENABLED=true`+ - Queries now use ClickHouse+ - Monitor for any issues++4. **Phase 4** — Cleanup (optional):+ - Once confident ClickHouse is working correctly, prune old PostgreSQL audit logs or set `DISABLE_AUDIT_LOG_STORAGE=true` to stop PostgreSQL writes entirely++## Docker Compose Example++Add a ClickHouse service to your `docker-compose.yml`:++```yaml+services:+ clickhouse:+ image: clickhouse/clickhouse-server:24-alpine+ restart: unless-stopped+ environment:+ CLICKHOUSE_DB: infisical_audit+ CLICKHOUSE_USER: infisical+ CLICKHOUSE_PASSWORD: changeme+ CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: 1+ ports:+ - "8123:8123"+ - "9000:9000"+ volumes:+ - clickhouse-data:/var/lib/clickhouse+ ulimits:+ nofile:+ soft: 262144+ hard: 262144++ backend:+ # ... existing backend config+ environment:+ # ... existing env vars+ CLICKHOUSE_URL: http://infisical:changeme@clickhouse:8123/infisical_audit+ CLICKHOUSE_AUDIT_LOG_ENABLED: true+ # Optional: switch reads to ClickHouse after historical data is migrated+ # CLICKHOUSE_AUDIT_LOG_QUERY_ENABLED: true+ depends_on:+ - clickhouse++volumes:+ clickhouse-data:+```++## Verification++After configuration, verify ClickHouse integration:++1. **Check backend logs** on startup for ClickHouse connection success+2. **Perform an action** in Infisical (e.g., read a secret)+3. **Query ClickHouse directly**:++```sql+SELECT count() FROM audit_logs;+SELECT * FROM audit_logs ORDER BY createdAt DESC LIMIT 10;+```++If rows appear in ClickHouse, the integration is working correctly.++## Troubleshooting++### Connection Errors++- Verify network connectivity: `curl http://clickhouse-host:8123/ping`+- Check credentials in `CLICKHOUSE_URL`+- Ensure the database exists in ClickHouse++### No Data in ClickHouse++- Check backend logs for batch insert errors+- Verify `CLICKHOUSE_AUDIT_LOG_ENABLED=true`+- Ensure Redis is configured (required for the audit log queue)++### Slow Queries in ClickHouse++- Verify the table was created with proper partitioning and primary key (Infisical creates this automatically on first run)+- Check ClickHouse query logs: `SELECT query, query_duration_ms FROM system.query_log ORDER BY event_time DESC LIMIT 10;`diff --git a/docs/documentation/platform/audit-logs.mdx b/docs/documentation/platform/audit-logs.mdxindex 10cf678850..3352d94472 100644--- a/docs/documentation/platform/audit-logs.mdx+++ b/docs/documentation/platform/audit-logs.mdx@@ -82,3 +82,7 @@ Each log contains the following data:}```</Accordion>++<Info>+**For high-volume self-hosted deployments:** If your audit log table is growing to hundreds of millions of rows, consider configuring [ClickHouse as your audit log storage backend](/documentation/platform/audit-logs-clickhouse-setup) to maintain query performance.+</Info>diff --git a/frontend/src/hooks/api/auditLogs/queries.tsx b/frontend/src/hooks/api/auditLogs/queries.tsxindex 006ae37ae7..e63c657dc1 100644--- a/frontend/src/hooks/api/auditLogs/queries.tsx+++ b/frontend/src/hooks/api/auditLogs/queries.tsx@@ -1,14 +1,15 @@-import { useInfiniteQuery } from "@tanstack/react-query";+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { onRequestError } from "@app/hooks/api/reactQuery";import { TReactQueryOptions } from "@app/types/reactQuery";-import { AuditLog, TGetAuditLogsFilter } from "./types";+import { AuditLog, AuditLogMigrationStatus, TGetAuditLogsFilter } from "./types";export const auditLogKeys = {getAuditLogs: (projectId: string | null, filters: TGetAuditLogsFilter) =>- [{ projectId, filters }, "audit-logs"] as const+ [{ projectId, filters }, "audit-logs"] as const,+ migrationStatus: ["audit-logs-migration-status"] as const};export const useGetAuditLogs = (@@ -53,3 +54,17 @@ export const useGetAuditLogs = (...options});};++const fetchAuditLogMigrationStatus = async () => {+ const { data } = await apiRequest.get<AuditLogMigrationStatus>(+ "/api/v1/organization/audit-logs/migration-status"+ );+ return data;+};++export const useGetAuditLogMigrationStatus = () => {+ return useQuery({+ queryKey: auditLogKeys.migrationStatus,+ queryFn: fetchAuditLogMigrationStatus+ });+};diff --git a/frontend/src/hooks/api/auditLogs/types.tsx b/frontend/src/hooks/api/auditLogs/types.tsxindex 9cab9d7f8d..762e0546ab 100644--- a/frontend/src/hooks/api/auditLogs/types.tsx+++ b/frontend/src/hooks/api/auditLogs/types.tsx@@ -4,6 +4,13 @@ import { PkiItemType } from "../pkiCollections/constants";import { WorkflowIntegration } from "../workflowIntegrations/types";import { ActorType, EventType, UserAgentType } from "./enums";+export type AuditLogMigrationStatus = {+ clickHouseConfigured: boolean;+ auditLogGenerationDisabled: boolean;+ auditLogStorageDisabled: boolean;+ auditLogRowCount: number;+};+export type TGetAuditLogsFilter = {eventType?: EventType[];userAgentType?: UserAgentType;diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsxindex a1583dba3d..c95ea95c2c 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx@@ -2,7 +2,11 @@ import { useEffect, useMemo, useState } from "react";import ms from "ms";import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";-import { DocumentationLinkBadge } from "@app/components/v3";+import {+ DocumentationLinkBadge,+ UnstableAlert,+ UnstableAlertDescription+} from "@app/components/v3";import {OrgPermissionAuditLogsActions,OrgPermissionSubjects,@@ -12,6 +16,7 @@ import {} from "@app/context";import { Timezone } from "@app/helpers/datetime";import { withPermission, withProjectPermission } from "@app/hoc";+import { useGetAuditLogMigrationStatus } from "@app/hooks/api/auditLogs";import { Project } from "@app/hooks/api/projects/types";import { usePopUp } from "@app/hooks/usePopUp";@@ -48,6 +53,16 @@ const LogsSectionComponent = ({}: Props) => {const { subscription } = useSubscription();const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);+ const { data: migrationStatus } = useGetAuditLogMigrationStatus();++ const AUDIT_LOG_ROW_WARNING_THRESHOLD = 300_000_000;+ const showClickHouseWarning =+ migrationStatus &&+ !migrationStatus.clickHouseConfigured &&+ !migrationStatus.auditLogStorageDisabled &&+ !migrationStatus.auditLogGenerationDisabled &&+ migrationStatus.auditLogRowCount >= AUDIT_LOG_ROW_WARNING_THRESHOLD;+const [logFilter, setLogFilter] = useState<TAuditLogFilterFormData>({eventType: presets?.eventType || [],actor: presets?.actorId,@@ -88,6 +103,25 @@ const LogsSectionComponent = ({if (pageView)return (<div className="w-full rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">+ {showClickHouseWarning && (+ <UnstableAlert variant="info" className="mb-4">+ <UnstableAlertDescription>+ <p>+ Your audit log table is growing large. PostgreSQL performance will degrade over time+ at this scale. Consider configuring{" "}+ <a+ href="https://infisical.com/docs/documentation/platform/audit-logs-clickhouse-setup"+ target="_blank"+ rel="noopener noreferrer"+ className="underline underline-offset-2 hover:opacity-80"+ >+ ClickHouse+ </a>{" "}+ as your audit log storage backend to maintain query performance.+ </p>+ </UnstableAlertDescription>+ </UnstableAlert>+ )}<div className="mb-4 flex flex-wrap items-center justify-between gap-y-2"><div><div className="flex items-center gap-x-2 whitespace-nowrap">@@ -154,6 +188,25 @@ const LogsSectionComponent = ({return (<div className="space-y-2">+ {showClickHouseWarning && (+ <UnstableAlert variant="info">+ <UnstableAlertDescription>+ <p>+ Your audit log table is growing large. PostgreSQL performance will degrade over time+ at this scale. Consider configuring{" "}+ <a+ href="https://infisical.com/docs/documentation/platform/audit-logs-clickhouse-setup"+ target="_blank"+ rel="noopener noreferrer"+ className="underline underline-offset-2 hover:opacity-80"+ >+ ClickHouse+ </a>{" "}+ as your audit log storage backend to maintain query performance.+ </p>+ </UnstableAlertDescription>+ </UnstableAlert>+ )}<div className="flex flex-wrap items-center gap-2 lg:justify-end">{showFilters && (<LogsDateFilter