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
add permission denial and settings
Thiago Araujo da Silva2ff92d52b016
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 7b22c041bc..2d448c580d 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -993,6 +993,35 @@ directly, so falling through turns a dangling gateway reference into a silent byboundary the gateway exists to enforce. And `app_connections.gatewayId` is **not** a v1 column — unlike thethree above it never grew a `gatewayV2Id`, so that one column carries v2 ids and must stay.+### Audit Log Event Classes and Settings++Every `EventType` belongs to exactly one class in+`src/ee/services/audit-log/audit-log-event-classes.ts`: `management`, `authentication`,+`authorization` (only `PERMISSION_DENIED`), or `data-access`. The class is derived from the event+type at write and read time, so stored rows carry no class column. **A new event type is+`management` unless you add it to one of the explicit lists**, and `audit-log-event-classes.test.ts`+fails if a type lands in two lists. Reads, lists, dashboards, insights views, CMEK use operations+and the dynamic secret lease lifecycle are data access; VIEW_AUDIT_LOGS and privileged session+lifecycle are management on purpose.++Any class can be turned off per org, and a project row overrides the org in either direction. The rows live in+`audit_log_settings` (one per scope and class, `projectId` null for the org scope; no row means+the default in `AUDIT_LOG_EVENT_CLASS_DEFAULTS`: data access on, authorization off) behind `audit-log-settings-service.ts`, which caches the org's whole picture in the+keystore for 60s (`getEffectiveSettings`, never throws: a lookup failure records everything).+Enforcement happens in `buildStreamEntry` in `audit-log-queue.ts`, memoized per request so a+batch of events costs one settings read. Suppressed events are dropped silently and do not+count on the dropped counter.++`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.+### Server PluginsKey plugins in `src/server/plugins/`:diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 9c0efc4678..1a0e2c87cd 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -13,6 +13,7 @@ import { TAgentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proimport { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";import { TAgentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-service";import { TAssumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-types";+import { TAuditLogSettingsServiceFactory } from "@app/ee/services/audit-log/audit-log-settings-service";import { TAuditLogServiceFactory, TCreateAuditLogDTO } from "@app/ee/services/audit-log/audit-log-types";import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";import { TAuditReportServiceFactory } from "@app/ee/services/audit-report/audit-report-service";@@ -353,6 +354,7 @@ declare module "fastify" {ldap: TLdapConfigServiceFactory;auditLog: TAuditLogServiceFactory;auditLogStream: TAuditLogStreamServiceFactory;+ auditLogSettings: TAuditLogSettingsServiceFactory;certificate: TCertificateServiceFactory;certificateCleanup: TCertificateCleanupServiceFactory;certificateInventoryView: TCertificateInventoryViewServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 62db78d2c4..c38989493d 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -99,6 +99,9 @@ import {TApprovalRequestStepsUpdate,TApprovalRequestsUpdate,TAuditLogs,+ TAuditLogSettings,+ TAuditLogSettingsInsert,+ TAuditLogSettingsUpdate,TAuditLogsInsert,TAuditLogStreams,TAuditLogStreamsInsert,@@ -1389,6 +1392,11 @@ declare module "knex/types/tables" {TAuditLogStreamsInsert,TAuditLogStreamsUpdate>;+ [TableName.AuditLogSettings]: KnexOriginal.CompositeTableType<+ TAuditLogSettings,+ TAuditLogSettingsInsert,+ TAuditLogSettingsUpdate+ >;[TableName.AuditReport]: KnexOriginal.CompositeTableType<TAuditReports, TAuditReportsInsert, TAuditReportsUpdate>;[TableName.GitAppInstallSession]: KnexOriginal.CompositeTableType<TGitAppInstallSessions,diff --git a/backend/src/db/migrations/20260924100000_audit-log-settings.ts b/backend/src/db/migrations/20260924100000_audit-log-settings.tsnew file mode 100644index 0000000000..54daecf6f8--- /dev/null+++ b/backend/src/db/migrations/20260924100000_audit-log-settings.ts@@ -0,0 +1,37 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.AuditLogSettings))) {+ await knex.schema.createTable(TableName.AuditLogSettings, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("orgId").notNullable();+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");+ t.string("projectId").nullable();+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");+ t.string("eventClass").notNullable();+ t.boolean("isEnabled").notNullable().defaultTo(true);+ t.timestamps(true, true, true);+ t.index(["orgId"]);+ });++ // Two partial indexes: NULLS NOT DISTINCT needs Postgres 15.+ await knex.raw(+ `CREATE UNIQUE INDEX "audit_log_settings_org_scope_unique" ON ??("orgId", "eventClass") WHERE "projectId" IS NULL`,+ [TableName.AuditLogSettings]+ );+ await knex.raw(+ `CREATE UNIQUE INDEX "audit_log_settings_project_scope_unique" ON ??("projectId", "eventClass") WHERE "projectId" IS NOT NULL`,+ [TableName.AuditLogSettings]+ );++ await createOnUpdateTrigger(knex, TableName.AuditLogSettings);+ }+}++export async function down(knex: Knex): Promise<void> {+ await dropOnUpdateTrigger(knex, TableName.AuditLogSettings);+ await knex.schema.dropTableIfExists(TableName.AuditLogSettings);+}diff --git a/backend/src/db/schemas/audit-log-settings.ts b/backend/src/db/schemas/audit-log-settings.tsnew file mode 100644index 0000000000..e904ff1beb--- /dev/null+++ b/backend/src/db/schemas/audit-log-settings.ts@@ -0,0 +1,22 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const AuditLogSettingsSchema = z.object({+ id: z.string().uuid(),+ orgId: z.string().uuid(),+ projectId: z.string().nullable().optional(),+ eventClass: z.string(),+ isEnabled: z.boolean().default(true),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAuditLogSettings = z.infer<typeof AuditLogSettingsSchema>;+export type TAuditLogSettingsInsert = Omit<z.input<typeof AuditLogSettingsSchema>, TImmutableDBKeys>;+export type TAuditLogSettingsUpdate = Partial<Omit<z.input<typeof AuditLogSettingsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 212f1056c9..067766fec6 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -30,6 +30,7 @@ export * from "./approval-request-grants";export * from "./approval-request-step-eligible-approvers";export * from "./approval-request-steps";export * from "./approval-requests";+export * from "./audit-log-settings";export * from "./audit-log-stream-outbox";export * from "./audit-log-streams";export * from "./audit-logs";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 635ff9e65e..9bae1ea5e1 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -153,6 +153,7 @@ export enum TableName {AuditLog = "audit_logs",AuditLogStream = "audit_log_streams",AuditLogStreamOutbox = "audit_log_stream_outbox",+ AuditLogSettings = "audit_log_settings",GitAppInstallSession = "git_app_install_sessions",GitAppOrg = "git_app_org",SecretScanningGitRisk = "secret_scanning_git_risks",diff --git a/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts b/backend/src/ee/services/audit-log/audit-log-event-classes.test.tsnew file mode 100644index 0000000000..6ee374a595--- /dev/null+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts@@ -0,0 +1,75 @@+import { describe, expect, test } from "vitest";++import {+ AUDIT_LOG_EVENT_CLASS_DEFAULTS,+ AUDIT_LOG_EVENT_CLASS_MEMBERS,+ AuditLogEventClass,+ getAuditLogEventClass,+ getEventTypesForClasses+} from "./audit-log-event-classes";+import { EventType } from "./audit-log-types";++describe("audit log event classes", () => {+ test("every event type belongs to exactly one class", () => {+ const seen = new Map<EventType, AuditLogEventClass[]>();+ Object.entries(AUDIT_LOG_EVENT_CLASS_MEMBERS).forEach(([eventClass, members]) => {+ members.forEach((type) => {+ seen.set(type, [...(seen.get(type) ?? []), eventClass as AuditLogEventClass]);+ });+ });++ const duplicates = [...seen.entries()].filter(([, classes]) => classes.length > 1);+ expect(duplicates).toEqual([]);++ const missing = Object.values(EventType).filter((type) => !seen.has(type));+ expect(missing).toEqual([]);+ expect(seen.size).toBe(Object.values(EventType).length);+ });++ test("every class has a default and only authorization is off", () => {+ expect(Object.keys(AUDIT_LOG_EVENT_CLASS_DEFAULTS).sort()).toEqual(Object.values(AuditLogEventClass).sort());+ expect(AUDIT_LOG_EVENT_CLASS_DEFAULTS[AuditLogEventClass.Authorization]).toBe(false);+ expect(AUDIT_LOG_EVENT_CLASS_DEFAULTS[AuditLogEventClass.Management]).toBe(true);+ expect(AUDIT_LOG_EVENT_CLASS_DEFAULTS[AuditLogEventClass.Authentication]).toBe(true);+ expect(AUDIT_LOG_EVENT_CLASS_DEFAULTS[AuditLogEventClass.DataAccess]).toBe(true);+ });++ test.each([+ [EventType.GET_SECRETS, AuditLogEventClass.DataAccess],+ [EventType.REVEAL_SECRET, AuditLogEventClass.DataAccess],+ [EventType.CMEK_DECRYPT, AuditLogEventClass.DataAccess],+ [EventType.CREATE_DYNAMIC_SECRET_LEASE, AuditLogEventClass.DataAccess],+ [EventType.PKI_SIGNER_SIGN, AuditLogEventClass.DataAccess],+ [EventType.DASHBOARD_LIST_SECRETS, AuditLogEventClass.DataAccess],+ [EventType.VIEW_INSIGHTS_AUTH_METHODS, AuditLogEventClass.DataAccess],+ [EventType.UPDATE_SECRET, AuditLogEventClass.Management],+ [EventType.CREATE_CMEK, AuditLogEventClass.Management],+ [EventType.VIEW_AUDIT_LOGS, AuditLogEventClass.Management],+ [EventType.CREATE_CERTIFICATE_INVENTORY_VIEW, AuditLogEventClass.Management],+ [EventType.EXPORT_CERT_MANAGER_PROJECT, AuditLogEventClass.Management],+ [EventType.PAM_SESSION_START, AuditLogEventClass.Management],+ [EventType.UPDATE_AUDIT_LOG_SETTINGS, AuditLogEventClass.Management],+ [EventType.USER_LOGIN, AuditLogEventClass.Authentication],+ [EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH_FAILED, AuditLogEventClass.Authentication],+ [EventType.SELECT_ORGANIZATION, AuditLogEventClass.Authentication],+ [EventType.GATEWAY_CONNECT, AuditLogEventClass.Authentication],+ [EventType.PERMISSION_DENIED, AuditLogEventClass.Authorization]+ ])("classifies %s as %s", (eventType, expected) => {+ expect(getAuditLogEventClass(eventType)).toBe(expected);+ });++ test("an unknown event type falls back to management", () => {+ expect(getAuditLogEventClass("not-a-real-event")).toBe(AuditLogEventClass.Management);+ });++ test("expands classes to their member event types", () => {+ const expanded = getEventTypesForClasses([AuditLogEventClass.Authorization, AuditLogEventClass.Authentication]);+ expect(expanded).toContain(EventType.PERMISSION_DENIED);+ expect(expanded).toContain(EventType.USER_LOGIN);+ expect(expanded).not.toContain(EventType.GET_SECRETS);+ expect(expanded.length).toBe(+ AUDIT_LOG_EVENT_CLASS_MEMBERS[AuditLogEventClass.Authorization].length ++ AUDIT_LOG_EVENT_CLASS_MEMBERS[AuditLogEventClass.Authentication].length+ );+ });+});diff --git a/backend/src/ee/services/audit-log/audit-log-event-classes.ts b/backend/src/ee/services/audit-log/audit-log-event-classes.tsnew file mode 100644index 0000000000..c160632070--- /dev/null+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.ts@@ -0,0 +1,255 @@+import { EventType } from "./audit-log-types";++export enum AuditLogEventClass {+ Management = "management",+ Authentication = "authentication",+ Authorization = "authorization",+ DataAccess = "data-access"+}++export const AUDIT_LOG_EVENT_CLASS_DEFAULTS: Record<AuditLogEventClass, boolean> = {+ [AuditLogEventClass.Management]: true,+ [AuditLogEventClass.Authentication]: true,+ [AuditLogEventClass.DataAccess]: true,+ [AuditLogEventClass.Authorization]: false+};++export const AUTHENTICATION_EVENT_TYPES: readonly EventType[] = [+ EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH,+ EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_KUBERNETES_AUTH,+ EventType.LOGIN_IDENTITY_KUBERNETES_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_OIDC_AUTH,+ EventType.LOGIN_IDENTITY_OIDC_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_JWT_AUTH,+ EventType.LOGIN_IDENTITY_JWT_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_SPIFFE_AUTH,+ EventType.LOGIN_IDENTITY_SPIFFE_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_GCP_AUTH,+ EventType.LOGIN_IDENTITY_GCP_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_ALICLOUD_AUTH,+ EventType.LOGIN_IDENTITY_ALICLOUD_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_TLS_CERT_AUTH,+ EventType.LOGIN_IDENTITY_TLS_CERT_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_AWS_AUTH,+ EventType.LOGIN_IDENTITY_AWS_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_OCI_AUTH,+ EventType.LOGIN_IDENTITY_OCI_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_AZURE_AUTH,+ EventType.LOGIN_IDENTITY_AZURE_AUTH_FAILED,+ EventType.LOGIN_IDENTITY_LDAP_AUTH,+ EventType.LOGIN_IDENTITY_LDAP_AUTH_FAILED,+ EventType.ORG_ADMIN_BYPASS_SSO,+ EventType.USER_LOGIN,+ EventType.SELECT_ORGANIZATION,+ EventType.SELECT_SUB_ORGANIZATION,+ EventType.KMIP_SERVER_CONNECT,+ EventType.PAM_SESSION_UPLOAD_TOKEN_INVALID,+ EventType.AGENT_VAULT_PROXY_ENROLL,+ EventType.OAUTH_CLIENT_AUTHORIZE,+ EventType.OAUTH_CLIENT_TOKEN_EXCHANGE,+ EventType.GATEWAY_ENROLL,+ EventType.GATEWAY_CONNECT,+ EventType.RESOURCE_AUTH_METHOD_LOGIN,+ EventType.RESOURCE_AUTH_METHOD_LOGIN_FAILED+];++export const AUTHORIZATION_EVENT_TYPES: readonly EventType[] = [EventType.PERMISSION_DENIED];++export const DATA_ACCESS_EVENT_TYPES: readonly EventType[] = [+ EventType.GET_SECRETS,+ EventType.GET_SECRET,+ EventType.REVEAL_SECRET,+ EventType.GET_PROJECT_KEY,+ EventType.GET_IDENTITY_UNIVERSAL_AUTH,+ EventType.GET_TOKENS_IDENTITY_TOKEN_AUTH,+ EventType.GET_TOKEN_IDENTITY_TOKEN_AUTH,+ EventType.GET_IDENTITY_TOKEN_AUTH,+ EventType.GET_IDENTITY_KUBERNETES_AUTH,+ EventType.GET_IDENTITY_OIDC_AUTH,+ EventType.GET_IDENTITY_JWT_AUTH,+ EventType.GET_IDENTITY_SPIFFE_AUTH,+ EventType.GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRETS,+ EventType.GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET_BY_ID,+ EventType.GET_IDENTITY_GCP_AUTH,+ EventType.GET_IDENTITY_ALICLOUD_AUTH,+ EventType.GET_IDENTITY_TLS_CERT_AUTH,+ EventType.GET_IDENTITY_AWS_AUTH,+ EventType.GET_IDENTITY_OCI_AUTH,+ EventType.GET_IDENTITY_AZURE_AUTH,+ EventType.GET_IDENTITY_LDAP_AUTH,+ EventType.GET_ENVIRONMENT,+ EventType.GET_PROJECT_MEMBER_PERMISSION_AUDIT,+ EventType.GET_PROJECT_IDENTITY_PERMISSION_AUDIT,+ EventType.GET_SECRET_IMPORTS,+ EventType.GET_SECRET_IMPORT,+ EventType.GET_AZURE_AD_TEMPLATES,+ EventType.GET_ADCS_TEMPLATES,+ EventType.GET_CA,+ EventType.GET_CAS,+ EventType.GET_CA_CSR,+ EventType.GET_CA_CERTS,+ EventType.GET_CA_CERT,+ EventType.GET_CA_CRLS,+ EventType.GET_CA_SIGNING_CONFIG,+ EventType.GET_CA_AUTO_RENEWAL_CONFIG,+ EventType.GET_CA_CERTIFICATE_TEMPLATES,+ EventType.GET_CERT,+ EventType.GET_CERT_BODY,+ EventType.GET_CERT_PRIVATE_KEY,+ EventType.GET_CERT_BUNDLE,+ EventType.EXPORT_CERT_PKCS12,+ EventType.GET_PKI_ALERT,+ EventType.GET_PKI_COLLECTION,+ EventType.GET_PKI_COLLECTION_ITEMS,+ EventType.GET_PKI_SUBSCRIBER,+ EventType.LIST_PKI_SUBSCRIBER_CERTS,+ EventType.GET_SUBSCRIBER_ACTIVE_CERT_BUNDLE,+ EventType.GET_KMS,+ EventType.GET_PROJECT_KMS_BACKUP,+ EventType.GET_CERTIFICATE_POLICY,+ EventType.LIST_CERTIFICATE_POLICIES,+ EventType.GET_CERTIFICATE_TEMPLATE_EST_CONFIG,+ EventType.GET_CERTIFICATE_PROFILE,+ EventType.LIST_CERTIFICATE_PROFILES,+ EventType.GET_PKI_APPLICATION,+ EventType.LIST_PKI_APPLICATIONS,+ EventType.LIST_PKI_APPLICATION_MEMBERS,+ EventType.GET_PKI_APPLICATION_ENROLLMENT,+ EventType.REVEAL_PKI_APPLICATION_ACME_EAB_SECRET,+ EventType.GET_CERT_MANAGER_INSTANCE_STATE,+ EventType.GET_CERTIFICATE_PROFILE_LATEST_ACTIVE_BUNDLE,+ EventType.GET_CERTIFICATE_REQUEST,+ EventType.GET_CERTIFICATE_FROM_REQUEST,+ EventType.LIST_CERTIFICATE_REQUESTS,+ EventType.GET_PROJECT_SLACK_CONFIG,+ EventType.GET_SLACK_INTEGRATION,+ EventType.GET_PROJECT_WORKFLOW_INTEGRATION_CONFIG,+ EventType.GET_CMEKS,+ EventType.GET_CMEK,+ EventType.CMEK_ENCRYPT,+ EventType.CMEK_DECRYPT,+ EventType.CMEK_SIGN,+ EventType.CMEK_VERIFY,+ EventType.CMEK_GENERATE_MAC,+ EventType.CMEK_VERIFY_MAC,+ EventType.CMEK_LIST_SIGNING_ALGORITHMS,+ EventType.CMEK_GET_PUBLIC_KEY,+ EventType.CMEK_GET_PRIVATE_KEY,+ EventType.CMEK_BULK_EXPORT_PRIVATE_KEYS,+ EventType.GET_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS,+ EventType.GET_PROJECT_TEMPLATES,+ EventType.GET_PROJECT_TEMPLATE,+ EventType.GET_APP_CONNECTIONS,+ EventType.GET_AVAILABLE_APP_CONNECTIONS_DETAILS,+ EventType.GET_APP_CONNECTION,+ EventType.GET_APP_CONNECTION_USAGE,+ EventType.READ_SHARED_SECRET,+ EventType.GET_SECRET_SYNCS,+ EventType.GET_SECRET_SYNC,+ EventType.GET_PKI_SYNCS,+ EventType.GET_PKI_SYNC,+ EventType.GET_PKI_SYNC_CERTIFICATES,+ EventType.GET_KMIP_CLIENT,+ EventType.GET_KMIP_CLIENTS,+ EventType.GET_KMIP,+ EventType.KMIP_OPERATION_GET,+ EventType.KMIP_OPERATION_GET_ATTRIBUTES,+ EventType.KMIP_OPERATION_LOCATE,+ EventType.GET_SECRET_ROTATIONS,+ EventType.GET_SECRET_ROTATION,+ EventType.GET_SECRET_ROTATION_GENERATED_CREDENTIALS,+ EventType.MICROSOFT_TEAMS_WORKFLOW_INTEGRATION_CHECK_INSTALLATION_STATUS,+ EventType.MICROSOFT_TEAMS_WORKFLOW_INTEGRATION_GET_TEAMS,+ EventType.MICROSOFT_TEAMS_WORKFLOW_INTEGRATION_GET,+ EventType.MICROSOFT_TEAMS_WORKFLOW_INTEGRATION_LIST,+ EventType.GET_PROJECT_PIT_COMMITS,+ EventType.GET_PROJECT_PIT_COMMIT_AUTHORS,+ EventType.GET_PROJECT_PIT_COMMIT_CHANGES,+ EventType.GET_PROJECT_PIT_COMMIT_COUNT,+ EventType.PIT_GET_FOLDER_STATE,+ EventType.PIT_COMPARE_FOLDER_STATES,+ EventType.SECRET_SCANNING_DATA_SOURCE_LIST,+ EventType.SECRET_SCANNING_DATA_SOURCE_GET,+ EventType.SECRET_SCANNING_RESOURCE_LIST,+ EventType.SECRET_SCANNING_SCAN_LIST,+ EventType.SECRET_SCANNING_FINDING_LIST,+ EventType.SECRET_SCANNING_CONFIG_GET,+ EventType.LIST_PROJECT_ROLES,+ EventType.GET_PROJECT_ROLE,+ EventType.GET_SECRET_REMINDER,+ EventType.DASHBOARD_LIST_SECRETS,+ EventType.DASHBOARD_GET_SECRET_VALUE,+ EventType.DASHBOARD_GET_SECRET_VERSION_VALUE,+ EventType.SEARCH_SECRETS_BY_METADATA,+ EventType.VIEW_INSIGHTS_AUTH_METHODS,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_CALENDAR,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_VOLUME,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ORG_AUTH_METHOD_DISTRIBUTION,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_ACCESS_LOCATIONS,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_SUMMARY,+ EventType.VIEW_INSIGHTS_SECRETS_DUPLICATION,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_COUNTS,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_USAGE,+ EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS,+ EventType.GET_AUDIT_REPORTS,+ EventType.GET_AUDIT_REPORT,+ EventType.GET_ORG_AUDIT_REPORTS,+ EventType.VIEW_INSIGHTS_PAM_SUMMARY,+ EventType.VIEW_INSIGHTS_PAM_SESSION_ACTIVITY,+ EventType.VIEW_INSIGHTS_PAM_TOP_ACTORS,+ EventType.VIEW_INSIGHTS_PAM_RESOURCE_BREAKDOWN,+ EventType.VIEW_INSIGHTS_PAM_ROTATION_CALENDAR,+ EventType.PAM_SESSION_CREDENTIALS_GET,+ EventType.PAM_ACCOUNT_CREDENTIALS_VIEW,+ EventType.APPROVAL_POLICY_LIST,+ EventType.APPROVAL_POLICY_GET,+ EventType.APPROVAL_REQUEST_GET,+ EventType.APPROVAL_REQUEST_LIST,+ EventType.APPROVAL_REQUEST_GRANT_LIST,+ EventType.APPROVAL_REQUEST_GRANT_GET,+ EventType.RETRIEVE_ACME_ACCOUNT,+ EventType.DOWNLOAD_ACME_CERTIFICATE,+ EventType.GET_DYNAMIC_SECRET,+ EventType.LIST_DYNAMIC_SECRETS,+ EventType.CREATE_DYNAMIC_SECRET_LEASE,+ EventType.DELETE_DYNAMIC_SECRET_LEASE,+ EventType.RENEW_DYNAMIC_SECRET_LEASE,+ EventType.LIST_DYNAMIC_SECRET_LEASES,+ EventType.GET_DYNAMIC_SECRET_LEASE,+ EventType.GET_PKI_DISCOVERY,+ EventType.GET_PKI_DISCOVERIES,+ EventType.GET_PKI_INSTALLATION,+ EventType.GET_PKI_INSTALLATIONS,+ EventType.GET_PKI_SIGNER,+ EventType.GET_PKI_SIGNERS,+ EventType.GET_PKI_SIGNER_PUBLIC_KEY,+ EventType.GET_PKI_SIGNING_OPERATIONS,+ EventType.GET_PKI_SIGNING_OPERATION,+ EventType.PKI_SIGNER_SIGN,+ EventType.EXPORT_PKI_SIGNER_CERTIFICATE,+ EventType.PKI_SIGNER_REQUEST_TO_SIGN+];++const EVENT_TYPE_TO_CLASS = new Map<EventType, AuditLogEventClass>([+ ...AUTHENTICATION_EVENT_TYPES.map((type) => [type, AuditLogEventClass.Authentication] as const),+ ...AUTHORIZATION_EVENT_TYPES.map((type) => [type, AuditLogEventClass.Authorization] as const),+ ...DATA_ACCESS_EVENT_TYPES.map((type) => [type, AuditLogEventClass.DataAccess] as const)+]);++export const MANAGEMENT_EVENT_TYPES: readonly EventType[] = Object.values(EventType).filter(+ (type) => !EVENT_TYPE_TO_CLASS.has(type)+);++export const AUDIT_LOG_EVENT_CLASS_MEMBERS: Record<AuditLogEventClass, readonly EventType[]> = {+ [AuditLogEventClass.Management]: MANAGEMENT_EVENT_TYPES,+ [AuditLogEventClass.Authentication]: AUTHENTICATION_EVENT_TYPES,+ [AuditLogEventClass.Authorization]: AUTHORIZATION_EVENT_TYPES,+ [AuditLogEventClass.DataAccess]: DATA_ACCESS_EVENT_TYPES+};++export const getAuditLogEventClass = (eventType: string): AuditLogEventClass =>+ EVENT_TYPE_TO_CLASS.get(eventType as EventType) ?? AuditLogEventClass.Management;++export const getEventTypesForClasses = (eventClasses: AuditLogEventClass[]): EventType[] =>+ eventClasses.flatMap((eventClass) => AUDIT_LOG_EVENT_CLASS_MEMBERS[eventClass]);diff --git a/backend/src/ee/services/audit-log/audit-log-queue.test.ts b/backend/src/ee/services/audit-log/audit-log-queue.test.tsindex baadb43cab..c2184a2c2e 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.test.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.test.ts@@ -98,6 +98,9 @@ const createHarness = async ({ clickhouse = false, streamsEnabled = false, generconst auditLogStreamOutboxService = {enqueueForLogs: vi.fn<(logs: unknown[]) => Promise<void>>(async () => undefined)};+ const auditLogSettingsService = {+ getEffectiveSettings: vi.fn<(orgId: string) => Promise<Record<string, unknown> | null>>(async () => null)+ };const clickhouseClient = clickhouse? {insert: vi.fn<(opts: { table: string; values: Record<string, unknown>[] }) => Promise<unknown>>(@@ -111,6 +114,7 @@ const createHarness = async ({ clickhouse = false, streamsEnabled = false, generqueueService: queueService as never,projectDAL: projectDAL as never,licenseService: licenseService as never,+ auditLogSettingsService: auditLogSettingsService as never,auditLogStreamOutboxService: auditLogStreamOutboxService as never,clickhouseClient: clickhouseClient as never,keyStore: keyStore as never@@ -125,6 +129,7 @@ const createHarness = async ({ clickhouse = false, streamsEnabled = false, generprojectDAL,licenseService,auditLogStreamOutboxService,+ auditLogSettingsService,clickhouseClient,consumer: startHandlers.get(QueueName.AuditLogClickHouseBatch)!};@@ -239,6 +244,105 @@ describe("audit-log-queue pushToLog", () => {});});+describe("audit-log-queue event class settings", () => {+ const settings = (overrides: Record<string, unknown> = {}) => ({+ org: {},+ projects: {},+ shouldUseNewPrivilegeSystem: true,+ ...overrides+ });++ test("drops a data-access event when the org disabled the class", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(settings({ org: { "data-access": false } }));++ await service.pushToLog(dto({ event: { type: "get-secrets", metadata: {} } }) as never);++ expect(keyStore.streamAdd).not.toHaveBeenCalled();+ });++ test("stores a data-access event when the class is enabled", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(settings({ org: { "data-access": true } }));++ await service.pushToLog(dto({ event: { type: "get-secrets", metadata: {} } }) as never);++ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);+ });++ test("drops a management event when the org turned the class off", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(settings({ org: { management: false } }));++ await service.pushToLog(dto({ event: { type: "update-secret", metadata: {} } }) as never);++ expect(keyStore.streamAdd).not.toHaveBeenCalled();+ });++ test("records a management event when no scope has a setting", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(settings());++ await service.pushToLog(dto({ event: { type: "update-secret", metadata: {} } }) as never);++ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);+ });++ test("a project setting overrides the org in both directions", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValue(+ settings({ org: { "data-access": false }, projects: { "p-on": { "data-access": true } } })+ );++ await service.pushToLog(dto({ projectId: "p-on", event: { type: "get-secrets", metadata: {} } }) as never);+ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);++ auditLogSettingsService.getEffectiveSettings.mockResolvedValue(+ settings({ org: {}, projects: { "p-off": { "data-access": false } } })+ );+ await service.pushToLog(dto({ projectId: "p-off", event: { type: "get-secrets", metadata: {} } }) as never);+ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);+ });++ test("an org-scoped event ignores project settings", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(+ settings({ org: {}, projects: { p1: { "data-access": false } } })+ );++ await service.pushToLog(dto({ event: { type: "get-secrets", metadata: {} } }) as never);++ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);+ });++ test("drops a permission denial when no scope has turned authorization on", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(settings());++ await service.pushToLog(dto({ event: { type: "permission-denied", metadata: {} } }) as never);++ expect(keyStore.streamAdd).not.toHaveBeenCalled();+ });++ test("records a data-access event when no scope has a setting", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(settings());++ await service.pushToLog(dto({ event: { type: "get-secrets", metadata: {} } }) as never);++ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);+ });++ test("records the event when the settings lookup returns nothing", async () => {+ const { service, keyStore, auditLogSettingsService } = await createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(null);++ await service.pushToLog(dto({ event: { type: "get-secrets", metadata: {} } }) as never);++ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);+ });+});+describe("audit-log-queue unified consumer", () => {test("does nothing on an empty stream", async () => {const { consumer, auditLogDAL, keyStore } = await createHarness();diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.tsindex bff2c60d18..c4bdaf1295 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts@@ -19,6 +19,8 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";import { TLicenseServiceFactory } from "../license/license-service";import { TAuditLogDALFactory } from "./audit-log-dal";+import { getAuditLogEventClass } from "./audit-log-event-classes";+import { isAuditLogEventClassEnabled, TAuditLogSettingsServiceFactory } from "./audit-log-settings-service";import { TAuditLogStreamEntry, TCreateAuditLogDTO } from "./audit-log-types";type TAuditLogQueueServiceFactoryDep = {@@ -27,6 +29,7 @@ type TAuditLogQueueServiceFactoryDep = {queueService: TQueueServiceFactory;projectDAL: Pick<TProjectDALFactory, "findById">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ auditLogSettingsService: Pick<TAuditLogSettingsServiceFactory, "getEffectiveSettings">;clickhouseClient: ClickHouseClient | null;keyStore: Pick<TKeyStoreFactory, "streamAdd" | "streamCollect" | "streamTrim" | "acquireLock">;};@@ -72,6 +75,7 @@ export const auditLogQueueServiceFactory = async ({queueService,projectDAL,licenseService,+ auditLogSettingsService,auditLogStreamOutboxService,clickhouseClient,keyStore@@ -103,6 +107,12 @@ export const auditLogQueueServiceFactory = async ({const orgId = data.orgId ?? project?.orgId;if (!orgId) return null;+ const eventClass = getAuditLogEventClass(data.event.type);+ const settings = await requestMemoize(requestMemoKeys.auditLogSettings(orgId), () =>+ auditLogSettingsService.getEffectiveSettings(orgId)+ );+ if (!isAuditLogEventClassEnabled(settings, eventClass, projectId)) return null;+const plan = await licenseService.getPlan(orgId);if (!plan?.auditLogsRetentionDays) return null;diff --git a/backend/src/ee/services/audit-log/audit-log-service.test.ts b/backend/src/ee/services/audit-log/audit-log-service.test.tsnew file mode 100644index 0000000000..7cda904aa0--- /dev/null+++ b/backend/src/ee/services/audit-log/audit-log-service.test.ts@@ -0,0 +1,204 @@+import { beforeEach, describe, expect, test, vi } from "vitest";++import { QueueJobs, QueueName } from "@app/queue";++import { AuditLogEventClass } from "./audit-log-event-classes";+import { auditLogServiceFactory } from "./audit-log-service";+import { TEffectiveAuditLogSettings } from "./audit-log-settings-types";+import { EventType, TRecordPermissionDeniedDTO } from "./audit-log-types";++vi.mock("@app/lib/config/env", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/lib/config/env")>()),+ getConfig: () => ({ DISABLE_AUDIT_LOG_GENERATION: false })+}));++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }+}));++type TFlushPayload = { collapseKey: string; windowStart: string; windowEnd: string; orgId: string };+type TPushedLog = { event: { metadata: Record<string, unknown> } };++const denial = (overrides: Partial<TRecordPermissionDeniedDTO> = {}): TRecordPermissionDeniedDTO => ({+ orgId: "org-1",+ projectId: "project-1",+ actor: { type: "identity", metadata: { identityId: "identity-1", name: "ci" } } as never,+ ipAddress: "127.0.0.1",+ userAgent: "test",+ userAgentType: "other" as never,+ metadata: {+ permissionAction: "create",+ permissionSubject: "secrets",+ errorName: "ForbiddenError",+ message: "denied",+ route: "/api/v3/secrets/raw/:secretName",+ method: "POST",+ projectId: "project-1"+ },+ ...overrides+});++const createHarness = ({ windowAcquired = true, storedCount = "0" } = {}) => {+ const startHandlers = new Map<string, (job: { data: unknown }) => Promise<void>>();+ const queueService = {+ start: vi.fn((name: string, fn: (job: { data: unknown }) => Promise<void>) => {+ startHandlers.set(name, fn);+ }),+ queue: vi.fn<+ (name: string, job: string, data: TFlushPayload, opts: { jobId: string; delay: number }) => Promise<void>+ >(async () => undefined)+ };+ const keyStore = {+ getItem: vi.fn<(key: string) => Promise<string | null>>(async () => storedCount),+ setItemWithExpiry: vi.fn(async () => "OK"),+ setItemWithExpiryNX: vi.fn<(key: string, ttl: number, value: string) => Promise<string | null>>(async () =>+ windowAcquired ? "OK" : null+ ),+ incrementByWithExpiry: vi.fn<(key: string, by: number, ttl: number) => Promise<number>>(async () => 1),+ deleteItem: vi.fn<(key: string) => Promise<number>>(async () => 1)+ };+ const auditLogQueue = { pushToLog: vi.fn<(data: TPushedLog) => Promise<void>>(async () => undefined) };+ const auditLogSettingsService = {+ getEffectiveSettings: vi.fn<(orgId: string) => Promise<TEffectiveAuditLogSettings>>(async () => ({+ org: { [AuditLogEventClass.Authorization]: true },+ projects: {},+ shouldUseNewPrivilegeSystem: true+ }))+ };++ const service = auditLogServiceFactory({+ auditLogDAL: {} as never,+ permissionService: {} as never,+ auditLogQueue: auditLogQueue as never,+ auditLogSettingsService: auditLogSettingsService as never,+ queueService: queueService as never,+ keyStore: keyStore as never,+ smtpService: {} as never,+ userDAL: {} as never,+ notificationService: {} as never+ });++ const flush = startHandlers.get(QueueName.AuditLogPermissionDeniedFlush);+ if (!flush) throw new Error("flush worker was not registered");++ return { service, queueService, keyStore, auditLogQueue, auditLogSettingsService, flush };+};++describe("recordPermissionDenied", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ test("first denial in a window is written and schedules the flush job", async () => {+ const { service, queueService, keyStore, auditLogQueue } = createHarness();++ await service.recordPermissionDenied(denial());++ expect(keyStore.incrementByWithExpiry).not.toHaveBeenCalled();+ expect(auditLogQueue.pushToLog).toHaveBeenCalledTimes(1);+ expect(auditLogQueue.pushToLog.mock.calls[0][0]).toMatchObject({+ orgId: "org-1",+ projectId: "project-1",+ event: { type: EventType.PERMISSION_DENIED, metadata: { permissionAction: "create", method: "POST" } }+ });+ expect(auditLogQueue.pushToLog.mock.calls[0][0].event.metadata).not.toHaveProperty("suppressedRepeats");++ 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(opts.delay).toBe(60_000);+ expect(opts.jobId).toContain(payload.collapseKey);+ expect(payload.orgId).toBe("org-1");+ expect(new Date(payload.windowEnd).getTime() - new Date(payload.windowStart).getTime()).toBe(60_000);+ expect(keyStore.setItemWithExpiryNX.mock.calls[0][0]).toContain(payload.collapseKey);+ });++ test("a repeat inside the window only bumps the counter", async () => {+ const { service, queueService, keyStore, auditLogQueue } = createHarness({ windowAcquired: false });++ await service.recordPermissionDenied(denial());++ expect(auditLogQueue.pushToLog).not.toHaveBeenCalled();+ expect(queueService.queue).not.toHaveBeenCalled();+ expect(keyStore.incrementByWithExpiry).toHaveBeenCalledTimes(1);+ });++ test("the method is part of the collapse key", async () => {+ const { service, keyStore } = createHarness();++ await service.recordPermissionDenied(denial({ metadata: { ...denial().metadata, method: "GET" } }));+ await service.recordPermissionDenied(denial({ metadata: { ...denial().metadata, method: "DELETE" } }));++ const [firstKey] = keyStore.setItemWithExpiryNX.mock.calls[0];+ const [secondKey] = keyStore.setItemWithExpiryNX.mock.calls[1];+ expect(firstKey).not.toBe(secondKey);+ });++ test("nothing is recorded when the authorization class is off", async () => {+ const { service, keyStore, auditLogQueue, auditLogSettingsService } = createHarness();+ auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce({+ org: { [AuditLogEventClass.Authorization]: false },+ projects: {},+ shouldUseNewPrivilegeSystem: true+ });++ await service.recordPermissionDenied(denial());++ expect(keyStore.setItemWithExpiryNX).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"));++ await expect(service.recordPermissionDenied(denial())).resolves.toBeUndefined();+ expect(auditLogQueue.pushToLog).not.toHaveBeenCalled();+ });+});++describe("permission denied flush job", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ const jobData = {+ ...denial(),+ collapseKey: "abc",+ windowStart: "2026-09-30T10:00:00.000Z",+ windowEnd: "2026-09-30T10:01:00.000Z"+ };++ test("writes one summary event carrying the repeat count and window", async () => {+ const { flush, keyStore, auditLogQueue } = createHarness({ storedCount: "41" });++ await flush({ data: jobData });++ expect(keyStore.deleteItem).toHaveBeenCalledTimes(1);+ expect(auditLogQueue.pushToLog).toHaveBeenCalledTimes(1);+ expect(auditLogQueue.pushToLog.mock.calls[0][0]).toMatchObject({+ orgId: "org-1",+ projectId: "project-1",+ actor: { type: "identity", metadata: { identityId: "identity-1" } },+ event: {+ type: EventType.PERMISSION_DENIED,+ metadata: {+ permissionAction: "create",+ suppressedRepeats: 41,+ suppressedFrom: "2026-09-30T10:00:00.000Z",+ suppressedUntil: "2026-09-30T10:01:00.000Z"+ }+ }+ });+ });++ test("writes nothing when no repeat was counted", async () => {+ const { flush, keyStore, auditLogQueue } = createHarness({ storedCount: "0" });++ await flush({ data: jobData });++ expect(keyStore.deleteItem).not.toHaveBeenCalled();+ expect(auditLogQueue.pushToLog).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/ee/services/audit-log/audit-log-service.ts b/backend/src/ee/services/audit-log/audit-log-service.tsindex e986a30cb3..fb3acf4305 100644--- a/backend/src/ee/services/audit-log/audit-log-service.ts+++ b/backend/src/ee/services/audit-log/audit-log-service.ts@@ -4,9 +4,11 @@ import { requestContext } from "@fastify/request-context";import { ActionProjectType, OrganizationActionScope, TUsers } from "@app/db/schemas";import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";+import { generateCacheKeyFromData } from "@app/lib/crypto/cache";import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TNotificationServiceFactory } from "@app/services/notification/notification-service";import { NotificationType } from "@app/services/notification/notification-types";@@ -18,18 +20,32 @@ import { TPermissionServiceFactory } from "../permission/permission-service-typeimport { ProjectPermissionAuditLogsActions, ProjectPermissionSub } from "../permission/project-permission";import { TClickHouseAuditLogDALFactory } from "./audit-log-clickhouse-dal";import { TAuditLogDALFactory, TPamAuditLogScope } from "./audit-log-dal";+import { AuditLogEventClass, getAuditLogEventClass, getEventTypesForClasses } from "./audit-log-event-classes";import { TAuditLogQueueServiceFactory } from "./audit-log-queue";-import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, TAuditLogServiceFactory } from "./audit-log-types";+import { isAuditLogEventClassEnabled, TAuditLogSettingsServiceFactory } from "./audit-log-settings-service";+import {+ ACTOR_TYPE_TO_METADATA_ID_KEY,+ EventType,+ TAuditLogPermissionDeniedFlushJobData,+ 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;type TAuditLogServiceFactoryDep = {auditLogDAL: TAuditLogDALFactory;clickhouseAuditLogDAL?: TClickHouseAuditLogDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;auditLogQueue: TAuditLogQueueServiceFactory;- keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;+ auditLogSettingsService: Pick<TAuditLogSettingsServiceFactory, "getEffectiveSettings">;+ queueService: Pick<TQueueServiceFactory, "queue" | "start">;+ keyStore: Pick<+ TKeyStoreFactory,+ "getItem" | "setItemWithExpiry" | "setItemWithExpiryNX" | "incrementByWithExpiry" | "deleteItem"+ >;smtpService: Pick<TSmtpService, "sendMail">;userDAL: Pick<TUserDALFactory, "getUsersByFilter">;notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;@@ -46,7 +62,9 @@ export const auditLogServiceFactory = ({auditLogDAL,clickhouseAuditLogDAL,auditLogQueue,+ auditLogSettingsService,permissionService,+ queueService,keyStore,smtpService,userDAL,@@ -115,12 +133,19 @@ export const auditLogServiceFactory = ({const appCfg = getConfig();const useClickHouse = appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED && clickhouseAuditLogDAL;+ let { eventType } = filter;+ if (filter.eventClass?.length) {+ const classEventTypes = getEventTypesForClasses(filter.eventClass);+ eventType = eventType?.length ? eventType.filter((type) => classEventTypes.includes(type)) : classEventTypes;+ if (!eventType.length) return [];+ }+const findArgs = {startDate: filter.startDate,endDate: filter.endDate,limit: filter.limit,offset: filter.offset,- eventType: filter.eventType,+ eventType,userAgentType: filter.userAgentType,actorId: filter.auditLogActorId,actorType: filter.actorType,@@ -147,6 +172,7 @@ export const auditLogServiceFactory = ({updatedAt: el.createdAt,expiresAt: el.expiresAt,event: { type: logEventType, metadata: eventMetadata },+ eventClass: getAuditLogEventClass(logEventType),actor: { type: eActor, metadata: actorMetadata }}));};@@ -169,6 +195,115 @@ export const auditLogServiceFactory = ({return auditLogQueue.pushToLog(el);};+ // 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 ({+ collapseKey,+ windowStart,+ windowEnd,+ orgId,+ projectId,+ metadata,+ ...auditLogInfo+ }: TAuditLogPermissionDeniedFlushJobData) => {+ const countKey = KeyStorePrefixes.AuditLogPermissionDeniedCount(collapseKey);+ const suppressedRepeats = Number(await keyStore.getItem(countKey)) || 0;+ if (!suppressedRepeats) return;+ await keyStore.deleteItem(countKey);++ await auditLogQueue.pushToLog({+ ...auditLogInfo,+ orgId,+ projectId,+ event: {+ type: EventType.PERMISSION_DENIED,+ metadata: { ...metadata, suppressedRepeats, suppressedFrom: windowStart, suppressedUntil: windowEnd }+ }+ });+ };++ queueService.start(QueueName.AuditLogPermissionDeniedFlush, async (job) => {+ await flushPermissionDeniedRepeats(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.+ const recordPermissionDenied: TAuditLogServiceFactory["recordPermissionDenied"] = async ({+ orgId,+ projectId,+ metadata,+ ...auditLogInfo+ }) => {+ const appCfg = getConfig();+ if (appCfg.DISABLE_AUDIT_LOG_GENERATION) return;++ try {+ const settings = await auditLogSettingsService.getEffectiveSettings(orgId);+ if (!settings?.shouldUseNewPrivilegeSystem) return;++ if (!isAuditLogEventClassEnabled(settings, AuditLogEventClass.Authorization, projectId)) 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({+ ...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,+ 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+ }+ );+ } catch (error) {+ logger.warn(error, `audit-log: failed to record permission denial [orgId=${orgId}] [route=${metadata.route}]`);+ }+ };+const getAuditLogPostgresStorageStatus: TAuditLogServiceFactory["getAuditLogPostgresStorageStatus"] = async ({actorAuthMethod,actorId,@@ -285,6 +420,7 @@ export const auditLogServiceFactory = ({return {createAuditLog,+ recordPermissionDenied,listAuditLogs,getAuditLogPostgresStorageStatus,checkPostgresAuditLogVolumeMigrationAlertdiff --git a/backend/src/ee/services/audit-log/audit-log-settings-dal.ts b/backend/src/ee/services/audit-log/audit-log-settings-dal.tsnew file mode 100644index 0000000000..5fab60b7ee--- /dev/null+++ b/backend/src/ee/services/audit-log/audit-log-settings-dal.ts@@ -0,0 +1,37 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify, TOrmify } from "@app/lib/knex";++export type TAuditLogSettingsDALFactory = TOrmify<TableName.AuditLogSettings> & {+ findByOrgIds: (+ orgIds: string[],+ tx?: Knex+ ) => Promise<+ {+ orgId: string;+ projectId: string | null;+ eventClass: string;+ isEnabled: boolean;+ }[]+ >;+};++export const auditLogSettingsDALFactory = (db: TDbClient): TAuditLogSettingsDALFactory => {+ const orm = ormify(db, TableName.AuditLogSettings);++ const findByOrgIds: TAuditLogSettingsDALFactory["findByOrgIds"] = async (orgIds, tx) => {+ if (!orgIds.length) return [];+ try {+ return await (tx || db.replicaNode())(TableName.AuditLogSettings)+ .whereIn("orgId", orgIds)+ .select("orgId", "projectId", "eventClass", "isEnabled");+ } catch (error) {+ throw new DatabaseError({ error, name: "Find audit log settings by org" });+ }+ };++ return { ...orm, findByOrgIds };+};diff --git a/backend/src/ee/services/audit-log/audit-log-settings-service.ts b/backend/src/ee/services/audit-log/audit-log-settings-service.tsnew file mode 100644index 0000000000..04cf5b974a--- /dev/null+++ b/backend/src/ee/services/audit-log/audit-log-settings-service.ts@@ -0,0 +1,261 @@+import { ForbiddenError } from "@casl/ability";++import { ActionProjectType, OrganizationActionScope, ProjectMembershipRole } from "@app/db/schemas";+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";+import { ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { TOrgDALFactory } from "@app/services/org/org-dal";+import { TProjectDALFactory } from "@app/services/project/project-dal";++import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";+import { TPermissionServiceFactory } from "../permission/permission-service-types";+import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";+import { AUDIT_LOG_EVENT_CLASS_DEFAULTS, AuditLogEventClass } from "./audit-log-event-classes";+import { TAuditLogSettingsDALFactory } from "./audit-log-settings-dal";+import {+ TAuditLogEventClassOverrides,+ TAuditLogEventClassSetting,+ TEffectiveAuditLogSettings,+ TGetOrgAuditLogSettingsDTO,+ TGetProjectAuditLogSettingsDTO,+ TProjectAuditLogEventClassSetting,+ TUpdateOrgAuditLogSettingsDTO,+ TUpdateProjectAuditLogSettingsDTO+} from "./audit-log-settings-types";++type TAuditLogSettingsServiceFactoryDep = {+ auditLogSettingsDAL: TAuditLogSettingsDALFactory;+ orgDAL: Pick<TOrgDALFactory, "findById">;+ projectDAL: Pick<TProjectDALFactory, "findById">;+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;+};++export type TAuditLogSettingsServiceFactory = ReturnType<typeof auditLogSettingsServiceFactory>;++const ORDERED_EVENT_CLASSES = [+ AuditLogEventClass.Management,+ AuditLogEventClass.DataAccess,+ AuditLogEventClass.Authentication,+ AuditLogEventClass.Authorization+] as const;++export const isAuditLogEventClassEnabled = (+ settings: TEffectiveAuditLogSettings | null,+ eventClass: AuditLogEventClass,+ projectId?: string | null+) => {+ // null means the lookup failed. Don't silence the log over it.+ if (!settings) return true;+ const projectValue = projectId ? settings.projects[projectId]?.[eventClass] : undefined;+ return projectValue ?? settings.org[eventClass] ?? AUDIT_LOG_EVENT_CLASS_DEFAULTS[eventClass];+};++const isKnownEventClass = (value: string): value is AuditLogEventClass =>+ (Object.values(AuditLogEventClass) as string[]).includes(value);++export const auditLogSettingsServiceFactory = ({+ auditLogSettingsDAL,+ orgDAL,+ projectDAL,+ permissionService,+ keyStore+}: TAuditLogSettingsServiceFactoryDep) => {+ const invalidateCache = async (orgId: string) => {+ await keyStore.deleteItem(KeyStorePrefixes.AuditLogOrgSettings(orgId));+ };++ // Org rows live on the root org, so a sub-org inherits them. Project rows carry the+ // project's own org id.+ const loadSettings = async (orgId: string): Promise<TEffectiveAuditLogSettings | null> => {+ const org = await orgDAL.findById(orgId);+ if (!org) return null;++ const settingsOrgId = org.rootOrgId ?? orgId;+ const orgIds = settingsOrgId === orgId ? [orgId] : [orgId, settingsOrgId];+ const rows = await auditLogSettingsDAL.findByOrgIds(orgIds);++ const settings: TEffectiveAuditLogSettings = {+ org: {},+ projects: {},+ shouldUseNewPrivilegeSystem: Boolean(org.shouldUseNewPrivilegeSystem)+ };+ rows.forEach((row) => {+ if (!isKnownEventClass(row.eventClass)) return;+ if (row.projectId) {+ settings.projects[row.projectId] = { ...settings.projects[row.projectId], [row.eventClass]: row.isEnabled };+ } else if (row.orgId === settingsOrgId) {+ settings.org[row.eventClass] = row.isEnabled;+ }+ });+ return settings;+ };++ // Hot path (every event and every denial), so it's cached and never throws. A failed+ // lookup means record everything, as before.+ const getEffectiveSettings = async (orgId: string): Promise<TEffectiveAuditLogSettings | null> => {+ const cacheKey = KeyStorePrefixes.AuditLogOrgSettings(orgId);+ try {+ const cached = await keyStore.getItem(cacheKey);+ if (cached) return JSON.parse(cached) as TEffectiveAuditLogSettings;+ } catch (error) {+ logger.warn(error, `audit-log-settings: failed to read cached settings [orgId=${orgId}]`);+ }++ try {+ const settings = await loadSettings(orgId);+ if (settings) {+ await keyStore.setItemWithExpiry(cacheKey, KeyStoreTtls.AuditLogOrgSettingsInSeconds, JSON.stringify(settings));+ }+ return settings;+ } catch (error) {+ logger.warn(error, `audit-log-settings: failed to load settings, recording all events [orgId=${orgId}]`);+ return null;+ }+ };++ const toOrgSettings = (overrides: TAuditLogEventClassOverrides): TAuditLogEventClassSetting[] =>+ ORDERED_EVENT_CLASSES.map((eventClass) => ({+ eventClass,+ isEnabled: overrides[eventClass] ?? AUDIT_LOG_EVENT_CLASS_DEFAULTS[eventClass]+ }));++ const getOrgSettings = async ({ actor }: TGetOrgAuditLogSettingsDTO) => {+ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor: actor.type,+ actorId: actor.id,+ orgId: actor.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId+ });+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);++ const settings = await loadSettings(actor.orgId);+ if (!settings) throw new NotFoundError({ message: `Organization with ID '${actor.orgId}' not found` });++ return {+ eventClasses: toOrgSettings(settings.org),+ shouldUseNewPrivilegeSystem: settings.shouldUseNewPrivilegeSystem+ };+ };++ const updateOrgSettings = async ({ actor, eventClasses }: TUpdateOrgAuditLogSettingsDTO) => {+ const { permission } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.ParentOrganization,+ actor: actor.type,+ actorId: actor.id,+ orgId: actor.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId+ });+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);++ const byClass = new Map(eventClasses.map((el) => [el.eventClass, el.isEnabled]));+ const changed = [...byClass.entries()];++ if (changed.length) {+ await auditLogSettingsDAL.transaction(async (tx) => {+ await auditLogSettingsDAL.delete(+ { orgId: actor.orgId, projectId: null, $in: { eventClass: changed.map(([eventClass]) => eventClass) } },+ tx+ );+ await auditLogSettingsDAL.insertMany(+ changed.map(([eventClass, isEnabled]) => ({ orgId: actor.orgId, projectId: null, eventClass, isEnabled })),+ tx+ );+ });+ await invalidateCache(actor.orgId);+ }++ return getOrgSettings({ actor });+ };++ const getProjectSettings = async ({+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ projectId+ }: TGetProjectAuditLogSettingsDTO) => {+ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.Any+ });+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Settings);++ const project = await projectDAL.findById(projectId);+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });++ const settings = await loadSettings(project.orgId);+ if (!settings) throw new NotFoundError({ message: `Organization with ID '${project.orgId}' not found` });++ const projectOverrides = settings.projects[projectId] ?? {};+ const eventClasses: TProjectAuditLogEventClassSetting[] = toOrgSettings(settings.org).map((setting) => {+ const override = projectOverrides[setting.eventClass];+ return {+ ...setting,+ isEnabled: override ?? setting.isEnabled,+ source: override === undefined ? "organization" : "project"+ };+ });++ return { eventClasses, shouldUseNewPrivilegeSystem: settings.shouldUseNewPrivilegeSystem };+ };++ const updateProjectSettings = async ({ eventClasses, ...dto }: TUpdateProjectAuditLogSettingsDTO) => {+ const { hasRole } = await permissionService.getProjectPermission({+ actor: dto.actor,+ actorId: dto.actorId,+ projectId: dto.projectId,+ actorAuthMethod: dto.actorAuthMethod,+ actorOrgId: dto.actorOrgId,+ actionProjectType: ActionProjectType.Any+ });+ if (!hasRole(ProjectMembershipRole.Admin)) {+ throw new ForbiddenRequestError({+ message: "Only project admins can change which audit log event classes are recorded"+ });+ }++ const project = await projectDAL.findById(dto.projectId);+ if (!project) throw new NotFoundError({ message: `Project with ID '${dto.projectId}' not found` });++ const byClass = new Map(eventClasses.map((el) => [el.eventClass, el.isEnabled]));+ const changed = [...byClass.entries()];++ if (changed.length) {+ await auditLogSettingsDAL.transaction(async (tx) => {+ await auditLogSettingsDAL.delete(+ { projectId: dto.projectId, $in: { eventClass: changed.map(([eventClass]) => eventClass) } },+ tx+ );+ const rows = changed+ .filter((entry): entry is [AuditLogEventClass, boolean] => typeof entry[1] === "boolean")+ .map(([eventClass, isEnabled]) => ({+ orgId: project.orgId,+ projectId: dto.projectId,+ eventClass,+ isEnabled+ }));+ if (rows.length) await auditLogSettingsDAL.insertMany(rows, tx);+ });+ await invalidateCache(project.orgId);+ }++ return getProjectSettings(dto);+ };++ return {+ getOrgSettings,+ updateOrgSettings,+ getProjectSettings,+ updateProjectSettings,+ getEffectiveSettings,+ invalidateCache+ };+};diff --git a/backend/src/ee/services/audit-log/audit-log-settings-types.ts b/backend/src/ee/services/audit-log/audit-log-settings-types.tsnew file mode 100644index 0000000000..b1e68f59c8--- /dev/null+++ b/backend/src/ee/services/audit-log/audit-log-settings-types.ts@@ -0,0 +1,36 @@+import { OrgServiceActor, TProjectPermission } from "@app/lib/types";++import { AuditLogEventClass } from "./audit-log-event-classes";++export type TAuditLogEventClassSetting = {+ eventClass: AuditLogEventClass;+ isEnabled: boolean;+};++export type TProjectAuditLogEventClassSetting = TAuditLogEventClassSetting & {+ source: "organization" | "project";+};++export type TGetOrgAuditLogSettingsDTO = {+ actor: OrgServiceActor;+};++export type TUpdateOrgAuditLogSettingsDTO = {+ actor: OrgServiceActor;+ eventClasses: { eventClass: AuditLogEventClass; isEnabled: boolean }[];+};++export type TGetProjectAuditLogSettingsDTO = TProjectPermission;++export type TUpdateProjectAuditLogSettingsDTO = TProjectPermission & {+ eventClasses: { eventClass: AuditLogEventClass; isEnabled: boolean | null }[];+};++// A missing key means not set at this scope.+export type TAuditLogEventClassOverrides = Partial<Record<AuditLogEventClass, boolean>>;++export type TEffectiveAuditLogSettings = {+ org: TAuditLogEventClassOverrides;+ projects: Record<string, TAuditLogEventClassOverrides>;+ shouldUseNewPrivilegeSystem: boolean;+};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 34db2ce729..c639f9421c 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -77,11 +77,13 @@ import { WorkflowIntegration } from "@app/services/workflow-integration/workflowimport { KmipPermission } from "../kmip/kmip-enum";import { AcmeChallengeType, AcmeIdentifierType } from "../pki-acme/pki-acme-schemas";import { ApprovalStatus } from "../secret-approval-request/secret-approval-request-types";+import type { AuditLogEventClass } from "./audit-log-event-classes";export type TListProjectAuditLogDTO = {filter: {userAgentType?: UserAgentType;eventType?: EventType[];+ eventClass?: AuditLogEventClass[];offset?: number;limit: number;endDate: string;@@ -120,6 +122,18 @@ 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">;+};++export type TAuditLogPermissionDeniedFlushJobData = TRecordPermissionDeniedDTO & {+ collapseKey: string;+ windowStart: string;+ windowEnd: string;+};+// 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.@@ -139,12 +153,14 @@ export type TAuditLogStreamEntry = TCreateAuditLogDTO & {export type TAuditLogServiceFactory = {createAuditLog: (data: TCreateAuditLogDTO) => Promise<void>;+ recordPermissionDenied: (data: TRecordPermissionDeniedDTO) => Promise<void>;listAuditLogs: (arg: TListProjectAuditLogDTO) => Promise<{event: {type: string;metadata: unknown;};+ eventClass: AuditLogEventClass;actor: {type: string;metadata: unknown;@@ -954,7 +970,13 @@ export enum EventType {CREATE_ALERT = "create-alert",UPDATE_ALERT = "update-alert",DELETE_ALERT = "delete-alert",- TEST_ALERT_CHANNEL = "test-alert-channel"+ TEST_ALERT_CHANNEL = "test-alert-channel",++ // Authorization+ PERMISSION_DENIED = "permission-denied",++ // Audit Log Settings+ UPDATE_AUDIT_LOG_SETTINGS = "update-audit-log-settings"}// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.@@ -5964,6 +5986,32 @@ interface ViewAuditLogsEvent {metadata?: Record<string, unknown>;}+interface PermissionDeniedEvent {+ type: EventType.PERMISSION_DENIED;+ metadata: {+ permissionAction?: string;+ permissionSubject?: string;+ permissionSubjectDetails?: Record<string, unknown>;+ errorName: string;+ message: string;+ route?: string;+ method: string;+ projectId?: string;+ suppressedRepeats?: number;+ suppressedFrom?: string;+ suppressedUntil?: string;+ };+}++interface UpdateAuditLogSettingsEvent {+ type: EventType.UPDATE_AUDIT_LOG_SETTINGS;+ metadata: {+ scope: "organization" | "project";+ projectId?: string;+ eventClasses: { eventClass: string; isEnabled: boolean | null }[];+ };+}+interface ProjectRoleCreateEvent {type: EventType.CREATE_PROJECT_ROLE;metadata: {@@ -8308,6 +8356,8 @@ export type Event =| GetOrgAuditReportsEvent| DeleteOrgAuditReportEvent| ViewAuditLogsEvent+ | PermissionDeniedEvent+ | UpdateAuditLogSettingsEvent| ProjectRoleCreateEvent| ProjectRoleUpdateEvent| ProjectRoleDeleteEventdiff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 4ef90d53b3..2522e721be 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -199,6 +199,9 @@ export const KeyStorePrefixes = {// Set alongside the free plan getPlan caches when the License Server fails, so callers can tell it from a real answer.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,// 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.@@ -269,6 +272,7 @@ export const KeyStoreTtls = {AuditLogMigrationAlertInSeconds: 604800, // 7 daysLicenseCloudPlanInSeconds: 900, // 15 minutesLicenseCloudPlanLastKnownInSeconds: 86400, // 24 hours+ AuditLogOrgSettingsInSeconds: 300, // 5 minutesPamDefaultProjectInSeconds: 300, // 5 minutesAgentVaultDefaultProjectInSeconds: 300, // 5 minutes// How long reads stay in stale-while-revalidate mode after a billing mutation (covers Stripe reconciliation).diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 032de566fe..e947534e27 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -1574,6 +1574,8 @@ export const AUDIT_LOGS = {environment:"The environment to filter logs by. If not provided, logs from all environments will be returned. Note that the projectId parameter must also be provided.",eventType: "The type of the event to export.",+ eventClass:+ "Filter by event class, comma-separated for multiple values (management, authentication, authorization, data-access). Combined with eventType, only event types in both are returned. The secretPath and secretKey filters only apply to secret events.",secretPath:"The path of the secret to query audit logs for. Note that the projectId parameter must also be provided.",secretKey:@@ -2078,6 +2080,28 @@ export const INTEGRATION = {}};+export const AUDIT_LOG_SETTINGS = {+ eventClass: "The audit log event class: management, authentication, data-access, or authorization.",+ isEnabled: "Whether events of this class are recorded.",+ source:+ 'Where the effective value comes from: "project" when the project has its own setting, "organization" when it inherits the organization default.',+ shouldUseNewPrivilegeSystem:+ "Whether the organization is on the new privilege system. Permission denials (the authorization class) are only recorded on the new privilege system.",+ UPDATE_ORG: {+ eventClasses: "The event classes to update.",+ isEnabled: "Whether to record events of this class for the organization. Projects can override it."+ },+ UPDATE_PROJECT: {+ projectId: "The ID of the project to update the audit log settings for.",+ eventClasses: "The event classes to update.",+ isEnabled:+ "Whether to record events of this class for the project. true or false overrides the organization default; null removes the override so the project follows the organization."+ },+ GET_PROJECT: {+ projectId: "The ID of the project to get the audit log settings for."+ }+} as const;+export const AUDIT_LOG_STREAMS = {CREATE: {url: "The HTTP URL to push logs to.",diff --git a/backend/src/lib/request-context/memo-keys.ts b/backend/src/lib/request-context/memo-keys.tsindex b778030861..96682c8394 100644--- a/backend/src/lib/request-context/memo-keys.ts+++ b/backend/src/lib/request-context/memo-keys.ts@@ -58,6 +58,8 @@ export const requestMemoKeys = {projectFindById: (projectId: string) => `project:findById:${projectId}`,+ auditLogSettings: (orgId: string) => `audit-log-settings:${orgId}`,+userFindById: (userId: string) => `user:findById:${userId}`,identityFindById: (identityId: string) => `identity:findById:${identityId}`,diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex 64b92a37ec..882d437d8a 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -11,6 +11,7 @@ import {} from "bullmq";import { SecretEncryptionAlgo, SecretKeyEncoding } from "@app/db/schemas";+import { TAuditLogPermissionDeniedFlushJobData } 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,@@ -124,6 +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",CaAutoRenewal = "ca-auto-renewal",ProjectHardDelete = "project-hard-delete",ProjectEnvHardDelete = "project-env-hard-delete",@@ -208,6 +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",CaDailyAutoRenewal = "ca-daily-auto-renewal",CaVenafiInstall = "ca-venafi-install-job",CaAdcsInstall = "ca-adcs-install-job",@@ -593,6 +596,10 @@ export type TQueueJobTypes = {name: QueueJobs.AuditLogStreamFlush;payload: TAuditLogStreamFlushJobData;};+ [QueueName.AuditLogPermissionDeniedFlush]: {+ name: QueueJobs.AuditLogPermissionDeniedFlush;+ payload: TAuditLogPermissionDeniedFlushJobData;+ };[QueueName.CaAutoRenewal]:| {name: QueueJobs.CaDailyAutoRenewal;diff --git a/backend/src/server/plugins/audit-log-permission-denied.ts b/backend/src/server/plugins/audit-log-permission-denied.tsnew file mode 100644index 0000000000..523fdb12f1--- /dev/null+++ b/backend/src/server/plugins/audit-log-permission-denied.ts@@ -0,0 +1,66 @@+import { AnyAbility, ForbiddenError } from "@casl/ability";+import { requestContext } from "@fastify/request-context";+import fp from "fastify-plugin";++import { PermissionBoundaryError } from "@app/lib/errors";+import { RequestContextKey } from "@app/lib/request-context/request-context-keys";++const isPrimitive = (value: unknown) => value === null || ["string", "number", "boolean"].includes(typeof value);++// Only the primitive fields of the CASL subject. The subject() marker is non-enumerable so+// it drops out, and nested objects are skipped on purpose since the subject can wrap a+// request body.+const pickSubjectDetails = (subject: unknown) => {+ if (!subject || typeof subject !== "object" || Array.isArray(subject)) return undefined;+ const details: Record<string, unknown> = {};+ Object.entries(subject as Record<string, unknown>).forEach(([key, value]) => {+ if (isPrimitive(value) || (Array.isArray(value) && value.every(isPrimitive))) {+ details[key] = value;+ }+ });+ return Object.keys(details).length ? details : undefined;+};++const readProjectId = (source: unknown) => {+ if (!source || typeof source !== "object") return undefined;+ const { projectId } = source as { projectId?: unknown };+ return typeof projectId === "string" ? projectId : undefined;+};++// Every RBAC denial is a thrown CASL ForbiddenError or PermissionBoundaryError, and onError+// hooks run before the error handler, so this one hook sees all of them. ForbiddenRequestError+// is left out on purpose: verifyAuth throws it for auth-mode mismatches and it's also used for+// plan gating and admin-only checks, none of which are permission decisions.+export const injectPermissionDeniedAuditLog = fp(async (server: FastifyZodProvider) => {+ server.addHook("onError", async (req, _reply, error) => {+ const isCaslDenial = error instanceof ForbiddenError;+ if (!isCaslDenial && !(error instanceof PermissionBoundaryError)) return;+ if (!req.auth || !req.auditLogInfo?.actor) return;++ const orgId = req.auditLogInfo.orgId ?? req.permission?.orgId;+ if (!orgId) return;++ const caslError = isCaslDenial ? (error as unknown as ForbiddenError<AnyAbility>) : undefined;+ const projectId =+ requestContext.get(RequestContextKey.ProjectDetails)?.id ??+ readProjectId(req.params) ??+ readProjectId(req.body) ??+ readProjectId(req.query);++ void server.services.auditLog.recordPermissionDenied({+ ...req.auditLogInfo,+ orgId,+ projectId,+ metadata: {+ permissionAction: caslError?.action ? String(caslError.action) : undefined,+ permissionSubject: caslError?.subjectType ? String(caslError.subjectType) : undefined,+ permissionSubjectDetails: pickSubjectDetails(caslError?.subject),+ errorName: error.name,+ message: error.message,+ route: req.routeOptions.url,+ method: req.method,+ projectId+ }+ });+ });+});diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 8720b9fb93..20946ed00d 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -46,6 +46,8 @@ import { clickhouseAuditLogDALFactory } from "@app/ee/services/audit-log/audit-limport { auditLogDALFactory } from "@app/ee/services/audit-log/audit-log-dal";import { auditLogQueueServiceFactory } from "@app/ee/services/audit-log/audit-log-queue";import { auditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-service";+import { auditLogSettingsDALFactory } from "@app/ee/services/audit-log/audit-log-settings-dal";+import { auditLogSettingsServiceFactory } from "@app/ee/services/audit-log/audit-log-settings-service";import { auditLogStreamDALFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-dal";import { auditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";import { auditLogStreamOutboxDALFactory } from "@app/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal";@@ -564,6 +566,7 @@ import { workflowIntegrationDALFactory } from "@app/services/workflow-integratioimport { workflowIntegrationServiceFactory } from "@app/services/workflow-integration/workflow-integration-service";import { injectAuditLogInfo } from "../plugins/audit-log";+import { injectPermissionDeniedAuditLog } from "../plugins/audit-log-permission-denied";import { injectAssumePrivilege } from "../plugins/auth/inject-assume-privilege";import { injectIdentity } from "../plugins/auth/inject-identity";import { injectPermission } from "../plugins/auth/inject-permission";@@ -718,6 +721,7 @@ export const registerRoutes = async (const auditLogDAL = auditLogDALFactory(auditLogDb ?? db);const auditLogStreamDAL = auditLogStreamDALFactory(db);+ const auditLogSettingsDAL = auditLogSettingsDALFactory(db);const auditLogStreamOutboxDAL = auditLogStreamOutboxDALFactory(db);const trustedIpDAL = trustedIpDALFactory(db);const telemetryDAL = telemetryDALFactory(db);@@ -1185,11 +1189,20 @@ export const registerRoutes = async (auditLogStreamOutboxService});+ const auditLogSettingsService = auditLogSettingsServiceFactory({+ auditLogSettingsDAL,+ orgDAL,+ projectDAL,+ permissionService,+ keyStore+ });+const auditLogQueue = await auditLogQueueServiceFactory({auditLogDAL,queueService,projectDAL,licenseService,+ auditLogSettingsService,auditLogStreamOutboxService,clickhouseClient: clickhouse,keyStore@@ -1207,6 +1220,8 @@ export const registerRoutes = async (clickhouseAuditLogDAL,permissionService,auditLogQueue,+ auditLogSettingsService,+ queueService,keyStore,smtpService,userDAL,@@ -1536,6 +1551,7 @@ export const registerRoutes = async (const certificatePolicyDAL = certificatePolicyDALFactory(db);const orgService = orgServiceFactory({+ keyStore,userAliasDAL,identityMetadataDAL,secretDAL,@@ -4343,6 +4359,7 @@ export const registerRoutes = async (ldap: ldapService,auditLog: auditLogService,auditLogStream: auditLogStreamService,+ auditLogSettings: auditLogSettingsService,certificate: certificateService,certificateCleanup: certificateCleanupService,certificateInventoryView: certificateInventoryViewService,@@ -4556,6 +4573,7 @@ export const registerRoutes = async (await server.register(injectAgentVaultProjectId);await server.register(injectRateLimits);await server.register(injectAuditLogInfo);+ await server.register(injectPermissionDeniedAuditLog);server.route({method: "GET",diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.tsindex 2e96bf6b99..c0fbb13069 100644--- a/backend/src/server/routes/v1/organization-router.ts+++ b/backend/src/server/routes/v1/organization-router.ts@@ -10,9 +10,10 @@ import {OrgMembershipStatus,OrgRolesSchema} from "@app/db/schemas";+import { AuditLogEventClass } from "@app/ee/services/audit-log/audit-log-event-classes";import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";import { KeyStorePrefixes, KeyStoreTtls } from "@app/keystore/keystore";-import { ApiDocsTags, AUDIT_LOGS, ORGANIZATIONS } from "@app/lib/api-docs";+import { ApiDocsTags, AUDIT_LOG_SETTINGS, AUDIT_LOGS, ORGANIZATIONS } from "@app/lib/api-docs";import { getLastMidnightDateISO, removeTrailingSlash } from "@app/lib/fn";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { GenericResourceNameSchema, slugSchema } from "@app/server/lib/schemas";@@ -143,6 +144,97 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "GET",+ url: "/audit-log-settings",+ config: {+ rateLimit: readLimit+ },+ schema: {+ hide: false,+ operationId: "getOrganizationAuditLogSettings",+ tags: [ApiDocsTags.AuditLogs],+ description: "Get which audit log event classes the organization records",+ response: {+ 200: z.object({+ auditLogSettings: z.object({+ eventClasses: z+ .object({+ eventClass: z.nativeEnum(AuditLogEventClass).describe(AUDIT_LOG_SETTINGS.eventClass),+ isEnabled: z.boolean().describe(AUDIT_LOG_SETTINGS.isEnabled)+ })+ .array(),+ shouldUseNewPrivilegeSystem: z.boolean().describe(AUDIT_LOG_SETTINGS.shouldUseNewPrivilegeSystem)+ })+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const auditLogSettings = await server.services.auditLogSettings.getOrgSettings({ actor: req.permission });+ return { auditLogSettings };+ }+ });++ server.route({+ method: "PUT",+ url: "/audit-log-settings",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ hide: false,+ operationId: "updateOrganizationAuditLogSettings",+ tags: [ApiDocsTags.AuditLogs],+ description: "Update which audit log event classes the organization records",+ body: z.object({+ eventClasses: z+ .object({+ eventClass: z.nativeEnum(AuditLogEventClass).describe(AUDIT_LOG_SETTINGS.eventClass),+ isEnabled: z.boolean().describe(AUDIT_LOG_SETTINGS.UPDATE_ORG.isEnabled)+ })+ .array()+ .min(1)+ .max(Object.values(AuditLogEventClass).length)+ .describe(AUDIT_LOG_SETTINGS.UPDATE_ORG.eventClasses)+ }),+ response: {+ 200: z.object({+ auditLogSettings: z.object({+ eventClasses: z+ .object({+ eventClass: z.nativeEnum(AuditLogEventClass).describe(AUDIT_LOG_SETTINGS.eventClass),+ isEnabled: z.boolean().describe(AUDIT_LOG_SETTINGS.isEnabled)+ })+ .array(),+ shouldUseNewPrivilegeSystem: z.boolean().describe(AUDIT_LOG_SETTINGS.shouldUseNewPrivilegeSystem)+ })+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const auditLogSettings = await server.services.auditLogSettings.updateOrgSettings({+ actor: req.permission,+ eventClasses: req.body.eventClasses+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ event: {+ type: EventType.UPDATE_AUDIT_LOG_SETTINGS,+ metadata: {+ scope: "organization",+ eventClasses: req.body.eventClasses+ }+ }+ });++ return { auditLogSettings };+ }+ });+server.route({method: "GET",url: "/audit-logs",@@ -171,6 +263,12 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {.optional().transform((val) => (val ? val.split(",") : undefined)).pipe(z.nativeEnum(EventType).array().optional()),+ eventClass: z+ .string()+ .optional()+ .transform((val) => (val ? val.split(",") : undefined))+ .pipe(z.nativeEnum(AuditLogEventClass).array().optional())+ .describe(AUDIT_LOGS.EXPORT.eventClass),userAgentType: z.nativeEnum(UserAgentType).optional().describe(AUDIT_LOGS.EXPORT.userAgentType),eventMetadata: z.string()@@ -238,6 +336,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {type: z.string(),metadata: z.any()}),+ eventClass: z.nativeEnum(AuditLogEventClass),actor: z.object({type: z.string(),metadata: z.any()@@ -258,7 +357,8 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {startDate: req.query.startDate || getLastMidnightDateISO(),auditLogActorId: req.query.actor,actorType: req.query.actorType,- eventType: req.query.eventType+ eventType: req.query.eventType,+ eventClass: req.query.eventClass},actorId: req.permission.id,actorOrgId: req.permission.orgId,diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.tsindex 10a8430f44..8470ee7b9a 100644--- a/backend/src/server/routes/v1/project-router.ts+++ b/backend/src/server/routes/v1/project-router.ts@@ -14,9 +14,10 @@ import {SortDirection} from "@app/db/schemas";import { ProjectMicrosoftTeamsConfigsSchema } from "@app/db/schemas/project-microsoft-teams-configs";+import { AuditLogEventClass } from "@app/ee/services/audit-log/audit-log-event-classes";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { InfisicalProjectTemplate } from "@app/ee/services/project-template/project-template-types";-import { ApiDocsTags, PROJECTS } from "@app/lib/api-docs";+import { ApiDocsTags, AUDIT_LOG_SETTINGS, PROJECTS } from "@app/lib/api-docs";import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";import { re2Validator } from "@app/lib/zod";import { JobState } from "@app/queue/queue-service";@@ -721,6 +722,117 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {}});+ server.route({+ method: "GET",+ url: "/:projectId/audit-log-settings",+ config: {+ rateLimit: readLimit+ },+ schema: {+ hide: false,+ operationId: "getProjectAuditLogSettings",+ tags: [ApiDocsTags.AuditLogs],+ description: "Get which audit log event classes the project records",+ params: z.object({+ projectId: z.string().trim().describe(AUDIT_LOG_SETTINGS.GET_PROJECT.projectId)+ }),+ response: {+ 200: z.object({+ auditLogSettings: z.object({+ eventClasses: z+ .object({+ eventClass: z.nativeEnum(AuditLogEventClass).describe(AUDIT_LOG_SETTINGS.eventClass),+ isEnabled: z.boolean().describe(AUDIT_LOG_SETTINGS.isEnabled),+ source: z.enum(["organization", "project"]).describe(AUDIT_LOG_SETTINGS.source)+ })+ .array(),+ shouldUseNewPrivilegeSystem: z.boolean().describe(AUDIT_LOG_SETTINGS.shouldUseNewPrivilegeSystem)+ })+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const auditLogSettings = await server.services.auditLogSettings.getProjectSettings({+ actorId: req.permission.id,+ actor: req.permission.type,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.params.projectId+ });+ return { auditLogSettings };+ }+ });++ server.route({+ method: "PUT",+ url: "/:projectId/audit-log-settings",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ hide: false,+ operationId: "updateProjectAuditLogSettings",+ tags: [ApiDocsTags.AuditLogs],+ description: "Update which audit log event classes the project records",+ params: z.object({+ projectId: z.string().trim().describe(AUDIT_LOG_SETTINGS.UPDATE_PROJECT.projectId)+ }),+ body: z.object({+ eventClasses: z+ .object({+ eventClass: z.nativeEnum(AuditLogEventClass).describe(AUDIT_LOG_SETTINGS.eventClass),+ isEnabled: z.boolean().nullable().describe(AUDIT_LOG_SETTINGS.UPDATE_PROJECT.isEnabled)+ })+ .array()+ .min(1)+ .max(Object.values(AuditLogEventClass).length)+ .describe(AUDIT_LOG_SETTINGS.UPDATE_PROJECT.eventClasses)+ }),+ response: {+ 200: z.object({+ auditLogSettings: z.object({+ eventClasses: z+ .object({+ eventClass: z.nativeEnum(AuditLogEventClass).describe(AUDIT_LOG_SETTINGS.eventClass),+ isEnabled: z.boolean().describe(AUDIT_LOG_SETTINGS.isEnabled),+ source: z.enum(["organization", "project"]).describe(AUDIT_LOG_SETTINGS.source)+ })+ .array(),+ shouldUseNewPrivilegeSystem: z.boolean().describe(AUDIT_LOG_SETTINGS.shouldUseNewPrivilegeSystem)+ })+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const auditLogSettings = await server.services.auditLogSettings.updateProjectSettings({+ actorId: req.permission.id,+ actor: req.permission.type,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ projectId: req.params.projectId,+ eventClasses: req.body.eventClasses+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.params.projectId,+ event: {+ type: EventType.UPDATE_AUDIT_LOG_SETTINGS,+ metadata: {+ scope: "project",+ projectId: req.params.projectId,+ eventClasses: req.body.eventClasses+ }+ }+ });++ return { auditLogSettings };+ }+ });+server.route({method: "GET",url: "/:projectId/integrations",diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.tsindex 214e8ab255..b4fe162cf6 100644--- a/backend/src/services/org/org-service.ts+++ b/backend/src/services/org/org-service.ts@@ -33,7 +33,7 @@ import {import { assertRoleSetBoundary } from "@app/ee/services/permission/permission-fns";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { TSamlConfigDALFactory } from "@app/ee/services/saml-config/saml-config-dal";-import { PgSqlLock } from "@app/keystore/keystore";+import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto/cryptography";import { generateUserSrpKeys } from "@app/lib/crypto/srp";@@ -148,6 +148,7 @@ type TOrgServiceFactoryDep = {gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "create">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;+ keyStore: Pick<TKeyStoreFactory, "deleteItem">;};export type TOrgServiceFactory = ReturnType<typeof orgServiceFactory>;@@ -187,7 +188,8 @@ export const orgServiceFactory = ({certificatePolicyDAL,usageMeteringService,pamSessionDAL,- gatewayV2Service+ gatewayV2Service,+ keyStore}: TOrgServiceFactoryDep) => {/** Get organization details by the organization id@@ -418,7 +420,7 @@ export const orgServiceFactory = ({});}- return orgDAL.transaction(async (tx) => {+ const upgradedOrg = await orgDAL.transaction(async (tx) => {const org = await orgDAL.findById(actorOrgId, tx);if (org.shouldUseNewPrivilegeSystem) {throw new BadRequestError({@@ -441,6 +443,12 @@ export const orgServiceFactory = ({tx);});++ // Denials are only recorded on the new privilege system, so bust the cache or the first+ // denial after the upgrade gets skipped.+ await keyStore.deleteItem(KeyStorePrefixes.AuditLogOrgSettings(actorOrgId));++ return upgradedOrg;};/*diff --git a/docs/api-reference/endpoints/audit-logs/get-organization-audit-log-settings.mdx b/docs/api-reference/endpoints/audit-logs/get-organization-audit-log-settings.mdxnew file mode 100644index 0000000000..8ff78334db--- /dev/null+++ b/docs/api-reference/endpoints/audit-logs/get-organization-audit-log-settings.mdx@@ -0,0 +1,4 @@+---+title: "Get organization audit log settings"+openapi: "GET /api/v1/organization/audit-log-settings"+---diff --git a/docs/api-reference/endpoints/audit-logs/get-project-audit-log-settings.mdx b/docs/api-reference/endpoints/audit-logs/get-project-audit-log-settings.mdxnew file mode 100644index 0000000000..1b7f6a7213--- /dev/null+++ b/docs/api-reference/endpoints/audit-logs/get-project-audit-log-settings.mdx@@ -0,0 +1,4 @@+---+title: "Get project audit log settings"+openapi: "GET /api/v1/projects/{projectId}/audit-log-settings"+---diff --git a/docs/api-reference/endpoints/audit-logs/update-organization-audit-log-settings.mdx b/docs/api-reference/endpoints/audit-logs/update-organization-audit-log-settings.mdxnew file mode 100644index 0000000000..3c0e54e355--- /dev/null+++ b/docs/api-reference/endpoints/audit-logs/update-organization-audit-log-settings.mdx@@ -0,0 +1,4 @@+---+title: "Update organization audit log settings"+openapi: "PUT /api/v1/organization/audit-log-settings"+---diff --git a/docs/api-reference/endpoints/audit-logs/update-project-audit-log-settings.mdx b/docs/api-reference/endpoints/audit-logs/update-project-audit-log-settings.mdxnew file mode 100644index 0000000000..0c502f875a--- /dev/null+++ b/docs/api-reference/endpoints/audit-logs/update-project-audit-log-settings.mdx@@ -0,0 +1,4 @@+---+title: "Update project audit log settings"+openapi: "PUT /api/v1/projects/{projectId}/audit-log-settings"+---diff --git a/docs/docs.json b/docs/docs.jsonindex 16be8632fc..aa34fb155d 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -2541,7 +2541,11 @@{"group": "Audit logs","pages": [- "api-reference/endpoints/audit-logs/export-audit-log"+ "api-reference/endpoints/audit-logs/export-audit-log",+ "api-reference/endpoints/audit-logs/get-organization-audit-log-settings",+ "api-reference/endpoints/audit-logs/update-organization-audit-log-settings",+ "api-reference/endpoints/audit-logs/get-project-audit-log-settings",+ "api-reference/endpoints/audit-logs/update-project-audit-log-settings"]},{diff --git a/docs/documentation/platform/audit-logs.mdx b/docs/documentation/platform/audit-logs.mdxindex f627dd6237..5c2aeebad9 100644--- a/docs/documentation/platform/audit-logs.mdx+++ b/docs/documentation/platform/audit-logs.mdx@@ -148,6 +148,10 @@ Each log contains the following fields:</Expandable></ResponseField>+<ResponseField name="eventClass" type="string">+ The [event class](#event-classes) the event type belongs to: `management`, `authentication`, `authorization`, or `data-access`.+</ResponseField>+<ResponseField name="actor" type="object">Who performed the action.<Expandable title="properties">@@ -221,6 +225,84 @@ Each log contains the following fields:}```+## Event classes++Every event type belongs to exactly one of four classes. The class tells you what kind of activity an event records, and it's also the unit you turn recording on or off for, so you can keep every configuration change and login while dropping the high-volume read events that make up most of the log.++| Class | What it covers | Default |+| ---------------- | -------------------------------------------------------------------------------------------------------------------------- | ------- |+| `management` | Creates, updates, deletes, membership, roles, policies, background jobs, and the start and end of privileged sessions | On |+| `data-access` | Reads and lists, plus the crypto operations that return or operate on secret material, such as KMS encrypt and decrypt | On |+| `authentication` | Logins, failed logins, organization selection, machine identity authentication, and Gateway and Relay connections | On |+| `authorization` | [Permission denials](#permission-denials) | Off |++A class follows the operation that was attempted, not its outcome, so a failed login sits in `authentication` next to a successful one. Every event type that isn't a read, a login, or a denial is `management`, including viewing the audit log itself.++### Choose which classes to record++By default, Infisical records every class except `authorization`. An organization admin can turn any class on or off for the whole organization, and a project admin can override that choice for one project in either direction.++<Tabs>+ <Tab title="For an organization">+ <Steps>+ <Step>+ From your organization's home page, go to **Audit Logs** and select the **Settings** tab.+ </Step>+ <Step>+ Turn a class on or off, then select **Save Changes**.+ </Step>+ </Steps>++ You need the **Edit** permission on **Settings** to change these toggles.+ </Tab>+ <Tab title="For a project">+ <Steps>+ <Step>+ Open the project and go to **Settings**.+ </Step>+ <Step>+ Under **Audit Log Event Classes**, turn a class on or off, then select **Save Changes**.+ </Step>+ </Steps>++ Only project admins can change these toggles. A row labeled **Organization Default** follows the organization setting. A row labeled **Project Override** uses the project's own setting, even if the organization turned the class off. Select **Use Organization Default** to remove an override.+ </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).++ ```bash+ curl -X PUT "https://app.infisical.com/api/v1/organization/audit-log-settings" \+ -H "Authorization: Bearer <your-access-token>" \+ -H "Content-Type: application/json" \+ -d '{"eventClasses": [{"eventClass": "data-access", "isEnabled": false}]}'+ ```++ For a project, `isEnabled` also accepts `null`, which removes the project's override so the project follows the organization again.+ </Tab>+</Tabs>++A change applies to new events within a minute. Events that were already recorded stay in the log until their retention period ends.++<Note>+ Secret Insights are counted from `data-access` events, so they stay flat for any project where the class is off.+</Note>++Every change to these settings is itself recorded as an `update-audit-log-settings` event in the `management` class, with the classes that changed in `event.metadata`.++### Permission denials++If a user or machine identity calls an endpoint that its role doesn't allow, Infisical returns a 403 response and, once you [turn the `authorization` class on](#choose-which-classes-to-record), records a `permission-denied` event. The event records who was denied, what they tried to do, and where:++- `permissionAction` and `permissionSubject`: the action and the resource type the role didn't allow (for example, `create` on `secrets`)+- `permissionSubjectDetails`: the resource the actor targeted, such as the environment and secret path+- `route` and `method`: the endpoint the actor called+- `projectId`: the project the request was scoped to, if any+- `suppressedRepeats`, `suppressedFrom`, and `suppressedUntil`: on a summary event, how many identical denials Infisical counted instead of recording, and the minute they fell in++Denials are only recorded for organizations on the new privilege system. If your organization still uses legacy privilege management, the **Authorization** toggle is disabled. To upgrade, go to **Access Control** in your organization and select **Learn More & Upgrade**.++To keep a misconfigured client from filling the log, Infisical records the first `permission-denied` event per actor, project, action, subject, and endpoint in each minute. Denials that repeat inside that minute are counted rather than recorded. When the minute ends, Infisical writes one more `permission-denied` event for the same combination with the count in `suppressedRepeats` and the minute in `suppressedFrom` and `suppressedUntil`. If nothing repeated, no summary event is written.+## Filtering audit logsYou can filter audit logs to find events more easily. When you set more than one filter, an event needs to match all of them to appear in the results.@@ -256,6 +338,7 @@ Every filter is an exact match, so wildcards like `*` aren't supported.| Filter | Matches | Requires || ------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------ || `event` | One or more event types (for example, `create-secret`, `update-secret`) | |+ | `class` | One or more [event classes](#event-classes) (for example, `data-access`, `authorization`) | || `actor` | The actor type (for example, `user`, `identity`, `platform`, `kmipClient`, `scimClient`, and so on) | || `actor_id` | A specific actor ID | `actor` set to a type that carries an ID (see below) || `source` | The client that made the request: `web`, `cli`, `k8-operator`, `terraform`, an SDK, or `other` | |@@ -270,6 +353,7 @@ Every filter is an exact match, so wildcards like `*` aren't supported.| Parameter | Matches | Requires || --------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- || `eventType` | One or more event types, comma-separated (for example, `create-secret,update-secret`) | |+ | `eventClass` | One or more [event classes](#event-classes), comma-separated (for example, `data-access,authorization`) | || `actorType` | The actor type (for example, `user`, `identity`, `platform`, `kmipClient`, `scimClient`) | || `actor` | A specific actor ID | `actorType` set to a type that carries an ID (see below) || `userAgentType` | The client that made the request: `web`, `cli`, `k8-operator`, `terraform`, an SDK, or `other` | |@@ -885,10 +969,16 @@ Infisical emits hundreds of event types. Here are some of the most common ones y| `secret-approval-request`, `secret-approval-request-review`, `secret-approval-merged`, `secret-approval-closed`, `secret-approval-reopened` | The lifecycle of a secret change request. || `approval-policy-create`, `approval-policy-update`, `approval-policy-delete` | An admin changed an approval policy. |</Accordion>+ <Accordion title="Authorization">+ | Event | When it fires |+ | ----------------------------------------------------------------------- | -------------------------------------------------------------------- |+ | `permission-denied` | A user or machine identity was refused an action its role doesn't allow. See [Permission denials](#permission-denials). |+ </Accordion><Accordion title="Audit logs">| Event | When it fires || ----------------------------------------------------------------------- | -------------------------------------------------------------------- || `view-audit-logs` | A user opened the audit log viewer. |+ | `update-audit-log-settings` | An admin changed which event classes an organization or project records. || `create-audit-report`, `get-audit-report`, `get-audit-reports`, `delete-audit-report` | A user managed a project-level audit report. || `create-org-audit-report`, `get-org-audit-reports`, `delete-org-audit-report` | A user managed an organization-level audit report. |</Accordion>diff --git a/frontend/src/components/auditLogSettings/AuditLogEventClassRow.tsx b/frontend/src/components/auditLogSettings/AuditLogEventClassRow.tsxnew file mode 100644index 0000000000..6346c8f91d--- /dev/null+++ b/frontend/src/components/auditLogSettings/AuditLogEventClassRow.tsx@@ -0,0 +1,104 @@+import { ReactNode } from "react";+import { TriangleAlert } from "lucide-react";+import { twMerge } from "tailwind-merge";++import {+ Alert,+ AlertDescription,+ Field,+ FieldContent,+ FieldDescription,+ FieldTitle,+ Toggle,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ auditLogEventClassToDescriptionMap,+ auditLogEventClassToNameMap+} from "@app/hooks/api/auditLogSettings/constants";+import { AuditLogEventClass } from "@app/hooks/api/auditLogSettings/types";+import { ScopeVariant } from "@app/hooks/useScopeVariant";++type Props = {+ eventClass: AuditLogEventClass;+ isEnabled: boolean;+ variant: ScopeVariant;+ lockedReason?: string;+ isDisabled?: boolean;+ onCheckedChange?: (isEnabled: boolean) => void;+ descriptionExtra?: ReactNode;+ warning?: ReactNode;+ badge?: ReactNode;+ action?: ReactNode;+ className?: string;+};++export const AuditLogEventClassRow = ({+ eventClass,+ isEnabled,+ variant,+ lockedReason,+ isDisabled,+ onCheckedChange,+ descriptionExtra,+ warning,+ badge,+ action,+ className+}: Props) => {+ const id = `audit-log-event-class-${eventClass}`;+ let status = isEnabled ? "Recording" : "Not recorded";+ if (lockedReason && !isEnabled) status = lockedReason;++ const toggle = (+ <Toggle+ id={id}+ variant={variant}+ checked={isEnabled}+ disabled={Boolean(lockedReason) || isDisabled}+ onCheckedChange={onCheckedChange}+ aria-label={`${auditLogEventClassToNameMap[eventClass]} events`}+ />+ );++ return (+ <Field orientation="horizontal" className={twMerge("gap-8 px-6 py-6", className)}>+ <FieldContent>+ <FieldTitle className="text-base">+ <label htmlFor={id}>{auditLogEventClassToNameMap[eventClass]}</label>+ {badge}+ </FieldTitle>+ <FieldDescription className="max-w-2xl text-sm text-accent">+ {auditLogEventClassToDescriptionMap[eventClass]}+ </FieldDescription>+ {descriptionExtra && (+ <FieldDescription className="max-w-2xl text-sm text-accent">+ {descriptionExtra}+ </FieldDescription>+ )}+ {warning && (+ <Alert variant="warning" className="mt-2 max-w-2xl">+ <TriangleAlert />+ <AlertDescription>{warning}</AlertDescription>+ </Alert>+ )}+ </FieldContent>+ <div className="flex shrink-0 flex-col items-end gap-1.5">+ {lockedReason ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <span>{toggle}</span>+ </TooltipTrigger>+ <TooltipContent side="left">{lockedReason}</TooltipContent>+ </Tooltip>+ ) : (+ toggle+ )}+ <span className="max-w-48 text-right text-sm text-muted">{status}</span>+ {action}+ </div>+ </Field>+ );+};diff --git a/frontend/src/components/auditLogSettings/index.tsx b/frontend/src/components/auditLogSettings/index.tsxnew file mode 100644index 0000000000..26825ed489--- /dev/null+++ b/frontend/src/components/auditLogSettings/index.tsx@@ -0,0 +1 @@+export { AuditLogEventClassRow } from "./AuditLogEventClassRow";diff --git a/frontend/src/hooks/api/auditLogSettings/constants.tsx b/frontend/src/hooks/api/auditLogSettings/constants.tsxnew file mode 100644index 0000000000..a3bf23dd13--- /dev/null+++ b/frontend/src/hooks/api/auditLogSettings/constants.tsx@@ -0,0 +1,35 @@+import { AuditLogEventClass } from "./types";++export const auditLogEventClassToNameMap: Record<AuditLogEventClass, string> = {+ [AuditLogEventClass.Management]: "Management",+ [AuditLogEventClass.Authentication]: "Authentication",+ [AuditLogEventClass.DataAccess]: "Data access",+ [AuditLogEventClass.Authorization]: "Authorization"+};++export const auditLogEventClassToDescriptionMap: Record<AuditLogEventClass, string> = {+ [AuditLogEventClass.Management]:+ "Creates, updates, deletes, membership, roles, policies, background jobs, privileged session start and end.",+ [AuditLogEventClass.Authentication]:+ "Logins, failed logins, org selection, machine identity auth, gateway and relay connects.",+ [AuditLogEventClass.DataAccess]:+ "Reads and lists, plus crypto use operations that hand back or operate on secret material.",+ [AuditLogEventClass.Authorization]:+ "Permission denials, recording the actor, the action, the subject and the endpoint. Repeats by the same actor within a minute are collapsed into one event."+};++// Mirrors the backend defaults.+export const AUDIT_LOG_EVENT_CLASS_DEFAULTS: Record<AuditLogEventClass, boolean> = {+ [AuditLogEventClass.Management]: true,+ [AuditLogEventClass.Authentication]: true,+ [AuditLogEventClass.DataAccess]: true,+ [AuditLogEventClass.Authorization]: false+};++// Display order.+export const AUDIT_LOG_EVENT_CLASSES = [+ AuditLogEventClass.Management,+ AuditLogEventClass.DataAccess,+ AuditLogEventClass.Authentication,+ AuditLogEventClass.Authorization+] as const;diff --git a/frontend/src/hooks/api/auditLogSettings/index.tsx b/frontend/src/hooks/api/auditLogSettings/index.tsxnew file mode 100644index 0000000000..18c60b46e9--- /dev/null+++ b/frontend/src/hooks/api/auditLogSettings/index.tsx@@ -0,0 +1,4 @@+export * from "./constants";+export * from "./mutations";+export * from "./queries";+export * from "./types";diff --git a/frontend/src/hooks/api/auditLogSettings/mutations.tsx b/frontend/src/hooks/api/auditLogSettings/mutations.tsxnew file mode 100644index 0000000000..02bca58ba9--- /dev/null+++ b/frontend/src/hooks/api/auditLogSettings/mutations.tsx@@ -0,0 +1,45 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";++import { auditLogSettingsKeys } from "./queries";+import {+ TOrgAuditLogSettings,+ TProjectAuditLogSettings,+ TUpdateOrgAuditLogSettingsDTO,+ TUpdateProjectAuditLogSettingsDTO+} from "./types";++export const useUpdateOrgAuditLogSettings = (orgId: string) => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async (dto: TUpdateOrgAuditLogSettingsDTO) => {+ const { data } = await apiRequest.put<{ auditLogSettings: TOrgAuditLogSettings }>(+ "/api/v1/organization/audit-log-settings",+ dto+ );+ return data.auditLogSettings;+ },+ onSuccess: (data) => {+ queryClient.setQueryData(auditLogSettingsKeys.org(orgId), data);+ // Project settings inherit from the org, so they may have changed too.+ queryClient.invalidateQueries({ queryKey: auditLogSettingsKeys.all });+ }+ });+};++export const useUpdateProjectAuditLogSettings = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ projectId, ...dto }: TUpdateProjectAuditLogSettingsDTO) => {+ const { data } = await apiRequest.put<{ auditLogSettings: TProjectAuditLogSettings }>(+ `/api/v1/projects/${projectId}/audit-log-settings`,+ dto+ );+ return data.auditLogSettings;+ },+ onSuccess: (data, { projectId }) => {+ queryClient.setQueryData(auditLogSettingsKeys.project(projectId), data);+ }+ });+};diff --git a/frontend/src/hooks/api/auditLogSettings/queries.tsx b/frontend/src/hooks/api/auditLogSettings/queries.tsxnew file mode 100644index 0000000000..eb81a4162a--- /dev/null+++ b/frontend/src/hooks/api/auditLogSettings/queries.tsx@@ -0,0 +1,37 @@+import { useQuery } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";++import { TOrgAuditLogSettings, TProjectAuditLogSettings } from "./types";++export const auditLogSettingsKeys = {+ all: ["audit-log-settings"] as const,+ org: (orgId: string) => [...auditLogSettingsKeys.all, "org", orgId] as const,+ project: (projectId: string) => [...auditLogSettingsKeys.all, "project", projectId] as const+};++export const useGetOrgAuditLogSettings = (orgId: string) => {+ return useQuery({+ queryKey: auditLogSettingsKeys.org(orgId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ auditLogSettings: TOrgAuditLogSettings }>(+ "/api/v1/organization/audit-log-settings"+ );+ return data.auditLogSettings;+ },+ enabled: Boolean(orgId)+ });+};++export const useGetProjectAuditLogSettings = (projectId: string) => {+ return useQuery({+ queryKey: auditLogSettingsKeys.project(projectId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ auditLogSettings: TProjectAuditLogSettings }>(+ `/api/v1/projects/${projectId}/audit-log-settings`+ );+ return data.auditLogSettings;+ },+ enabled: Boolean(projectId)+ });+};diff --git a/frontend/src/hooks/api/auditLogSettings/types.tsx b/frontend/src/hooks/api/auditLogSettings/types.tsxnew file mode 100644index 0000000000..ea0939aa13--- /dev/null+++ b/frontend/src/hooks/api/auditLogSettings/types.tsx@@ -0,0 +1,34 @@+export enum AuditLogEventClass {+ Management = "management",+ Authentication = "authentication",+ Authorization = "authorization",+ DataAccess = "data-access"+}++export type TAuditLogEventClassSetting = {+ eventClass: AuditLogEventClass;+ isEnabled: boolean;+};++export type TProjectAuditLogEventClassSetting = TAuditLogEventClassSetting & {+ source: "organization" | "project";+};++export type TOrgAuditLogSettings = {+ eventClasses: TAuditLogEventClassSetting[];+ shouldUseNewPrivilegeSystem: boolean;+};++export type TProjectAuditLogSettings = {+ eventClasses: TProjectAuditLogEventClassSetting[];+ shouldUseNewPrivilegeSystem: boolean;+};++export type TUpdateOrgAuditLogSettingsDTO = {+ eventClasses: { eventClass: AuditLogEventClass; isEnabled: boolean }[];+};++export type TUpdateProjectAuditLogSettingsDTO = {+ projectId: string;+ eventClasses: { eventClass: AuditLogEventClass; isEnabled: boolean | null }[];+};diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex a4039f320d..2f77b3853a 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -482,7 +482,9 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.AGENT_VAULT_PROXY_UPDATE]: "Update proxy",[EventType.AGENT_VAULT_PROXY_REVOKE]: "Revoke proxy access",[EventType.AGENT_VAULT_PROXY_DELETE]: "Delete proxy",- [EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE]: "Update session log settings"+ [EventType.AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE]: "Update session log settings",+ [EventType.PERMISSION_DENIED]: "Permission denied",+ [EventType.UPDATE_AUDIT_LOG_SETTINGS]: "Update audit log settings"};export const userAgentTypeToNameMap: { [K in UserAgentType]: string } = {diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex d707a20d19..4c228f3127 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -480,5 +480,7 @@ export enum EventType {AGENT_VAULT_PROXY_UPDATE = "agent-vault-proxy-update",AGENT_VAULT_PROXY_REVOKE = "agent-vault-proxy-revoke",AGENT_VAULT_PROXY_DELETE = "agent-vault-proxy-delete",- AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE = "agent-vault-session-log-settings-update"+ AGENT_VAULT_SESSION_LOG_SETTINGS_UPDATE = "agent-vault-session-log-settings-update",+ PERMISSION_DENIED = "permission-denied",+ UPDATE_AUDIT_LOG_SETTINGS = "update-audit-log-settings"}diff --git a/frontend/src/hooks/api/auditLogs/queries.tsx b/frontend/src/hooks/api/auditLogs/queries.tsxindex f1995eeadc..ca9dc51dcb 100644--- a/frontend/src/hooks/api/auditLogs/queries.tsx+++ b/frontend/src/hooks/api/auditLogs/queries.tsx@@ -38,6 +38,7 @@ export const useGetAuditLogs = (}: {}),...(filters.eventType?.length ? { eventType: filters.eventType.join(",") } : {}),+ ...(filters.eventClass?.length ? { eventClass: filters.eventClass.join(",") } : {}),...(projectId ? { projectId } : {})}}diff --git a/frontend/src/hooks/api/auditLogs/types.tsx b/frontend/src/hooks/api/auditLogs/types.tsxindex 18095fb02a..dfef666f68 100644--- a/frontend/src/hooks/api/auditLogs/types.tsx+++ b/frontend/src/hooks/api/auditLogs/types.tsx@@ -1,3 +1,4 @@+import { AuditLogEventClass } from "../auditLogSettings/types";import { CaStatus } from "../ca";import { CrlReason } from "../certificates/enums";import { IdentityTrustedIp } from "../identities/types";@@ -14,6 +15,7 @@ export type AuditLogPostgresStorageStatus = {export type TGetAuditLogsFilter = {eventType?: EventType[];+ eventClass?: AuditLogEventClass[];userAgentType?: UserAgentType;eventMetadata?: Record<string, string>;actorType?: ActorType;@@ -1129,6 +1131,7 @@ export type AuditLog = {workspace: string;ipAddress: string;event: Event;+ eventClass: AuditLogEventClass;userAgent: string;userAgentType: UserAgentType;createdAt: string;diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsxindex b463b00a9b..eee0b0efdd 100644--- a/frontend/src/hooks/api/index.tsx+++ b/frontend/src/hooks/api/index.tsx@@ -7,6 +7,7 @@ export * from "./approvalPolicies";export * from "./approvalRequests";export * from "./assumePrivileges";export * from "./auditLogs";+export * from "./auditLogSettings";export * from "./auditLogStreams";export * from "./auditReports";export * from "./auth";diff --git a/frontend/src/pages/organization/AuditLogsPage/AuditLogsPage.tsx b/frontend/src/pages/organization/AuditLogsPage/AuditLogsPage.tsxindex a7197e0d89..c92b51d974 100644--- a/frontend/src/pages/organization/AuditLogsPage/AuditLogsPage.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/AuditLogsPage.tsx@@ -12,12 +12,14 @@ import {import { ROUTE_PATHS } from "@app/const/routes";import { useOrganization } from "@app/context";+import { AuditLogSettingsTab } from "./components/AuditLogSettingsTab";import { AuditLogStreamsTab } from "./components/AuditLogStreamTab";import { LogsSection } from "./components";enum AuditLogsPageTabs {AuditLogs = "audit-logs",- Streams = "streams"+ Streams = "streams",+ Settings = "settings"}const AuditLogsTab = () => <LogsSection pageView />;@@ -31,7 +33,12 @@ export const AuditLogsPage = () => {const tabs = [{ key: AuditLogsPageTabs.AuditLogs, label: "Audit Logs", component: AuditLogsTab },- { key: AuditLogsPageTabs.Streams, label: "External Log Streams", component: AuditLogStreamsTab }+ {+ key: AuditLogsPageTabs.Streams,+ label: "External Log Streams",+ component: AuditLogStreamsTab+ },+ { key: AuditLogsPageTabs.Settings, label: "Settings", component: AuditLogSettingsTab }];const activeTab = tabs.some((tab) => tab.key === selectedTab)diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogDetailsSheet.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogDetailsSheet.tsxindex b3c879f2c2..3c1ed037f0 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogDetailsSheet.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogDetailsSheet.tsx@@ -1,6 +1,13 @@import { useState } from "react";-import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@app/components/v3";+import {+ Badge,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle+} from "@app/components/v3";import { formatDateTime, Timezone } from "@app/helpers/datetime";import { AuditLog } from "@app/hooks/api/auditLogs/types";@@ -32,6 +39,9 @@ export const AuditLogDetailsSheet = ({ isOpen, onOpenChange, auditLog, timezone<SheetDescription>{formatDateTime({ timestamp: displayedLog.createdAt, timezone })}</SheetDescription>+ <div>+ <Badge variant="neutral">{displayedLog.eventClass}</Badge>+ </div></SheetHeader><div className="min-h-0 flex-1 p-4"><JsonHighlight value={displayedLog} className="h-full" />diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsxnew file mode 100644index 0000000000..103acabdfe--- /dev/null+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx@@ -0,0 +1,169 @@+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 {+ OrgPermissionActions,+ OrgPermissionSubjects,+ useOrganization,+ useOrgPermission+} from "@app/context";+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+} 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";++export const AuditLogSettingsTab = withPermission(+ () => {+ const { currentOrg } = useOrganization();+ const { permission } = useOrgPermission();+ const scopeVariant = useScopeVariant();+ const canEdit = permission.can(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);++ const { data: settings, isPending } = useGetOrgAuditLogSettings(currentOrg.id);+ const { mutateAsync: updateSettings, isPending: isSaving } = useUpdateOrgAuditLogSettings(+ 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) => {+ await updateSettings({+ eventClasses: AUDIT_LOG_EVENT_CLASSES.map((eventClass) => ({+ eventClass,+ isEnabled: form[eventClass]+ }))+ });+ 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 events are recorded. Every event type belongs to exactly one+ class.+ </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 isAuthorization = eventClass === AuditLogEventClass.Authorization;+ const isLocked = isAuthorization && !shouldUseNewPrivilegeSystem;+ return (+ <Controller+ key={eventClass}+ control={control}+ name={eventClass}+ render={({ field }) => (+ <AuditLogEventClassRow+ eventClass={eventClass}+ isEnabled={isLocked ? false : field.value}+ variant={scopeVariant}+ isDisabled={!canEdit}+ lockedReason={isLocked ? REQUIRES_NEW_PRIVILEGE_SYSTEM : undefined}+ 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 border-neutral/15 bg-neutral/5 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>+ );+ },+ {+ action: OrgPermissionActions.Read,+ subject: OrgPermissionSubjects.Settings,+ accessRestrictedMode: "dialog"+ }+);diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/index.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/index.tsxnew file mode 100644index 0000000000..2a6f2030cb--- /dev/null+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/index.tsx@@ -0,0 +1 @@+export { AuditLogSettingsTab } from "./AuditLogSettingsTab";diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsxindex df37fd2a92..32d43a20d7 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx@@ -12,6 +12,11 @@ import {ActorSuggestion,useAuditLogActorSuggestions} from "@app/hooks/api/auditLogs/useAuditLogActorSuggestions";+import {+ AUDIT_LOG_EVENT_CLASSES,+ auditLogEventClassToNameMap+} from "@app/hooks/api/auditLogSettings/constants";+import { AuditLogEventClass } from "@app/hooks/api/auditLogSettings/types";import { ProjectType } from "@app/hooks/api/projects/types";export interface AppliedFilter {@@ -38,6 +43,14 @@ const FILTER_PROPERTIES: FilterProperty[] = [label: `${value} (${label})`}))},+ {+ key: "class",+ hints: "management, authentication, authorization, data-access",+ suggestions: AUDIT_LOG_EVENT_CLASSES.map((value) => ({+ value,+ label: `${value} (${auditLogEventClassToNameMap[value]})`+ }))+ },{key: "actor",hints: "user, identity, unknownUser, ...",@@ -64,7 +77,7 @@ const FILTER_PROPERTIES: FilterProperty[] = [const PROJECT_DEPENDENT_KEYS = new Set(["environment", "secret_path", "secret_key"]);// Filters available to every product. Anything beyond these is product-specific-const GENERIC_FILTER_KEYS = ["event", "actor", "actor_id", "source"];+const GENERIC_FILTER_KEYS = ["event", "class", "actor", "actor_id", "source"];// Per-product filter keys. Products not listed fall back to the full set (secrets default)const PRODUCT_FILTER_KEYS: Partial<Record<ProjectType, string[]>> = {@@ -210,7 +223,7 @@ export const AuditSearchFilter = ({if (editingIndex !== null) {updated = filters.map((filter, index) => (index === editingIndex ? newFilter : filter));- } else if (property === "event") {+ } else if (property === "event" || property === "class") {if (filters.some((filter) => filter.property === property && filter.value === value)) {resetQuery();focusInput();@@ -613,6 +626,7 @@ export const appliedFiltersToLogFilter = (filters: AppliedFilter[]): {eventType: EventType[];+ eventClass: AuditLogEventClass[];userAgentType?: UserAgentType;actorType?: ActorType;actor?: string;@@ -621,7 +635,7 @@ export const appliedFiltersToLogFilter = (secretPath?: string;secretKey?: string;} => {- const result: ReturnType<typeof appliedFiltersToLogFilter> = { eventType: [] };+ const result: ReturnType<typeof appliedFiltersToLogFilter> = { eventType: [], eventClass: [] };filters.forEach(({ property, value }) => {switch (property) {@@ -630,6 +644,11 @@ export const appliedFiltersToLogFilter = (result.eventType.push(value as EventType);}break;+ case "class":+ if (Object.values(AuditLogEventClass).includes(value as AuditLogEventClass)) {+ result.eventClass.push(value as AuditLogEventClass);+ }+ break;case "source":if (Object.values(UserAgentType).includes(value as UserAgentType)) {result.userAgentType = value as UserAgentType;diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsxindex c801612d85..28fbdcb65a 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx@@ -30,6 +30,11 @@ import {userAgentTypeToNameMap} from "@app/hooks/api/auditLogs/constants";import { EventType } from "@app/hooks/api/auditLogs/enums";+import {+ AUDIT_LOG_EVENT_CLASSES,+ auditLogEventClassToNameMap+} from "@app/hooks/api/auditLogSettings/constants";+import { AuditLogEventClass } from "@app/hooks/api/auditLogSettings/types";import { UserAgentType } from "@app/hooks/api/auth/types";import { Project } from "@app/hooks/api/projects/types";@@ -37,6 +42,10 @@ import { LogFilterItem } from "./LogFilterItem";import { auditLogFilterFormSchema, Presets, TAuditLogFilterFormData } from "./types";const eventTypes = Object.entries(eventToNameMap).map(([value, label]) => ({ label, value }));+const eventClasses = AUDIT_LOG_EVENT_CLASSES.map((value) => ({+ label: auditLogEventClassToNameMap[value],+ value+}));const userAgentTypes = Object.entries(userAgentTypeToNameMap).map(([value, label]) => ({label,value@@ -54,6 +63,7 @@ const getActiveFilterCount = (filter: TAuditLogFilterFormData) => {"actor","project","eventType",+ "eventClass","environment","secretPath","userAgentType",@@ -89,6 +99,7 @@ export const LogsFilter = ({ presets, setFilter, filter, project }: Props) => {secretPath: "",actor: presets?.actorId,eventType: filter?.eventType || [],+ eventClass: filter?.eventClass || [],userAgentType: null},values: {@@ -159,6 +170,7 @@ export const LogsFilter = ({ presets, setFilter, filter, project }: Props) => {onClick={() => {setFilter({eventType: presets?.eventType || [],+ eventClass: [],actor: presets?.actorId,userAgentType: null,project: null,@@ -174,6 +186,36 @@ export const LogsFilter = ({ presets, setFilter, filter, project }: Props) => {</div><div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <LogFilterItem+ label="Event Class"+ tooltipText="Every event type belongs to exactly one class. Combined with an event filter, only events in both are shown."+ className="sm:col-span-2"+ >+ <Controller+ control={control}+ name="eventClass"+ render={({ field }) => (+ <Field>+ <Combobox+ aria-label="Event class"+ clearAriaLabel="Clear event classes"+ value={eventClasses.filter((eventClass) =>+ (field.value ?? []).includes(eventClass.value)+ )}+ multiple+ isClearable+ onValueChange={(options) =>+ field.onChange(options.map((option) => option.value as AuditLogEventClass))+ }+ placeholder="All classes"+ options={eventClasses}+ getOptionValue={(option) => option.value}+ getOptionLabel={(option) => option.label}+ />+ </Field>+ )}+ />+ </LogFilterItem><LogFilterItem label="Events" className="sm:col-span-2"><Controllercontrol={control}diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsxindex bea36bfacd..01f79ae35b 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx@@ -202,6 +202,10 @@ const LogsSectionComponent = ({actorType: searchDerived.actorType || presets?.actorType,eventType:searchDerived.eventType.length > 0 ? searchDerived.eventType : logFilter?.eventType,+ eventClass:+ searchDerived.eventClass.length > 0+ ? searchDerived.eventClass+ : logFilter?.eventClass,userAgentType: searchDerived.userAgentType || logFilter?.userAgentType || undefined,environment: searchDerived.environment || logFilter?.environment?.slug,secretPath: searchDerived.secretPath,@@ -290,6 +294,7 @@ const LogsSectionComponent = ({actorType: presets?.actorType,limit: 15,eventType: logFilter?.eventType,+ eventClass: logFilter?.eventClass,userAgentType: logFilter?.userAgentType ?? undefined,startDate: dateRange.startDate,endDate: dateRange.endDate,diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsxindex 6a9dddd1e3..0e9e78d7ad 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx@@ -65,6 +65,7 @@ export const LogsTableRow = ({ auditLog, rowNumber, timezone, onClick }: Props)<TableCell><div className="flex flex-wrap items-center gap-2 text-sm"><Tag label="event" value={auditLog.event.type} />+ <Tag label="class" value={auditLog.eventClass} /><Tag label="actor" value={auditLog.actor.type} />{auditLog.actor.type === ActorType.USER && (<>diff --git a/frontend/src/pages/organization/AuditLogsPage/components/types.tsx b/frontend/src/pages/organization/AuditLogsPage/components/types.tsxindex af54e03ea3..2bb2ee9f52 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/types.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/types.tsx@@ -2,6 +2,7 @@ import ms from "ms";import { z } from "zod";import { ActorType, EventType, UserAgentType } from "@app/hooks/api/auditLogs/enums";+import { AuditLogEventClass } from "@app/hooks/api/auditLogSettings/types";import { ProjectType } from "@app/hooks/api/projects/types";export enum AuditLogDateFilterType {@@ -17,6 +18,7 @@ export const auditLogFilterFormSchema = z.object({.nullable(),environment: z.object({ name: z.string(), slug: z.string() }).optional().nullable(),eventType: z.nativeEnum(EventType).array(),+ eventClass: z.nativeEnum(AuditLogEventClass).array().optional(),actor: z.string().optional(),userAgentType: z.nativeEnum(UserAgentType).nullish(),secretPath: z.string().optional(),diff --git a/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsxnew file mode 100644index 0000000000..12dfb97087--- /dev/null+++ b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx@@ -0,0 +1,195 @@+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 {+ Badge,+ Button,+ Card,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ DocumentationLinkBadge,+ Skeleton+} from "@app/components/v3";+import { useOrganization, useProject, useProjectPermission } from "@app/context";+import { useGetProjectAuditLogSettings, useUpdateProjectAuditLogSettings } from "@app/hooks/api";+import {+ AUDIT_LOG_EVENT_CLASS_DEFAULTS,+ AUDIT_LOG_EVENT_CLASSES+} from "@app/hooks/api/auditLogSettings/constants";+import {+ AuditLogEventClass,+ TProjectAuditLogEventClassSetting+} 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";++export const AuditLogEventClassesSection = () => {+ const { currentProject } = useProject();+ const { currentOrg } = useOrganization();+ const { hasProjectRole } = useProjectPermission();+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);++ const { data: settings, isPending } = useGetProjectAuditLogSettings(currentProject.id);+ const { mutateAsync: updateSettings, isPending: isSaving } = useUpdateProjectAuditLogSettings();++ const settingFor = (eventClass: AuditLogEventClass): TProjectAuditLogEventClassSetting =>+ settings?.eventClasses.find((el) => el.eventClass === eventClass) ?? {+ eventClass,+ isEnabled: AUDIT_LOG_EVENT_CLASS_DEFAULTS[eventClass],+ source: "organization"+ };++ const {+ control,+ handleSubmit,+ reset,+ formState: { isDirty, dirtyFields }+ } = useForm<TForm>({+ values: Object.fromEntries(+ AUDIT_LOG_EVENT_CLASSES.map((eventClass) => [eventClass, settingFor(eventClass).isEnabled])+ ) as TForm+ });++ const shouldUseNewPrivilegeSystem =+ settings?.shouldUseNewPrivilegeSystem ?? currentOrg.shouldUseNewPrivilegeSystem;++ // Only send touched rows, so untouched ones keep following the org.+ const onSubmit = async (form: TForm) => {+ const eventClasses = AUDIT_LOG_EVENT_CLASSES.filter(+ (eventClass) => dirtyFields[eventClass]+ ).map((eventClass) => ({ eventClass, isEnabled: form[eventClass] }));+ if (!eventClasses.length) return;++ await updateSettings({ projectId: currentProject.id, eventClasses });+ createNotification({ text: "Audit log settings saved", type: "success" });+ };++ const applyOrgDefault = async (eventClass: AuditLogEventClass) => {+ await updateSettings({+ projectId: currentProject.id,+ eventClasses: [{ eventClass, isEnabled: null }]+ });+ createNotification({+ text: "Project now follows the organization default for this class",+ 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. Rows without an override follow the+ organization setting.+ </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 isAuthorization = eventClass === AuditLogEventClass.Authorization;+ const isLocked = isAuthorization && !shouldUseNewPrivilegeSystem;+ const hasOverride = settingFor(eventClass).source === "project";+ return (+ <Controller+ key={eventClass}+ control={control}+ name={eventClass}+ render={({ field }) => (+ <AuditLogEventClassRow+ eventClass={eventClass}+ isEnabled={isLocked ? false : field.value}+ variant="project"+ isDisabled={!isAdmin}+ lockedReason={isLocked ? REQUIRES_NEW_PRIVILEGE_SYSTEM : undefined}+ onCheckedChange={field.onChange}+ badge={+ hasOverride ? (+ <Badge variant="project">Project Override</Badge>+ ) : (+ <Badge variant="neutral">Organization Default</Badge>+ )+ }+ action={+ isAdmin && hasOverride && !isLocked ? (+ <Button+ type="button"+ variant="ghost"+ size="xs"+ className="h-auto px-1.5 py-0.5 text-2xs font-normal text-muted hover:text-foreground"+ isDisabled={isSaving}+ onClick={() => applyOrgDefault(eventClass)}+ >+ Use Organization Default+ </Button>+ ) : undefined+ }+ 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 border-neutral/15 bg-neutral/5 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>+ );+};diff --git a/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/index.tsx b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/index.tsxnew file mode 100644index 0000000000..a85e03044c--- /dev/null+++ b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/index.tsx@@ -0,0 +1 @@+export { AuditLogEventClassesSection } from "./AuditLogEventClassesSection";diff --git a/frontend/src/pages/project/SettingsPage/components/ProjectGeneralTab/ProjectGeneralTab.tsx b/frontend/src/pages/project/SettingsPage/components/ProjectGeneralTab/ProjectGeneralTab.tsxindex c6773f6a7c..ac128a5a91 100644--- a/frontend/src/pages/project/SettingsPage/components/ProjectGeneralTab/ProjectGeneralTab.tsx+++ b/frontend/src/pages/project/SettingsPage/components/ProjectGeneralTab/ProjectGeneralTab.tsx@@ -1,5 +1,6 @@import { ProjectOverviewChangeSection } from "@app/components/project/ProjectOverviewChangeSection";+import { AuditLogEventClassesSection } from "../AuditLogEventClassesSection";import { AuditLogsRetentionSection } from "../AuditLogsRetentionSection";import { DeleteProjectSection } from "../DeleteProjectSection";@@ -8,6 +9,7 @@ export const ProjectGeneralTab = () => {<div><ProjectOverviewChangeSection /><AuditLogsRetentionSection />+ <AuditLogEventClassesSection /><DeleteProjectSection /></div>);