Skip to content

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

fix small stuff

Thiago Araujo da Silva580c7811d56c
diff --git a/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts b/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
index 73466c9ce9..f6da19a0e6 100644
--- a/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
+++ b/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts
@@ -26,6 +26,7 @@ type TClickHouseFindArg = {
secretPath?: string;
secretKey?: string;
eventType?: EventType[];
+ excludeEventType?: EventType[];
eventMetadata?: Record<string, string>;
pamScope?: TPamAuditLogScope;
};
@@ -128,6 +129,11 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,
params.eventTypes = arg.eventType;
}
+ if (arg.excludeEventType?.length) {
+ conditions.push("eventType NOT IN ({excludeEventTypes:Array(String)})");
+ params.excludeEventTypes = arg.excludeEventType;
+ }
+
// Optional: eventMetadata dynamic key/value filters
if (arg.eventMetadata && Object.keys(arg.eventMetadata).length) {
let metaIdx = 0;
diff --git a/backend/src/ee/services/audit-log/audit-log-dal.ts b/backend/src/ee/services/audit-log/audit-log-dal.ts
index e3b24c9e17..299948ac96 100644
--- a/backend/src/ee/services/audit-log/audit-log-dal.ts
+++ b/backend/src/ee/services/audit-log/audit-log-dal.ts
@@ -32,6 +32,7 @@ export interface TAuditLogDALFactory extends Omit<TOrmify<TableName.AuditLog>, "
secretPath?: string | undefined;
secretKey?: string | undefined;
eventType?: EventType[] | undefined;
+ excludeEventType?: EventType[] | undefined;
eventMetadata?: Record<string, string> | undefined;
pamScope?: TPamAuditLogScope | undefined;
},
@@ -90,6 +91,7 @@ export const auditLogDALFactory = (db: TDbClient) => {
secretPath,
secretKey,
eventType,
+ excludeEventType,
eventMetadata,
pamScope
},
@@ -208,6 +210,10 @@ export const auditLogDALFactory = (db: TDbClient) => {
void sqlQuery.whereIn("eventType", eventType);
}
+ if (excludeEventType?.length) {
+ void sqlQuery.whereNotIn("eventType", excludeEventType);
+ }
+
// we timeout long running queries to prevent DB resource issues (2 minutes)
const docs = await sqlQuery.timeout(1000 * 120);
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.ts
index 6ee374a595..4ed01af6e3 100644
--- 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.ts
@@ -5,7 +5,8 @@ import {
AUDIT_LOG_EVENT_CLASS_MEMBERS,
AuditLogEventClass,
getAuditLogEventClass,
- getEventTypesForClasses
+ getEventTypesForClasses,
+ resolveEventClassFilter
} from "./audit-log-event-classes";
import { EventType } from "./audit-log-types";
@@ -73,3 +74,36 @@ describe("audit log event classes", () => {
);
});
});
+
+describe("resolveEventClassFilter", () => {
+ test("lists the member types when management isn't selected", () => {
+ expect(resolveEventClassFilter([AuditLogEventClass.Authorization])).toEqual({
+ eventType: [EventType.PERMISSION_DENIED]
+ });
+ });
+
+ test("excludes the unselected classes when management is selected", () => {
+ const resolved = resolveEventClassFilter([AuditLogEventClass.Management, AuditLogEventClass.DataAccess]);
+ expect(resolved?.eventType).toBeUndefined();
+ expect(resolved?.excludeEventType).toEqual(
+ getEventTypesForClasses([AuditLogEventClass.Authentication, AuditLogEventClass.Authorization])
+ );
+ });
+
+ test("excludes nothing when every class is selected", () => {
+ expect(resolveEventClassFilter(Object.values(AuditLogEventClass))).toEqual({ excludeEventType: [] });
+ });
+
+ test("keeps only the requested event types that are in the selected classes", () => {
+ expect(
+ resolveEventClassFilter(
+ [AuditLogEventClass.Management],
+ [EventType.UPDATE_SECRET, EventType.GET_SECRETS, EventType.USER_LOGIN]
+ )
+ ).toEqual({ eventType: [EventType.UPDATE_SECRET] });
+ });
+
+ test("returns null when no requested event type is in the selected classes", () => {
+ expect(resolveEventClassFilter([AuditLogEventClass.Authorization], [EventType.GET_SECRETS])).toBeNull();
+ });
+});
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 89910159b0..945ba8bfe3 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
@@ -275,3 +275,18 @@ export const getAuditLogEventClass = (eventType: string): AuditLogEventClass =>
export const getEventTypesForClasses = (eventClasses: AuditLogEventClass[]): EventType[] =>
eventClasses.flatMap((eventClass) => AUDIT_LOG_EVENT_CLASS_MEMBERS[eventClass]);
+
+export const resolveEventClassFilter = (
+ eventClasses: AuditLogEventClass[],
+ eventType?: EventType[]
+): { eventType?: EventType[]; excludeEventType?: EventType[] } | null => {
+ if (eventType?.length) {
+ const matching = eventType.filter((type) => eventClasses.includes(getAuditLogEventClass(type)));
+ return matching.length ? { eventType: matching } : null;
+ }
+ if (eventClasses.includes(AuditLogEventClass.Management)) {
+ const excluded = AUDIT_LOG_EVENT_CLASSES.filter((eventClass) => !eventClasses.includes(eventClass));
+ return { excludeEventType: getEventTypesForClasses(excluded) };
+ }
+ return { eventType: getEventTypesForClasses(eventClasses) };
+};
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.ts
index 527ca3cbbc..34f57de242 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
@@ -277,34 +277,15 @@ describe("audit-log-queue event class settings", () => {
expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);
});
- test("records a data-access event even if a row says the class is off", async () => {
+ test("records management and data-access events without looking up settings", async () => {
const { service, keyStore, auditLogSettingsService } = await createHarness();
- auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(
- settings({ org: { "data-access": false }, projects: { p1: { "data-access": false } } })
- );
+ await service.pushToLog(dto({ event: { type: "update-secret", metadata: {} } }) as never);
await service.pushToLog(dto({ event: { type: "get-secrets", metadata: {} } }) as never);
await service.pushToLog(dto({ projectId: "p1", event: { type: "get-secrets", metadata: {} } }) as never);
- expect(keyStore.streamAdd).toHaveBeenCalledTimes(2);
- });
-
- test("records a management event even if a row says the class is 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).toHaveBeenCalledTimes(1);
- });
-
- 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);
+ expect(keyStore.streamAdd).toHaveBeenCalledTimes(3);
+ expect(auditLogSettingsService.getEffectiveSettings).not.toHaveBeenCalled();
});
test("a project event uses the project's own setting, never the org's", async () => {
@@ -340,11 +321,11 @@ describe("audit-log-queue event class settings", () => {
expect(keyStore.streamAdd).not.toHaveBeenCalled();
});
- test("records a data-access event when no scope has a setting", async () => {
+ test("records an authentication 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);
+ await service.pushToLog(dto({ event: { type: "user-login", metadata: {} } }) as never);
expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);
});
@@ -353,7 +334,7 @@ describe("audit-log-queue event class settings", () => {
const { service, keyStore, auditLogSettingsService } = await createHarness();
auditLogSettingsService.getEffectiveSettings.mockResolvedValueOnce(null);
- await service.pushToLog(dto({ event: { type: "get-secrets", metadata: {} } }) as never);
+ await service.pushToLog(dto({ event: { type: "permission-denied", metadata: {} } }) as never);
expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);
});
diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.ts
index a1e7fa66e0..e4b6dbdc73 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,7 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TLicenseServiceFactory } from "../license/license-service";
import { TAuditLogDALFactory } from "./audit-log-dal";
+import { getAuditLogEventClass, isAlwaysRecordedEventClass } from "./audit-log-event-classes";
import { isAuditLogEventEnabled, TAuditLogSettingsServiceFactory } from "./audit-log-settings-service";
import { TAuditLogStreamEntry, TCreateAuditLogDTO } from "./audit-log-types";
@@ -107,10 +108,12 @@ export const auditLogQueueServiceFactory = async ({
const orgId = data.orgId ?? project?.orgId;
if (!orgId) return null;
- const settings = await requestMemoize(requestMemoKeys.auditLogSettings(orgId), () =>
- auditLogSettingsService.getEffectiveSettings(orgId)
- );
- if (!isAuditLogEventEnabled(settings, data.event.type, projectId)) return null;
+ if (!isAlwaysRecordedEventClass(getAuditLogEventClass(data.event.type))) {
+ const settings = await requestMemoize(requestMemoKeys.auditLogSettings(orgId), () =>
+ auditLogSettingsService.getEffectiveSettings(orgId)
+ );
+ if (!isAuditLogEventEnabled(settings, data.event.type, 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.ts b/backend/src/ee/services/audit-log/audit-log-service.ts
index b032c97ce9..678f78bde1 100644
--- a/backend/src/ee/services/audit-log/audit-log-service.ts
+++ b/backend/src/ee/services/audit-log/audit-log-service.ts
@@ -21,7 +21,7 @@ import { TPermissionServiceFactory } from "../permission/permission-service-type
import { ProjectPermissionAuditLogsActions, ProjectPermissionSub } from "../permission/project-permission";
import { TClickHouseAuditLogDALFactory } from "./audit-log-clickhouse-dal";
import { TAuditLogDALFactory, TPamAuditLogScope } from "./audit-log-dal";
-import { getAuditLogEventClass, getEventTypesForClasses } from "./audit-log-event-classes";
+import { getAuditLogEventClass, resolveEventClassFilter } from "./audit-log-event-classes";
import { TAuditLogQueueServiceFactory } from "./audit-log-queue";
import { isAuditLogEventEnabled, TAuditLogSettingsServiceFactory } from "./audit-log-settings-service";
import {
@@ -142,11 +142,11 @@ export const auditLogServiceFactory = ({
const appCfg = getConfig();
const useClickHouse = appCfg.CLICKHOUSE_AUDIT_LOG_ENABLED && clickhouseAuditLogDAL;
- let { eventType } = filter;
+ let eventTypeFilter: { eventType?: EventType[]; excludeEventType?: EventType[] } = { eventType: filter.eventType };
if (filter.eventClass?.length) {
- const classEventTypes = getEventTypesForClasses(filter.eventClass);
- eventType = eventType?.length ? eventType.filter((type) => classEventTypes.includes(type)) : classEventTypes;
- if (!eventType.length) return [];
+ const resolved = resolveEventClassFilter(filter.eventClass, filter.eventType);
+ if (!resolved) return [];
+ eventTypeFilter = resolved;
}
const findArgs = {
@@ -154,7 +154,7 @@ export const auditLogServiceFactory = ({
endDate: filter.endDate,
limit: filter.limit,
offset: filter.offset,
- eventType,
+ ...eventTypeFilter,
userAgentType: filter.userAgentType,
actorId: filter.auditLogActorId,
actorType: filter.actorType,
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 db2af4b86c..432c4843a7 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
@@ -70,6 +70,7 @@ const orgActor = {
} as never;
const createHarness = ({ rows = [] as TRow[], shouldUseNewPrivilegeSystem = true, isAdmin = true } = {}) => {
+ const tx = { raw: vi.fn(async () => undefined) };
const orgDAL = {
findById: vi.fn(async (id: string) => ({ id, shouldUseNewPrivilegeSystem }))
};
@@ -79,7 +80,7 @@ const createHarness = ({ rows = [] as TRow[], shouldUseNewPrivilegeSystem = true
(row) => row.orgId === filter.orgId && (filter.projectId === undefined || row.projectId === filter.projectId)
)
),
- transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb({})),
+ transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb(tx)),
delete: vi.fn(async () => []),
insertMany: vi.fn(async (data: TRow[]) => data)
};
@@ -119,7 +120,7 @@ const createHarness = ({ rows = [] as TRow[], shouldUseNewPrivilegeSystem = true
keyStore: keyStore as never
});
- return { service, orgDAL, auditLogSettingsDAL, keyStore };
+ return { service, orgDAL, auditLogSettingsDAL, keyStore, tx };
};
describe("getEffectiveSettings", () => {
@@ -292,6 +293,28 @@ describe("updateOrgSettings", () => {
});
});
+describe("writing settings", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test("takes a per-scope lock before replacing the rows", async () => {
+ const { service, tx, auditLogSettingsDAL } = createHarness();
+
+ await service.updateOrgSettings({ actor: orgActor, eventClasses: fullEventClasses });
+
+ expect(tx.raw).toHaveBeenCalledWith("SELECT pg_advisory_xact_lock(?)", [expect.any(Number)]);
+ expect(tx.raw.mock.invocationCallOrder[0]).toBeLessThan(auditLogSettingsDAL.delete.mock.invocationCallOrder[0]);
+ });
+
+ test("still succeeds when the cache can't be invalidated after the write", async () => {
+ const { service, keyStore } = createHarness();
+ keyStore.deleteItem.mockRejectedValueOnce(new Error("redis down"));
+
+ await expect(service.updateOrgSettings({ actor: orgActor, eventClasses: fullEventClasses })).resolves.toBeDefined();
+ });
+});
+
describe("updateProjectSettings", () => {
beforeEach(() => {
vi.clearAllMocks();
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 7572922358..fd4868651b 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
@@ -7,7 +7,7 @@ import {
ProjectMembershipRole,
TAuditLogSettings
} from "@app/db/schemas";
-import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { KeyStorePrefixes, KeyStoreTtls, PgSqlLock, 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";
@@ -155,7 +155,11 @@ export const auditLogSettingsServiceFactory = ({
});
const invalidateCache = async (orgId: string) => {
- await keyStore.deleteItem(KeyStorePrefixes.AuditLogOrgSettings(orgId));
+ try {
+ await keyStore.deleteItem(KeyStorePrefixes.AuditLogOrgSettings(orgId));
+ } catch (error) {
+ logger.warn(error, `audit-log-settings: failed to invalidate cached settings [orgId=${orgId}]`);
+ }
};
const loadSettings = async (orgId: string): Promise<TEffectiveAuditLogSettings | null> => {
@@ -201,6 +205,9 @@ export const auditLogSettingsServiceFactory = ({
const writeScopeSettings = async (scope: TScope, overrides: TFullOverrides) => {
await auditLogSettingsDAL.transaction(async (tx) => {
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [
+ PgSqlLock.AuditLogSettingsUpdate(scope.projectId ?? scope.orgId)
+ ]);
await auditLogSettingsDAL.delete(scope, tx);
await auditLogSettingsDAL.insertMany(
CONFIGURABLE_AUDIT_LOG_EVENT_CLASSES.map((eventClass) => ({
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index bd5db1a591..e4dd2de05b 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -43,7 +43,8 @@ export const PgSqlLock = {
OrgAuditReportRequest: (orgId: string) => pgAdvisoryLockHashText(`audit-report-request:org:${orgId}`),
OrgAgentProxyConfigInit: (orgId: string) => pgAdvisoryLockHashText(`org-agent-proxy-config-init:${orgId}`),
ExternalGroupOrgRoleMappingUpdate: (orgId: string) =>
- pgAdvisoryLockHashText(`external-group-org-role-mapping-update:${orgId}`)
+ pgAdvisoryLockHashText(`external-group-org-role-mapping-update:${orgId}`),
+ AuditLogSettingsUpdate: (scopeId: string) => pgAdvisoryLockHashText(`audit-log-settings-update:${scopeId}`)
} as const;
// all the key prefixes used must be set here to avoid conflict
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index e640175281..a63b53f03b 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -1575,7 +1575,7 @@ export const AUDIT_LOGS = {
"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.",
+ "Filter by event class, comma-separated for multiple values (management, authentication, authorization, data-access). Combined with eventType, only event types in both are returned. If the selected classes include secret events, the environment, secretPath, and secretKey filters drop every event whose metadata doesn't match, including events that aren't about secrets. If they don't, those filters are ignored.",
secretPath:
"The path of the secret to query audit logs for. Note that the projectId parameter must also be provided.",
secretKey:
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 6c50f49527..df48e7699b 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -445,8 +445,8 @@ export const orgServiceFactory = ({
);
});
- // Denials only get recorded on the new privilege system, so bust the cache or the first
- // denial after upgrading gets missed.
+ // Denials only get recorded on the new privilege system, so bust the cache or denials right
+ // after upgrading get missed. Never throws, since the upgrade has already committed.
await auditLogSettingsService.invalidateCache(actorOrgId);
return upgradedOrg;
diff --git a/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx b/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx
index f4bbc87970..19521b9ab8 100644
--- a/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx
+++ b/frontend/src/components/auditLogSettings/AuditLogEventClassesForm.tsx
@@ -1,8 +1,11 @@
import { Controller, useForm } from "react-hook-form";
import { Link } from "@tanstack/react-router";
+import { Info } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import {
+ Alert,
+ AlertDescription,
Button,
Card,
CardDescription,
@@ -38,8 +41,10 @@ type Props = {
description: string;
settings?: TAuditLogSettings;
isPending: boolean;
+ isError?: boolean;
isSaving: boolean;
canEdit: boolean;
+ readOnlyMessage: string;
variant: ScopeVariant;
onSave: (eventClasses: TAuditLogEventClassSetting[]) => Promise<unknown>;
className?: string;
@@ -51,8 +56,10 @@ export const AuditLogEventClassesForm = ({
description,
settings,
isPending,
+ isError,
isSaving,
canEdit,
+ readOnlyMessage,
variant,
onSave,
className,
@@ -96,6 +103,12 @@ export const AuditLogEventClassesForm = ({
return (
<form onSubmit={handleSubmit(onSubmit)} className={className}>
+ {!canEdit && !isError && !isPending && (
+ <Alert variant="info" className="mb-4">
+ <Info />
+ <AlertDescription>{readOnlyMessage}</AlertDescription>
+ </Alert>
+ )}
<Card className="gap-0 overflow-hidden p-0">
<CardHeader className="border-b p-6">
<CardTitle className={titleClassName}>
@@ -104,57 +117,64 @@ export const AuditLogEventClassesForm = ({
</CardTitle>
<CardDescription>{description}</CardDescription>
</CardHeader>
- {isPending ? (
- <div className="space-y-4 p-6">
- {AUDIT_LOG_EVENT_CLASSES.map((eventClass) => (
- <Skeleton key={eventClass} className="h-12 w-full" />
- ))}
- </div>
- ) : (
- <div className="divide-y divide-border">
- {AUDIT_LOG_EVENT_CLASSES.map((eventClass) => {
- const isAlwaysRecorded = ALWAYS_RECORDED_AUDIT_LOG_EVENT_CLASSES.includes(eventClass);
- const isAuthorization = eventClass === AuditLogEventClass.Authorization;
- const isLocked = isAuthorization && !shouldUseNewPrivilegeSystem;
- let lockedReason: string | undefined;
- if (isAlwaysRecorded)
- lockedReason = `${auditLogEventClassToNameMap[eventClass]} events are always recorded`;
- else if (isLocked) lockedReason = REQUIRES_NEW_PRIVILEGE_SYSTEM;
- return (
- <Controller
- key={eventClass}
- control={control}
- name={eventClass}
- render={({ field }) => (
- <AuditLogEventClassRow
- eventClass={eventClass}
- isEnabled={isAlwaysRecorded || (!isLocked && field.value)}
- variant={variant}
- isDisabled={!canEdit}
- lockedReason={lockedReason}
- onCheckedChange={field.onChange}
- 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>
+ {isError && (
+ <p className="p-6 text-sm text-muted">
+ Couldn&apos;t load the audit log settings. Refresh the page to try again.
+ </p>
)}
- {canEdit && (
+ {!isError &&
+ (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 isAlwaysRecorded =
+ ALWAYS_RECORDED_AUDIT_LOG_EVENT_CLASSES.includes(eventClass);
+ const isAuthorization = eventClass === AuditLogEventClass.Authorization;
+ const isLocked = isAuthorization && !shouldUseNewPrivilegeSystem;
+ let lockedReason: string | undefined;
+ if (isAlwaysRecorded)
+ lockedReason = `${auditLogEventClassToNameMap[eventClass]} events are always recorded`;
+ else if (isLocked) lockedReason = REQUIRES_NEW_PRIVILEGE_SYSTEM;
+ return (
+ <Controller
+ key={eventClass}
+ control={control}
+ name={eventClass}
+ render={({ field }) => (
+ <AuditLogEventClassRow
+ eventClass={eventClass}
+ isEnabled={isAlwaysRecorded || (!isLocked && field.value)}
+ variant={variant}
+ isDisabled={!canEdit}
+ lockedReason={lockedReason}
+ onCheckedChange={field.onChange}
+ 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 && !isError && (
<CardFooter className="min-h-8 justify-end gap-2 border-t p-4">
<Button
type="button"
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx
index 5fb840280c..2024833e0a 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditLogSettingsTab/AuditLogSettingsTab.tsx
@@ -17,7 +17,7 @@ export const AuditLogSettingsTab = withPermission(
const scopeVariant = useScopeVariant();
const canEdit = hasOrgRole(OrgMembershipRole.Admin);
- const { data: settings, isPending } = useGetOrgAuditLogSettings(currentOrg.id);
+ const { data: settings, isPending, isError } = useGetOrgAuditLogSettings(currentOrg.id);
const { mutateAsync: updateSettings, isPending: isSaving } = useUpdateOrgAuditLogSettings(
currentOrg.id
);
@@ -28,8 +28,10 @@ export const AuditLogSettingsTab = withPermission(
description="Choose which classes of organization-level events are recorded. Each project has its own setting for its events."
settings={settings}
isPending={isPending}
+ isError={isError}
isSaving={isSaving}
canEdit={canEdit}
+ readOnlyMessage={`Only ${scopeVariant === "sub-org" ? "sub-organization" : "organization"} admins can change these settings.`}
variant={scopeVariant}
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 f9903f7884..80443007db 100644
--- a/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx
+++ b/frontend/src/pages/project/SettingsPage/components/AuditLogEventClassesSection/AuditLogEventClassesSection.tsx
@@ -1,14 +1,19 @@
import { AuditLogEventClassesForm } from "@app/components/auditLogSettings";
-import { useProject, useProjectPermission } from "@app/context";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionSub,
+ useProject,
+ useProjectPermission
+} from "@app/context";
import { useGetProjectAuditLogSettings, useUpdateProjectAuditLogSettings } from "@app/hooks/api";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-export const AuditLogEventClassesSection = () => {
+const AuditLogEventClassesSectionContent = () => {
const { currentProject } = useProject();
const { hasProjectRole } = useProjectPermission();
const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);
- const { data: settings, isPending } = useGetProjectAuditLogSettings(currentProject.id);
+ const { data: settings, isPending, isError } = useGetProjectAuditLogSettings(currentProject.id);
const { mutateAsync: updateSettings, isPending: isSaving } = useUpdateProjectAuditLogSettings();
return (
@@ -19,10 +24,18 @@ export const AuditLogEventClassesSection = () => {
description="Choose which classes of events this project records."
settings={settings}
isPending={isPending}
+ isError={isError}
isSaving={isSaving}
canEdit={isAdmin}
+ readOnlyMessage="Only project admins can change these settings."
variant="project"
onSave={(eventClasses) => updateSettings({ projectId: currentProject.id, eventClasses })}
/>
);
};
+
+export const AuditLogEventClassesSection = () => {
+ const { permission } = useProjectPermission();
+ if (!permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Settings)) return null;
+ return <AuditLogEventClassesSectionContent />;
+};