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
refactor(audit-log): rename migration status methods and update alert logic
Victor Hugo dos Santos16c3d2acebe7
diff --git a/backend/src/ee/services/audit-log/audit-log-service.ts b/backend/src/ee/services/audit-log/audit-log-service.tsindex 42e6ef69ab..f4563c206e 100644--- a/backend/src/ee/services/audit-log/audit-log-service.ts+++ b/backend/src/ee/services/audit-log/audit-log-service.ts@@ -9,7 +9,6 @@ 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 { TOrgDALFactory } from "@app/services/org/org-dal";import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";import { TUserDALFactory } from "@app/services/user/user-dal";@@ -23,6 +22,7 @@ import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, TAuditLogServiceFactory } froconst AUDIT_LOG_ROW_WARNING_THRESHOLD = 300_000_000;const AUDIT_LOG_ALERT_ROW_INCREMENT = 10_000_000;+const AUDIT_LOG_MIGRATION_ALERT_STATE_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 daystype TAuditLogServiceFactoryDep = {auditLogDAL: TAuditLogDALFactory;@@ -32,7 +32,6 @@ type TAuditLogServiceFactoryDep = {keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;smtpService: Pick<TSmtpService, "sendMail">;userDAL: Pick<TUserDALFactory, "getUsersByFilter">;- orgDAL: Pick<TOrgDALFactory, "findAllOrgsByUserId">;notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;};@@ -44,7 +43,6 @@ export const auditLogServiceFactory = ({keyStore,smtpService,userDAL,- orgDAL,notificationService}: TAuditLogServiceFactoryDep): TAuditLogServiceFactory => {const listAuditLogs: TAuditLogServiceFactory["listAuditLogs"] = async ({@@ -147,7 +145,7 @@ export const auditLogServiceFactory = ({return auditLogQueue.pushToLog(el);};- const getAuditLogMigrationStatus: TAuditLogServiceFactory["getAuditLogMigrationStatus"] = async ({+ const getAuditLogPostgresStorageStatus: TAuditLogServiceFactory["getAuditLogPostgresStorageStatus"] = async ({actorAuthMethod,actorId,actorOrgId,@@ -178,22 +176,22 @@ export const auditLogServiceFactory = ({};};- const checkClickHouseMigrationAlert = async () => {+ const checkPostgresAuditLogVolumeMigrationAlert = async () => {const appCfg = getConfig();const isClickHouseConfigured = appCfg.isClickHouseConfigured && appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED;- if (isClickHouseConfigured) return;+ if (isClickHouseConfigured || appCfg.isCloud) 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;+ const lastAlertedRowCountStr: string | null = await keyStore.getItem("audit-log-migration-alert-last-row-count");+ const lastAlertedRowCount = lastAlertedRowCountStr ? Number(lastAlertedRowCountStr) : 0;if (lastAlertedRowCount > 0 && rowCount < lastAlertedRowCount + AUDIT_LOG_ALERT_ROW_INCREMENT) return;logger.info(- `checkClickHouseMigrationAlert: alert triggered (rowCount=${rowCount}, lastAlerted=${lastAlertedRowCount})`+ `checkPostgresAuditLogVolumeMigrationAlert: alert triggered (rowCount=${rowCount}, lastAlerted=${lastAlertedRowCount})`);const superAdminsResult: { users: TUsers[]; total: number } = await userDAL.getUsersByFilter({@@ -210,36 +208,22 @@ export const auditLogServiceFactory = ({);if (adminsWithEmail.length > 0) {- const emailResults = await Promise.allSettled(- adminsWithEmail.map((admin) =>- smtpService.sendMail({- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment- template: SmtpTemplates.AuditLogMigrationAlert,- subjectLine: "Action recommended: Optimize your audit log storage",- recipients: [admin.email],- substitutions: {- siteUrl: appCfg.SITE_URL- }- })- )- );-- const failedEmails = emailResults.filter((r) => r.status === "rejected");- if (failedEmails.length > 0) {- logger.error({ failedCount: failedEmails.length }, "Failed to send some audit log migration alert emails");+ const recipientEmails = [...new Set(adminsWithEmail.map((admin) => admin.email))];+ try {+ await smtpService.sendMail({+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ template: SmtpTemplates.AuditLogMigrationAlert,+ subjectLine: "Action recommended: Optimize your audit log storage",+ recipients: recipientEmails,+ substitutions: {+ siteUrl: appCfg.SITE_URL+ }+ });+ } catch (error) {+ logger.error(error, "Failed to send audit log migration alert email");}}- const adminOrgMap = new Map<string, string>();- await Promise.all(- superAdminsResult.users.map(async (admin: TUsers) => {- const orgs = await orgDAL.findAllOrgsByUserId(admin.id);- if (orgs.length > 0) {- adminOrgMap.set(admin.id, orgs[0].id);- }- })- );-await notificationService.createUserNotifications(superAdminsResult.users.map((admin: TUsers) => ({@@ -247,22 +231,25 @@ export const auditLogServiceFactory = ({// eslint-disable-next-line @typescript-eslint/no-unsafe-assignmenttype: NotificationType.AUDIT_LOG_MIGRATION_RECOMMENDED,title: "Optimize your audit log storage",- body: "Your audit log volume is growing. To keep searches fast and reduce database load, we recommend streaming logs to an external destination like Splunk or using the built-in ClickHouse integration.",- link: adminOrgMap.has(admin.id) ? `/organizations/${adminOrgMap.get(admin.id)}/audit-logs` : undefined+ body: "Your audit log volume is growing. To keep searches fast and reduce database load, we recommend streaming logs to an external destination like Splunk or using the built-in ClickHouse integration."}))).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})`);+ await keyStore.setItemWithExpiry(+ "audit-log-migration-alert-last-row-count",+ AUDIT_LOG_MIGRATION_ALERT_STATE_TTL_SECONDS,+ String(rowCount)+ );+ logger.info(`checkPostgresAuditLogVolumeMigrationAlert: alert sent to super admins (rowCount=${rowCount})`);};return {createAuditLog,listAuditLogs,- getAuditLogMigrationStatus,- checkClickHouseMigrationAlert+ getAuditLogPostgresStorageStatus,+ checkPostgresAuditLogVolumeMigrationAlert};};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 8a5ac898ba..af5859376d 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -117,13 +117,13 @@ export type TAuditLogServiceFactory = {projectName?: string | null | undefined;}[]>;- getAuditLogMigrationStatus: (arg: TOrgPermission) => Promise<{+ getAuditLogPostgresStorageStatus: (arg: TOrgPermission) => Promise<{clickHouseConfigured: boolean;auditLogGenerationDisabled: boolean;auditLogStorageDisabled: boolean;auditLogRowCount: number;}>;- checkClickHouseMigrationAlert: () => Promise<void>;+ checkPostgresAuditLogVolumeMigrationAlert: () => 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 e693011522..7ffa00504a 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -830,7 +830,6 @@ export const registerRoutes = async (keyStore,smtpService,userDAL,- orgDAL,notificationService});const secretApprovalPolicyService = secretApprovalPolicyServiceFactory({diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.tsindex cd8c426ef5..c1f31ae288 100644--- a/backend/src/server/routes/v1/organization-router.ts+++ b/backend/src/server/routes/v1/organization-router.ts@@ -263,7 +263,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",- url: "/audit-logs/migration-status",+ url: "/audit-logs/postgres-storage-status",config: {rateLimit: readLimit},@@ -277,9 +277,9 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {})}},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- return server.services.auditLog.getAuditLogMigrationStatus({+ return server.services.auditLog.getAuditLogPostgresStorageStatus({actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,diff --git a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts b/backend/src/services/resource-cleanup/resource-cleanup-queue.tsindex cf76ed933c..dfb2d1070b 100644--- a/backend/src/services/resource-cleanup/resource-cleanup-queue.ts+++ b/backend/src/services/resource-cleanup/resource-cleanup-queue.ts@@ -23,7 +23,7 @@ import { TServiceTokenServiceFactory } from "../service-token/service-token-servtype TDailyResourceCleanUpQueueServiceFactoryDep = {auditLogDAL: Pick<TAuditLogDALFactory, "pruneAuditLog">;- auditLogService: Pick<TAuditLogServiceFactory, "checkClickHouseMigrationAlert">;+ auditLogService: Pick<TAuditLogServiceFactory, "checkPostgresAuditLogVolumeMigrationAlert">;identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "removeExpiredTokens">;identityUniversalAuthClientSecretDAL: Pick<TIdentityUaClientSecretDALFactory, "removeExpiredClientSecrets">;secretVersionDAL: Pick<TSecretVersionDALFactory, "pruneExcessVersions">;@@ -92,8 +92,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({await serviceTokenService.notifyExpiringTokens();await scimService.notifyExpiringTokens();await orgService.notifyInvitedUsers();- await auditLogDAL.pruneAuditLog();- await auditLogService.checkClickHouseMigrationAlert();+ await auditLogService.checkPostgresAuditLogVolumeMigrationAlert();await userNotificationDAL.pruneNotifications();await keyValueStoreDAL.pruneExpiredKeys();await queueJobsDAL.pruneQueueJobs();@@ -103,6 +102,7 @@ export const dailyResourceCleanUpQueueServiceFactory = ({await certificateRequestDAL.markExpiredApprovalRequests(expiredApprovalRequestIds);}await approvalRequestGrantsDAL.markExpiredGrants();+ await auditLogDAL.pruneAuditLog();logger.info(`${QueueName.DailyResourceCleanUp}: queue task completed`);} catch (error) {logger.error(error, `${QueueName.DailyResourceCleanUp}: resource cleanup failed`);diff --git a/frontend/src/hooks/api/auditLogs/queries.tsx b/frontend/src/hooks/api/auditLogs/queries.tsxindex e63c657dc1..f1995eeadc 100644--- a/frontend/src/hooks/api/auditLogs/queries.tsx+++ b/frontend/src/hooks/api/auditLogs/queries.tsx@@ -4,12 +4,12 @@ import { apiRequest } from "@app/config/request";import { onRequestError } from "@app/hooks/api/reactQuery";import { TReactQueryOptions } from "@app/types/reactQuery";-import { AuditLog, AuditLogMigrationStatus, TGetAuditLogsFilter } from "./types";+import { AuditLog, AuditLogPostgresStorageStatus, TGetAuditLogsFilter } from "./types";export const auditLogKeys = {getAuditLogs: (projectId: string | null, filters: TGetAuditLogsFilter) =>[{ projectId, filters }, "audit-logs"] as const,- migrationStatus: ["audit-logs-migration-status"] as const+ postgresStorageStatus: ["audit-logs-postgres-storage-status"] as const};export const useGetAuditLogs = (@@ -55,16 +55,16 @@ export const useGetAuditLogs = (});};-const fetchAuditLogMigrationStatus = async () => {- const { data } = await apiRequest.get<AuditLogMigrationStatus>(- "/api/v1/organization/audit-logs/migration-status"+const fetchAuditLogPostgresStorageStatus = async () => {+ const { data } = await apiRequest.get<AuditLogPostgresStorageStatus>(+ "/api/v1/organization/audit-logs/postgres-storage-status");return data;};-export const useGetAuditLogMigrationStatus = () => {+export const useGetAuditLogPostgresStorageStatus = () => {return useQuery({- queryKey: auditLogKeys.migrationStatus,- queryFn: fetchAuditLogMigrationStatus+ queryKey: auditLogKeys.postgresStorageStatus,+ queryFn: fetchAuditLogPostgresStorageStatus});};diff --git a/frontend/src/hooks/api/auditLogs/types.tsx b/frontend/src/hooks/api/auditLogs/types.tsxindex 762e0546ab..3925a6433d 100644--- a/frontend/src/hooks/api/auditLogs/types.tsx+++ b/frontend/src/hooks/api/auditLogs/types.tsx@@ -4,7 +4,7 @@ import { PkiItemType } from "../pkiCollections/constants";import { WorkflowIntegration } from "../workflowIntegrations/types";import { ActorType, EventType, UserAgentType } from "./enums";-export type AuditLogMigrationStatus = {+export type AuditLogPostgresStorageStatus = {clickHouseConfigured: boolean;auditLogGenerationDisabled: boolean;auditLogStorageDisabled: boolean;diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsxindex 758a31b488..1009880254 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx@@ -15,8 +15,9 @@ import {useSubscription} from "@app/context";import { Timezone } from "@app/helpers/datetime";+import { isInfisicalCloud } from "@app/helpers/platform";import { withPermission, withProjectPermission } from "@app/hoc";-import { useGetAuditLogMigrationStatus } from "@app/hooks/api/auditLogs";+import { useGetAuditLogPostgresStorageStatus } from "@app/hooks/api/auditLogs";import { Project } from "@app/hooks/api/projects/types";import { usePopUp } from "@app/hooks/usePopUp";@@ -53,15 +54,16 @@ const LogsSectionComponent = ({}: Props) => {const { subscription } = useSubscription();const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);- const { data: migrationStatus } = useGetAuditLogMigrationStatus();+ const { data: postgresStorageStatus } = useGetAuditLogPostgresStorageStatus();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;+ !isInfisicalCloud() &&+ postgresStorageStatus &&+ !postgresStorageStatus.clickHouseConfigured &&+ !postgresStorageStatus.auditLogStorageDisabled &&+ !postgresStorageStatus.auditLogGenerationDisabled &&+ postgresStorageStatus.auditLogRowCount >= AUDIT_LOG_ROW_WARNING_THRESHOLD;const [logFilter, setLogFilter] = useState<TAuditLogFilterFormData>({eventType: presets?.eventType || [],