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: added redis stream based log aggregator
=a1d2fe5c6fec
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex 25782feee6..d112b54b0b 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -134,6 +134,10 @@ export const mockKeyStore = (): TKeyStoreFactory => {list = JSON.parse(existing) as string[];}return list.length;- }+ },+ streamAdd: async () => null,+ streamRange: async () => [],+ streamTrim: async () => 0,+ streamCollect: async () => ({ entries: [], lastId: null })};};diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.tsindex 70671bb9f0..5f0a369eeb 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts@@ -3,6 +3,7 @@ import { randomUUID } from "crypto";import type { TProjects } from "@app/db/schemas";import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";+import { TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { logger } from "@app/lib/logger";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";@@ -19,6 +20,7 @@ type TAuditLogQueueServiceFactoryDep = {projectDAL: Pick<TProjectDALFactory, "findById">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;clickhouseClient: ClickHouseClient | null;+ keyStore: Pick<TKeyStoreFactory, "streamAdd" | "streamCollect" | "streamTrim">;};export type TAuditLogQueueServiceFactory = {@@ -28,6 +30,10 @@ export type TAuditLogQueueServiceFactory = {// keep this timeout 5s it must be fast because else the queue will take time to finish// audit log is a crowded queue thus needs to be fastexport const AUDIT_LOG_STREAM_TIMEOUT = 5 * 1000;+const MS_IN_DAY = 24 * 60 * 60 * 1000;+const AUDIT_LOG_CLICKHOUSE_STREAM_KEY = "audit-log-clickhouse-stream";+const AUDIT_LOG_CLICKHOUSE_BATCH_SIZE = 10_000;+const AUDIT_LOG_CLICKHOUSE_MAX_ENTRIES = 50_000;export const auditLogQueueServiceFactory = async ({auditLogDAL,@@ -35,12 +41,59 @@ export const auditLogQueueServiceFactory = async ({projectDAL,licenseService,auditLogStreamService,- clickhouseClient+ clickhouseClient,+ keyStore}: TAuditLogQueueServiceFactoryDep): Promise<TAuditLogQueueServiceFactory> => {const { CLICKHOUSE_AUDIT_LOG_ENABLED, CLICKHOUSE_AUDIT_LOG_TABLE_NAME, CLICKHOUSE_AUDIT_LOG_INSERT_SETTINGS } =getConfig();+ const isClickHouseBatchEnabled = Boolean(clickhouseClient && CLICKHOUSE_AUDIT_LOG_ENABLED);+const pushToLog = async (data: TCreateAuditLogDTO) => {+ // Push to Redis stream for ClickHouse batch processing+ if (isClickHouseBatchEnabled) {+ try {+ const { actor, event, ipAddress, projectId, userAgent, userAgentType } = data;+ let { orgId } = data;++ let project: TProjects | undefined;+ if (!orgId) {+ project = await projectDAL.findById(projectId as string);+ orgId = project.orgId;+ }++ const plan = await licenseService.getPlan(orgId);+ const ttlInDays =+ project?.auditLogsRetentionDays && project.auditLogsRetentionDays < plan.auditLogsRetentionDays+ ? project.auditLogsRetentionDays+ : plan.auditLogsRetentionDays;++ const ttl = ttlInDays * MS_IN_DAY;++ if (plan.auditLogsRetentionDays !== 0) {+ await keyStore.streamAdd(AUDIT_LOG_CLICKHOUSE_STREAM_KEY, "*", {+ data: JSON.stringify({+ id: randomUUID(),+ actor: actor.type,+ actorMetadata: actor.metadata ?? {},+ ipAddress: ipAddress ?? "",+ eventType: event.type,+ eventMetadata: event.metadata ?? {},+ userAgent: userAgent ?? "",+ userAgentType: userAgentType ?? "",+ projectId: projectId ?? "",+ orgId,+ expiresAt: new Date(Date.now() + ttl),+ createdAt: new Date(),+ updatedAt: new Date()+ })+ });+ }+ } catch (error) {+ logger.error(error, "Failed to push audit log to Redis stream for ClickHouse batch");+ }+ }+await queueService.queue<QueueName.AuditLog>(QueueName.AuditLog, QueueJobs.AuditLog, data, {removeOnFail: {count: 3@@ -53,7 +106,6 @@ export const auditLogQueueServiceFactory = async ({queueService.start(QueueName.AuditLog, async (job) => {const { actor, event, ipAddress, projectId, userAgent, userAgentType } = job.data;let { orgId } = job.data;- const MS_IN_DAY = 24 * 60 * 60 * 1000;let project: TProjects | undefined;if (!orgId) {@@ -90,40 +142,48 @@ export const auditLogQueueServiceFactory = async ({userAgentType});await auditLogStreamService.streamLog(orgId, auditLog);-- if (clickhouseClient && CLICKHOUSE_AUDIT_LOG_ENABLED) {- try {- await clickhouseClient.insert({- table: CLICKHOUSE_AUDIT_LOG_TABLE_NAME,- clickhouse_settings: CLICKHOUSE_AUDIT_LOG_INSERT_SETTINGS,- values: [- {- // with the same id as the audit log in clickhouse, so that it's much easier to- // find the corresponding audit log in postgres- id: auditLog.id,- actor: actor.type,- actorMetadata: actor.metadata ?? {},- ipAddress: ipAddress ?? "",- eventType: event.type,- eventMetadata: event.metadata ?? {},- userAgent: userAgent ?? "",- userAgentType: userAgentType ?? "",- // with the same createdAt as the audit log from postgres, so that it's much easier to- // deduplicate the audit logs- createdAt: auditLog.createdAt,- projectId: projectId ?? "",- orgId- }- ],- format: "JSONEachRow"- });- } catch (error) {- logger.error(error, `Failed to insert audit log to ClickHouse [auditLogId=${auditLog.id}]`);- }- }}});+ // Batch consumer: reads from Redis stream and inserts into ClickHouse every 5 seconds+ if (isClickHouseBatchEnabled) {+ queueService.start(QueueName.AuditLogClickHouseBatch, async () => {+ const { entries, lastId } = await keyStore.streamCollect(+ AUDIT_LOG_CLICKHOUSE_STREAM_KEY,+ AUDIT_LOG_CLICKHOUSE_BATCH_SIZE,+ AUDIT_LOG_CLICKHOUSE_MAX_ENTRIES+ );++ if (entries.length === 0 || !lastId) return;++ const values = entries.map(([, fields]) => JSON.parse(fields[1]) as Record<string, unknown>);++ // Single insert into ClickHouse+ await clickhouseClient!.insert({+ table: CLICKHOUSE_AUDIT_LOG_TABLE_NAME,+ clickhouse_settings: CLICKHOUSE_AUDIT_LOG_INSERT_SETTINGS,+ values,+ format: "JSONEachRow"+ });++ // Only trim after successful insert+ await keyStore.streamTrim(AUDIT_LOG_CLICKHOUSE_STREAM_KEY, lastId, true);++ logger.info({ count: values.length }, "Batch inserted audit logs into ClickHouse");+ });++ // Schedule repeatable job every 5 seconds+ await queueService.queue(QueueName.AuditLogClickHouseBatch, QueueJobs.AuditLogClickHouseBatch, undefined, {+ jobId: "audit-log-clickhouse-batch",+ repeat: {+ every: 5000,+ key: "audit-log-clickhouse-batch"+ },+ removeOnFail: true,+ removeOnComplete: true+ });+ }+return {pushToLog};diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 119a618b29..f950f5e4d5 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -151,6 +151,15 @@ export type TKeyStoreFactory = {listRange: (key: string, start: number, stop: number) => Promise<string[]>;listRemove: (key: string, count: number, value: string) => Promise<number>;listLength: (key: string) => Promise<number>;+ // stream operations+ streamAdd: (key: string, id: string, fieldValue: Record<string, string>, maxLen?: number) => Promise<string | null>;+ streamRange: (key: string, start: string, end: string, count?: number) => Promise<[string, string[]][]>;+ streamTrim: (key: string, minId: string, inclusive?: boolean) => Promise<number>;+ streamCollect: (+ key: string,+ batchSize: number,+ maxEntries: number+ ) => Promise<{ entries: [string, string[]][]; lastId: string | null }>;// pgpgIncrementBy: (key: string, dto: { incr?: number; expiry?: string; tx?: Knex }) => Promise<number>;pgGetIntItem: (key: string, prefix?: string) => Promise<number | undefined>;@@ -293,6 +302,52 @@ export const keyStoreFactory = (const listLength = async (key: string) => pickPrimaryOrSecondaryRedis(primaryRedis, redisReadReplicas).llen(key);+ // Stream operations+ const streamAdd = async (key: string, id: string, fieldValue: Record<string, string>, maxLen = 1000000) => {+ const args: string[] = [];+ for (const [field, value] of Object.entries(fieldValue)) {+ args.push(field, value);+ }+ return primaryRedis.xadd(key, "MAXLEN", "~", maxLen, id, ...args);+ };++ const streamRange = async (key: string, start: string, end: string, count?: number) => {+ if (count) {+ return primaryRedis.xrange(key, start, end, "COUNT", count);+ }+ return primaryRedis.xrange(key, start, end);+ };++ const streamTrim = async (key: string, minId: string, inclusive = false) => {+ let id = minId;+ if (inclusive) {+ const [ts, seq] = minId.split("-");+ id = `${ts}-${Number(seq) + 1}`;+ }+ return primaryRedis.xtrim(key, "MINID", id);+ };++ const streamCollect = async (key: string, batchSize: number, maxEntries: number) => {+ let lastId: string | null = null;+ const allEntries: [string, string[]][] = [];++ for (let i = 0; i < Math.ceil(maxEntries / batchSize); i += 1) {+ const start: string = lastId ? `(${lastId}` : "-";+ // eslint-disable-next-line no-await-in-loop+ const batch: [string, string[]][] = await primaryRedis.xrange(key, start, "+", "COUNT", batchSize);++ if (batch.length === 0) break;++ allEntries.push(...batch);+ // eslint-disable-next-line prefer-destructuring+ lastId = batch[batch.length - 1][0];++ if (allEntries.length >= maxEntries || batch.length < batchSize) break;+ }++ return { entries: allEntries, lastId };+ };+const waitTillReady = async ({key,waitingCb,@@ -336,6 +391,10 @@ export const keyStoreFactory = (listPush,listRange,listRemove,- listLength+ listLength,+ streamAdd,+ streamRange,+ streamTrim,+ streamCollect};};diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex 913252f405..556da56e2a 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -112,6 +112,10 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {},listLength: async (key) => {return listStore[key]?.length ?? 0;- }+ },+ streamAdd: async () => null,+ streamRange: async () => [],+ streamTrim: async () => 0,+ streamCollect: async () => ({ entries: [], lastId: null })};};diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex c67162342f..bbdd88b5a2 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -95,7 +95,8 @@ export enum QueueName {PamAccountRotation = "pam-account-rotation",PamSessionExpiration = "pam-session-expiration",PkiAcmeChallengeValidation = "pki-acme-challenge-validation",- PkiDiscoveryScan = "pki-discovery-scan"+ PkiDiscoveryScan = "pki-discovery-scan",+ AuditLogClickHouseBatch = "audit-log-clickhouse-batch"}export enum QueueJobs {@@ -158,7 +159,8 @@ export enum QueueJobs {PamSessionExpiration = "pam-session-expiration",PkiAcmeChallengeValidation = "pki-acme-challenge-validation",PkiDiscoveryRunScan = "pki-discovery-run-scan",- PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan"+ PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan",+ AuditLogClickHouseBatch = "audit-log-clickhouse-batch-job"}export type TQueueOptions = {@@ -489,6 +491,10 @@ export type TQueueJobTypes = {name: QueueJobs.PkiDiscoveryScheduledScan;payload: undefined;};+ [QueueName.AuditLogClickHouseBatch]: {+ name: QueueJobs.AuditLogClickHouseBatch;+ payload: undefined;+ };};const SECRET_SCANNING_QUEUES = [diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex ede9548aba..7a72d08a65 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -772,7 +772,8 @@ export const registerRoutes = async (projectDAL,licenseService,auditLogStreamService,- clickhouseClient: clickhouse+ clickhouseClient: clickhouse,+ keyStore});const notificationQueue = notificationQueueServiceFactory({