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
refactor(alerts): let the alert module own a resource's alert end to end
Calvind0b201c6fbc3
diff --git a/backend/src/services/alert/alert-dal.ts b/backend/src/services/alert/alert-dal.tsindex dfe04248e9..5c471dc96a 100644--- a/backend/src/services/alert/alert-dal.ts+++ b/backend/src/services/alert/alert-dal.ts@@ -9,7 +9,7 @@ import { AlertTriggerType } from "./alert-types";export type TAlertDALFactory = ReturnType<typeof alertDALFactory>;-export type TAlertChannelSummary = {+export type TAlertWithChannels = {id: string;name: string;resourceId: string | null;@@ -228,14 +228,14 @@ export const alertDALFactory = (db: TDbClient) => {}};- // For a service that owns alerts on its own resource and needs to know whether one exists and what- // channels it has, without decrypting channel configs. Reads the primary: the caller decides between- // create and update on the result, and a replica that has not seen the alert yet sends it into the- // create path and the unique index.- const findChannelSummariesForResources = async (+ // Each alert on these resources with its channels' ids, names, types and enabled flags, without+ // decrypting any channel config. Reads the primary: prepareAlertForResource decides between creating+ // and updating on this, and a replica that has not yet seen a new alert would send it into the unique+ // index.+ const findWithChannelsForResources = async ({ resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },tx?: Knex- ): Promise<TAlertChannelSummary[]> => {+ ): Promise<TAlertWithChannels[]> => {if (resourceIds.length === 0) return [];try {const rows = await (tx || db)(TableName.Alert)@@ -280,13 +280,13 @@ export const alertDALFactory = (db: TDbClient) => {]});} catch (error) {- throw new DatabaseError({ error, name: "FindChannelSummariesForResources" });+ throw new DatabaseError({ error, name: "FindWithChannelsForResources" });}};return {...alertOrm,- findChannelSummariesForResources,+ findWithChannelsForResources,findRecipientsForResources,findEnabledByResourceType,findEnabledForEvent,diff --git a/backend/src/services/alert/alert-service-types.ts b/backend/src/services/alert/alert-service-types.tsindex 86501b130e..4ac30a5eae 100644--- a/backend/src/services/alert/alert-service-types.ts+++ b/backend/src/services/alert/alert-service-types.ts@@ -1,13 +1,6 @@-import { TAlerts, TAlertsInsert } from "@app/db/schemas";import { TGenericPermission } from "@app/lib/types";-import {- TAlertChannelEmbedded,- TAlertChannelInput,- TChannelRecipientInput,- TPreparedChannelCreate,- TPreparedChannelUpdate-} from "./alert-channel-service-types";+import { TAlertChannelEmbedded, TAlertChannelInput, TChannelRecipientInput } from "./alert-channel-service-types";import { AlertChannelType } from "./alert-channel-types";import { AlertRunStatus } from "./alert-types";@@ -93,20 +86,16 @@ export type TAlertLastRun = {status: AlertRunStatus;};-// An alert write that has passed every check, with channel configs already encrypted. Built by-// prepareCreateAlert or prepareUpdateAlert and written by applyAlertWrite, which a caller can run inside-// its own transaction so the alert lands, or does not, together with the caller's rows.-export 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[];- };+// The alert a domain service keeps on one of its own resources, set in full each time. `channels` is either+// the alert's complete channel list, or the recipients of its channels of one type, which leaves every other+// channel (eg a Slack or webhook channel added through the alert API) as it is.+export type TPrepareAlertForResourceDTO = TGenericPermission & {+ resourceType: string;+ resourceId: string;+ projectId: string;+ eventType: string;+ name: string;+ channels:+ | { replaceAll: TAlertChannelInput[] }+ | { replaceRecipients: { channelType: AlertChannelType; recipients: TChannelRecipientInput[] } };+};diff --git a/backend/src/services/alert/alert-service.test.ts b/backend/src/services/alert/alert-service.test.tsindex e474f8e41d..555001ca5c 100644--- a/backend/src/services/alert/alert-service.test.ts+++ b/backend/src/services/alert/alert-service.test.ts@@ -113,6 +113,24 @@ const buildService = (opts?: {return row;},findActiveById: async (id: string) => alerts.get(id),+ findWithChannelsForResources: async ({+ resourceType,+ resourceIds+ }: {+ resourceType: string;+ resourceIds: string[];+ }) =>+ [...alerts.values()]+ .filter((row) => row.resourceType === resourceType && resourceIds.includes(row.resourceId as string))+ .map((row) => ({+ id: row.id,+ name: row.name,+ resourceId: row.resourceId,+ channels: (memberships.get(row.id as string) ?? []).map((channelId) => {+ const channel = channels.get(channelId) as TChannelRow;+ return { id: channel.id, name: channel.name, channelType: channel.channelType, enabled: channel.enabled };+ })+ })),findActiveByScope: async (filter: Record<string, unknown>) => {findFilters.push(filter);return [...alerts.values()].filter((row) => matches(row, filter));@@ -505,15 +523,63 @@ describe("alert service", () => {);});- test("a prepared write changes nothing until it is applied", async () => {- const { service, alerts, channels } = buildService();- const plan = await service.prepareCreateAlert(validCreate);- expect(alerts.size).toBe(0);- expect(channels.size).toBe(0);+ describe("an alert a service keeps on its own resource", () => {+ const resourceAlert = (recipientIds: string[]) => ({+ resourceType: RESOURCE_TYPE,+ resourceId: "resource-1",+ projectId: "proj-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;++ 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);- await service.applyAlertWrite(plan, {} as never);- expect(alerts.size).toBe(1);- expect(channels.size).toBe(2);+ await service.applyPreparedAlert(prepared, tx);+ expect(alerts.size).toBe(1);+ expect([...channels.values()].map((c) => c.name)).toEqual(["Email"]);+ });++ 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);++ expect([...channels.values()].map((c) => [c.name, c.recipients.length])).toEqual([+ ["Email", 20],+ ["Email 2", 20],+ ["Email 3", 5]+ ]);+ });++ 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" })+ ]);+ });});test("update rejects an empty channel list", async () => {diff --git a/backend/src/services/alert/alert-service.ts b/backend/src/services/alert/alert-service.tsindex c726f40fbb..9611b8dddf 100644--- a/backend/src/services/alert/alert-service.ts+++ b/backend/src/services/alert/alert-service.ts@@ -1,7 +1,7 @@import { Knex } from "knex";import { z } from "zod";-import { TAlertChannels, TAlerts } from "@app/db/schemas";+import { TAlertChannels, TAlerts, TAlertsInsert } from "@app/db/schemas";import { Event as TAuditEvent, EventType } from "@app/ee/services/audit-log/audit-log-types";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";@@ -15,22 +15,24 @@ import { TAlertChannelRecipientDALFactory } from "./alert-channel-recipient-dal"import { TAlertChannelServiceFactory } from "./alert-channel-service";import {TAlertChannelEmbedded,+ TAlertChannelInput,TChannelRecipientInput,TPreparedChannelCreate,TPreparedChannelUpdate} from "./alert-channel-service-types";-import { TAlertDALFactory } from "./alert-dal";+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 {TAlertLastRun,TAlertResponse,- TAlertWritePlan,TCreateAlertDTO,TDeleteAlertDTO,TGetAlertDTO,TListAlertsDTO,+ TPrepareAlertForResourceDTO,TUpdateAlertDTO} from "./alert-service-types";import {@@ -40,6 +42,7 @@ import {AlertTelemetryAction,IResourceAlertProvider,MAX_CHANNELS_PER_ALERT,+ MAX_RECIPIENTS_PER_CHANNEL,TAlertAuditInput,TAlertEventDefinition,toAlertActor@@ -67,6 +70,27 @@ 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 => {if (input.action === AlertAuditAction.TestChannel) {const { test } = input;@@ -415,10 +439,8 @@ export const alertServiceFactory = ({return { plan, provider, cipher };};- // Writes a plan from prepareCreateAlert or prepareUpdateAlert. Everything that can be refused was checked- // and every channel config encrypted while preparing, so this is plain inserts and updates and can run- // inside another service's transaction.- const applyAlertWrite = async (plan: TAlertWritePlan, tx: Knex): Promise<TAlerts> => {+ // 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 {@@ -461,15 +483,71 @@ export const alertServiceFactory = ({return updatedAlert;};- const prepareCreateAlert = async (dto: TCreateAlertDTO): Promise<TAlertWritePlan> => (await $prepareCreate(dto)).plan;+ // Spreads recipients over as many channels of one type as they need, reusing that type's existing channels+ // in order so their ids, names and settings survive, and keeps every other channel as it is.+ const $channelsWithRecipients = (+ existing: TAlertWithChannels | undefined,+ { channelType, recipients }: { channelType: AlertChannelType; recipients: TChannelRecipientInput[] }+ ): TAlertChannelInput[] => {+ const sameType = existing?.channels.filter((channel) => channel.channelType === channelType) ?? [];+ const label = channelType.charAt(0).toUpperCase() + channelType.slice(1);++ const replaced: TAlertChannelInput[] = [];+ for (let i = 0; i < recipients.length; i += MAX_RECIPIENTS_PER_CHANNEL) {+ const index = replaced.length;+ replaced.push({+ ...(sameType[index] ? { id: sameType[index].id } : {}),+ name: sameType[index]?.name ?? (index === 0 ? label : `${label} ${index + 1}`),+ channelType,+ recipients: recipients.slice(i, i + MAX_RECIPIENTS_PER_CHANNEL)+ });+ }- const prepareUpdateAlert = async (dto: TUpdateAlertDTO): Promise<TAlertWritePlan> => (await $prepareUpdate(dto)).plan;+ const others: TAlertChannelInput[] = (existing?.channels ?? [])+ .filter((channel) => channel.channelType !== channelType)+ .map((channel) => ({+ id: channel.id,+ name: channel.name,+ channelType: channel.channelType as AlertChannelType,+ enabled: channel.enabled+ }));++ return [...replaced, ...others];+ };++ // For a service that keeps one alert on each of its own resources (eg a secret's reminder): creates it or+ // updates it, with every check the alert API runs, and returns it ready for applyPreparedAlert inside the+ // caller's transaction. Nothing is written here.+ const prepareAlertForResource = async (dto: TPrepareAlertForResourceDTO): Promise<TPreparedAlert> => {+ const { resourceType, resourceId, projectId, eventType, name, channels, ...actor } = dto;+ const [existing] = await alertDAL.findWithChannelsForResources({ resourceType, resourceIds: [resourceId] });+ const alertChannels =+ "replaceAll" in channels ? channels.replaceAll : $channelsWithRecipients(existing, channels.replaceRecipients);++ const { plan } = existing+ ? await $prepareUpdate({ alertId: existing.id, name, channels: alertChannels, ...actor })+ : await $prepareCreate({+ name,+ resourceType,+ resourceId,+ eventType,+ condition: null,+ projectId,+ channels: alertChannels,+ ...actor+ });+ return { [PREPARED_ALERT]: plan };+ };++ const applyPreparedAlert = async (prepared: TPreparedAlert, tx: Knex): Promise<void> => {+ await $applyPlan(prepared[PREPARED_ALERT], tx);+ };const createAlert = async (dto: TCreateAlertDTO): Promise<TAlertResponse> => {const { plan, provider, cipher } = await $prepareCreate(dto);const { created, channels } = await alertDAL.transaction(async (tx) => {- const createdAlert = await applyAlertWrite(plan, tx);+ const createdAlert = await $applyPlan(plan, tx);const attachedChannels = await alertChannelDAL.findByAlertId(createdAlert.id, {}, tx);const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);return { created: createdAlert, channels: details };@@ -566,7 +644,7 @@ export const alertServiceFactory = ({const { plan, provider, cipher } = await $prepareUpdate(dto);const { updated, channels } = await alertDAL.transaction(async (tx) => {- const updatedAlert = await applyAlertWrite(plan, tx);+ const updatedAlert = await $applyPlan(plan, tx);const attachedChannels = await alertChannelDAL.findByAlertId(updatedAlert.id, {}, tx);const details = await alertChannelService.getDetailsForChannels(attachedChannels, cipher, tx);return { updated: updatedAlert, channels: details };@@ -655,9 +733,6 @@ export const alertServiceFactory = ({tx?: Knex): Promise<number> => $reapAlerts({ resourceType, resourceId }, tx);- const findAlertChannelSummariesForResources = (input: { resourceType: string; resourceIds: string[] }, tx?: Knex) =>- alertDAL.findChannelSummariesForResources(input, tx);-const deleteAlertsForDeletedResources = async ({ resourceType, resourceIds }: { resourceType: string; resourceIds: string[] },tx?: Knex@@ -787,16 +862,14 @@ export const alertServiceFactory = ({getTelemetryEvent,getAuditEvent,createAlert,- prepareCreateAlert,- prepareUpdateAlert,- applyAlertWrite,+ prepareAlertForResource,+ applyPreparedAlert,getAlertById,listAlerts,updateAlert,deleteAlert,deleteAlertsForResource,deleteAlertsForDeletedResource,- findAlertChannelSummariesForResources,deleteAlertsForDeletedResources,repointAlertsForResource,copyAlertsForResource,diff --git a/backend/src/services/reminder/reminder-service.test.ts b/backend/src/services/reminder/reminder-service.test.tsindex 7deed62867..9c5af9289c 100644--- a/backend/src/services/reminder/reminder-service.test.ts+++ b/backend/src/services/reminder/reminder-service.test.ts@@ -195,24 +195,10 @@ describe("orphaned reminder alert reaping", () => {});});-type TStoredAlert = {- id: string;- name: string;- resourceId: string;- channels: Array<{- id: string;- name: string;- channelType: string;- enabled: boolean;- }>;-};--const buildWriteService = (- opts: { existingAlert?: TStoredAlert; projectUserIds?: string[]; alertRefusal?: Error } = {}-) => {+const buildWriteService = (opts: { projectUserIds?: string[]; alertRefusal?: Error } = {}) => {const calls: string[] = [];- const created: unknown[] = [];- const updated: Array<{ alertId: string; name?: string; channels?: unknown[] }> = [];+ // What the reminder asked the alert module to set on its secret.+ const alertRequests: Array<Record<string, unknown>> = [];const copied: unknown[] = [];const deletedAlerts: Array<{ resourceIds: string[]; tx: unknown }> = [];const repointed: Array<{ fromResourceId: string; toResourceId: string; tx: unknown }> = [];@@ -254,26 +240,12 @@ const buildWriteService = (alertService: {filterRecipientsInScope: async (_scope: unknown, recipients: { principalType: string; principalId: string }[]) =>opts.projectUserIds ? recipients.filter((r) => opts.projectUserIds!.includes(r.principalId)) : recipients,- findAlertChannelSummariesForResources: async () => (opts.existingAlert ? [opts.existingAlert] : []),- prepareCreateAlert: async (input: unknown) => {+ prepareAlertForResource: async (input: Record<string, unknown>) => {if (opts.alertRefusal) throw opts.alertRefusal;- created.push(input);- return { kind: "create" };+ alertRequests.push(input);+ return {};},- prepareUpdateAlert: async ({- alertId,- name,- channels- }: {- alertId: string;- name?: string;- channels?: unknown[];- }) => {- if (opts.alertRefusal) throw opts.alertRefusal;- updated.push({ alertId, name, channels });- return { kind: "update" };- },- applyAlertWrite: async (_plan: unknown, trx: unknown) => {+ applyPreparedAlert: async (_prepared: unknown, trx: unknown) => {calls.push("alert:apply");writeTxs.push(trx);},@@ -295,7 +267,7 @@ const buildWriteService = (}} as never);- return { service, calls, created, updated, deletedAlerts, repointed, copied, reminderTx, writeTxs };+ return { service, calls, alertRequests, deletedAlerts, repointed, copied, reminderTx, writeTxs };};const caller = { actor: "user", actorId: "user-1", actorOrgId: "org-1", actorAuthMethod: null };@@ -311,10 +283,10 @@ const saveReminder = (describe("reminder alert sync", () => {test("a new reminder gets an alert with an email channel to its recipients, written as the caller", async () => {- const { service, created } = buildWriteService();+ const { service, alertRequests } = buildWriteService();await saveReminder(service, { recipients: ["user-1", "user-2"] });- expect(created).toEqual([+ expect(alertRequests).toEqual([expect.objectContaining({name: "Reminder for DB_PASSWORD",resourceType: SECRET_REMINDER_RESOURCE_TYPE,@@ -322,16 +294,15 @@ describe("reminder alert sync", () => {eventType: SECRET_REMINDER_DUE_EVENT,projectId: "proj-1",...caller,- channels: [- {- name: "Email",+ channels: {+ replaceRecipients: {channelType: "email",recipients: [{ principalType: "user", principalId: "user-1" },{ principalType: "user", principalId: "user-2" }]}- ]+ }})]);});@@ -367,29 +338,29 @@ describe("reminder alert sync", () => {});test("a rename in the same request names the alert after the new key", async () => {- const { service, created } = buildWriteService();+ const { service, alertRequests } = buildWriteService();await service.prepareReminder({...caller,secretKey: "RENAMED",reminder: { secretId: "secret-1", repeatDays: 30, recipients: ["user-1"] }} as never);- expect(created).toEqual([expect.objectContaining({ name: "Reminder for RENAMED" })]);+ expect(alertRequests).toEqual([expect.objectContaining({ name: "Reminder for RENAMED" })]);});test("no recipients means everyone in the project", async () => {- const { service, created } = buildWriteService();+ const { service, alertRequests } = buildWriteService();await saveReminder(service, { recipients: [] });- expect((created[0] as { channels: { recipients: unknown }[] }).channels[0].recipients).toEqual([- { principalType: "project-members", principalId: "proj-1" }- ]);+ expect(+ (alertRequests[0].channels as { replaceRecipients: { recipients: unknown } }).replaceRecipients.recipients+ ).toEqual([{ principalType: "project-members", principalId: "proj-1" }]);});test("recipients who left the project are dropped instead of failing the write", async () => {- const { service, created } = buildWriteService({ projectUserIds: ["user-1"] });+ const { service, alertRequests } = buildWriteService({ projectUserIds: ["user-1"] });await saveReminder(service, { recipients: ["user-1", "user-gone"] });- expect((created[0] as { channels: { recipients: unknown }[] }).channels[0].recipients).toEqual([- { principalType: "user", principalId: "user-1" }- ]);+ expect(+ (alertRequests[0].channels as { replaceRecipients: { recipients: unknown } }).replaceRecipients.recipients+ ).toEqual([{ principalType: "user", principalId: "user-1" }]);});test("refuses a recipient list with nobody left in the project rather than sending to everyone", async () => {@@ -400,7 +371,7 @@ describe("reminder alert sync", () => {expect(calls).toEqual([]);});- test("given channels, saves them as the alert's complete channel list", async () => {+ test("given channels, sets them as the alert's complete channel list", async () => {const channels = [{name: "Email",@@ -409,58 +380,9 @@ describe("reminder alert sync", () => {},{ name: "Webhook", channelType: "webhook", config: { url: "https://example.com" } }];- const save = (service: ReturnType<typeof buildWriteService>["service"]) =>- saveReminder(service, { recipients: ["user-1"], channels });-- const existing = buildWriteService({- existingAlert: { id: "alert-1", name: "Reminder for OLD_NAME", resourceId: "secret-1", channels: [] }- });- await save(existing.service);- expect(existing.updated).toEqual([{ alertId: "alert-1", name: "Reminder for DB_PASSWORD", channels }]);-- const fresh = buildWriteService();- await save(fresh.service);- expect(fresh.created).toEqual([expect.objectContaining({ resourceId: "secret-1", channels })]);- });-- test("more than 20 recipients are split across email channels", async () => {- const { service, created } = buildWriteService();- await saveReminder(service, { recipients: Array.from({ length: 45 }, (_, i) => `user-${i}`) });- const { channels } = created[0] as { channels: { name: string; recipients: unknown[] }[] };- expect(channels.map((c) => c.name)).toEqual(["Email", "Email 2", "Email 3"]);- expect(channels.map((c) => c.recipients.length)).toEqual([20, 20, 5]);- });-- test("updating keeps Slack, webhook and PagerDuty channels and reuses the email channel", async () => {- const { service, updated, created } = buildWriteService({- existingAlert: {- id: "alert-1",- name: "Reminder for OLD_NAME",- resourceId: "secret-1",- channels: [- { id: "ch-email", name: "Team email", channelType: "email", enabled: true },- { id: "ch-hook", name: "Webhook", channelType: "webhook", enabled: false }- ]- }- });- await saveReminder(service, { recipients: ["user-1"] });-- expect(created).toHaveLength(0);- expect(updated).toEqual([- {- alertId: "alert-1",- name: "Reminder for DB_PASSWORD",- channels: [- {- id: "ch-email",- name: "Team email",- channelType: "email",- recipients: [{ principalType: "user", principalId: "user-1" }]- },- { id: "ch-hook", name: "Webhook", channelType: "webhook", enabled: false }- ]- }- ]);+ const { service, alertRequests } = buildWriteService();+ await saveReminder(service, { recipients: ["user-1"], channels });+ expect(alertRequests).toEqual([expect.objectContaining({ channels: { replaceAll: channels } })]);});test("deleting a reminder by secret also removes its alert inside the caller's transaction", async () => {diff --git a/backend/src/services/reminder/reminder-service.ts b/backend/src/services/reminder/reminder-service.tsindex 0a730c7e1a..635ee3a970 100644--- a/backend/src/services/reminder/reminder-service.ts+++ b/backend/src/services/reminder/reminder-service.ts@@ -8,13 +8,11 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { ProjectPermissionSecretActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";-import { TGenericPermission } from "@app/lib/types";-import { TAlertChannelInput, TChannelRecipientInput } from "../alert/alert-channel-service-types";+import { TChannelRecipientInput } from "../alert/alert-channel-service-types";import { AlertChannelType } from "../alert/alert-channel-types";import { TAlertServiceFactory } from "../alert/alert-service";-import { TAlertWritePlan } from "../alert/alert-service-types";-import { AlertPrincipalType, MAX_RECIPIENTS_PER_CHANNEL } from "../alert/alert-types";+import { AlertPrincipalType } from "../alert/alert-types";import { ActorAuthMethod, ActorType } from "../auth/auth-type";import { TEventEmitter } from "../event-outbox/event-outbox-types";import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";@@ -35,10 +33,8 @@ type TReminderServiceFactoryDep = {eventEmitter: TEventEmitter;alertService: Pick<TAlertServiceFactory,- | "prepareCreateAlert"- | "prepareUpdateAlert"- | "applyAlertWrite"- | "findAlertChannelSummariesForResources"+ | "prepareAlertForResource"+ | "applyPreparedAlert"| "findRecipientsForResources"| "deleteAlertsForDeletedResources"| "repointAlertsForResource"@@ -108,79 +104,6 @@ export const reminderServiceFactory = ({return inScope.length ? inScope : [{ principalType: AlertPrincipalType.PROJECT_MEMBERS, principalId: projectId }];};- // Given `channels`, they are the alert's complete channel list. Otherwise the reminder API only knows- // user ids, so it owns the alert's email channels and leaves every other channel (Slack, webhook,- // PagerDuty) as the user configured it. The alert is prepared as the caller, so the reminder provider- // checks they can edit the secret, and the alert module refuses anything it would not accept from its- // own API (eg more channels than an alert can hold).- const $prepareReminderAlert = async ({- secretId,- secretKey,- projectId,- recipients,- channels,- actor- }: {- secretId: string;- secretKey: string;- projectId: string;- recipients?: string[] | null;- channels?: TAlertChannelInput[];- actor: TGenericPermission;- }): Promise<TAlertWritePlan> => {- const [existing] = await alertService.findAlertChannelSummariesForResources({- resourceType: SECRET_REMINDER_RESOURCE_TYPE,- resourceIds: [secretId]- });-- const $plan = (alertChannels: TAlertChannelInput[]) =>- existing- ? alertService.prepareUpdateAlert({- alertId: existing.id,- name: reminderAlertName(secretKey),- channels: alertChannels,- ...actor- })- : alertService.prepareCreateAlert({- name: reminderAlertName(secretKey),- resourceType: SECRET_REMINDER_RESOURCE_TYPE,- resourceId: secretId,- eventType: SECRET_REMINDER_DUE_EVENT,- condition: null,- projectId,- channels: alertChannels,- ...actor- });-- if (channels) return $plan(channels);-- const emailRecipients = await $resolveEmailRecipients({ orgId: actor.actorOrgId, projectId, recipients });- const existingEmailChannels =- existing?.channels.filter((channel) => channel.channelType === AlertChannelType.EMAIL) ?? [];-- const emailChannels: TAlertChannelInput[] = [];- for (let i = 0; i < emailRecipients.length; i += MAX_RECIPIENTS_PER_CHANNEL) {- const index = emailChannels.length;- emailChannels.push({- ...(existingEmailChannels[index] ? { id: existingEmailChannels[index].id } : {}),- name: existingEmailChannels[index]?.name ?? (index === 0 ? "Email" : `Email ${index + 1}`),- channelType: AlertChannelType.EMAIL,- recipients: emailRecipients.slice(i, i + MAX_RECIPIENTS_PER_CHANNEL)- });- }-- const otherChannels: TAlertChannelInput[] = (existing?.channels ?? [])- .filter((channel) => channel.channelType !== AlertChannelType.EMAIL)- .map((channel) => ({- id: channel.id,- name: channel.name,- channelType: channel.channelType as AlertChannelType,- enabled: channel.enabled- }));-- return $plan([...emailChannels, ...otherChannels]);- };-const $getSecretForPermissionCheck = async (secretId: string) => {const secret = await secretV2BridgeDAL.findOneWithTags({ [`${TableName.SecretV2}.id` as "id"]: secretId });if (!secret) {@@ -262,33 +185,51 @@ export const reminderServiceFactory = ({);const { nextReminderDate, fromDate } = $schedule(reminder);- const alertPlan = await $prepareReminderAlert({- secretId: secret.id,- secretKey: secretKey ?? secret.key,++ // Given `channels`, they are the alert's complete channel list. Otherwise the reminder API only knows+ // user ids, so it sets the alert's email recipients and leaves every other channel as the user set it.+ const alert = await alertService.prepareAlertForResource({+ resourceType: SECRET_REMINDER_RESOURCE_TYPE,+ resourceId: secret.id,projectId: secret.projectId,- recipients: reminder.recipients,- channels: reminder.channels,- actor: { actor, actorId, actorOrgId, actorAuthMethod }+ eventType: SECRET_REMINDER_DUE_EVENT,+ name: reminderAlertName(secretKey ?? secret.key),+ channels: reminder.channels+ ? { replaceAll: reminder.channels }+ : {+ replaceRecipients: {+ channelType: AlertChannelType.EMAIL,+ recipients: await $resolveEmailRecipients({+ orgId: actorOrgId,+ projectId: secret.projectId,+ recipients: reminder.recipients+ })+ }+ },+ actor,+ actorId,+ actorOrgId,+ actorAuthMethod});return {secretId: secret.id,projectId: secret.projectId,- row: { message: reminder.message, repeatDays: reminder.repeatDays, nextReminderDate, fromDate },- alertPlan+ schedule: { message: reminder.message, repeatDays: reminder.repeatDays, nextReminderDate, fromDate },+ alert};};// Writes a prepared reminder and its alert in the caller's transaction, so the two land together.const applyReminder: TReminderServiceFactory["applyReminder"] = async (prepared, tx) => {- await alertService.applyAlertWrite(prepared.alertPlan, tx);+ await alertService.applyPreparedAlert(prepared.alert, tx);const existingReminder = await reminderDAL.findOne({ secretId: prepared.secretId }, tx);if (existingReminder) {- await reminderDAL.updateById(existingReminder.id, prepared.row, tx);+ await reminderDAL.updateById(existingReminder.id, prepared.schedule, tx);return { id: existingReminder.id, created: false };}- const newReminder = await reminderDAL.create({ secretId: prepared.secretId, ...prepared.row }, tx);+ const newReminder = await reminderDAL.create({ secretId: prepared.secretId, ...prepared.schedule }, tx);return { id: newReminder.id, created: true };};diff --git a/backend/src/services/reminder/reminder-types.ts b/backend/src/services/reminder/reminder-types.tsindex 32367ec332..0243ace4d1 100644--- a/backend/src/services/reminder/reminder-types.ts+++ b/backend/src/services/reminder/reminder-types.ts@@ -1,7 +1,7 @@import { Knex } from "knex";import { TAlertChannelInput } from "../alert/alert-channel-service-types";-import { TAlertWritePlan } from "../alert/alert-service-types";+import { TPreparedAlert } from "../alert/alert-service";import { ActorAuthMethod, ActorType } from "../auth/auth-type";export type TReminder = {@@ -42,13 +42,13 @@ export type TPrepareReminderDTO = TCreateReminderDTO & {export type TPreparedReminder = {secretId: string;projectId: string;- row: {+ schedule: {message?: string | null;repeatDays?: number | null;nextReminderDate: Date;fromDate?: Date;};- alertPlan: TAlertWritePlan;+ alert: TPreparedAlert;};export type TBatchCreateReminderDTO = {