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
Merge remote-tracking branch 'origin/main' into feat/secret-reminder-alerts-ui
Calvin4802afabb375
diff --cc backend/src/server/routes/index.tsindex b7e2f0119c,b90c1c5a21..7351e3d609--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@@ -251,12 -251,13 +251,15 @@@ import { alertProviderRegistryFactoryimport { alertQueueServiceFactory } from "@app/services/alert/alert-queue";import { alertRecipientResolverFactory } from "@app/services/alert/alert-recipient-resolver";import { alertServiceFactory } from "@app/services/alert/alert-service";- import { certManagerApplicationAlertDALFactory } from "@app/services/alert/providers/cert-manager-application-alert-dal";+ import { certManagerAlertProviderFactory } from "@app/services/alert/providers/cert-manager-alert-provider";import { certManagerApplicationAlertProviderFactory } from "@app/services/alert/providers/cert-manager-application-alert-provider";+ import { certManagerCertificateAlertDALFactory } from "@app/services/alert/providers/cert-manager-certificate-alert-dal";+ import { certManagerSignerAlertDALFactory } from "@app/services/alert/providers/cert-manager-signer-alert-dal";+ import { certManagerSignerAlertProviderFactory } from "@app/services/alert/providers/cert-manager-signer-alert-provider";import { identityCredentialAlertDALFactory } from "@app/services/alert/providers/identity-credential-alert-dal";import { identityCredentialAlertProviderFactory } from "@app/services/alert/providers/identity-credential-alert-provider";+import { secretReminderAlertDALFactory } from "@app/services/alert/providers/secret-reminder-alert-dal";+import { secretReminderAlertProviderFactory } from "@app/services/alert/providers/secret-reminder-alert-provider";import { announcementServiceFactory } from "@app/services/announcement/announcement-service";import { appConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { appConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";@@@ -1097,16 -1104,9 +1104,16 @@@ export const registerRoutes = asyncpermissionService}));+ alertProviderRegistry.register(+ secretReminderAlertProviderFactory({+ secretReminderAlertDAL: secretReminderAlertDALFactory(db),+ folderDAL,+ permissionService+ })+ );alertProviderRegistry.register(certManagerApplicationAlertProviderFactory({- certManagerApplicationAlertDAL,+ certManagerCertificateAlertDAL,permissionService,licenseService})diff --cc backend/src/services/alert/alert-service.test.tsindex 555001ca5c,85ca801107..43e511abda--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@@ -33,9 -30,12 +33,10 @@@ const buildService = (opts?:assertPermission?: (input: TAlertPermissionInput) => Promise<void>;resourceScopeThrows?: boolean;duplicateExists?: boolean;+ createError?: Error;resolvedProjectId?: string;+ supportsScopeWideAlerts?: boolean;atOrgScope?: boolean;- // Runs right after a find() has taken its snapshot, to stand in for a concurrent transaction- // committing between two statements of ours.- afterFindAlerts?: (alerts: Map<string, Record<string, unknown>>) => void;}) => {const permissionCalls: TAlertPermissionInput[] = [];const gatedChannelTypeCalls: string[][] = [];@@@ -461,6 -485,37 +502,26 @@@ describe("alert service", () =>);});+ const listBase = {+ resourceType: RESOURCE_TYPE,+ resourceId: null,+ eventType: "test.resource.expiration",+ condition: null,+ enabled: true,+ orgId: "org-1",+ createdAt: new Date(),+ updatedAt: new Date()+ };+- test("org-scoped list returns only org-level alerts, never other projects'", async () => {- const { service, alerts, findFilters } = buildService();- alerts.set("org-alert", { id: "org-alert", name: "org", projectId: null, ...listBase });- alerts.set("proj-alert", { id: "proj-alert", name: "proj", projectId: "proj-x", ...listBase });-- const result = await service.listAlerts({ resourceType: RESOURCE_TYPE, ...actor });-- expect(result.map((a) => a.id)).toEqual(["org-alert"]);- expect(findFilters[0]).toMatchObject({ projectId: null });- });-+ test("listing without a resource returns only resource-less alerts when the provider supports them", async () => {+ const { service, alerts } = buildService({ supportsScopeWideAlerts: true });+ alerts.set("bound", { id: "bound", name: "bound", projectId: "proj-x", ...listBase, resourceId: "resource-1" });+ alerts.set("scope-wide", { id: "scope-wide", name: "scope-wide", projectId: "proj-x", ...listBase });++ const listed = await service.listAlerts({ resourceType: RESOURCE_TYPE, projectId: "proj-x", ...actor });+ expect(listed.map((alert) => alert.id)).toEqual(["scope-wide"]);+ });+test("create and list resolve the project from the resource when projectId is omitted", async () => {const { service, permissionCalls, findFilters } = buildService({ resolvedProjectId: "proj-resolved" });@@@ -506,105 -595,279 +567,132 @@@expect(gatedChannelTypeCalls.at(-1)).toEqual([]);});+ test("update gates a disabled channel being enabled again", async () => {+ const { service, gatedChannelTypeCalls } = buildService();+ const created = await service.createAlert(validCreate);+ const email = created.channels.find((c) => c.channelType === AlertChannelType.EMAIL)!;+ const webhook = created.channels.find((c) => c.channelType === AlertChannelType.WEBHOOK)!;++ await service.updateAlert({+ alertId: "alert-1",+ channels: [+ { id: email.id, name: email.name, channelType: AlertChannelType.EMAIL, enabled: false },+ { id: webhook.id, name: webhook.name, channelType: AlertChannelType.WEBHOOK, enabled: false }+ ],+ ...actor+ });+ expect(gatedChannelTypeCalls.at(-1)).toEqual([]);++ await service.updateAlert({+ alertId: "alert-1",+ channels: [+ { id: email.id, name: email.name, channelType: AlertChannelType.EMAIL },+ { id: webhook.id, name: webhook.name, channelType: AlertChannelType.WEBHOOK, enabled: true }+ ],+ ...actor+ });+ expect(gatedChannelTypeCalls.at(-1)).toEqual([AlertChannelType.WEBHOOK]);+ });+- test("update rejects a channel id that does not belong to the alert", async () => {+ test("refuses more channels than an alert can hold", async () => {const { service } = buildService();- await service.createAlert(validCreate);- await expect(- service.updateAlert({- alertId: "alert-1",- channels: [{ id: "ch-foreign", name: "x", channelType: AlertChannelType.WEBHOOK }],- ...actor- })- ).rejects.toThrow(/does not belong to this alert/);- });-- test("update rejects an empty channel list", async () => {- const { service } = buildService();- await service.createAlert(validCreate);- await expect(service.updateAlert({ alertId: "alert-1", channels: [], ...actor })).rejects.toThrow(- "At least one channel is required"+ const channels = Array.from({ length: 11 }, (_, i) => ({+ name: `hook-${i}`,+ channelType: AlertChannelType.WEBHOOK,+ config: { url: `https://example.com/${i}` }+ }));+ await expect(service.createAlert({ ...validCreate, channels })).rejects.toThrow(+ "An alert can have at most 10 channels, and this would leave it with 11");- });- test("deletes an alert and its owned channels after checking Delete permission", async () => {- const { service, permissionCalls, alerts, channels } = buildService();await service.createAlert(validCreate);- expect(channels.size).toBe(2);-- const result = await service.deleteAlert({ alertId: "alert-1", ...actor });-- expect(result.id).toBe("alert-1");- expect(permissionCalls.some((c) => c.action === "delete")).toBe(true);- expect(alerts.size).toBe(0);- // Same reaping as deleteAlertsForResource: no channel is left dangling.- expect(channels.size).toBe(0);- });-- test("deleteAlertsForResource reaps a resource's alerts and their owned channels", async () => {- const { service, alerts, channels, memberships } = buildService();- await service.createAlert({ ...validCreate, resourceId: "ident-1" });- expect(alerts.size).toBe(1);- expect(channels.size).toBe(2);-- const deleted = await service.deleteAlertsForResource({- orgId: "org-1",- resourceType: RESOURCE_TYPE,- resourceId: "ident-1"- });-- expect(deleted).toBe(1);- expect(alerts.size).toBe(0);- // The alert's two inline channels are removed too, not left dangling.- expect(channels.size).toBe(0);- expect(memberships.get("alert-1") ?? []).toHaveLength(0);+ await expect(service.updateAlert({ alertId: "alert-1", channels, ...actor })).rejects.toThrow(+ "An alert can have at most 10 channels, and this would leave it with 11"+ );});- test("deleteAlertsForResource narrowed to a project spares the resource's org-scoped alerts", async () => {- const { service, alerts } = buildService();- await service.createAlert({ ...validCreate, resourceId: "ident-1" });- // A second alert on the same identity, this one bound to a project. Inserted directly because- // the fake create() always mints "alert-1".- alerts.set("alert-2", {- id: "alert-2",- orgId: "org-1",- projectId: "proj-1",+ describe("an alert a service keeps on its own resource", () => {+ const resourceAlert = (recipientIds: string[]) => ({resourceType: RESOURCE_TYPE,- resourceId: "ident-1",- eventType: "test.resource.expiration"- });-- // The identity only left proj-1, so its org-scoped alert must survive.- const deleted = await service.deleteAlertsForResource({- orgId: "org-1",+ resourceId: "resource-1",projectId: "proj-1",- resourceType: RESOURCE_TYPE,- resourceId: "ident-1"+ eventType: "test.resource.opened",+ name: "Resource alert",+ channels: {+ replaceRecipients: {+ channelType: AlertChannelType.EMAIL,+ recipients: recipientIds.map((principalId) => ({ principalType: AlertPrincipalType.USER, principalId }))+ }+ },+ ...actor});+ const tx = {} as never;- expect(deleted).toBe(1);- expect([...alerts.keys()]).toEqual(["alert-1"]);- });-- test("deleteAlertsForResource is a no-op when nothing matches", async () => {- const { service, alerts } = buildService();- await service.createAlert({ ...validCreate, resourceId: "ident-1" });+ test("is written only when applied", async () => {+ const { service, alerts, channels } = buildService();+ const prepared = await service.prepareAlertForResource(resourceAlert(["user-1"]));+ expect(alerts.size).toBe(0);+ expect(channels.size).toBe(0);- const deleted = await service.deleteAlertsForResource({- orgId: "org-1",- resourceType: RESOURCE_TYPE,- resourceId: "ident-other"+ await service.applyPreparedAlert(prepared, tx);+ expect(alerts.size).toBe(1);+ expect([...channels.values()].map((c) => c.name)).toEqual(["Email"]);});- expect(deleted).toBe(0);- expect(alerts.size).toBe(1);- });+ test("spreads recipients over as many email channels as they need", async () => {+ const { service, channels } = buildService();+ const recipientIds = Array.from({ length: 45 }, (_, i) => `user-${i}`);+ await service.applyPreparedAlert(await service.prepareAlertForResource(resourceAlert(recipientIds)), tx);- test("deleteAlertsForResource leaves the resource's alerts in other orgs alone", async () => {- const { service, alerts } = buildService();- await service.createAlert({ ...validCreate, resourceId: "ident-1" });- // The same identity watched from a second org it was invited into. Inserted directly because- // the fake create() always mints "alert-1".- alerts.set("alert-2", {- id: "alert-2",- orgId: "org-2",- projectId: null,- resourceType: RESOURCE_TYPE,- resourceId: "ident-1",- eventType: "test.resource.expiration"+ expect([...channels.values()].map((c) => [c.name, c.recipients.length])).toEqual([+ ["Email", 20],+ ["Email 2", 20],+ ["Email 3", 5]+ ]);});- const deleted = await service.deleteAlertsForResource({- orgId: "org-1",- resourceType: RESOURCE_TYPE,- resourceId: "ident-1"+ test("updates the existing alert, reusing its email channel and keeping its other channels", async () => {+ const { service, alerts, channels } = buildService();+ await service.createAlert({ ...validCreate, eventType: "test.resource.opened", condition: null });+ const [emailBefore, webhookBefore] = [...channels.values()];++ await service.applyPreparedAlert(await service.prepareAlertForResource(resourceAlert(["user-2"])), tx);++ expect(alerts.size).toBe(1);+ expect([...channels.values()]).toEqual([+ expect.objectContaining({+ id: emailBefore.id,+ name: "email-ch",+ recipients: [expect.objectContaining({ principalId: "user-2" })]+ }),+ expect.objectContaining({ id: webhookBefore.id, name: "webhook-ch" })+ ]);});-- expect(deleted).toBe(1);- expect([...alerts.keys()]).toEqual(["alert-2"]);});- test("deleteAlertsForDeletedResource reaps the resource's alerts in every org and project", async () => {- const { service, alerts, channels } = buildService();- await service.createAlert({ ...validCreate, resourceId: "ident-1" });- expect(channels.size).toBe(2);- // A root-org identity can be invited into a child org and watched from there, so a hard delete- // has to reach alerts outside the org that owns the identity.- alerts.set("alert-2", {- id: "alert-2",- orgId: "org-2",- projectId: null,- resourceType: RESOURCE_TYPE,- resourceId: "ident-1",- eventType: "test.resource.expiration"- });- alerts.set("alert-3", {- id: "alert-3",- orgId: "org-2",- projectId: "proj-1",- resourceType: RESOURCE_TYPE,- resourceId: "ident-1",- eventType: "test.resource.expiration"- });-- const deleted = await service.deleteAlertsForDeletedResource({- resourceType: RESOURCE_TYPE,- resourceId: "ident-1"- });-- expect(deleted).toBe(3);- expect(alerts.size).toBe(0);- expect(channels.size).toBe(0);- });-- test("deleteAlertsForDeletedResource reaps an alert created between the find and the delete", async () => {- let raced = false;- const { service, alerts, channels } = buildService({- afterFindAlerts: (rows) => {- if (raced) return;- raced = true;- // Another transaction created an alert on the same resource and committed after our find took- // its snapshot. Reaping by the ids the find returned would leave this row dangling, so the- // delete has to run off the resource filter instead.- rows.set("alert-race", {- id: "alert-race",- orgId: "org-1",- projectId: null,- resourceType: RESOURCE_TYPE,- resourceId: "ident-1",- eventType: "test.resource.expiration"- });- }- });- await service.createAlert({ ...validCreate, resourceId: "ident-1" });-- const deleted = await service.deleteAlertsForDeletedResource({- resourceType: RESOURCE_TYPE,- resourceId: "ident-1"- });-- expect(raced).toBe(true);- expect(deleted).toBe(2);- expect(alerts.size).toBe(0);- expect(channels.size).toBe(0);+ test("update rejects an empty channel list", async () => {+ const { service } = buildService();+ await service.createAlert(validCreate);+ await expect(service.updateAlert({ alertId: "alert-1", channels: [], ...actor })).rejects.toThrow(+ "At least one channel is required"+ );});- test("deleteAlertsForResource reaps an alert created in scope between the find and the delete", async () => {- let raced = false;- const { service, alerts } = buildService({- afterFindAlerts: (rows) => {- if (raced) return;- raced = true;- rows.set("alert-race", {- id: "alert-race",- orgId: "org-1",- projectId: "proj-1",- resourceType: RESOURCE_TYPE,- resourceId: "ident-1",- eventType: "test.resource.expiration"- });- // Out of the reaped scope, so it must survive even though it races the same way.- rows.set("alert-other-project", {- id: "alert-other-project",- orgId: "org-1",- projectId: "proj-2",- resourceType: RESOURCE_TYPE,- resourceId: "ident-1",- eventType: "test.resource.expiration"- });- }- });- await service.createAlert({ ...validCreate, resourceId: "ident-1" });+ test("checks Delete permission before deleting an alert", async () => {+ const { service, permissionCalls } = buildService();+ await service.createAlert(validCreate);- const deleted = await service.deleteAlertsForResource({- orgId: "org-1",- projectId: "proj-1",- resourceType: RESOURCE_TYPE,- resourceId: "ident-1"- });+ await service.deleteAlert({ alertId: "alert-1", ...actor });- expect(deleted).toBe(1);- expect([...alerts.keys()].sort()).toEqual(["alert-1", "alert-other-project"]);+ expect(permissionCalls.map((call) => call.action)).toContain("delete");});- test("deleteAlertsForDeletedResource spares other resources and other resource types", async () => {- const { service, alerts } = buildService();- await service.createAlert({ ...validCreate, resourceId: "ident-1" });- alerts.set("other-resource", {- id: "other-resource",- orgId: "org-2",- projectId: null,- resourceType: RESOURCE_TYPE,- resourceId: "ident-2",- eventType: "test.resource.expiration"- });- alerts.set("other-type", {- id: "other-type",- orgId: "org-2",- projectId: null,- resourceType: "other.resource",- resourceId: "ident-1",- eventType: "other.resource.expiration"- });-- const deleted = await service.deleteAlertsForDeletedResource({- resourceType: RESOURCE_TYPE,- resourceId: "ident-1"+ test("a concurrent duplicate create surfaces as a readable error, not a 500", async () => {+ const { service } = buildService({+ createError: new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation }, name: "Create" })});-- expect(deleted).toBe(1);- expect([...alerts.keys()]).toEqual(["other-resource", "other-type"]);+ await expect(service.createAlert(validCreate)).rejects.toThrow(+ "An alert for this resource and event already exists"+ );});});diff --cc backend/src/services/alert/alert-service.tsindex 4f66ba13d3,bc25c49409..ebdf37ec90--- a/backend/src/services/alert/alert-service.ts+++ b/backend/src/services/alert/alert-service.ts@@@ -11,20 -10,17 +11,25 @@@ import { TKmsServiceFactory } from "@apimport { getAlertChannelCipher } from "./alert-channel-crypto-fns";import { TAlertChannelDALFactory } from "./alert-channel-dal";import { TAlertChannelMembershipDALFactory } from "./alert-channel-membership-dal";+import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal";import { TAlertChannelServiceFactory } from "./alert-channel-service";-import { TAlertChannelEmbedded, TAlertChannelInput } from "./alert-channel-service-types";-import { TAlertDALFactory } from "./alert-dal";+import {+ TAlertChannelEmbedded,+ TAlertChannelInput,+ TChannelRecipientInput,+ TPreparedChannelCreate,+ TPreparedChannelUpdate+} from "./alert-channel-service-types";+import { AlertChannelType } from "./alert-channel-types";+import { TAlertDALFactory, TAlertWithChannels } from "./alert-dal";import { TAlertHistoryDALFactory } from "./alert-history-dal";import { getRecipientScope } from "./alert-principal-scope-fns";- import { getAlertResourceName, resolveAlertProjectId, TAlertProviderRegistry } from "./alert-provider-registry";+ import {+ getAlertEvent,+ getAlertResourceName,+ resolveAlertProjectId,+ TAlertProviderRegistry+ } from "./alert-provider-registry";import {TAlertLastRun,TAlertResponse,@@@ -42,10 -36,10 +47,11 @@@ importAlertRunStatus,AlertTelemetryAction,IResourceAlertProvider,+ MAX_CHANNELS_PER_ALERT,+ MAX_RECIPIENTS_PER_CHANNEL,TAlertAuditInput,TAlertEventDefinition,+ TAlertFilters,- TAlertRecipientScope,toAlertActor} from "./alert-types";@@@ -71,28 -58,7 +77,28 @@@ export type TAlertServiceFactoryDep =export type TAlertServiceFactory = ReturnType<typeof alertServiceFactory>;+// An alert write that has passed every check and is ready to be written.+type TAlertWritePlan =+ | {+ kind: "create";+ alert: TAlertsInsert;+ channels: TPreparedChannelCreate[];+ }+ | {+ kind: "update";+ alert: TAlerts;+ patch: Partial<Pick<TAlertsInsert, "name" | "description" | "condition" | "enabled">>;+ deleteChannelIds: string[];+ channelUpdates: TPreparedChannelUpdate[];+ channelCreates: TPreparedChannelCreate[];+ };++// What prepareAlertForResource returns. Its contents belong to this module: a caller only hands it back+// to applyPreparedAlert, inside the caller's own transaction.+const PREPARED_ALERT = Symbol("prepared alert");+export type TPreparedAlert = { readonly [PREPARED_ALERT]: TAlertWritePlan };+- const buildGenericAlertAuditEvent = (input: TAlertAuditInput): TAuditEvent => {+ const getAuditEvent = (input: TAlertAuditInput): TAuditEvent => {if (input.action === AlertAuditAction.TestChannel) {const { test } = input;return {@@@ -231,11 -191,11 +240,11 @@@ export const alertServiceFactory = (updatedAt: alert.updatedAt});- const createAlert = async (dto: TCreateAlertDTO): Promise<TAlertResponse> => {+ const $prepareCreate = async (dto: TCreateAlertDTO) => {- if (!dto.resourceId) {+ const provider = $getProvider(dto.resourceType);+ if (!dto.resourceId && !provider.supportsScopeWideAlerts) {throw new BadRequestError({- message:- "Alerts must be bound to a specific resource. Organization wide and project wide alerts are not supported yet."+ message: `Alerts for resource type '${dto.resourceType}' must be bound to a specific resource. Pass resourceId.`});}@@@ -307,158 -264,27 +315,172 @@@createdByActorId: dto.actorId,createdByActorType: dto.actor},- tx+ cipher.encryptor);+ channels.push(prepared);+ }++ const plan: TAlertWritePlan = {+ kind: "create",+ alert: {+ name: dto.name,+ description: dto.description,+ resourceType: dto.resourceType,+ resourceId: dto.resourceId,+ eventType: dto.eventType,+ triggerType: event.triggerType,- condition: dto.condition != null ? JSON.stringify(dto.condition) : null,++ condition: condition != null ? JSON.stringify(condition) : null,+ enabled: dto.enabled ?? true,+ orgId: dto.actorOrgId,+ projectId,+ createdByActorId: dto.actorId,+ createdByActorType: dto.actor+ },+ channels+ };+ return { plan, provider, cipher };+ };++ const $prepareUpdate = async (dto: TUpdateAlertDTO) => {+ const alert = await alertDAL.findActiveById(dto.alertId);+ if (!alert) throw new NotFoundError({ message: `Alert with ID '${dto.alertId}' not found` });++ const provider = $getProvider(alert.resourceType);+ await $assertAlertPermission(+ provider,+ AlertPermissionAction.Edit,+ { orgId: alert.orgId, projectId: alert.projectId, resourceId: alert.resourceId },+ dto+ );+- if (dto.condition !== undefined) $validateCondition($getEvent(provider, alert.eventType), dto.condition);++ let condition: unknown;++ if (dto.condition !== undefined) {++ condition = $parseCondition(getAlertEvent(provider, alert.eventType), dto.condition);++ await provider.assertConditionInScope?.({++ projectId: alert.projectId,++ resourceId: alert.resourceId,++ condition,++ previousCondition: alert.condition++ });++ }+ if (dto.channels !== undefined && dto.channels.length === 0) {+ throw new BadRequestError({ message: "At least one channel is required" });+ }+ if (dto.channels !== undefined) $assertChannelCount(dto.channels.length);++ // Read from the primary: the plan below decides which channels to keep, update or delete, and is+ // applied later in the caller's transaction.+ const existing = await alertChannelDAL.findByAlertId(alert.id, { readFromPrimary: true });+ const existingById = new Map<string, TAlertChannels>(existing.map((channel) => [channel.id, channel]));++ if (dto.channels && provider.assertChannelTypesAllowed) {+ await provider.assertChannelTypesAllowed({+ orgId: alert.orgId,+ channelTypes: dto.channels- .filter((channel) => !channel.id || existingById.get(channel.id)?.channelType !== channel.channelType)++ .filter((channel) => {++ const existingChannel = channel.id ? existingById.get(channel.id) : undefined;++ return (++ !existingChannel ||++ existingChannel.channelType !== channel.channelType ||++ (!existingChannel.enabled && channel.enabled === true)++ );++ })+ .map((channel) => channel.channelType)+ });+ }++ const scope = { orgId: alert.orgId, projectId: alert.projectId };+ const cipher = await getAlertChannelCipher(kmsService, scope);++ const deleteChannelIds: string[] = [];+ const channelUpdates: TPreparedChannelUpdate[] = [];+ const channelCreates: TPreparedChannelCreate[] = [];+ if (dto.channels !== undefined) {+ const recipientScope = getRecipientScope(provider, alert.projectId);+ const incomingIds = new Set(dto.channels.filter((channel) => channel.id).map((channel) => channel.id as string));+ for (const id of incomingIds) {+ if (!existingById.has(id)) {+ throw new BadRequestError({ message: `Channel '${id}' does not belong to this alert` });+ }+ }+ existing+ .filter((channel) => !incomingIds.has(channel.id))+ .forEach((channel) => deleteChannelIds.push(channel.id));for (const channelInput of dto.channels) {+ if (channelInput.id) {+ // eslint-disable-next-line no-await-in-loop -- each channel's recipients are checked in turn+ const prepared = await alertChannelService.prepareChannelUpdate(+ {+ channelId: channelInput.id,+ channelType: channelInput.channelType,+ name: channelInput.name,+ config: channelInput.config,+ enabled: channelInput.enabled,+ recipients: channelInput.recipients,+ recipientScope+ },+ existingById.get(channelInput.id) as TAlertChannels,+ cipher+ );+ channelUpdates.push(prepared);+ } else {+ // eslint-disable-next-line no-await-in-loop -- each channel's recipients are checked in turn+ const prepared = await alertChannelService.prepareChannelCreate(+ {+ name: channelInput.name,+ channelType: channelInput.channelType,+ config: channelInput.config ?? {},+ enabled: channelInput.enabled,+ recipients: channelInput.recipients,+ orgId: alert.orgId,+ projectId: alert.projectId,+ recipientScope,+ createdByActorId: alert.createdByActorId ?? null,+ createdByActorType: alert.createdByActorType+ },+ cipher.encryptor+ );+ channelCreates.push(prepared);+ }+ }+ }++ const plan: TAlertWritePlan = {+ kind: "update",+ alert,+ patch: {+ ...(dto.name !== undefined ? { name: dto.name } : {}),+ ...(dto.description !== undefined ? { description: dto.description } : {}),- ...(dto.condition !== undefined- ? { condition: dto.condition != null ? JSON.stringify(dto.condition) : null }- : {}),++ ...(dto.condition !== undefined ? { condition: condition != null ? JSON.stringify(condition) : null } : {}),+ ...(dto.enabled !== undefined ? { enabled: dto.enabled } : {})+ },+ deleteChannelIds,+ channelUpdates,+ channelCreates+ };+ return { plan, provider, cipher };+ };++ // Everything that can be refused was checked while preparing, so this only writes.+ const $applyPlan = async (plan: TAlertWritePlan, tx: Knex): Promise<TAlerts> => {+ if (plan.kind === "create") {+ let createdAlert: TAlerts;+ try {+ createdAlert = await alertDAL.create(plan.alert, tx);+ } catch (err) {+ // findScopedDuplicate reads the replica, so two concurrent creates can both pass it.+ if (+ err instanceof DatabaseError &&+ (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation+ ) {+ throw new BadRequestError({ message: "An alert for this resource and event already exists" });+ }+ throw err;+ }+ for (const prepared of plan.channels) {// eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serial- const channel = await alertChannelService.createChannelInTx(- {- name: channelInput.name,- channelType: channelInput.channelType,- config: channelInput.config ?? {},- enabled: channelInput.enabled,- recipients: channelInput.recipients,- orgId: dto.actorOrgId,- projectId: projectId ?? null,- recipientScope: getRecipientScope(provider, projectId),- createdByActorId: dto.actorId,- createdByActorType: dto.actor- },- cipher.encryptor,- tx- );+ const channel = await alertChannelService.applyChannelCreate(prepared, tx);// eslint-disable-next-line no-await-in-loop -- one shared tx connection; writes must be serialawait alertChannelMembershipDAL.insertMany([{ alertId: createdAlert.id, channelId: channel.id }], tx);}@@@ -554,8 -294,10 +576,12 @@@return { created: createdAlert, channels: details };});- const filters = await $getFilters(provider, scope, [created]);++ const filters = await $getFilters(provider, { orgId: created.orgId, projectId: created.projectId ?? null }, [++ created++ ]);return $assembleResponse(provider, created, channels, {- resourceName: await $getResourceName(provider, created)+ resourceName: await $getResourceName(provider, created),+ filters: filters.get(created.id)});};@@@ -651,10 -519,12 +681,14 @@@return { updated: updatedAlert, channels: details };});- const lastRuns = await $getLastRuns(provider, [alert.id]);- const filters = await $getFilters(provider, { orgId: alert.orgId, projectId: alert.projectId ?? null }, [updated]);+ const lastRuns = await $getLastRuns(provider, [updated.id]);++ const filters = await $getFilters(provider, { orgId: updated.orgId, projectId: updated.projectId ?? null }, [++ updated++ ]);return $assembleResponse(provider, updated, channels, {- resourceName: await $getResourceName(provider, alert),- lastRun: lastRuns.get(alert.id),+ resourceName: await $getResourceName(provider, updated),- lastRun: lastRuns.get(updated.id)++ lastRun: lastRuns.get(updated.id),+ filters: filters.get(updated.id)});};diff --cc frontend/src/hooks/api/alerts/types.tsindex 17074da079,a75883b7f6..67fbbcde5c--- a/frontend/src/hooks/api/alerts/types.ts+++ b/frontend/src/hooks/api/alerts/types.ts@@@ -1,8 -1,9 +1,10 @@@import { z } from "zod";+ import { CertSource } from "@app/hooks/api/certificates/enums";+export enum AlertResourceType {- IdentityAuthentication = "identity.authentication"+ IdentityAuthentication = "identity.authentication",+ SecretReminder = "secret.reminder"}export enum AlertEventType {@@@ -44,10 -61,10 +63,11 @@@ export enum CertificateManagerAlertEvenexport const MIN_ALERT_BEFORE_DAYS = 1;export const MAX_ALERT_BEFORE_DAYS = 90;export const MAX_CERTIFICATE_ALERT_BEFORE_DAYS = 365;+ export const MAX_CERTIFICATE_ALERT_FILTER_IDS = 100;export const ALERT_RESOURCE_TYPE_LABELS: Record<AlertResourceType, string> = {- [AlertResourceType.IdentityAuthentication]: "Machine Identity Authentication"+ [AlertResourceType.IdentityAuthentication]: "Machine Identity Authentication",+ [AlertResourceType.SecretReminder]: "Secret Reminder"};export const ALERT_EVENT_TYPE_LABELS: Record<AlertEventType, string> = {