Skip to content

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

if clickhouse enabled read insights from there

Dimitris Staratzis6e930628c327
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 2c0beea4fa..8cfd84f163 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -1056,6 +1056,21 @@ on must stay editable. The check reads the setting, not the plan, so it keeps ap
Only exempt a mode that refuses pools outright, the way gateway Kubernetes auth in Gateway review mode does
(`$assertCanAttachProxy` in `resource-auth-method-service.ts`), or the policy removes that mode entirely.
+### Audit Log Storage
+
+Audit logs live in **one** store at a time. When a ClickHouse client is configured and
+`CLICKHOUSE_AUDIT_LOG_ENABLED` is on (its default), `insertBatch` in `audit-log-queue.ts` writes only to
+ClickHouse and Postgres `audit_logs` receives nothing new. So **every reader of audit logs has to pick
+the store the same way** (`CLICKHOUSE_AUDIT_LOG_ENABLED && clickhouseAuditLogDAL`), as `auditLogService`,
+the audit report generators and insights do. A reader that only queries Postgres goes silently empty on
+ClickHouse instances, with no error anywhere; that is how the project insights cards broke. Postgres rows
+written before the switch are not backfilled, and readers do not merge the two stores.
+
+Two things to get right in a ClickHouse aggregate. `createdAt` is a `DateTime64(6)` with no column
+timezone, so pin day grouping and bound parameters to `'UTC'` or they follow the server's timezone. And
+the table is a `ReplacingMergeTree`: a retried batch inserts the same `id` twice and the copy goes away
+only at some later merge, so read with `FINAL` when an exact count matters.
+
### Audit Log Event Classes and Settings
Every `EventType` belongs to exactly one class in
diff --git a/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts b/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
index f6da19a0e6..a932d3f2ae 100644
--- a/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
+++ b/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
@@ -53,6 +53,33 @@ type TClickHouseAuthMethodRow = {
type TClickHouseAuthMethodRawRow = Omit<TClickHouseAuthMethodRow, "count"> & { count: string };
+type TClickHouseCountForProjectArg = TClickHouseCountByDateArg & { projectId: string };
+
+// actorMetadata is stored as the JSON text the client sent, so its key order is not stable and
+// grouping on the whole string would split one actor across rows. Only the keys insights reads
+// are extracted and grouped on.
+type TClickHouseProjectActorVolumeRawRow = {
+ date: string;
+ actor: string;
+ userId: string;
+ email: string;
+ username: string;
+ identityId: string;
+ name: string;
+ count: string;
+};
+
+type TClickHouseProjectAuthMethodRawRow = {
+ actor: string;
+ authMethod: string;
+ count: string;
+};
+
+// JSONExtractString returns "" for a missing key. Dropping those gives callers the same shape a
+// Postgres actorMetadata has, so their `||` fallbacks behave the same for both stores.
+const compactActorMetadata = (metadata: Record<string, string>) =>
+ Object.fromEntries(Object.entries(metadata).filter(([, value]) => value !== ""));
+
// Shape of a row returned from ClickHouse's JSONEachRow format
// actorMetadata and eventMetadata are String columns — they come back as raw JSON strings
type TClickHouseAuditLogRow = {
@@ -258,6 +285,8 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
}
};
+ // createdAt is stored without a timezone, so the bounds and toDate() are pinned to UTC. Otherwise
+ // they follow the server's timezone and disagree with the UTC day buckets insights builds.
const countByDateForOrg = async ({
orgId,
eventTypes,
@@ -266,12 +295,12 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
}: TClickHouseCountByDateArg): Promise<TClickHouseDateVolumeRow[]> => {
const query = `
SELECT
- toDate(createdAt) AS date,
+ toDate(createdAt, 'UTC') AS date,
count() AS count
FROM ${tableName}
WHERE orgId = {orgId:UUID}
- AND createdAt >= {startDate:DateTime64(6)}
- AND createdAt < {endDate:DateTime64(6)}
+ AND createdAt >= {startDate:DateTime64(6, 'UTC')}
+ AND createdAt < {endDate:DateTime64(6, 'UTC')}
AND eventType IN ({eventTypes:Array(String)})
GROUP BY date
`;
@@ -313,8 +342,8 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
count() AS count
FROM ${tableName}
WHERE orgId = {orgId:UUID}
- AND createdAt >= {startDate:DateTime64(6)}
- AND createdAt < {endDate:DateTime64(6)}
+ AND createdAt >= {startDate:DateTime64(6, 'UTC')}
+ AND createdAt < {endDate:DateTime64(6, 'UTC')}
AND eventType IN ({eventTypes:Array(String)})
AND actor = {actorType:String}
GROUP BY authMethod
@@ -348,5 +377,131 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
}
};
- return { find, countByDateForOrg, countByIdentityAuthMethodForOrg };
+ // FINAL collapses rows a retried batch inserted twice (same id), which ReplacingMergeTree otherwise
+ // removes only at some later merge. The primary key confines it to this project's time range.
+ const countByDateAndActorForProject = async ({
+ orgId,
+ projectId,
+ eventTypes,
+ startDate,
+ endDate
+ }: TClickHouseCountForProjectArg): Promise<
+ { date: string; actor: string; actorMetadata: Record<string, string>; count: number }[]
+ > => {
+ const query = `
+ SELECT
+ toDate(createdAt, 'UTC') AS date,
+ actor,
+ JSONExtractString(actorMetadata, 'userId') AS userId,
+ JSONExtractString(actorMetadata, 'email') AS email,
+ JSONExtractString(actorMetadata, 'username') AS username,
+ JSONExtractString(actorMetadata, 'identityId') AS identityId,
+ JSONExtractString(actorMetadata, 'name') AS name,
+ count() AS count
+ FROM ${tableName} FINAL
+ WHERE orgId = {orgId:UUID}
+ AND projectId = {projectId:String}
+ AND createdAt >= {startDate:DateTime64(6, 'UTC')}
+ AND createdAt < {endDate:DateTime64(6, 'UTC')}
+ AND eventType IN ({eventTypes:Array(String)})
+ GROUP BY date, actor, userId, email, username, identityId, name
+ `;
+
+ try {
+ const result = await clickhouseClient.query({
+ query,
+ query_params: {
+ orgId,
+ projectId,
+ // ClickHouse's DateTime64 parser rejects the trailing 'Z'
+ startDate: startDate.replace("Z", ""),
+ endDate: endDate.replace("Z", ""),
+ eventTypes
+ },
+ clickhouse_settings: {
+ max_execution_time: 10
+ },
+ format: "JSONEachRow"
+ });
+
+ const rows = await result.json<TClickHouseProjectActorVolumeRawRow>();
+
+ return rows.map(({ date, actor, count, ...actorMetadata }) => ({
+ date,
+ actor,
+ actorMetadata: compactActorMetadata(actorMetadata),
+ count: Number(count)
+ }));
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to aggregate audit logs by date and actor from ClickHouse [orgId=${orgId}] [projectId=${projectId}]`
+ );
+ throw new DatabaseError({ error });
+ }
+ };
+
+ const countByAuthMethodForProject = async ({
+ orgId,
+ projectId,
+ eventTypes,
+ startDate,
+ endDate
+ }: TClickHouseCountForProjectArg): Promise<
+ { actor: string; actorMetadata: Record<string, string>; count: number }[]
+ > => {
+ const query = `
+ SELECT
+ actor,
+ JSONExtractString(actorMetadata, 'authMethod') AS authMethod,
+ count() AS count
+ FROM ${tableName} FINAL
+ WHERE orgId = {orgId:UUID}
+ AND projectId = {projectId:String}
+ AND createdAt >= {startDate:DateTime64(6, 'UTC')}
+ AND createdAt < {endDate:DateTime64(6, 'UTC')}
+ AND eventType IN ({eventTypes:Array(String)})
+ GROUP BY actor, authMethod
+ `;
+
+ try {
+ const result = await clickhouseClient.query({
+ query,
+ query_params: {
+ orgId,
+ projectId,
+ // ClickHouse's DateTime64 parser rejects the trailing 'Z'
+ startDate: startDate.replace("Z", ""),
+ endDate: endDate.replace("Z", ""),
+ eventTypes
+ },
+ clickhouse_settings: {
+ max_execution_time: 10
+ },
+ format: "JSONEachRow"
+ });
+
+ const rows = await result.json<TClickHouseProjectAuthMethodRawRow>();
+
+ return rows.map(({ actor, authMethod, count }) => ({
+ actor,
+ actorMetadata: compactActorMetadata({ authMethod }),
+ count: Number(count)
+ }));
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to aggregate audit logs by auth method from ClickHouse [orgId=${orgId}] [projectId=${projectId}]`
+ );
+ throw new DatabaseError({ error });
+ }
+ };
+
+ return {
+ find,
+ countByDateForOrg,
+ countByIdentityAuthMethodForOrg,
+ countByDateAndActorForProject,
+ countByAuthMethodForProject
+ };
};
diff --git a/backend/src/ee/services/insights/insights-service.test.ts b/backend/src/ee/services/insights/insights-service.test.ts
index d6e4420716..0c2f2a2604 100644
--- a/backend/src/ee/services/insights/insights-service.test.ts
+++ b/backend/src/ee/services/insights/insights-service.test.ts
@@ -1,17 +1,28 @@
import { createMongoAbility, MongoAbility } from "@casl/ability";
-import { describe, expect, test } from "vitest";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { IdentityAuthMethod } from "@app/db/schemas";
import { TFeatureSet } from "@app/ee/services/license/license-types";
import {
OrgPermissionSecretsManagementInsightsActions,
OrgPermissionSet,
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
+import { ProjectPermissionInsightsActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
+import { OrgServiceActor } from "@app/lib/types";
import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
import { insightsServiceFactory, PROJECT_WARNINGS_CHUNK_SIZE, TInsightsServiceFactoryDep } from "./insights-service";
import { TSecretsProjectWarning } from "./insights-types";
+type TClickHouseAuditLogDAL = NonNullable<TInsightsServiceFactoryDep["clickhouseAuditLogDAL"]>;
+
+const appConfig = { CLICKHOUSE_AUDIT_LOG_ENABLED: false };
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => appConfig
+}));
+
const ORG_ID = "org-insights-chunk";
const CATALOG_SIZE = 1500;
@@ -206,3 +217,152 @@ describe("getSecretsProjects chunk pagination", () => {
expect(result.projects).toEqual(catalog.slice(offset, offset + limit));
});
});
+
+describe("project access insights audit log store", () => {
+ const PROJECT_ID = "project-insights-store";
+ const today = new Date().toISOString().slice(0, 10);
+
+ const projectActor = {
+ type: ActorType.USER,
+ id: "user-1",
+ authMethod: AuthMethod.EMAIL,
+ orgId: ORG_ID,
+ rootOrgId: ORG_ID,
+ parentOrgId: ORG_ID
+ } as OrgServiceActor;
+
+ const buildProjectService = ({ withClickHouse }: { withClickHouse: boolean }) => {
+ const cachedKeys: string[] = [];
+ const postgres = {
+ countByDateAndActor: vi.fn(async () => []),
+ countByAuthMethod: vi.fn(async () => [])
+ };
+ const volumeRows: Awaited<ReturnType<TClickHouseAuditLogDAL["countByDateAndActorForProject"]>> = [
+ { date: today, actor: ActorType.USER, actorMetadata: { userId: "user-1", email: "[email protected]" }, count: 2 },
+ { date: today, actor: ActorType.IDENTITY, actorMetadata: { identityId: "identity-1", name: "ci-bot" }, count: 4 }
+ ];
+ const authMethodRows: Awaited<ReturnType<TClickHouseAuditLogDAL["countByAuthMethodForProject"]>> = [
+ { actor: ActorType.IDENTITY, actorMetadata: { authMethod: IdentityAuthMethod.UNIVERSAL_AUTH }, count: 4 },
+ { actor: ActorType.USER, actorMetadata: { authMethod: AuthMethod.EMAIL }, count: 2 }
+ ];
+ const clickhouse = {
+ countByDateForOrg: unreachable("clickhouseAuditLogDAL.countByDateForOrg"),
+ countByIdentityAuthMethodForOrg: unreachable("clickhouseAuditLogDAL.countByIdentityAuthMethodForOrg"),
+ countByDateAndActorForProject: vi.fn(async () => volumeRows),
+ countByAuthMethodForProject: vi.fn(async () => authMethodRows)
+ };
+
+ const service = insightsServiceFactory({
+ ...projectScopedDepStubs,
+ auditLogDAL: postgres,
+ clickhouseAuditLogDAL: withClickHouse ? clickhouse : undefined,
+ userDAL: {
+ find: async () => [{ id: "user-1", firstName: "Ada", lastName: "Lovelace" }]
+ } as unknown as TInsightsServiceFactoryDep["userDAL"],
+ permissionService: {
+ getProjectPermission: async () => ({
+ permission: createMongoAbility([
+ { action: ProjectPermissionInsightsActions.Read, subject: ProjectPermissionSub.Insights }
+ ])
+ }),
+ getOrgPermission: unreachable("permissionService.getOrgPermission")
+ } as unknown as TInsightsServiceFactoryDep["permissionService"],
+ licenseService: {
+ getPlan: async () => ({ secretAccessInsights: true }) as unknown as TFeatureSet
+ } as TInsightsServiceFactoryDep["licenseService"],
+ keyStore: {
+ getItem: async () => null,
+ setItemWithExpiry: async (key: string) => {
+ cachedKeys.push(key);
+ return "OK";
+ },
+ ttl: async () => -2
+ } as unknown as TInsightsServiceFactoryDep["keyStore"],
+ orgDAL: {
+ countSecretManagerProjectMembers: unreachable("orgDAL.countSecretManagerProjectMembers"),
+ findById: unreachable("orgDAL.findById")
+ },
+ identityOrgMembershipDAL: {
+ countSecretManagerProjectIdentities: unreachable("identityOrgMembershipDAL.countSecretManagerProjectIdentities")
+ },
+ dynamicSecretLeaseDAL: {
+ countLeasesForOrg: unreachable("dynamicSecretLeaseDAL.countLeasesForOrg")
+ },
+ insightsDAL: {
+ findSecretCreationsByWeekForOrg: unreachable("insightsDAL.findSecretCreationsByWeekForOrg"),
+ countSecretCreationsForOrg: unreachable("insightsDAL.countSecretCreationsForOrg"),
+ findProjectWarningsForOrg: unreachable("insightsDAL.findProjectWarningsForOrg")
+ }
+ });
+
+ return { service, postgres, clickhouse, cachedKeys };
+ };
+
+ beforeEach(() => {
+ appConfig.CLICKHOUSE_AUDIT_LOG_ENABLED = false;
+ });
+
+ test("reads Postgres when ClickHouse audit logging is off", async () => {
+ const { service, postgres, clickhouse } = buildProjectService({ withClickHouse: true });
+
+ await service.getAccessVolume({ projectId: PROJECT_ID }, projectActor);
+ await service.getAuthMethodDistribution({ projectId: PROJECT_ID, days: 30 }, projectActor);
+
+ expect(postgres.countByDateAndActor).toHaveBeenCalledOnce();
+ expect(postgres.countByAuthMethod).toHaveBeenCalledOnce();
+ expect(clickhouse.countByDateAndActorForProject).not.toHaveBeenCalled();
+ expect(clickhouse.countByAuthMethodForProject).not.toHaveBeenCalled();
+ });
+
+ test("reads Postgres when ClickHouse audit logging is on but no ClickHouse is configured", async () => {
+ appConfig.CLICKHOUSE_AUDIT_LOG_ENABLED = true;
+ const { service, postgres } = buildProjectService({ withClickHouse: false });
+
+ await service.getAccessVolume({ projectId: PROJECT_ID }, projectActor);
+ await service.getAuthMethodDistribution({ projectId: PROJECT_ID, days: 30 }, projectActor);
+
+ expect(postgres.countByDateAndActor).toHaveBeenCalledOnce();
+ expect(postgres.countByAuthMethod).toHaveBeenCalledOnce();
+ });
+
+ test("reads ClickHouse when it holds the audit logs, and labels actors and auth methods as for Postgres", async () => {
+ appConfig.CLICKHOUSE_AUDIT_LOG_ENABLED = true;
+ const { service, postgres, clickhouse } = buildProjectService({ withClickHouse: true });
+
+ const volume = await service.getAccessVolume({ projectId: PROJECT_ID }, projectActor);
+ const { methods } = await service.getAuthMethodDistribution({ projectId: PROJECT_ID, days: 30 }, projectActor);
+
+ expect(postgres.countByDateAndActor).not.toHaveBeenCalled();
+ expect(postgres.countByAuthMethod).not.toHaveBeenCalled();
+ expect(clickhouse.countByDateAndActorForProject).toHaveBeenCalledWith(
+ expect.objectContaining({ orgId: ORG_ID, projectId: PROJECT_ID })
+ );
+ expect(clickhouse.countByAuthMethodForProject).toHaveBeenCalledWith(
+ expect.objectContaining({ orgId: ORG_ID, projectId: PROJECT_ID })
+ );
+
+ expect(volume.days.find((day) => day.date === today)).toEqual({
+ date: today,
+ total: 6,
+ actors: [
+ { name: "ci-bot", type: ActorType.IDENTITY, count: 4 },
+ { name: "Ada Lovelace", type: ActorType.USER, count: 2 }
+ ]
+ });
+ expect(methods).toEqual([
+ { method: "Universal Auth", count: 4 },
+ { method: "Email", count: 2 }
+ ]);
+ });
+
+ test("caches each store's counts under its own key", async () => {
+ const { service, cachedKeys } = buildProjectService({ withClickHouse: true });
+ await service.getAccessVolume({ projectId: PROJECT_ID }, projectActor);
+
+ appConfig.CLICKHOUSE_AUDIT_LOG_ENABLED = true;
+ await service.getAccessVolume({ projectId: PROJECT_ID }, projectActor);
+
+ expect(cachedKeys).toHaveLength(2);
+ expect(new Set(cachedKeys).size).toBe(2);
+ });
+});
diff --git a/backend/src/ee/services/insights/insights-service.ts b/backend/src/ee/services/insights/insights-service.ts
index d2425030d0..4709d45f14 100644
--- a/backend/src/ee/services/insights/insights-service.ts
+++ b/backend/src/ee/services/insights/insights-service.ts
@@ -73,7 +73,13 @@ export type TInsightsServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
auditLogDAL: Pick<TAuditLogDALFactory, "countByDateAndActor" | "countByAuthMethod">;
- clickhouseAuditLogDAL?: Pick<TClickHouseAuditLogDALFactory, "countByDateForOrg" | "countByIdentityAuthMethodForOrg">;
+ clickhouseAuditLogDAL?: Pick<
+ TClickHouseAuditLogDALFactory,
+ | "countByDateForOrg"
+ | "countByIdentityAuthMethodForOrg"
+ | "countByDateAndActorForProject"
+ | "countByAuthMethodForProject"
+ >;
secretRotationV2DAL: Pick<
TSecretRotationV2DALFactory,
"findByProjectAndDateRange" | "findByProject" | "countByProject"
@@ -257,10 +263,20 @@ export const insightsServiceFactory = ({
});
};
+ // With ClickHouse audit logging on, new audit logs are written only to ClickHouse, so the project
+ // cards must read from there or they show nothing that happened after the switch.
+ const $getClickHouseAuditLogDAL = () =>
+ getConfig().CLICKHOUSE_AUDIT_LOG_ENABLED && clickhouseAuditLogDAL ? clickhouseAuditLogDAL : undefined;
+
const getAccessVolume = async (dto: TGetAccessVolumeDTO, actorDto: OrgServiceActor) => {
await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);
- const cacheKey = KeyStorePrefixes.InsightsCache(dto.projectId, "access-volume");
+ const clickhouseDAL = $getClickHouseAuditLogDAL();
+ // The store is part of the key so switching it never serves counts cached from the other one.
+ const cacheKey = KeyStorePrefixes.InsightsCache(
+ dto.projectId,
+ `access-volume:${clickhouseDAL ? "clickhouse" : "postgres"}`
+ );
return withCache({
keyStore,
key: cacheKey,
@@ -268,13 +284,16 @@ export const insightsServiceFactory = ({
fetcher: async () => {
const { dates, startDate, endDate } = buildAccessVolumeWindow();
- const rows = await auditLogDAL.countByDateAndActor({
+ const countQuery = {
orgId: actorDto.orgId,
projectId: dto.projectId,
eventTypes: VALUE_EVENT_TYPES,
startDate: startDate.toISOString(),
endDate: endDate.toISOString()
- });
+ };
+ const rows = clickhouseDAL
+ ? await clickhouseDAL.countByDateAndActorForProject(countQuery)
+ : await auditLogDAL.countByDateAndActor(countQuery);
const userNameMap = await resolveUserDisplayNames(userDAL, [
...new Set(
@@ -314,7 +333,11 @@ export const insightsServiceFactory = ({
const getAuthMethodDistribution = async (dto: TGetAuthMethodDistributionDTO, actorDto: OrgServiceActor) => {
await checkInsightsPermission(permissionService, licenseService, dto.projectId, actorDto);
- const cacheKey = KeyStorePrefixes.InsightsCache(dto.projectId, `auth-methods:${dto.days}`);
+ const clickhouseDAL = $getClickHouseAuditLogDAL();
+ const cacheKey = KeyStorePrefixes.InsightsCache(
+ dto.projectId,
+ `auth-methods:${dto.days}:${clickhouseDAL ? "clickhouse" : "postgres"}`
+ );
return withCache({
keyStore,
key: cacheKey,
@@ -324,13 +347,16 @@ export const insightsServiceFactory = ({
const startDate = new Date();
startDate.setUTCDate(startDate.getUTCDate() - dto.days);
- const authRows = await auditLogDAL.countByAuthMethod({
+ const countQuery = {
orgId: actorDto.orgId,
projectId: dto.projectId,
eventTypes: VALUE_EVENT_TYPES,
startDate: startDate.toISOString(),
endDate: endDate.toISOString()
- });
+ };
+ const authRows = clickhouseDAL
+ ? await clickhouseDAL.countByAuthMethodForProject(countQuery)
+ : await auditLogDAL.countByAuthMethod(countQuery);
const methodCounts = new Map<string, number>();