Skip to content

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

fix: change the api to receive an array instead of filtered events

adilson084d5aed915b
diff --git a/backend/src/db/migrations/20260409120000_add-webhook-event-toggles.ts b/backend/src/db/migrations/20260409120000_add-webhook-event-toggles.ts
index 827adcdda8..f6fcae8223 100644
--- a/backend/src/db/migrations/20260409120000_add-webhook-event-toggles.ts
+++ b/backend/src/db/migrations/20260409120000_add-webhook-event-toggles.ts
@@ -2,17 +2,17 @@ import { Knex } from "knex";
import { TableName } from "../schemas";
-const BLOCKED_EVENTS_COLUMN = "blockedEvents";
+const FILTERED_EVENTS_COLUMN = "filteredEvents";
export async function up(knex: Knex): Promise<void> {
const hasWebhookTable = await knex.schema.hasTable(TableName.Webhook);
if (!hasWebhookTable) return;
- const hasBlockedEventsColumn = await knex.schema.hasColumn(TableName.Webhook, BLOCKED_EVENTS_COLUMN);
+ const hasFilteredEventsColumn = await knex.schema.hasColumn(TableName.Webhook, FILTERED_EVENTS_COLUMN);
await knex.schema.alterTable(TableName.Webhook, (table) => {
- if (!hasBlockedEventsColumn) {
- table.specificType(BLOCKED_EVENTS_COLUMN, "text[]").nullable();
+ if (!hasFilteredEventsColumn) {
+ table.specificType(FILTERED_EVENTS_COLUMN, "text[]").nullable();
}
});
}
@@ -21,11 +21,11 @@ export async function down(knex: Knex): Promise<void> {
const hasWebhookTable = await knex.schema.hasTable(TableName.Webhook);
if (!hasWebhookTable) return;
- const hasBlockedEventsColumn = await knex.schema.hasColumn(TableName.Webhook, BLOCKED_EVENTS_COLUMN);
+ const hasFilteredEventsColumn = await knex.schema.hasColumn(TableName.Webhook, FILTERED_EVENTS_COLUMN);
await knex.schema.alterTable(TableName.Webhook, (table) => {
- if (hasBlockedEventsColumn) {
- table.dropColumn(BLOCKED_EVENTS_COLUMN);
+ if (hasFilteredEventsColumn) {
+ table.dropColumn(FILTERED_EVENTS_COLUMN);
}
});
}
diff --git a/backend/src/db/schemas/webhooks.ts b/backend/src/db/schemas/webhooks.ts
index af30b4a090..1d603e1012 100644
--- a/backend/src/db/schemas/webhooks.ts
+++ b/backend/src/db/schemas/webhooks.ts
@@ -30,7 +30,7 @@ export const WebhooksSchema = z.object({
type: z.string().default("general").nullable().optional(),
encryptedPassKey: zodBuffer.nullable().optional(),
encryptedUrl: zodBuffer,
- blockedEvents: z.string().array().nullable().optional()
+ filteredEvents: z.string().array().nullable().optional()
});
export type TWebhooks = z.infer<typeof WebhooksSchema>;
diff --git a/backend/src/server/routes/v1/webhook-router.ts b/backend/src/server/routes/v1/webhook-router.ts
index cc219da32a..ebf465100e 100644
--- a/backend/src/server/routes/v1/webhook-router.ts
+++ b/backend/src/server/routes/v1/webhook-router.ts
@@ -8,7 +8,7 @@ import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
-import { WebhookType } from "@app/services/webhook/webhook-types";
+import { WebhookEvents, WebhookType } from "@app/services/webhook/webhook-types";
export const sanitizedWebhookSchema = WebhooksSchema.pick({
id: true,
@@ -27,8 +27,11 @@ export const sanitizedWebhookSchema = WebhooksSchema.pick({
name: z.string(),
slug: z.string()
}),
- isSecretModifiedEventEnabled: z.boolean(),
- isSecretRotationFailedEventEnabled: z.boolean()
+ eventsFilter: z.array(
+ z.object({
+ eventName: z.enum([WebhookEvents.SecretModified, WebhookEvents.SecretRotationFailed])
+ })
+ )
});
export const registerWebhookRouter = async (server: FastifyZodProvider) => {
@@ -49,8 +52,13 @@ export const registerWebhookRouter = async (server: FastifyZodProvider) => {
webhookUrl: z.string().url().trim(),
webhookSecretKey: z.string().trim().optional(),
secretPath: z.string().trim().default("/").transform(removeTrailingSlash),
- isSecretModifiedEventEnabled: z.boolean().default(true),
- isSecretRotationFailedEventEnabled: z.boolean().default(true)
+ eventsFilter: z
+ .array(
+ z.object({
+ eventName: z.enum([WebhookEvents.SecretModified, WebhookEvents.SecretRotationFailed])
+ })
+ )
+ .optional()
})
.superRefine((data, ctx) => {
if (data.type === WebhookType.SLACK && !data.webhookUrl.includes("hooks.slack.com")) {
@@ -122,15 +130,16 @@ export const registerWebhookRouter = async (server: FastifyZodProvider) => {
body: z
.object({
isDisabled: z.boolean().optional(),
- isSecretModifiedEventEnabled: z.boolean().optional(),
- isSecretRotationFailedEventEnabled: z.boolean().optional()
+ eventsFilter: z
+ .array(
+ z.object({
+ eventName: z.enum([WebhookEvents.SecretModified, WebhookEvents.SecretRotationFailed])
+ })
+ )
+ .optional()
})
- .refine(({ isDisabled, isSecretModifiedEventEnabled, isSecretRotationFailedEventEnabled }) => {
- return (
- isDisabled !== undefined ||
- isSecretModifiedEventEnabled !== undefined ||
- isSecretRotationFailedEventEnabled !== undefined
- );
+ .refine(({ isDisabled, eventsFilter }) => {
+ return isDisabled !== undefined || eventsFilter !== undefined;
}, "At least one field is required"),
response: {
200: z.object({
@@ -147,8 +156,7 @@ export const registerWebhookRouter = async (server: FastifyZodProvider) => {
actorOrgId: req.permission.orgId,
id: req.params.webhookId,
isDisabled: req.body.isDisabled,
- isSecretModifiedEventEnabled: req.body.isSecretModifiedEventEnabled,
- isSecretRotationFailedEventEnabled: req.body.isSecretRotationFailedEventEnabled
+ eventsFilter: req.body.eventsFilter
});
await server.services.auditLog.createAuditLog({
diff --git a/backend/src/services/webhook/webhook-fns.ts b/backend/src/services/webhook/webhook-fns.ts
index 632e4505e5..61b8136a90 100644
--- a/backend/src/services/webhook/webhook-fns.ts
+++ b/backend/src/services/webhook/webhook-fns.ts
@@ -292,8 +292,8 @@ export const fnTriggerWebhook = async ({
auditLogService
}: TFnTriggerWebhookDTO) => {
const webhooks = await webhookDAL.findAllWebhooks(projectId, environment);
- const toBeTriggeredHooks = webhooks.filter(({ secretPath: hookSecretPath, isDisabled, blockedEvents }) => {
- const isEventSubscribed = !blockedEvents || blockedEvents.length === 0 || !blockedEvents.includes(event.type);
+ const toBeTriggeredHooks = webhooks.filter(({ secretPath: hookSecretPath, isDisabled, filteredEvents }) => {
+ const isEventSubscribed = !filteredEvents || filteredEvents.length === 0 || !filteredEvents.includes(event.type);
return !isDisabled && picomatch.isMatch(secretPath, hookSecretPath, { strictSlashes: false }) && isEventSubscribed;
});
diff --git a/backend/src/services/webhook/webhook-service.ts b/backend/src/services/webhook/webhook-service.ts
index 13d70cd2d2..48d5195d2e 100644
--- a/backend/src/services/webhook/webhook-service.ts
+++ b/backend/src/services/webhook/webhook-service.ts
@@ -38,20 +38,12 @@ export const webhookServiceFactory = ({
projectDAL,
kmsService
}: TWebhookServiceFactoryDep) => {
- const toBlockedEvents = (
- isSecretModifiedEventEnabled?: boolean,
- isSecretRotationFailedEventEnabled?: boolean
- ): string[] => {
- const blocked: string[] = [];
- if (isSecretModifiedEventEnabled === false) blocked.push(WebhookEvents.SecretModified);
- if (isSecretRotationFailedEventEnabled === false) blocked.push(WebhookEvents.SecretRotationFailed);
- return blocked;
- };
-
- const withEventFlags = <T extends { blockedEvents?: string[] | null }>(webhook: T) => ({
+ // `eventsFilter` on the API mirrors the DB's `filteredEvents` column: both are the blocklist
+ // of events that should NOT trigger the webhook. Empty array => no events are filtered out
+ // (webhook fires on everything subscribable).
+ const withEventsFilter = <T extends { filteredEvents?: string[] | null }>(webhook: T) => ({
...webhook,
- isSecretModifiedEventEnabled: !webhook.blockedEvents?.includes(WebhookEvents.SecretModified),
- isSecretRotationFailedEventEnabled: !webhook.blockedEvents?.includes(WebhookEvents.SecretRotationFailed)
+ eventsFilter: (webhook.filteredEvents ?? []).map((eventName) => ({ eventName }))
});
const createWebhook = async ({
@@ -65,8 +57,7 @@ export const webhookServiceFactory = ({
secretPath,
webhookSecretKey,
type,
- isSecretModifiedEventEnabled,
- isSecretRotationFailedEventEnabled
+ eventsFilter
}: TCreateWebhookDTO) => {
const { permission } = await permissionService.getProjectPermission({
actor,
@@ -89,7 +80,7 @@ export const webhookServiceFactory = ({
projectId
});
- const blockedEvents = toBlockedEvents(isSecretModifiedEventEnabled, isSecretRotationFailedEventEnabled);
+ const filteredEvents = eventsFilter?.map((e) => e.eventName) ?? [];
const insertDoc: TWebhooksInsert = {
envId: env.id,
@@ -97,7 +88,7 @@ export const webhookServiceFactory = ({
secretPath: secretPath || "/",
type,
encryptedUrl: secretManagerEncryptor({ plainText: Buffer.from(webhookUrl) }).cipherTextBlob,
- blockedEvents
+ filteredEvents
};
if (webhookSecretKey) {
@@ -105,7 +96,7 @@ export const webhookServiceFactory = ({
}
const webhook = await webhookDAL.create(insertDoc);
- return { ...withEventFlags(webhook), projectId, environment: env };
+ return { ...withEventsFilter(webhook), projectId, environment: env };
};
const updateWebhook = async ({
@@ -115,8 +106,7 @@ export const webhookServiceFactory = ({
actorAuthMethod,
id,
isDisabled,
- isSecretModifiedEventEnabled,
- isSecretRotationFailedEventEnabled
+ eventsFilter
}: TUpdateWebhookDTO) => {
const webhook = await webhookDAL.findById(id);
if (!webhook) throw new NotFoundError({ message: `Webhook with ID '${id}' not found` });
@@ -131,39 +121,15 @@ export const webhookServiceFactory = ({
});
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Webhooks);
- const hasEventToggleUpdate =
- isSecretModifiedEventEnabled !== undefined || isSecretRotationFailedEventEnabled !== undefined;
-
- let blockedEvents: string[] | undefined;
- if (hasEventToggleUpdate) {
- const currentBlocked = new Set<string>(webhook.blockedEvents ?? []);
-
- if (isSecretModifiedEventEnabled !== undefined) {
- if (isSecretModifiedEventEnabled) {
- currentBlocked.delete(WebhookEvents.SecretModified);
- } else {
- currentBlocked.add(WebhookEvents.SecretModified);
- }
- }
-
- if (isSecretRotationFailedEventEnabled !== undefined) {
- if (isSecretRotationFailedEventEnabled) {
- currentBlocked.delete(WebhookEvents.SecretRotationFailed);
- } else {
- currentBlocked.add(WebhookEvents.SecretRotationFailed);
- }
- }
-
- blockedEvents = Array.from(currentBlocked);
- }
+ const filteredEvents = eventsFilter?.map((e) => e.eventName);
const updateData = {
...(isDisabled !== undefined ? { isDisabled } : {}),
- ...(blockedEvents !== undefined ? { blockedEvents } : {})
+ ...(filteredEvents !== undefined ? { filteredEvents } : {})
};
const updatedWebhook = await webhookDAL.updateById(id, updateData);
- return withEventFlags({ ...webhook, ...updatedWebhook });
+ return withEventsFilter({ ...webhook, ...updatedWebhook });
};
const deleteWebhook = async ({ id, actor, actorId, actorAuthMethod, actorOrgId }: TDeleteWebhookDTO) => {
@@ -181,7 +147,7 @@ export const webhookServiceFactory = ({
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Delete, ProjectPermissionSub.Webhooks);
const deletedWebhook = await webhookDAL.deleteById(id);
- return withEventFlags({ ...webhook, ...deletedWebhook });
+ return withEventsFilter({ ...webhook, ...deletedWebhook });
};
const testWebhook = async ({ id, actor, actorId, actorAuthMethod, actorOrgId }: TTestWebhookDTO) => {
@@ -232,7 +198,7 @@ export const webhookServiceFactory = ({
lastStatus: isSuccess ? "success" : "failed",
lastRunErrorMessage: isSuccess ? null : webhookError
});
- return withEventFlags({ ...webhook, ...updatedWebhook });
+ return withEventsFilter({ ...webhook, ...updatedWebhook });
};
const listWebhooks = async ({
@@ -263,7 +229,7 @@ export const webhookServiceFactory = ({
return webhooks.map((w) => {
const { url } = decryptWebhookDetails(w, (value) => secretManagerDecryptor({ cipherTextBlob: value }).toString());
return {
- ...withEventFlags(w),
+ ...withEventsFilter(w),
url
};
});
diff --git a/backend/src/services/webhook/webhook-types.ts b/backend/src/services/webhook/webhook-types.ts
index 5e9ede3723..16ccdc44e7 100644
--- a/backend/src/services/webhook/webhook-types.ts
+++ b/backend/src/services/webhook/webhook-types.ts
@@ -8,15 +8,13 @@ export type TCreateWebhookDTO = {
webhookUrl: string;
webhookSecretKey?: string;
type: string;
- isSecretModifiedEventEnabled?: boolean;
- isSecretRotationFailedEventEnabled?: boolean;
+ eventsFilter?: { eventName: TSubscribableWebhookEvent }[];
} & TProjectPermission;
export type TUpdateWebhookDTO = {
id: string;
isDisabled?: boolean;
- isSecretModifiedEventEnabled?: boolean;
- isSecretRotationFailedEventEnabled?: boolean;
+ eventsFilter?: { eventName: TSubscribableWebhookEvent }[];
} & Omit<TProjectPermission, "projectId">;
export type TTestWebhookDTO = {
@@ -44,6 +42,10 @@ export enum WebhookEvents {
TestEvent = "test"
}
+export const SUBSCRIBABLE_WEBHOOK_EVENTS = [WebhookEvents.SecretModified, WebhookEvents.SecretRotationFailed] as const;
+
+export type TSubscribableWebhookEvent = (typeof SUBSCRIBABLE_WEBHOOK_EVENTS)[number];
+
type TWebhookSecretModifiedEventPayload = {
type: WebhookEvents.SecretModified;
payload: {
diff --git a/docs/documentation/platform/webhooks.mdx b/docs/documentation/platform/webhooks.mdx
index f987861cdd..6153495322 100644
--- a/docs/documentation/platform/webhooks.mdx
+++ b/docs/documentation/platform/webhooks.mdx
@@ -23,6 +23,15 @@ The header will be in the format `t=<timestamp>;<signature>`. You can then gener
If the signature in the header matches the signature that you generated, then you can be sure that the request was sent by Infisical and is intended for your integration. The timestamp in the header ensures that the request is not replayed.
+## Event Filtering
+
+By default, webhooks trigger on every supported event. You can narrow this down under **Advanced Settings** when creating a webhook, and only receive the events you care about. You can also change the events on existing webhooks by clicking **Edit** and selecting the events you want.
+
+Supported events:
+
+- **Secret Modified** (`secrets.modified`) — triggered when secrets in the configured scope are created, updated, or deleted.
+- **Secret Rotation Failed** (`secrets.rotation-failed`) — triggered when a secret rotation in the configured scope fails.
+
### Webhook Payload Format
```json
diff --git a/frontend/src/hooks/api/webhooks/mutation.tsx b/frontend/src/hooks/api/webhooks/mutation.tsx
index 277a748d12..4eed0b23fb 100644
--- a/frontend/src/hooks/api/webhooks/mutation.tsx
+++ b/frontend/src/hooks/api/webhooks/mutation.tsx
@@ -3,7 +3,13 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { queryKeys } from "./query";
-import { TCreateWebhookDto, TDeleteWebhookDto, TTestWebhookDTO, TUpdateWebhookDto } from "./types";
+import {
+ TCreateWebhookDto,
+ TDeleteWebhookDto,
+ TTestWebhookDTO,
+ TUpdateWebhookDto,
+ WebhookEvent
+} from "./types";
export const useCreateWebhook = () => {
const queryClient = useQueryClient();
@@ -43,20 +49,15 @@ export const useUpdateWebhook = () => {
mutationFn: async (dto) => {
const payload: {
isDisabled?: boolean;
- isSecretModifiedEventEnabled?: boolean;
- isSecretRotationFailedEventEnabled?: boolean;
+ eventsFilter?: { eventName: WebhookEvent }[];
} = {};
if (dto.isDisabled !== undefined) {
payload.isDisabled = dto.isDisabled;
}
- if (dto.isSecretModifiedEventEnabled !== undefined) {
- payload.isSecretModifiedEventEnabled = dto.isSecretModifiedEventEnabled;
- }
-
- if (dto.isSecretRotationFailedEventEnabled !== undefined) {
- payload.isSecretRotationFailedEventEnabled = dto.isSecretRotationFailedEventEnabled;
+ if (dto.eventsFilter !== undefined) {
+ payload.eventsFilter = dto.eventsFilter;
}
const { data } = await apiRequest.patch(`/api/v1/webhooks/${dto.webhookId}`, {
diff --git a/frontend/src/hooks/api/webhooks/types.ts b/frontend/src/hooks/api/webhooks/types.ts
index cb3958d2ce..98c8d2e6ca 100644
--- a/frontend/src/hooks/api/webhooks/types.ts
+++ b/frontend/src/hooks/api/webhooks/types.ts
@@ -9,13 +9,7 @@ export enum WebhookEvent {
SecretRotationFailed = "secrets.rotation-failed"
}
-export type TWebhookEventToggleKey = Exclude<
- keyof TUpdateWebhookDto,
- "webhookId" | "projectId" | "isDisabled"
->;
-
export type TWebhookEventMetadata = {
- key: TWebhookEventToggleKey;
label: string;
description: string;
};
@@ -24,12 +18,10 @@ export const WEBHOOK_EVENTS = Object.values(WebhookEvent) as WebhookEvent[];
export const WEBHOOK_EVENT_METADATA: Record<WebhookEvent, TWebhookEventMetadata> = {
[WebhookEvent.SecretRotationFailed]: {
- key: "isSecretRotationFailedEventEnabled",
label: "Secret Rotation Failed",
description: "Triggered when a secret rotation fails"
},
[WebhookEvent.SecretModified]: {
- key: "isSecretModifiedEventEnabled",
label: "Secret Modified",
description: "Triggered when secrets are modified"
}
@@ -50,8 +42,7 @@ export type TWebhook = {
lastStatus: "success" | "failed";
lastRunErrorMessage?: string;
isDisabled: boolean;
- isSecretModifiedEventEnabled: boolean;
- isSecretRotationFailedEventEnabled: boolean;
+ eventsFilter: { eventName: WebhookEvent }[];
createdAt: string;
updatedAt: string;
};
@@ -63,16 +54,14 @@ export type TCreateWebhookDto = {
webhookSecretKey?: string;
secretPath: string;
type: WebhookType;
- isSecretModifiedEventEnabled?: boolean;
- isSecretRotationFailedEventEnabled?: boolean;
+ eventsFilter?: { eventName: WebhookEvent }[];
};
export type TUpdateWebhookDto = {
webhookId: string;
projectId: string;
isDisabled?: boolean;
- isSecretModifiedEventEnabled?: boolean;
- isSecretRotationFailedEventEnabled?: boolean;
+ eventsFilter?: { eventName: WebhookEvent }[];
};
export type TDeleteWebhookDto = {
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/AddWebhookForm.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/AddWebhookForm.tsx
index 3122c7ef66..19b402eb78 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/AddWebhookForm.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/AddWebhookForm.tsx
@@ -19,9 +19,9 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import {
- TWebhookEventToggleKey,
WEBHOOK_EVENT_METADATA,
WEBHOOK_EVENTS,
+ WebhookEvent,
WebhookType
} from "@app/hooks/api/webhooks/types";
@@ -32,8 +32,10 @@ const formSchema = z
webhookSecretKey: z.string().trim().optional().describe("Secret Key"),
secretPath: z.string().trim().describe("Secret Path"),
type: z.nativeEnum(WebhookType).describe("Type").default(WebhookType.GENERAL),
- isSecretModifiedEventEnabled: z.boolean().default(true),
- isSecretRotationFailedEventEnabled: z.boolean().default(true)
+ enabledEvents: z.record(z.nativeEnum(WebhookEvent), z.boolean()).default({
+ [WebhookEvent.SecretModified]: true,
+ [WebhookEvent.SecretRotationFailed]: true
+ })
})
.superRefine((data, ctx) => {
if (data.type === WebhookType.SLACK && !data.webhookUrl.includes("hooks.slack.com")) {
@@ -71,8 +73,10 @@ export const AddWebhookForm = ({
resolver: zodResolver(formSchema),
defaultValues: {
type: WebhookType.GENERAL,
- isSecretModifiedEventEnabled: true,
- isSecretRotationFailedEventEnabled: true
+ enabledEvents: {
+ [WebhookEvent.SecretModified]: true,
+ [WebhookEvent.SecretRotationFailed]: true
+ }
}
});
@@ -140,8 +144,10 @@ export const AddWebhookForm = ({
if (!isOpen) {
reset({
type: WebhookType.GENERAL,
- isSecretModifiedEventEnabled: true,
- isSecretRotationFailedEventEnabled: true,
+ enabledEvents: {
+ [WebhookEvent.SecretModified]: true,
+ [WebhookEvent.SecretRotationFailed]: true
+ },
environment: environments?.[0]?.slug,
secretPath: ""
});
@@ -227,7 +233,7 @@ export const AddWebhookForm = ({
</FormControl>
)}
/>
- {selectedWebhookType === WebhookType.SLACK ? slackFormFields : generalFormFields}
+ {renderFormFields()}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="advanced-settings" className="data-[state=open]:border-none">
<AccordionTrigger className="h-fit flex-none pl-1 text-sm">
@@ -237,30 +243,33 @@ export const AddWebhookForm = ({
<p className="mb-4 text-sm text-mineshaft-400">
Select which events will trigger this webhook
</p>
- <div className="space-y-4">
- {WEBHOOK_EVENTS.map((event) => {
- const { key, label, description } = WEBHOOK_EVENT_METADATA[event];
+ <Controller
+ control={control}
+ name="enabledEvents"
+ render={({ field: { value, onChange } }) => (
+ <div className="space-y-4">
+ {WEBHOOK_EVENTS.map((event) => {
+ const { label, description } = WEBHOOK_EVENT_METADATA[event];
+ const isChecked = value?.[event] ?? true;
- return (
- <Controller
- key={event}
- control={control}
- name={key as TWebhookEventToggleKey}
- render={({ field: { value, onChange } }) => (
+ return (
<Checkbox
+ key={event}
id={`webhook-event-${event}`}
- isChecked={value}
- onCheckedChange={(checked) => onChange(checked === true)}
+ isChecked={isChecked}
+ onCheckedChange={(checked) =>
+ onChange({ ...value, [event]: checked === true })
+ }
allowMultilineLabel
>
<p className="font-medium text-mineshaft-50">{label}</p>
<p className="text-mineshaft-400">{description}</p>
</Checkbox>
- )}
- />
- );
- })}
- </div>
+ );
+ })}
+ </div>
+ )}
+ />
</AccordionContent>
</AccordionItem>
</Accordion>
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/EditWebhookEventsModal.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/EditWebhookEventsModal.tsx
index 16d33fff81..c25cddb01f 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/EditWebhookEventsModal.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/EditWebhookEventsModal.tsx
@@ -3,12 +3,12 @@ import { FormEvent, useEffect, useMemo, useState } from "react";
import { Button, Checkbox, Modal, ModalContent } from "@app/components/v2";
import {
TWebhook,
- TWebhookEventToggleKey,
WEBHOOK_EVENT_METADATA,
- WEBHOOK_EVENTS
+ WEBHOOK_EVENTS,
+ WebhookEvent
} from "@app/hooks/api/webhooks/types";
-type TWebhookEventSettings = Record<TWebhookEventToggleKey, boolean>;
+type TWebhookEventSettings = Record<WebhookEvent, boolean>;
type Props = {
isOpen?: boolean;
webhook?: TWebhook;
@@ -24,8 +24,11 @@ export const EditWebhookEventsModal = ({
onOpenChange,
onSave
}: Props) => {
- const defaultSettings = useMemo(
- () => ({ isSecretModifiedEventEnabled: true, isSecretRotationFailedEventEnabled: true }),
+ const defaultSettings = useMemo<TWebhookEventSettings>(
+ () => ({
+ [WebhookEvent.SecretModified]: true,
+ [WebhookEvent.SecretRotationFailed]: true
+ }),
[]
);
const [eventSettings, setEventSettings] = useState<TWebhookEventSettings>(defaultSettings);
@@ -38,19 +41,20 @@ export const EditWebhookEventsModal = ({
return;
}
+ // eventsFilter is the blocklist — an event is enabled when it is NOT in the filter.
+ const filteredEventNames = new Set(webhook.eventsFilter.map((e) => e.eventName));
setEventSettings(
WEBHOOK_EVENTS.reduce<TWebhookEventSettings>((acc, event) => {
- const { key } = WEBHOOK_EVENT_METADATA[event];
- acc[key] = webhook[key] ?? true;
+ acc[event] = !filteredEventNames.has(event);
return acc;
}, {} as TWebhookEventSettings)
);
}, [isOpen, webhook, defaultSettings]);
- const handleToggle = (key: TWebhookEventToggleKey, isEnabled: boolean) => {
+ const handleToggle = (event: WebhookEvent, isEnabled: boolean) => {
setEventSettings((curr) => ({
...curr,
- [key]: isEnabled
+ [event]: isEnabled
}));
};
@@ -68,14 +72,14 @@ export const EditWebhookEventsModal = ({
<form onSubmit={handleSave}>
<div className="space-y-4">
{WEBHOOK_EVENTS.map((event) => {
- const { key, label, description } = WEBHOOK_EVENT_METADATA[event];
+ const { label, description } = WEBHOOK_EVENT_METADATA[event];
return (
<Checkbox
key={event}
id={`webhook-event-${event}`}
- isChecked={eventSettings[key]}
- onCheckedChange={(checked) => handleToggle(key, checked === true)}
+ isChecked={eventSettings[event]}
+ onCheckedChange={(checked) => handleToggle(event, checked === true)}
allowMultilineLabel
>
<p className="font-medium text-mineshaft-50">{label}</p>
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/WebhooksTab.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/WebhooksTab.tsx
index 87004df825..6572f91294 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/WebhooksTab.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/WebhooksTab.tsx
@@ -29,7 +29,12 @@ import {
useTestWebhook,
useUpdateWebhook
} from "@app/hooks/api";
-import { TWebhook, WEBHOOK_EVENT_METADATA, WEBHOOK_EVENTS } from "@app/hooks/api/webhooks/types";
+import {
+ TWebhook,
+ WEBHOOK_EVENT_METADATA,
+ WEBHOOK_EVENTS,
+ WebhookEvent
+} from "@app/hooks/api/webhooks/types";
import { AddWebhookForm, TFormSchema } from "./AddWebhookForm";
import { EditWebhookEventsModal } from "./EditWebhookEventsModal";
@@ -63,8 +68,14 @@ export const WebhooksTab = withProjectPermission(
const { mutateAsync: deleteWebhook } = useDeleteWebhook();
const handleWebhookCreate = async (data: TFormSchema) => {
+ // eventsFilter is the blocklist of events to filter OUT
+ const eventsFilter = WEBHOOK_EVENTS.filter((event) => !data.enabledEvents[event]).map(
+ (event) => ({ eventName: event })
+ );
+
await createWebhook({
...data,
+ eventsFilter,
projectId
});
handlePopUpClose("addWebhook");
@@ -88,15 +99,17 @@ export const WebhooksTab = withProjectPermission(
const handleWebhookEventsUpdate = async (
webhookId: string,
- settings: {
- isSecretModifiedEventEnabled: boolean;
- isSecretRotationFailedEventEnabled: boolean;
- }
+ settings: Record<WebhookEvent, boolean>
) => {
+ // eventsFilter is the blocklist — every unchecked event goes in.
+ const eventsFilter = WEBHOOK_EVENTS.filter((event) => !settings[event]).map((event) => ({
+ eventName: event
+ }));
+
await updateWebhook({
webhookId,
projectId,
- ...settings
+ eventsFilter
});
handlePopUpClose("editWebhook");
createNotification({
@@ -195,9 +208,8 @@ export const WebhooksTab = withProjectPermission(
lastRunErrorMessage
} = webhook;
- const enabledEvents = WEBHOOK_EVENTS.filter(
- (event) => webhook[WEBHOOK_EVENT_METADATA[event].key] !== false
- );
+ const filteredSet = new Set(webhook.eventsFilter.map((e) => e.eventName));
+ const enabledEvents = WEBHOOK_EVENTS.filter((event) => !filteredSet.has(event));
const enabledEventsCount = enabledEvents.length;
const hasEnabledEvents = enabledEventsCount > 0;