Skip to content

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

refactor

Thiago Araujo da Silva51977bf2b32d
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.ts
index 1e70ae7b85..67303abcca 100644
--- a/backend/src/ee/services/audit-log/audit-log-event-classes.ts
+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.ts
@@ -14,6 +14,13 @@ export const AUDIT_LOG_EVENT_CLASS_DEFAULTS: Record<AuditLogEventClass, boolean>
[AuditLogEventClass.Authorization]: false
};
+export const AUDIT_LOG_EVENT_CLASSES = [
+ AuditLogEventClass.Management,
+ AuditLogEventClass.DataAccess,
+ AuditLogEventClass.Authentication,
+ AuditLogEventClass.Authorization
+] as const;
+
export const CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES = [
AuditLogEventClass.DataAccess,
AuditLogEventClass.Authentication,
@@ -22,7 +29,7 @@ export const CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES = [
export type TConfigurableAuditLogEventClass = (typeof CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES)[number];
-export const AUTHENTICATION_EVENT_TYPES: readonly EventType[] = [
+const AUTHENTICATION_EVENT_TYPES: readonly EventType[] = [
EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH,
EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH_FAILED,
EventType.LOGIN_IDENTITY_KUBERNETES_AUTH,
@@ -62,9 +69,9 @@ export const AUTHENTICATION_EVENT_TYPES: readonly EventType[] = [
EventType.RESOURCE_AUTH_METHOD_LOGIN_FAILED
];
-export const AUTHORIZATION_EVENT_TYPES: readonly EventType[] = [EventType.PERMISSION_DENIED];
+const AUTHORIZATION_EVENT_TYPES: readonly EventType[] = [EventType.PERMISSION_DENIED];
-export const DATA_ACCESS_EVENT_TYPES: readonly EventType[] = [
+const DATA_ACCESS_EVENT_TYPES: readonly EventType[] = [
EventType.GET_SECRETS,
EventType.GET_SECRET,
EventType.REVEAL_SECRET,
@@ -245,7 +252,7 @@ const EVENT_TYPE_TO_CLASS = new Map<EventType, AuditLogEventClass>([
...DATA_ACCESS_EVENT_TYPES.map((type) => [type, AuditLogEventClass.DataAccess] as const)
]);
-export const MANAGEMENT_EVENT_TYPES: readonly EventType[] = Object.values(EventType).filter(
+const MANAGEMENT_EVENT_TYPES: readonly EventType[] = Object.values(EventType).filter(
(type) => !EVENT_TYPE_TO_CLASS.has(type)
);
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.ts
index 0c4f697a3d..8de68e2ca3 100644
--- a/backend/src/ee/services/audit-log/audit-log-service.test.ts
+++ b/backend/src/ee/services/audit-log/audit-log-service.test.ts
@@ -32,8 +32,7 @@ const denial = (overrides: Partial<TRecordPermissionDeniedDTO> = {}): TRecordPer
errorName: "ForbiddenError",
message: "denied",
route: "/api/v3/secrets/raw/:secretName",
- method: "POST",
- projectId: "project-1"
+ method: "POST"
},
...overrides
});
diff --git a/backend/src/ee/services/audit-log/audit-log-settings-dal.ts b/backend/src/ee/services/audit-log/audit-log-settings-dal.ts
index 5fab60b7ee..d1e1a47d90 100644
--- a/backend/src/ee/services/audit-log/audit-log-settings-dal.ts
+++ b/backend/src/ee/services/audit-log/audit-log-settings-dal.ts
@@ -1,37 +1,7 @@
-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);
+import { ormify } from "@app/lib/knex";
- 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" });
- }
- };
+export type TAuditLogSettingsDALFactory = ReturnType<typeof auditLogSettingsDALFactory>;
- return { ...orm, findByOrgIds };
-};
+export const auditLogSettingsDALFactory = (db: TDbClient) => ormify(db, TableName.AuditLogSettings);
diff --git a/backend/src/ee/services/audit-log/audit-log-settings-schemas.ts b/backend/src/ee/services/audit-log/audit-log-settings-schemas.ts
new file mode 100644
index 0000000000..8c5e321212
--- /dev/null
+++ b/backend/src/ee/services/audit-log/audit-log-settings-schemas.ts
@@ -0,0 +1,30 @@
+import { z } from "zod";
+
+import { AUDIT_LOG_SETTINGS } from "@app/lib/api-docs";
+
+import { AuditLogEventClass } from "./audit-log-event-classes";
+
+export const AuditLogSettingsResponseSchema = 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)
+ })
+});
+
+export const updateAuditLogSettingsBodySchema = (isEnabledDescription: string) =>
+ z.object({
+ eventClasses: z
+ .object({
+ eventClass: z.nativeEnum(AuditLogEventClass).describe(AUDIT_LOG_SETTINGS.eventClass),
+ isEnabled: z.boolean().describe(isEnabledDescription)
+ })
+ .array()
+ .min(1)
+ .max(Object.values(AuditLogEventClass).length)
+ .describe(AUDIT_LOG_SETTINGS.eventClasses)
+ });
diff --git a/backend/src/ee/services/audit-log/audit-log-settings-service.test.ts b/backend/src/ee/services/audit-log/audit-log-settings-service.test.ts
index a140074771..711eb7a9dd 100644
--- a/backend/src/ee/services/audit-log/audit-log-settings-service.test.ts
+++ b/backend/src/ee/services/audit-log/audit-log-settings-service.test.ts
@@ -62,7 +62,11 @@ const createHarness = ({ rows = [] as TRow[] } = {}) => {
findById: vi.fn(async (id: string) => ({ id, shouldUseNewPrivilegeSystem: true }))
};
const auditLogSettingsDAL = {
- findByOrgIds: vi.fn(async (orgIds: string[]) => rows.filter((row) => orgIds.includes(row.orgId))),
+ find: vi.fn(async (filter: { orgId: string; projectId?: string | null }) =>
+ rows.filter(
+ (row) => row.orgId === filter.orgId && (filter.projectId === undefined || row.projectId === filter.projectId)
+ )
+ ),
transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb({})),
delete: vi.fn(async () => []),
insertMany: vi.fn(async (data: TRow[]) => data)
@@ -106,7 +110,7 @@ describe("getEffectiveSettings", () => {
const result = await service.getEffectiveSettings("org-1");
- expect(auditLogSettingsDAL.findByOrgIds).toHaveBeenCalledWith(["org-1"]);
+ expect(auditLogSettingsDAL.find).toHaveBeenCalledWith({ orgId: "org-1" });
expect(result).toEqual({
org: { "data-access": false },
projects: { p1: { authentication: false } },
@@ -189,7 +193,7 @@ describe("updateOrgSettings", () => {
]
});
- expect(auditLogSettingsDAL.findByOrgIds).not.toHaveBeenCalled();
+ expect(auditLogSettingsDAL.find).not.toHaveBeenCalled();
expect(auditLogSettingsDAL.delete).toHaveBeenCalledWith({ orgId: "org-1", projectId: null }, expect.anything());
expect(auditLogSettingsDAL.insertMany).toHaveBeenCalledWith(
[
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.ts
index 5a68f2fbaa..8bcb4208d8 100644
--- a/backend/src/ee/services/audit-log/audit-log-settings-service.ts
+++ b/backend/src/ee/services/audit-log/audit-log-settings-service.ts
@@ -1,9 +1,10 @@
import { ForbiddenError } from "@casl/ability";
-import { ActionProjectType, OrganizationActionScope, ProjectMembershipRole } from "@app/db/schemas";
+import { ActionProjectType, OrganizationActionScope, ProjectMembershipRole, TAuditLogSettings } from "@app/db/schemas";
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { OrgServiceActor } from "@app/lib/types";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -12,6 +13,7 @@ import { TPermissionServiceFactory } from "../permission/permission-service-type
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
import {
AUDIT_LOG_EVENT_CLASS_DEFAULTS,
+ AUDIT_LOG_EVENT_CLASSES,
AuditLogEventClass,
CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES,
getAuditLogEventClass,
@@ -29,7 +31,7 @@ import {
} from "./audit-log-settings-types";
type TAuditLogSettingsServiceFactoryDep = {
- auditLogSettingsDAL: TAuditLogSettingsDALFactory;
+ auditLogSettingsDAL: Pick<TAuditLogSettingsDALFactory, "find" | "transaction" | "delete" | "insertMany">;
orgDAL: Pick<TOrgDALFactory, "findById">;
projectDAL: Pick<TProjectDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
@@ -38,12 +40,9 @@ type TAuditLogSettingsServiceFactoryDep = {
export type TAuditLogSettingsServiceFactory = ReturnType<typeof auditLogSettingsServiceFactory>;
-const ORDERED_EVENT_CLASSES = [
- AuditLogEventClass.Management,
- AuditLogEventClass.DataAccess,
- AuditLogEventClass.Authentication,
- AuditLogEventClass.Authorization
-] as const;
+type TScope = Pick<TAuditLogSettings, "orgId" | "projectId">;
+type TScopeRow = Pick<TAuditLogSettings, "projectId" | "eventClass" | "isEnabled">;
+type TFullOverrides = Record<TConfigurableAuditLogEventClass, boolean>;
// Scopes don't inherit. A project without a row gets the default, not its org's value.
export const isAuditLogEventEnabled = (
@@ -61,8 +60,13 @@ export const isAuditLogEventEnabled = (
const isKnownEventClass = (value: string): value is AuditLogEventClass =>
(Object.values(AuditLogEventClass) as string[]).includes(value);
+const toOverrides = (rows: TScopeRow[]): TAuditLogEventClassOverrides =>
+ Object.fromEntries(
+ rows.filter((row) => isKnownEventClass(row.eventClass)).map((row) => [row.eventClass, row.isEnabled])
+ );
+
const toSettings = (overrides: TAuditLogEventClassOverrides): TAuditLogEventClassSetting[] =>
- ORDERED_EVENT_CLASSES.map((eventClass) => ({
+ AUDIT_LOG_EVENT_CLASSES.map((eventClass) => ({
eventClass,
isEnabled:
eventClass === AuditLogEventClass.Management
@@ -71,9 +75,7 @@ const toSettings = (overrides: TAuditLogEventClassOverrides): TAuditLogEventClas
}));
// An update replaces the scope's settings, so the request must name every configurable class once.
-const toFullOverrides = (
- eventClasses: TAuditLogEventClassSetting[]
-): Record<TConfigurableAuditLogEventClass, boolean> => {
+const toFullOverrides = (eventClasses: TAuditLogEventClassSetting[]): TFullOverrides => {
if (eventClasses.some((el) => el.eventClass === AuditLogEventClass.Management)) {
throw new BadRequestError({ message: "Management events are always recorded and cannot be changed" });
}
@@ -90,10 +92,7 @@ const toFullOverrides = (
message: `Every event class except management must be included. Missing: ${missing.join(", ")}`
});
}
- return Object.fromEntries(eventClasses.map((el) => [el.eventClass, el.isEnabled])) as Record<
- TConfigurableAuditLogEventClass,
- boolean
- >;
+ return Object.fromEntries(eventClasses.map((el) => [el.eventClass, el.isEnabled])) as TFullOverrides;
};
export const auditLogSettingsServiceFactory = ({
@@ -103,6 +102,38 @@ export const auditLogSettingsServiceFactory = ({
permissionService,
keyStore
}: TAuditLogSettingsServiceFactoryDep) => {
+ const findOrgOrThrow = async (orgId: string) => {
+ const org = await orgDAL.findById(orgId);
+ if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
+ return org;
+ };
+
+ const findProjectOrThrow = async (projectId: string) => {
+ const project = await projectDAL.findById(projectId);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
+ return project;
+ };
+
+ const assertOrgSettingsPermission = async (actor: OrgServiceActor, action: OrgPermissionActions) => {
+ 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(action, OrgPermissionSubjects.Settings);
+ };
+
+ const toResponse = (
+ overrides: TAuditLogEventClassOverrides,
+ org: { shouldUseNewPrivilegeSystem?: boolean | null }
+ ) => ({
+ eventClasses: toSettings(overrides),
+ shouldUseNewPrivilegeSystem: Boolean(org.shouldUseNewPrivilegeSystem)
+ });
+
const invalidateCache = async (orgId: string) => {
await keyStore.deleteItem(KeyStorePrefixes.AuditLogOrgSettings(orgId));
};
@@ -111,21 +142,19 @@ export const auditLogSettingsServiceFactory = ({
const org = await orgDAL.findById(orgId);
if (!org) return null;
- const rows = await auditLogSettingsDAL.findByOrgIds([orgId]);
- const settings: TEffectiveAuditLogSettings = {
- org: {},
- projects: {},
- shouldUseNewPrivilegeSystem: Boolean(org.shouldUseNewPrivilegeSystem)
- };
+ const rows = await auditLogSettingsDAL.find({ orgId });
+ const projectRows = new Map<string, TScopeRow[]>();
rows.forEach((row) => {
- if (!isKnownEventClass(row.eventClass)) return;
- if (row.projectId) {
- settings.projects[row.projectId] = { ...settings.projects[row.projectId], [row.eventClass]: row.isEnabled };
- } else {
- settings.org[row.eventClass] = row.isEnabled;
- }
+ if (!row.projectId) return;
+ projectRows.set(row.projectId, [...(projectRows.get(row.projectId) ?? []), row]);
});
- return settings;
+ return {
+ org: toOverrides(rows.filter((row) => !row.projectId)),
+ projects: Object.fromEntries(
+ [...projectRows].map(([projectId, scopeRows]) => [projectId, toOverrides(scopeRows)])
+ ),
+ shouldUseNewPrivilegeSystem: Boolean(org.shouldUseNewPrivilegeSystem)
+ };
};
// Hot path, so cached and never throws. On failure we fall back to recording everything.
@@ -150,10 +179,7 @@ export const auditLogSettingsServiceFactory = ({
}
};
- const writeScopeSettings = async (
- scope: { orgId: string; projectId: string | null },
- overrides: Record<TConfigurableAuditLogEventClass, boolean>
- ) => {
+ const writeScopeSettings = async (scope: TScope, overrides: TFullOverrides) => {
await auditLogSettingsDAL.transaction(async (tx) => {
await auditLogSettingsDAL.delete(scope, tx);
await auditLogSettingsDAL.insertMany(
@@ -169,45 +195,18 @@ export const auditLogSettingsServiceFactory = ({
};
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: toSettings(settings.org),
- shouldUseNewPrivilegeSystem: settings.shouldUseNewPrivilegeSystem
- };
+ await assertOrgSettingsPermission(actor, OrgPermissionActions.Read);
+ const org = await findOrgOrThrow(actor.orgId);
+ const rows = await auditLogSettingsDAL.find({ orgId: org.id, projectId: null });
+ return toResponse(toOverrides(rows), org);
};
const updateOrgSettings = async ({ actor, eventClasses }: TUpdateOrgAuditLogSettingsDTO) => {
- 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.Edit, OrgPermissionSubjects.Settings);
-
- const org = await orgDAL.findById(actor.orgId);
- if (!org) throw new NotFoundError({ message: `Organization with ID '${actor.orgId}' not found` });
-
+ await assertOrgSettingsPermission(actor, OrgPermissionActions.Edit);
+ const org = await findOrgOrThrow(actor.orgId);
const overrides = toFullOverrides(eventClasses);
- await writeScopeSettings({ orgId: actor.orgId, projectId: null }, overrides);
- return {
- eventClasses: toSettings(overrides),
- shouldUseNewPrivilegeSystem: Boolean(org.shouldUseNewPrivilegeSystem)
- };
+ await writeScopeSettings({ orgId: org.id, projectId: null }, overrides);
+ return toResponse(overrides, org);
};
const getProjectSettings = async ({
@@ -227,16 +226,10 @@ export const auditLogSettingsServiceFactory = ({
});
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` });
-
- return {
- eventClasses: toSettings(settings.projects[projectId] ?? {}),
- shouldUseNewPrivilegeSystem: settings.shouldUseNewPrivilegeSystem
- };
+ const project = await findProjectOrThrow(projectId);
+ const org = await findOrgOrThrow(project.orgId);
+ const rows = await auditLogSettingsDAL.find({ orgId: org.id, projectId });
+ return toResponse(toOverrides(rows), org);
};
const updateProjectSettings = async ({ eventClasses, ...dto }: TUpdateProjectAuditLogSettingsDTO) => {
@@ -254,18 +247,11 @@ export const auditLogSettingsServiceFactory = ({
});
}
- const project = await projectDAL.findById(dto.projectId);
- if (!project) throw new NotFoundError({ message: `Project with ID '${dto.projectId}' not found` });
-
- const org = await orgDAL.findById(project.orgId);
- if (!org) throw new NotFoundError({ message: `Organization with ID '${project.orgId}' not found` });
-
+ const project = await findProjectOrThrow(dto.projectId);
+ const org = await findOrgOrThrow(project.orgId);
const overrides = toFullOverrides(eventClasses);
- await writeScopeSettings({ orgId: project.orgId, projectId: dto.projectId }, overrides);
- return {
- eventClasses: toSettings(overrides),
- shouldUseNewPrivilegeSystem: Boolean(org.shouldUseNewPrivilegeSystem)
- };
+ await writeScopeSettings({ orgId: org.id, projectId: project.id }, overrides);
+ return toResponse(overrides, org);
};
return {
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 389fb0e35e..352e551f9e 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -6011,7 +6011,6 @@ interface PermissionDeniedEvent {
message: string;
route?: string;
method: string;
- projectId?: string;
};
}
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index b08a63a8a3..866c0b267a 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2085,16 +2085,14 @@ export const AUDIT_LOG_SETTINGS = {
isEnabled: "Whether events of this class are recorded.",
shouldUseNewPrivilegeSystem:
"Whether the organization is on the new privilege system. Permission denials (the authorization class) are only recorded on the new privilege system.",
+ eventClasses:
+ "Every event class except management, each exactly once. The request replaces the current settings. Management events are always recorded, so a request that includes the management class is rejected.",
UPDATE_ORG: {
- eventClasses:
- "Every event class except management, each exactly once. The request replaces the current settings. Management events are always recorded, so a request that includes the management class is rejected.",
isEnabled:
"Whether to record events of this class for the organization. This only covers organization-level events; each project has its own setting."
},
UPDATE_PROJECT: {
projectId: "The ID of the project to update the audit log settings for.",
- eventClasses:
- "Every event class except management, each exactly once. The request replaces the current settings. Management events are always recorded, so a request that includes the management class is rejected.",
isEnabled:
"Whether to record events of this class for the project. A project that has never saved a setting uses the default."
},
diff --git a/backend/src/server/plugins/audit-log-permission-denied.ts b/backend/src/server/plugins/audit-log-permission-denied.ts
index e6af7067f0..c9e717eb7d 100644
--- a/backend/src/server/plugins/audit-log-permission-denied.ts
+++ b/backend/src/server/plugins/audit-log-permission-denied.ts
@@ -57,8 +57,7 @@ export const injectPermissionDeniedAuditLog = fp(async (server: FastifyZodProvid
errorName: error.name,
message: error.message,
route: req.routeOptions.url,
- method: req.method,
- projectId
+ method: req.method
}
});
});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 3baa8040a6..7f6038a947 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1552,7 +1552,7 @@ export const registerRoutes = async (
const certificatePolicyDAL = certificatePolicyDALFactory(db);
const orgService = orgServiceFactory({
- keyStore,
+ auditLogSettingsService,
userAliasDAL,
identityMetadataDAL,
secretDAL,
diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.ts
index c0fbb13069..623ec0a527 100644
--- a/backend/src/server/routes/v1/organization-router.ts
+++ b/backend/src/server/routes/v1/organization-router.ts
@@ -11,6 +11,10 @@ import {
OrgRolesSchema
} from "@app/db/schemas";
import { AuditLogEventClass } from "@app/ee/services/audit-log/audit-log-event-classes";
+import {
+ AuditLogSettingsResponseSchema,
+ updateAuditLogSettingsBodySchema
+} from "@app/ee/services/audit-log/audit-log-settings-schemas";
import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { KeyStorePrefixes, KeyStoreTtls } from "@app/keystore/keystore";
import { ApiDocsTags, AUDIT_LOG_SETTINGS, AUDIT_LOGS, ORGANIZATIONS } from "@app/lib/api-docs";
@@ -156,17 +160,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
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)
- })
- })
+ 200: AuditLogSettingsResponseSchema
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
@@ -187,29 +181,9 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
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)
- }),
+ body: updateAuditLogSettingsBodySchema(AUDIT_LOG_SETTINGS.UPDATE_ORG.isEnabled),
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)
- })
- })
+ 200: AuditLogSettingsResponseSchema
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.ts
index 9571fbedf6..3fd8d10a72 100644
--- a/backend/src/server/routes/v1/project-router.ts
+++ b/backend/src/server/routes/v1/project-router.ts
@@ -14,7 +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 {
+ AuditLogSettingsResponseSchema,
+ updateAuditLogSettingsBodySchema
+} from "@app/ee/services/audit-log/audit-log-settings-schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { InfisicalProjectTemplate } from "@app/ee/services/project-template/project-template-types";
import { ApiDocsTags, AUDIT_LOG_SETTINGS, PROJECTS } from "@app/lib/api-docs";
@@ -737,17 +740,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
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)
- })
- .array(),
- shouldUseNewPrivilegeSystem: z.boolean().describe(AUDIT_LOG_SETTINGS.shouldUseNewPrivilegeSystem)
- })
- })
+ 200: AuditLogSettingsResponseSchema
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
@@ -777,29 +770,9 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
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().describe(AUDIT_LOG_SETTINGS.UPDATE_PROJECT.isEnabled)
- })
- .array()
- .min(1)
- .max(Object.values(AuditLogEventClass).length)
- .describe(AUDIT_LOG_SETTINGS.UPDATE_PROJECT.eventClasses)
- }),
+ body: updateAuditLogSettingsBodySchema(AUDIT_LOG_SETTINGS.UPDATE_PROJECT.isEnabled),
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)
- })
- })
+ 200: AuditLogSettingsResponseSchema
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 9a079c54d6..adfe7f9ad8 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -13,6 +13,7 @@ import {
TSamlConfigs
} from "@app/db/schemas";
import { bootstrapAgentVaultProject } from "@app/ee/services/agent-vault-project/agent-vault-project-bootstrap";
+import { TAuditLogSettingsServiceFactory } from "@app/ee/services/audit-log/audit-log-settings-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
@@ -33,7 +34,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 { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";
+import { PgSqlLock } 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,7 +149,7 @@ type TOrgServiceFactoryDep = {
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "create">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
- keyStore: Pick<TKeyStoreFactory, "deleteItem">;
+ auditLogSettingsService: Pick<TAuditLogSettingsServiceFactory, "invalidateCache">;
};
export type TOrgServiceFactory = ReturnType<typeof orgServiceFactory>;
@@ -189,7 +190,7 @@ export const orgServiceFactory = ({
usageMeteringService,
pamSessionDAL,
gatewayV2Service,
- keyStore
+ auditLogSettingsService
}: TOrgServiceFactoryDep) => {
/*
* Get organization details by the organization id
@@ -446,7 +447,7 @@ export const orgServiceFactory = ({
// Denials are only recorded on the new privilege system, so bust the cache or the first
// denial after the upgrade is skipped.
- await keyStore.deleteItem(KeyStorePrefixes.AuditLogOrgSettings(actorOrgId));
+ await auditLogSettingsService.invalidateCache(actorOrgId);
return upgradedOrg;
};
diff --git a/frontend/src/components/auditLogSettings/AuditLogEventClassRow.tsx b/frontend/src/components/auditLogSettings/AuditLogEventClassRow.tsx
index afafd2462c..d78b1423a6 100644
--- a/frontend/src/components/auditLogSettings/AuditLogEventClassRow.tsx
+++ b/frontend/src/components/auditLogSettings/AuditLogEventClassRow.tsx
@@ -1,6 +1,5 @@
import { ReactNode } from "react";
import { TriangleAlert } from "lucide-react";
-import { twMerge } from "tailwind-merge";
import {
Alert,
@@ -30,9 +29,6 @@ type Props = {
onCheckedChange?: (isEnabled: boolean) => void;
descriptionExtra?: ReactNode;
warning?: ReactNode;
- badge?: ReactNode;
- action?: ReactNode;
- className?: string;
};
export const AuditLogEventClassRow = ({
@@ -43,10 +39,7 @@ export const AuditLogEventClassRow = ({
isDisabled,
onCheckedChange,
descriptionExtra,
- warning,
- badge,
- action,
- className
+ warning
}: Props) => {
const id = `audit-log-event-class-${eventClass}`;
@@ -62,11 +55,10 @@ export const AuditLogEventClassRow = ({
);
return (
- <Field orientation="horizontal" className={twMerge("gap-8 px-6 py-6", className)}>
+ <Field orientation="horizontal" className="gap-8 px-6 py-6">
<FieldContent>
<FieldTitle className="text-base leading-5">
<label htmlFor={id}>{auditLogEventClassToNameMap[eventClass]}</label>
- {badge}
</FieldTitle>
<FieldDescription className="max-w-2xl text-sm text-accent">
{auditLogEventClassToDescriptionMap[eventClass]}
@@ -83,7 +75,7 @@ export const AuditLogEventClassRow = ({
</Alert>
)}
</FieldContent>
- <div className="flex shrink-0 flex-col items-end gap-1.5">
+ <div className="shrink-0">
{lockedReason ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -94,7 +86,6 @@ export const AuditLogEventClassRow = ({
) : (
toggle
)}
- {action}
</div>
</Field>
);
diff --git a/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx b/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx
index 7698be18ee..e8f5defaf3 100644
--- a/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx
+++ b/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx
@@ -1,4 +1,3 @@
-import { ReactNode } from "react";
import { Controller, useForm } from "react-hook-form";
import { Link } from "@tanstack/react-router";
@@ -13,6 +12,7 @@ import {
DocumentationLinkBadge,
Skeleton
} from "@app/components/v3";
+import { useOrganization } from "@app/context";
import {
AUDIT_LOG_EVENT_CLASS_DEFAULTS,
AUDIT_LOG_EVENT_CLASSES,
@@ -33,15 +33,13 @@ const REQUIRES_NEW_PRIVILEGE_SYSTEM = "Requires the new privilege system";
const ALWAYS_RECORDED = "Management events are always recorded";
type Props = {
- title: ReactNode;
+ title: string;
description: string;
settings?: TAuditLogSettings;
isPending: boolean;
isSaving: boolean;
canEdit: boolean;
variant: ScopeVariant;
- orgId: string;
- shouldUseNewPrivilegeSystem: boolean;
onSave: (eventClasses: TAuditLogEventClassSetting[]) => Promise<unknown>;
className?: string;
titleClassName?: string;
@@ -55,12 +53,14 @@ export const AuditLogEventClassesForm = ({
isSaving,
canEdit,
variant,
- orgId,
- shouldUseNewPrivilegeSystem,
onSave,
className,
titleClassName
}: Props) => {
+ const { currentOrg } = useOrganization();
+ const shouldUseNewPrivilegeSystem =
+ settings?.shouldUseNewPrivilegeSystem ?? currentOrg.shouldUseNewPrivilegeSystem;
+
const isEnabled = (eventClass: AuditLogEventClass) =>
settings?.eventClasses.find((el) => el.eventClass === eventClass)?.isEnabled ??
AUDIT_LOG_EVENT_CLASS_DEFAULTS[eventClass];
@@ -137,7 +137,10 @@ export const AuditLogEventClassesForm = ({
isLocked ? (
<>
Denials are only recorded on the new privilege system.{" "}
- <Link to="/organizations/$orgId/access-management" params={{ orgId }}>
+ <Link
+ to="/organizations/$orgId/access-management"
+ params={{ orgId: currentOrg.id }}
+ >
Upgrade the privilege system
</Link>{" "}
in Access Control to enable this class.
diff --git a/frontend/src/components/auditLogSettings/index.tsx b/frontend/src/components/auditLogSettings/index.tsx
index 564c348f66..10c4afb0e3 100644
--- a/frontend/src/components/auditLogSettings/index.tsx
+++ b/frontend/src/components/auditLogSettings/index.tsx
@@ -1,2 +1 @@
export { AuditLogEventClassesForm } from "./AuditLogEventClassesForm";
-export { AuditLogEventClassRow } from "./AuditLogEventClassRow";
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx
index 2914e4d01b..30ae5c988a 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx
@@ -30,10 +30,6 @@ export const AuditLogSettingsTab = withPermission(
isSaving={isSaving}
canEdit={canEdit}
variant={scopeVariant}
- orgId={currentOrg.id}
- shouldUseNewPrivilegeSystem={
- settings?.shouldUseNewPrivilegeSystem ?? currentOrg.shouldUseNewPrivilegeSystem
- }
onSave={(eventClasses) => updateSettings({ eventClasses })}
/>
);
diff --git a/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx
index 1cb54c4005..f9903f7884 100644
--- a/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx
+++ b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx
@@ -1,11 +1,10 @@
import { AuditLogEventClassesForm } from "@app/components/auditLogSettings";
-import { useOrganization, useProject, useProjectPermission } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import { useGetProjectAuditLogSettings, useUpdateProjectAuditLogSettings } from "@app/hooks/api";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
export const AuditLogEventClassesSection = () => {
const { currentProject } = useProject();
- const { currentOrg } = useOrganization();
const { hasProjectRole } = useProjectPermission();
const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
@@ -23,10 +22,6 @@ export const AuditLogEventClassesSection = () => {
isSaving={isSaving}
canEdit={isAdmin}
variant="project"
- orgId={currentOrg.id}
- shouldUseNewPrivilegeSystem={
- settings?.shouldUseNewPrivilegeSystem ?? currentOrg.shouldUseNewPrivilegeSystem
- }
onSave={(eventClasses) => updateSettings({ projectId: currentProject.id, eventClasses })}
/>
);