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
abstract collapse window
Thiago Araujo da Silvab9d378a6d06c
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 4c4416c75c..3631f76806 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -1022,12 +1022,18 @@ inserts the new set, so there is no merge with what was stored before.`PERMISSION_DENIED` is recorded by the `onError` hook in`src/server/plugins/audit-log-permission-denied.ts` for every CASL `ForbiddenError` and`PermissionBoundaryError` (not `ForbiddenRequestError`, which verifyAuth and plan gates also throw),-only for orgs on the new privilege system, and collapsed per actor, project, action, subject, route and-method for one minute (a constant in the service, not a setting). The first denial in a window is-written at once and schedules a delayed `AuditLogPermissionDeniedFlush` job; repeats only bump a-keystore counter, and the job writes one summary event with `suppressedRepeats` and the window-bounds when the minute ends, so a burst that stops is still accounted for. `recordPermissionDenied`-on the audit log service never throws to the request.+only for orgs on the new privilege system whose plan has audit log retention, and collapsed per+actor, project, action, subject, route and method for one minute. `recordPermissionDenied` on the+audit log service never throws to the request.++The collapse itself is generic. `createCollapsedAuditLog` on the audit log service takes any+`TCreateAuditLogDTO` plus `collapseKeyParts` (the event type is always part of the key) and an+optional `collapseWindowSeconds` (default 60). The first event per key is written at once and+schedules a delayed `AuditLogCollapsedFlush` job; repeats inside the window only bump a keystore+counter, and the job writes one summary event with `suppressedRepeats`, `suppressedFrom` and+`suppressedUntil` in its metadata when the window closes, so a burst that stops is still accounted+for. To collapse another event, call it instead of `createAuditLog` and add+`TAuditLogCollapseSummary` to that event's metadata type so the summary fields are typed.### Server Pluginsdiff --git a/backend/src/ee/services/audit-log/audit-log-service.test.ts b/backend/src/ee/services/audit-log/audit-log-service.test.tsindex 2c29ab40da..0c4f697a3d 100644--- a/backend/src/ee/services/audit-log/audit-log-service.test.ts+++ b/backend/src/ee/services/audit-log/audit-log-service.test.ts@@ -38,7 +38,7 @@ const denial = (overrides: Partial<TRecordPermissionDeniedDTO> = {}): TRecordPer...overrides});-const createHarness = ({ windowAcquired = true, storedCount = "0" } = {}) => {+const createHarness = ({ windowAcquired = true, storedCount = "0", retentionDays = 30 } = {}) => {const startHandlers = new Map<string, (job: { data: unknown }) => Promise<void>>();const queueService = {start: vi.fn((name: string, fn: (job: { data: unknown }) => Promise<void>) => {@@ -58,6 +58,7 @@ const createHarness = ({ windowAcquired = true, storedCount = "0" } = {}) => {deleteItem: vi.fn<(key: string) => Promise<number>>(async () => 1)};const auditLogQueue = { pushToLog: vi.fn<(data: TPushedLog) => Promise<void>>(async () => undefined) };+ const licenseService = { getPlan: vi.fn(async () => ({ auditLogsRetentionDays: retentionDays })) };const auditLogSettingsService = {getEffectiveSettings: vi.fn<(orgId: string) => Promise<TEffectiveAuditLogSettings>>(async () => ({org: {},@@ -71,6 +72,7 @@ const createHarness = ({ windowAcquired = true, storedCount = "0" } = {}) => {permissionService: {} as never,auditLogQueue: auditLogQueue as never,auditLogSettingsService: auditLogSettingsService as never,+ licenseService: licenseService as never,queueService: queueService as never,keyStore: keyStore as never,smtpService: {} as never,@@ -78,7 +80,7 @@ const createHarness = ({ windowAcquired = true, storedCount = "0" } = {}) => {notificationService: {} as never});- const flush = startHandlers.get(QueueName.AuditLogPermissionDeniedFlush);+ const flush = startHandlers.get(QueueName.AuditLogCollapsedFlush);if (!flush) throw new Error("flush worker was not registered");return { service, queueService, keyStore, auditLogQueue, auditLogSettingsService, flush };@@ -105,8 +107,8 @@ describe("recordPermissionDenied", () => {expect(queueService.queue).toHaveBeenCalledTimes(1);const [queueName, jobName, payload, opts] = queueService.queue.mock.calls[0];- expect(queueName).toBe(QueueName.AuditLogPermissionDeniedFlush);- expect(jobName).toBe(QueueJobs.AuditLogPermissionDeniedFlush);+ expect(queueName).toBe(QueueName.AuditLogCollapsedFlush);+ expect(jobName).toBe(QueueJobs.AuditLogCollapsedFlush);expect(opts.delay).toBe(60_000);expect(opts.jobId).toContain(payload.collapseKey);expect(payload.orgId).toBe("org-1");@@ -149,6 +151,16 @@ describe("recordPermissionDenied", () => {expect(auditLogQueue.pushToLog).not.toHaveBeenCalled();});+ test("nothing is recorded when the plan has no audit log retention", async () => {+ const { service, keyStore, queueService, auditLogQueue } = createHarness({ retentionDays: 0 });++ await service.recordPermissionDenied(denial());++ expect(keyStore.setItemWithExpiryNX).not.toHaveBeenCalled();+ expect(queueService.queue).not.toHaveBeenCalled();+ expect(auditLogQueue.pushToLog).not.toHaveBeenCalled();+ });+test("a keystore failure is swallowed", async () => {const { service, keyStore, auditLogQueue } = createHarness();keyStore.setItemWithExpiryNX.mockRejectedValueOnce(new Error("redis down"));@@ -158,13 +170,48 @@ describe("recordPermissionDenied", () => {});});-describe("permission denied flush job", () => {+describe("createCollapsedAuditLog", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ const { metadata, ...auditLogInfo } = denial();+ const collapsed = (type: EventType) => ({+ ...auditLogInfo,+ event: { type, metadata } as never,+ collapseKeyParts: ["org-1", "identity-1"]+ });++ test("the event type is part of the collapse key", async () => {+ const { service, keyStore } = createHarness();++ await service.createCollapsedAuditLog(collapsed(EventType.PERMISSION_DENIED));+ await service.createCollapsedAuditLog(collapsed(EventType.GET_SECRETS));++ const [firstKey] = keyStore.setItemWithExpiryNX.mock.calls[0];+ const [secondKey] = keyStore.setItemWithExpiryNX.mock.calls[1];+ expect(firstKey).not.toBe(secondKey);+ });++ test("a custom window sets the key ttl and the job delay", async () => {+ const { service, keyStore, queueService } = createHarness();++ await service.createCollapsedAuditLog({ ...collapsed(EventType.GET_SECRETS), collapseWindowSeconds: 300 });++ expect(keyStore.setItemWithExpiryNX.mock.calls[0][1]).toBe(300);+ expect(queueService.queue.mock.calls[0][3].delay).toBe(300_000);+ });+});++describe("collapsed audit log flush job", () => {beforeEach(() => {vi.clearAllMocks();});+ const { metadata, ...auditLogInfo } = denial();const jobData = {- ...denial(),+ ...auditLogInfo,+ event: { type: EventType.PERMISSION_DENIED, metadata } as never,collapseKey: "abc",windowStart: "2026-09-30T10:00:00.000Z",windowEnd: "2026-09-30T10:01:00.000Z"diff --git a/backend/src/ee/services/audit-log/audit-log-service.ts b/backend/src/ee/services/audit-log/audit-log-service.tsindex 0de88a9ae8..8b78101655 100644--- a/backend/src/ee/services/audit-log/audit-log-service.ts+++ b/backend/src/ee/services/audit-log/audit-log-service.ts@@ -15,6 +15,7 @@ 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 { TLicenseServiceFactory } from "../license/license-service";import { OrgPermissionAuditLogsActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";import { ProjectPermissionAuditLogsActions, ProjectPermissionSub } from "../permission/project-permission";@@ -25,15 +26,16 @@ import { TAuditLogQueueServiceFactory } from "./audit-log-queue";import { isAuditLogEventEnabled, TAuditLogSettingsServiceFactory } from "./audit-log-settings-service";import {ACTOR_TYPE_TO_METADATA_ID_KEY,+ Event,EventType,- TAuditLogPermissionDeniedFlushJobData,+ TAuditLogCollapsedFlushJobData,+ TAuditLogCollapseSummary,TAuditLogServiceFactory} from "./audit-log-types";const AUDIT_LOG_ROW_WARNING_THRESHOLD = 350_000_000;const AUDIT_LOG_ALERT_ROW_INCREMENT = 10_000_000;-const PERMISSION_DENIED_COLLAPSE_WINDOW_SECONDS = 60;-const PERMISSION_DENIED_COUNT_TTL_SECONDS = PERMISSION_DENIED_COLLAPSE_WINDOW_SECONDS * 10;+const DEFAULT_COLLAPSE_WINDOW_SECONDS = 60;type TAuditLogServiceFactoryDep = {auditLogDAL: TAuditLogDALFactory;@@ -41,6 +43,7 @@ type TAuditLogServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;auditLogQueue: TAuditLogQueueServiceFactory;auditLogSettingsService: Pick<TAuditLogSettingsServiceFactory, "getEffectiveSettings">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;queueService: Pick<TQueueServiceFactory, "queue" | "start">;keyStore: Pick<TKeyStoreFactory,@@ -63,6 +66,7 @@ export const auditLogServiceFactory = ({clickhouseAuditLogDAL,auditLogQueue,auditLogSettingsService,+ licenseService,permissionService,queueService,keyStore,@@ -197,39 +201,76 @@ export const auditLogServiceFactory = ({// Runs when a collapse window closes. Pushes straight to the log rather than through// createAuditLog: we're outside a request here, and the payload already carries the actor's- // permission metadata from the first denial.- const flushPermissionDeniedRepeats = async ({+ // permission metadata from the first event.+ const flushCollapsedRepeats = async ({collapseKey,windowStart,windowEnd,- orgId,- projectId,- metadata,- ...auditLogInfo- }: TAuditLogPermissionDeniedFlushJobData) => {- const countKey = KeyStorePrefixes.AuditLogPermissionDeniedCount(collapseKey);+ ...auditLog+ }: TAuditLogCollapsedFlushJobData) => {+ const countKey = KeyStorePrefixes.AuditLogCollapseCount(collapseKey);const suppressedRepeats = Number(await keyStore.getItem(countKey)) || 0;if (!suppressedRepeats) return;await keyStore.deleteItem(countKey);+ const summary: TAuditLogCollapseSummary = {+ suppressedRepeats,+ suppressedFrom: windowStart,+ suppressedUntil: windowEnd+ };await auditLogQueue.pushToLog({- ...auditLogInfo,- orgId,- projectId,- event: {- type: EventType.PERMISSION_DENIED,- metadata: { ...metadata, suppressedRepeats, suppressedFrom: windowStart, suppressedUntil: windowEnd }- }+ ...auditLog,+ event: { ...auditLog.event, metadata: { ...auditLog.event.metadata, ...summary } } as Event});};- queueService.start(QueueName.AuditLogPermissionDeniedFlush, async (job) => {- await flushPermissionDeniedRepeats(job.data);+ queueService.start(QueueName.AuditLogCollapsedFlush, async (job) => {+ await flushCollapsedRepeats(job.data);});- // Called from the onError hook, so it must never throw or slow the response. The first denial- // per key is written right away and opens a one minute window; repeats just bump a counter- // that the flush job turns into a summary event.+ // The first event per key is written right away and opens a window; repeats inside it only+ // bump a counter that the flush job turns into one summary event when the window closes.+ const createCollapsedAuditLog: TAuditLogServiceFactory["createCollapsedAuditLog"] = async ({+ collapseKeyParts,+ collapseWindowSeconds = DEFAULT_COLLAPSE_WINDOW_SECONDS,+ ...data+ }) => {+ const appCfg = getConfig();+ if (appCfg.DISABLE_AUDIT_LOG_GENERATION) return;++ const collapseKey = generateCacheKeyFromData([data.event.type, ...collapseKeyParts]);+ const acquired = await keyStore.setItemWithExpiryNX(+ KeyStorePrefixes.AuditLogCollapseWindow(collapseKey),+ collapseWindowSeconds,+ "1"+ );+ if (!acquired) {+ await keyStore.incrementByWithExpiry(+ KeyStorePrefixes.AuditLogCollapseCount(collapseKey),+ 1,+ collapseWindowSeconds * 10+ );+ return;+ }++ await createAuditLog(data);++ const windowStart = new Date();+ const windowEnd = new Date(windowStart.getTime() + collapseWindowSeconds * 1000);+ await queueService.queue(+ QueueName.AuditLogCollapsedFlush,+ QueueJobs.AuditLogCollapsedFlush,+ { ...data, collapseKey, windowStart: windowStart.toISOString(), windowEnd: windowEnd.toISOString() },+ {+ jobId: `audit-log-collapse-${collapseKey}-${windowStart.getTime()}`,+ delay: collapseWindowSeconds * 1000,+ removeOnComplete: true,+ removeOnFail: true+ }+ );+ };++ // Called from the onError hook, so it must never throw or slow the response.const recordPermissionDenied: TAuditLogServiceFactory["recordPermissionDenied"] = async ({orgId,projectId,@@ -245,60 +286,26 @@ export const auditLogServiceFactory = ({if (!isAuditLogEventEnabled(settings, EventType.PERMISSION_DENIED, projectId)) return;+ const plan = await licenseService.getPlan(orgId);+ if (!plan?.auditLogsRetentionDays) return;+const actorIdKey = ACTOR_TYPE_TO_METADATA_ID_KEY[auditLogInfo.actor.type];const actorId = actorIdKey ? (auditLogInfo.actor.metadata as Record<string, unknown>)[actorIdKey] : undefined;- const collapseKey = generateCacheKeyFromData([- orgId,- projectId ?? null,- actorId ?? null,- metadata.permissionAction ?? null,- metadata.permissionSubject ?? null,- metadata.route ?? null,- metadata.method- ]);-- const acquired = await keyStore.setItemWithExpiryNX(- KeyStorePrefixes.AuditLogPermissionDeniedWindow(collapseKey),- PERMISSION_DENIED_COLLAPSE_WINDOW_SECONDS,- "1"- );- if (!acquired) {- await keyStore.incrementByWithExpiry(- KeyStorePrefixes.AuditLogPermissionDeniedCount(collapseKey),- 1,- PERMISSION_DENIED_COUNT_TTL_SECONDS- );- return;- }-- await createAuditLog({+ await createCollapsedAuditLog({...auditLogInfo,orgId,projectId,- event: { type: EventType.PERMISSION_DENIED, metadata }- });-- const windowStart = new Date();- const windowEnd = new Date(windowStart.getTime() + PERMISSION_DENIED_COLLAPSE_WINDOW_SECONDS * 1000);- await queueService.queue(- QueueName.AuditLogPermissionDeniedFlush,- QueueJobs.AuditLogPermissionDeniedFlush,- {- ...auditLogInfo,+ event: { type: EventType.PERMISSION_DENIED, metadata },+ collapseKeyParts: [orgId,- projectId,- metadata,- collapseKey,- windowStart: windowStart.toISOString(),- windowEnd: windowEnd.toISOString()- },- {- jobId: `permission-denied-${collapseKey}-${windowStart.getTime()}`,- delay: PERMISSION_DENIED_COLLAPSE_WINDOW_SECONDS * 1000,- removeOnComplete: true,- removeOnFail: true- }- );+ projectId ?? null,+ actorId ?? null,+ metadata.permissionAction ?? null,+ metadata.permissionSubject ?? null,+ metadata.route ?? null,+ metadata.method+ ]+ });} catch (error) {logger.warn(error, `audit-log: failed to record permission denial [orgId=${orgId}] [route=${metadata.route}]`);}@@ -420,6 +427,7 @@ export const auditLogServiceFactory = ({return {createAuditLog,+ createCollapsedAuditLog,recordPermissionDenied,listAuditLogs,getAuditLogPostgresStorageStatus,diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex acd181cda4..4d0f62eca1 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -122,18 +122,33 @@ export type TCreateAuditLogDTO = {export type AuditLogInfo = Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor">;-export type TRecordPermissionDeniedDTO = AuditLogInfo & {- orgId: string;- projectId?: string;- metadata: Omit<PermissionDeniedEvent["metadata"], "suppressedRepeats" | "suppressedFrom" | "suppressedUntil">;+// Added to the event metadata by the summary event a collapse window writes when it closes.+// An event passed to createCollapsedAuditLog should include this in its metadata type.+export type TAuditLogCollapseSummary = {+ suppressedRepeats?: number;+ suppressedFrom?: string;+ suppressedUntil?: string;};-export type TAuditLogPermissionDeniedFlushJobData = TRecordPermissionDeniedDTO & {+export type TCreateCollapsedAuditLogDTO = TCreateAuditLogDTO & {+ // Together with the event type, identifies a repeat: events with the same parts inside the+ // window collapse into the first one plus a summary.+ collapseKeyParts: unknown[];+ collapseWindowSeconds?: number;+};++export type TAuditLogCollapsedFlushJobData = TCreateAuditLogDTO & {collapseKey: string;windowStart: string;windowEnd: string;};+export type TRecordPermissionDeniedDTO = AuditLogInfo & {+ orgId: string;+ projectId?: string;+ metadata: Omit<PermissionDeniedEvent["metadata"], keyof TAuditLogCollapseSummary>;+};+// What `pushToLog` writes to the Redis ingest stream. We pin `id` and `createdAt` at// push time so a consumer retry (reprocessing the same batch after a failed insert)// re-inserts byte-identical rows instead of regenerating ids and creating duplicates.@@ -153,6 +168,7 @@ export type TAuditLogStreamEntry = TCreateAuditLogDTO & {export type TAuditLogServiceFactory = {createAuditLog: (data: TCreateAuditLogDTO) => Promise<void>;+ createCollapsedAuditLog: (data: TCreateCollapsedAuditLogDTO) => Promise<void>;recordPermissionDenied: (data: TRecordPermissionDeniedDTO) => Promise<void>;listAuditLogs: (arg: TListProjectAuditLogDTO) => Promise<{@@ -5988,7 +6004,7 @@ interface ViewAuditLogsEvent {interface PermissionDeniedEvent {type: EventType.PERMISSION_DENIED;- metadata: {+ metadata: TAuditLogCollapseSummary & {permissionAction?: string;permissionSubject?: string;permissionSubjectDetails?: Record<string, unknown>;@@ -5997,9 +6013,6 @@ interface PermissionDeniedEvent {route?: string;method: string;projectId?: string;- suppressedRepeats?: number;- suppressedFrom?: string;- suppressedUntil?: string;};}diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 2522e721be..0e4e38f4b3 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -200,8 +200,8 @@ export const KeyStorePrefixes = {LicenseCloudPlanFallback: (orgId: string) => `infisical-cloud-plan-fallback-${orgId}` as const,LicenseCloudPlanLastKnown: (orgId: string) => `infisical-cloud-plan-last-known-${orgId}` as const,AuditLogOrgSettings: (orgId: string) => `audit-log-settings-${orgId}` as const,- AuditLogPermissionDeniedWindow: (key: string) => `audit-log-permission-denied-window-${key}` as const,- AuditLogPermissionDeniedCount: (key: string) => `audit-log-permission-denied-count-${key}` as const,+ AuditLogCollapseWindow: (key: string) => `audit-log-collapse-window-${key}` as const,+ AuditLogCollapseCount: (key: string) => `audit-log-collapse-count-${key}` as const,// Set after a billing mutation to flag the org's plan cache for stale-while-revalidate reads.LicenseCachePassThrough: (orgId: string) => `license-cache-passthrough-${orgId}` as const,// Single-flight guard so only one background revalidation runs per org per lock window.diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 882d437d8a..089d960ec9 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -11,7 +11,7 @@ import {} from "bullmq";import { SecretEncryptionAlgo, SecretKeyEncoding } from "@app/db/schemas";-import { TAuditLogPermissionDeniedFlushJobData } from "@app/ee/services/audit-log/audit-log-types";+import { TAuditLogCollapsedFlushJobData } from "@app/ee/services/audit-log/audit-log-types";import { TAuditLogStreamFlushJobData } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-types";import {TSecretRotationRotateSecretsJobPayload,@@ -125,7 +125,7 @@ export enum QueueName {AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",AuditLogClickHouseBatch = "audit-log-clickhouse-batch",AuditLogStreamOutbox = "audit-log-stream-outbox",- AuditLogPermissionDeniedFlush = "audit-log-permission-denied-flush",+ AuditLogCollapsedFlush = "audit-log-collapsed-flush",CaAutoRenewal = "ca-auto-renewal",ProjectHardDelete = "project-hard-delete",ProjectEnvHardDelete = "project-env-hard-delete",@@ -210,7 +210,7 @@ export enum QueueJobs {AppConnectionCredentialRotationSendNotification = "app-connection-credential-rotation-send-notification",AuditLogClickHouseBatch = "audit-log-clickhouse-batch-job",AuditLogStreamFlush = "audit-log-stream-flush",- AuditLogPermissionDeniedFlush = "audit-log-permission-denied-flush-job",+ AuditLogCollapsedFlush = "audit-log-collapsed-flush-job",CaDailyAutoRenewal = "ca-daily-auto-renewal",CaVenafiInstall = "ca-venafi-install-job",CaAdcsInstall = "ca-adcs-install-job",@@ -596,9 +596,9 @@ export type TQueueJobTypes = {name: QueueJobs.AuditLogStreamFlush;payload: TAuditLogStreamFlushJobData;};- [QueueName.AuditLogPermissionDeniedFlush]: {- name: QueueJobs.AuditLogPermissionDeniedFlush;- payload: TAuditLogPermissionDeniedFlushJobData;+ [QueueName.AuditLogCollapsedFlush]: {+ name: QueueJobs.AuditLogCollapsedFlush;+ payload: TAuditLogCollapsedFlushJobData;};[QueueName.CaAutoRenewal]:| {diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 20946ed00d..3baa8040a6 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1221,6 +1221,7 @@ export const registerRoutes = async (permissionService,auditLogQueue,auditLogSettingsService,+ licenseService,queueService,keyStore,smtpService,diff --git a/docs/documentation/platform/audit-logs.mdx b/docs/documentation/platform/audit-logs.mdxindex 165bd7a06a..a937b65d24 100644--- a/docs/documentation/platform/audit-logs.mdx+++ b/docs/documentation/platform/audit-logs.mdx@@ -265,7 +265,7 @@ By default, Infisical records every class except `authorization`. The `managemen</Step></Steps>- Only project admins can change these toggles. A project that has never saved a setting uses the defaults.+ Only project admins can change these toggles. A project that has never saved a setting uses the defaults. The section appears in the settings of Secret Manager, KMS, and Secret Scanning projects. For other project types, use the API.</Tab><Tab title="API">Update the organization's classes with [the organization audit log settings endpoint](/api-reference/endpoints/audit-logs/update-organization-audit-log-settings), or one project's classes with [the project audit log settings endpoint](/api-reference/endpoints/audit-logs/update-project-audit-log-settings). The request replaces the current settings, so include every class except `management`.diff --git a/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx b/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsxnew file mode 100644index 0000000000..7698be18ee--- /dev/null+++ b/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx@@ -0,0 +1,179 @@+import { ReactNode } from "react";+import { Controller, useForm } from "react-hook-form";+import { Link } from "@tanstack/react-router";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Card,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ DocumentationLinkBadge,+ Skeleton+} from "@app/components/v3";+import {+ AUDIT_LOG_EVENT_CLASS_DEFAULTS,+ AUDIT_LOG_EVENT_CLASSES,+ CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES+} from "@app/hooks/api/auditLogSettings/constants";+import {+ AuditLogEventClass,+ TAuditLogEventClassSetting,+ TAuditLogSettings+} from "@app/hooks/api/auditLogSettings/types";+import { ScopeVariant } from "@app/hooks/useScopeVariant";++import { AuditLogEventClassRow } from "./AuditLogEventClassRow";++type TForm = Record<AuditLogEventClass, boolean>;++const REQUIRES_NEW_PRIVILEGE_SYSTEM = "Requires the new privilege system";+const ALWAYS_RECORDED = "Management events are always recorded";++type Props = {+ title: ReactNode;+ description: string;+ settings?: TAuditLogSettings;+ isPending: boolean;+ isSaving: boolean;+ canEdit: boolean;+ variant: ScopeVariant;+ orgId: string;+ shouldUseNewPrivilegeSystem: boolean;+ onSave: (eventClasses: TAuditLogEventClassSetting[]) => Promise<unknown>;+ className?: string;+ titleClassName?: string;+};++export const AuditLogEventClassesForm = ({+ title,+ description,+ settings,+ isPending,+ isSaving,+ canEdit,+ variant,+ orgId,+ shouldUseNewPrivilegeSystem,+ onSave,+ className,+ titleClassName+}: Props) => {+ const isEnabled = (eventClass: AuditLogEventClass) =>+ settings?.eventClasses.find((el) => el.eventClass === eventClass)?.isEnabled ??+ AUDIT_LOG_EVENT_CLASS_DEFAULTS[eventClass];++ const {+ control,+ handleSubmit,+ reset,+ formState: { isDirty }+ } = useForm<TForm>({+ values: Object.fromEntries(+ AUDIT_LOG_EVENT_CLASSES.map((eventClass) => [eventClass, isEnabled(eventClass)])+ ) as TForm+ });++ const onSubmit = async (form: TForm) => {+ const eventClasses = CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES.map((eventClass) => ({+ eventClass,+ isEnabled: form[eventClass]+ }));++ try {+ await onSave(eventClasses);+ createNotification({ text: "Audit log settings saved", type: "success" });+ } catch {+ createNotification({ text: "Failed to save audit log settings", type: "error" });+ }+ };++ return (+ <form onSubmit={handleSubmit(onSubmit)} className={className}>+ <Card className="gap-0 overflow-hidden p-0">+ <CardHeader className="border-b p-6">+ <CardTitle className={titleClassName}>+ {title}+ <DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/audit-logs" />+ </CardTitle>+ <CardDescription>{description}</CardDescription>+ </CardHeader>+ {isPending ? (+ <div className="space-y-4 p-6">+ {AUDIT_LOG_EVENT_CLASSES.map((eventClass) => (+ <Skeleton key={eventClass} className="h-12 w-full" />+ ))}+ </div>+ ) : (+ <div className="divide-y divide-border">+ {AUDIT_LOG_EVENT_CLASSES.map((eventClass) => {+ const isManagement = eventClass === AuditLogEventClass.Management;+ const isAuthorization = eventClass === AuditLogEventClass.Authorization;+ const isLocked = isAuthorization && !shouldUseNewPrivilegeSystem;+ let lockedReason: string | undefined;+ if (isManagement) lockedReason = ALWAYS_RECORDED;+ else if (isLocked) lockedReason = REQUIRES_NEW_PRIVILEGE_SYSTEM;+ return (+ <Controller+ key={eventClass}+ control={control}+ name={eventClass}+ render={({ field }) => (+ <AuditLogEventClassRow+ eventClass={eventClass}+ isEnabled={isManagement || (!isLocked && field.value)}+ variant={variant}+ isDisabled={!canEdit}+ lockedReason={lockedReason}+ onCheckedChange={field.onChange}+ warning={+ eventClass === AuditLogEventClass.DataAccess && !field.value+ ? "Secret Insights are counted from these events and stay flat while this is off."+ : undefined+ }+ descriptionExtra={+ isLocked ? (+ <>+ Denials are only recorded on the new privilege system.{" "}+ <Link to="/organizations/$orgId/access-management" params={{ orgId }}>+ Upgrade the privilege system+ </Link>{" "}+ in Access Control to enable this class.+ </>+ ) : undefined+ }+ />+ )}+ />+ );+ })}+ </div>+ )}+ {canEdit && (+ <CardFooter className="min-h-8 justify-end gap-2 border-t p-4">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ isDisabled={!isDirty || isSaving}+ onClick={() => reset()}+ >+ Reset+ </Button>+ <Button+ type="submit"+ variant={variant}+ size="sm"+ isDisabled={!isDirty}+ isPending={isSaving}+ >+ Save Changes+ </Button>+ </CardFooter>+ )}+ </Card>+ </form>+ );+};diff --git a/frontend/src/components/auditLogSettings/index.tsx b/frontend/src/components/auditLogSettings/index.tsxindex 26825ed489..564c348f66 100644--- a/frontend/src/components/auditLogSettings/index.tsx+++ b/frontend/src/components/auditLogSettings/index.tsx@@ -1 +1,2 @@+export { AuditLogEventClassesForm } from "./AuditLogEventClassesForm";export { AuditLogEventClassRow } from "./AuditLogEventClassRow";diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsxindex 519f1ada76..2914e4d01b 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx@@ -1,18 +1,4 @@-import { Controller, useForm } from "react-hook-form";-import { Link } from "@tanstack/react-router";--import { AuditLogEventClassRow } from "@app/components/auditLogSettings";-import { createNotification } from "@app/components/notifications";-import {- Button,- Card,- CardDescription,- CardFooter,- CardHeader,- CardTitle,- DocumentationLinkBadge,- Skeleton-} from "@app/components/v3";+import { AuditLogEventClassesForm } from "@app/components/auditLogSettings";import {OrgPermissionActions,OrgPermissionSubjects,@@ -22,17 +8,6 @@ import {import { withPermission } from "@app/hoc";import { useScopeVariant } from "@app/hooks";import { useGetOrgAuditLogSettings, useUpdateOrgAuditLogSettings } from "@app/hooks/api";-import {- AUDIT_LOG_EVENT_CLASS_DEFAULTS,- AUDIT_LOG_EVENT_CLASSES,- CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES-} from "@app/hooks/api/auditLogSettings/constants";-import { AuditLogEventClass } from "@app/hooks/api/auditLogSettings/types";--type TForm = Record<AuditLogEventClass, boolean>;--const REQUIRES_NEW_PRIVILEGE_SYSTEM = "Requires the new privilege system";-const ALWAYS_RECORDED = "Management events are always recorded";export const AuditLogSettingsTab = withPermission(() => {@@ -46,125 +21,21 @@ export const AuditLogSettingsTab = withPermission(currentOrg.id);- const isEnabled = (eventClass: AuditLogEventClass) =>- settings?.eventClasses.find((el) => el.eventClass === eventClass)?.isEnabled ??- AUDIT_LOG_EVENT_CLASS_DEFAULTS[eventClass];-- const {- control,- handleSubmit,- reset,- formState: { isDirty }- } = useForm<TForm>({- values: Object.fromEntries(- AUDIT_LOG_EVENT_CLASSES.map((eventClass) => [eventClass, isEnabled(eventClass)])- ) as TForm- });-- const shouldUseNewPrivilegeSystem =- settings?.shouldUseNewPrivilegeSystem ?? currentOrg.shouldUseNewPrivilegeSystem;-- const onSubmit = async (form: TForm) => {- const eventClasses = CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES.map((eventClass) => ({- eventClass,- isEnabled: form[eventClass]- }));-- await updateSettings({ eventClasses });- createNotification({ text: "Audit log settings saved", type: "success" });- };-return (- <form onSubmit={handleSubmit(onSubmit)}>- <Card className="gap-0 overflow-hidden p-0">- <CardHeader className="border-b p-6">- <CardTitle>- Event Classes- <DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/audit-logs" />- </CardTitle>- <CardDescription>- Choose which classes of organization-level events are recorded. Each project has its- own setting for its events.- </CardDescription>- </CardHeader>- {isPending ? (- <div className="space-y-4 p-6">- {AUDIT_LOG_EVENT_CLASSES.map((eventClass) => (- <Skeleton key={eventClass} className="h-12 w-full" />- ))}- </div>- ) : (- <div className="divide-y divide-border">- {AUDIT_LOG_EVENT_CLASSES.map((eventClass) => {- const isManagement = eventClass === AuditLogEventClass.Management;- const isAuthorization = eventClass === AuditLogEventClass.Authorization;- const isLocked = isAuthorization && !shouldUseNewPrivilegeSystem;- let lockedReason: string | undefined;- if (isManagement) lockedReason = ALWAYS_RECORDED;- else if (isLocked) lockedReason = REQUIRES_NEW_PRIVILEGE_SYSTEM;- return (- <Controller- key={eventClass}- control={control}- name={eventClass}- render={({ field }) => (- <AuditLogEventClassRow- eventClass={eventClass}- isEnabled={isManagement || (!isLocked && field.value)}- variant={scopeVariant}- isDisabled={!canEdit}- lockedReason={lockedReason}- onCheckedChange={field.onChange}- warning={- eventClass === AuditLogEventClass.DataAccess && !field.value- ? "Secret Insights are counted from these events and stay flat while this is off."- : undefined- }- descriptionExtra={- isLocked ? (- <>- Denials are only recorded on the new privilege system.{" "}- <Link- to="/organizations/$orgId/access-management"- params={{ orgId: currentOrg.id }}- >- Upgrade the privilege system- </Link>{" "}- in Access Control to enable this class.- </>- ) : undefined- }- />- )}- />- );- })}- </div>- )}- {canEdit && (- <CardFooter className="min-h-8 justify-end gap-2 border-t p-4">- <Button- type="button"- variant="ghost"- size="sm"- isDisabled={!isDirty || isSaving}- onClick={() => reset()}- >- Reset- </Button>- <Button- type="submit"- variant={scopeVariant}- size="sm"- isDisabled={!isDirty}- isPending={isSaving}- >- Save Changes- </Button>- </CardFooter>- )}- </Card>- </form>+ <AuditLogEventClassesForm+ title="Event Classes"+ description="Choose which classes of organization-level events are recorded. Each project has its own setting for its events."+ settings={settings}+ isPending={isPending}+ isSaving={isSaving}+ canEdit={canEdit}+ variant={scopeVariant}+ orgId={currentOrg.id}+ shouldUseNewPrivilegeSystem={+ settings?.shouldUseNewPrivilegeSystem ?? currentOrg.shouldUseNewPrivilegeSystem+ }+ onSave={(eventClasses) => updateSettings({ eventClasses })}+ />);},{diff --git a/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsxindex 389e67a93b..1cb54c4005 100644--- a/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx+++ b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx@@ -1,33 +1,8 @@-import { Controller, useForm } from "react-hook-form";-import { Link } from "@tanstack/react-router";--import { AuditLogEventClassRow } from "@app/components/auditLogSettings";-import { createNotification } from "@app/components/notifications";-import {- Button,- Card,- CardDescription,- CardFooter,- CardHeader,- CardTitle,- DocumentationLinkBadge,- Skeleton-} from "@app/components/v3";+import { AuditLogEventClassesForm } from "@app/components/auditLogSettings";import { useOrganization, useProject, useProjectPermission } from "@app/context";import { useGetProjectAuditLogSettings, useUpdateProjectAuditLogSettings } from "@app/hooks/api";-import {- AUDIT_LOG_EVENT_CLASS_DEFAULTS,- AUDIT_LOG_EVENT_CLASSES,- CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES-} from "@app/hooks/api/auditLogSettings/constants";-import { AuditLogEventClass } from "@app/hooks/api/auditLogSettings/types";import { ProjectMembershipRole } from "@app/hooks/api/roles/types";-type TForm = Record<AuditLogEventClass, boolean>;--const REQUIRES_NEW_PRIVILEGE_SYSTEM = "Requires the new privilege system";-const ALWAYS_RECORDED = "Management events are always recorded";-export const AuditLogEventClassesSection = () => {const { currentProject } = useProject();const { currentOrg } = useOrganization();@@ -37,121 +12,22 @@ export const AuditLogEventClassesSection = () => {const { data: settings, isPending } = useGetProjectAuditLogSettings(currentProject.id);const { mutateAsync: updateSettings, isPending: isSaving } = useUpdateProjectAuditLogSettings();- const isEnabled = (eventClass: AuditLogEventClass) =>- settings?.eventClasses.find((el) => el.eventClass === eventClass)?.isEnabled ??- AUDIT_LOG_EVENT_CLASS_DEFAULTS[eventClass];-- const {- control,- handleSubmit,- reset,- formState: { isDirty }- } = useForm<TForm>({- values: Object.fromEntries(- AUDIT_LOG_EVENT_CLASSES.map((eventClass) => [eventClass, isEnabled(eventClass)])- ) as TForm- });-- const shouldUseNewPrivilegeSystem =- settings?.shouldUseNewPrivilegeSystem ?? currentOrg.shouldUseNewPrivilegeSystem;-- const onSubmit = async (form: TForm) => {- const eventClasses = CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES.map((eventClass) => ({- eventClass,- isEnabled: form[eventClass]- }));-- await updateSettings({ projectId: currentProject.id, eventClasses });- createNotification({ text: "Audit log settings saved", type: "success" });- };-return (- <form onSubmit={handleSubmit(onSubmit)} className="mb-6">- <Card className="gap-0 overflow-hidden p-0">- <CardHeader className="border-b p-6">- <CardTitle className="font-alliance">- Audit Log Event Classes- <DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/audit-logs" />- </CardTitle>- <CardDescription>Choose which classes of events this project records.</CardDescription>- </CardHeader>- {isPending ? (- <div className="space-y-4 p-6">- {AUDIT_LOG_EVENT_CLASSES.map((eventClass) => (- <Skeleton key={eventClass} className="h-12 w-full" />- ))}- </div>- ) : (- <div className="divide-y divide-border">- {AUDIT_LOG_EVENT_CLASSES.map((eventClass) => {- const isManagement = eventClass === AuditLogEventClass.Management;- const isAuthorization = eventClass === AuditLogEventClass.Authorization;- const isLocked = isAuthorization && !shouldUseNewPrivilegeSystem;- let lockedReason: string | undefined;- if (isManagement) lockedReason = ALWAYS_RECORDED;- else if (isLocked) lockedReason = REQUIRES_NEW_PRIVILEGE_SYSTEM;- return (- <Controller- key={eventClass}- control={control}- name={eventClass}- render={({ field }) => (- <AuditLogEventClassRow- eventClass={eventClass}- isEnabled={isManagement || (!isLocked && field.value)}- variant="project"- isDisabled={!isAdmin}- lockedReason={lockedReason}- onCheckedChange={field.onChange}- warning={- eventClass === AuditLogEventClass.DataAccess && !field.value- ? "Secret Insights are counted from these events and stay flat while this is off."- : undefined- }- descriptionExtra={- isLocked ? (- <>- Denials are only recorded on the new privilege system.{" "}- <Link- to="/organizations/$orgId/access-management"- params={{ orgId: currentOrg.id }}- >- Upgrade the privilege system- </Link>{" "}- in Access Control to enable this class.- </>- ) : undefined- }- />- )}- />- );- })}- </div>- )}- {isAdmin && (- <CardFooter className="min-h-8 justify-end gap-2 border-t p-4">- <Button- type="button"- variant="ghost"- size="sm"- isDisabled={!isDirty || isSaving}- onClick={() => reset()}- >- Reset- </Button>- <Button- type="submit"- variant="project"- size="sm"- isDisabled={!isDirty}- isPending={isSaving}- >- Save Changes- </Button>- </CardFooter>- )}- </Card>- </form>+ <AuditLogEventClassesForm+ className="mb-6"+ titleClassName="font-alliance"+ title="Audit Log Event Classes"+ description="Choose which classes of events this project records."+ settings={settings}+ isPending={isPending}+ isSaving={isSaving}+ canEdit={isAdmin}+ variant="project"+ orgId={currentOrg.id}+ shouldUseNewPrivilegeSystem={+ settings?.shouldUseNewPrivilegeSystem ?? currentOrg.shouldUseNewPrivilegeSystem+ }+ onSave={(eventClasses) => updateSettings({ projectId: currentProject.id, eventClasses })}+ />);};